branch_name stringclasses 149 values | text stringlengths 23 89.3M | directory_id stringlengths 40 40 | languages listlengths 1 19 | num_files int64 1 11.8k | repo_language stringclasses 38 values | repo_name stringlengths 6 114 | revision_id stringlengths 40 40 | snapshot_id stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|
refs/heads/master | <repo_name>SAMTHP/S4_DATING<file_sep>/app/models/message.rb
class Message < ApplicationRecord
validates :subject, presence: true
validates :content, presence: true
belongs_to :conversation
end
<file_sep>/db/seeds.rb
require 'faker'
100.times do
celib = Celib.create!
end
100.times do
man_user = ManUser.create!(first_name: Faker::Hobbit.character,last_name: Faker::Hobbit.character, detail: Faker::HowIMetYourMother.quote, pseudo: Faker::Superhero.prefix, email: Faker::Internet.email, celib_id: rand(1..100))
end
100.times do
woman_user = WomanUser.create!(first_name: Faker::Hobbit.character,last_name: Faker::Hobbit.character, detail: Faker::HowIMetYourMother.quote, pseudo: Faker::Superhero.prefix, email: Faker::Internet.email, celib_id: rand(1..100))
end
100.times do
no = NegativeAcceptance.create!(man_user_id: rand(1..10), woman_user_id: rand(1..10))
end
100.times do
yes = PositiveAcceptance.create!(man_user_id: rand(1..10), woman_user_id: rand(1..10))
end
100.times do
conversation = Conversation.create!
end
100.times do
particip = Participate.create!(positive_acceptance_id: rand(1..10), conversation_id: rand(1..100))
end
100.times do
message = Message.create!(subject: Faker::NewGirl.character, content: Faker::NewGirl.quote, conversation_id: rand(1..100))
end
100.times do
man_picture = ManPhoto.create!(url: Faker::Internet.url('example.com') , description: Faker::NewGirl.quote, man_user_id: rand(1..100))
end
100.times do
woman_picture = WomanPhoto.create!(url: Faker::Internet.url('example.com') , description: Faker::NewGirl.quote, woman_user_id: rand(1..100))
end
<file_sep>/app/models/woman_user.rb
class WomanUser < ApplicationRecord
validates :first_name, presence: true
validates :last_name, presence: true
validates :detail, presence: true
validates :pseudo, presence: true
validates :email, presence: true
belongs_to :celib
has_many :woman_photos
has_many :negative_acceptances
has_many :man_users, through: :negative_acceptances
has_many :positive_acceptances
has_many :man_users, through: :positive_acceptances
end
<file_sep>/app/models/conversation.rb
class Conversation < ApplicationRecord
has_many :participates
has_many :positive_acceptances, through: :participates
has_many :messages
end
<file_sep>/app/models/negative_acceptance.rb
class NegativeAcceptance < ApplicationRecord
belongs_to :man_user
belongs_to :woman_user
end
<file_sep>/app/models/man_user.rb
class ManUser < ApplicationRecord
validates :first_name, presence: true
validates :last_name, presence: true
validates :detail, presence: true
validates :pseudo, presence: true
validates :email, presence: true
belongs_to :celib
has_many :man_photos
has_many :negative_acceptances
has_many :woman_users, through: :negative_acceptances
has_many :positive_acceptances
has_many :woman_users, through: :positive_acceptances
end
<file_sep>/app/models/participate.rb
class Participate < ApplicationRecord
belongs_to :positive_acceptance
belongs_to :conversation
end
<file_sep>/app/models/man_photo.rb
class ManPhoto < ApplicationRecord
validates :url, presence: true
validates :description, presence: true
belongs_to :man_user
end
<file_sep>/app/models/woman_photo.rb
class WomanPhoto < ApplicationRecord
validates :url, presence: true
validates :description, presence: true
belongs_to :woman_user
end
<file_sep>/README.md
# README
## Database relationship shema

<file_sep>/app/models/positive_acceptance.rb
class PositiveAcceptance < ApplicationRecord
belongs_to :man_user
belongs_to :woman_user
has_many :participates
has_many :conversations, through: :participates
end
<file_sep>/app/models/celib.rb
class Celib < ApplicationRecord
has_many :man_users
has_many :woman_users
end
| cf6e5492b0ea21064224654af1889f0cc677f092 | [
"Markdown",
"Ruby"
] | 12 | Ruby | SAMTHP/S4_DATING | f823c35fcafb53e32e708f35b7b3ec3822a51cb5 | 57c48a50c897a16ee6cbd424d278461420fd7a16 |
refs/heads/master | <file_sep>require "y/version"
module Y
# Your code goes here...
end
<file_sep>require "x/version"
module X
# Your code goes here...
end
| 8b46cf7a3ee150a26dc4738ebd9a3f78d0cf6071 | [
"Ruby"
] | 2 | Ruby | villi/gemtest | a1d08a93ae976d1e0db1eb72952e34234ad43a4c | fca217c5f0d33c7ae1bd89b7269885172ca05df8 |
refs/heads/master | <repo_name>assassindesign/SimpleRenderer<file_sep>/src/include/geometry.h
// This file is a part of Simple-XX/SimpleRenderer
// (https://github.com/Simple-XX/SimpleRenderer).
//
// geometry.h for Simple-XX/SimpleRenderer.
#ifndef __GEOMTRY_H__
#define __GEOMTRY_H__
#include "string"
#include "common.h"
#include "image.h"
#include "vector.hpp"
// 负责确定几何图形的绘制
class Geometry {
private:
// 判断 _p 是否为三角形重心
bool is_barycentric(const Vectors2 &_vertex1, const Vectors2 &_vertex2,
const Vectors2 &_vertex3, const Vectors2 &_p) const;
bool is_barycentric(const Vectorf3 &_vertex1, const Vectorf3 &_vertex2,
const Vectorf3 &_vertex3, const Vectorf3 &_p) const;
// 获取最小 (x,y)
Vectors2 get_min(const Vectors2 &_vertex1, const Vectors2 &_vertex2,
const Vectors2 &_vertex3) const;
// 获取最大 (x,y)
Vectors2 get_max(const Vectors2 &_vertex1, const Vectors2 &_vertex2,
const Vectors2 &_vertex3) const;
// 获取最小 (x,y,z)
Vectorf3 get_min(const Vectorf3 &_vertex1, const Vectorf3 &_vertex2,
const Vectorf3 &_vertex3) const;
// 获取最大 (x,y,z)
Vectorf3 get_max(const Vectorf3 &_vertex1, const Vectorf3 &_vertex2,
const Vectorf3 &_vertex3) const;
// 求平面法向量
Vectorf3 normal(const Vectorf3 &_vertex1, const Vectorf3 &_vertex2,
const Vectorf3 &_vertex3) const;
// 计算平面上 (x, y) 位置的深度
float get_z(const Vectorf3 &_vertex1, const Vectorf3 &_vertex2,
const Vectorf3 &_vertex3, size_t _x, size_t _y) const;
protected:
TGAImage & image;
std::string filename = "output.tga";
// 背景色默认黑色
const TGAColor color_bg = black;
public:
Geometry(TGAImage &_image, const std::string &_filename = "output.tga");
virtual ~Geometry(void);
// 获取画布宽度
size_t get_width(void) const;
// 获取画布高度
size_t get_height(void) const;
// 保存修改
bool save(std::string _filename = "output.tga") const;
// 直线 Bresenham
void line(size_t _x0, size_t _y0, size_t _x1, size_t _y1,
const TGAColor &_color) const;
void line(Vectors2 _v0, Vectors2 _v1, const TGAColor &_color) const;
void line(Vectors2 *_vertexes, const TGAColor &_color) const;
// 带 zbufferr 的直线
void line(float _x0, float _y0, float _z0, float _x1, float _y1, float _z1,
float *_zbuffer, const TGAColor &_color);
void line(Vectorf3 _v0, Vectorf3 _v1, float *_zbuffer,
const TGAColor &_color);
void line(Vectorf3 *_vertexes, float *_zbuffer, const TGAColor &_color);
// 三角形
void triangle(const Vectors2 &_vertex1, const Vectors2 &_vertex2,
const Vectors2 &_vertex3, const TGAColor &_color) const;
void triangle(const Vectors2 *_vertexes, const TGAColor &_color) const;
// 带 zbufferr 的三角形
void triangle(const Vectorf3 &_vertex1, const Vectorf3 &_vertex2,
const Vectorf3 &_vertex3, float *_zbuffer,
const TGAColor &_color) const;
void triangle(const Vectorf3 *_vertexes, float *_zbuffer,
const TGAColor &_color);
// 圆 Bresenham
void circle(size_t _x0, size_t _y0, float _r, TGAColor _color) const;
// 带 zbufferr 的圆
void circle(size_t _x0, size_t _y0, float _r, float *_zbuffer,
const TGAColor &_color) const;
};
#endif /* __GEOMTRY_H__ */
<file_sep>/README.md




# SimpleRenderer
A software renderer
软件光栅化渲染器
参考:https://github.com/ssloy/tinyrenderer
正在开发中...
<file_sep>/src/include/test.h
// This file is a part of Simple-XX/SimpleRenderer
// (https://github.com/Simple-XX/SimpleRenderer).
//
// test.h for Simple-XX/SimpleRenderer.
#ifndef __TEST_H__
#define __TEST_H__
#include "image.h"
class Test {
private:
const TGAColor white = TGAColor(255, 255, 255, 255);
const TGAColor red = TGAColor(255, 0, 0, 255);
const int width = 1920;
const int height = 1080;
bool test_line(void) const;
bool test_triangle(void) const;
bool test_fill(void) const;
public:
Test(void);
~Test(void);
bool test_vector(void) const;
bool test_matrix(void) const;
bool test_2d() const;
bool test_tga(void) const;
};
#endif /* __TEST_H__ */
<file_sep>/src/test.cpp
// This file is a part of Simple-XX/SimpleRenderer
// (https://github.com/Simple-XX/SimpleRenderer).
//
// test.cpp for Simple-XX/SimpleRenderer.
#include "vector"
#include "iostream"
#include "math.h"
#include "stdarg.h"
#include "assert.h"
#include "test.h"
#include "vector.hpp"
#include "geometry.h"
#include "matrix.hpp"
using namespace std;
Test::Test(void) {
return;
}
Test::~Test(void) {
return;
}
bool Test::test_vector(void) const {
Vector<int, 2> test(vector<int>{2, 3});
Vector<int, 2> test2(vector<int>{-1, 3});
Vector<int, 2> test3 = test - test2;
assert(test.coord.x == 2);
assert(test.coord.y == 3);
assert(test2.coord.x == -1);
assert(test2.coord.y == 3);
assert(test3.coord.x == 3);
assert(test3.coord.y == 0);
assert((test3 * 3).coord.x == 9);
assert((test3 * 3).coord.y == 0);
assert((Vector<int, 2>(vector<int>{0, 1}) *
Vector<int, 2>(vector<int>{1, 0})) == 0);
assert(test.norm() == sqrt(13));
assert((-test).coord.x == -2);
assert((-test).coord.y == -3);
assert(test == true);
Vector<int, 2> test4;
assert(test4 == false);
Vector<int, 3> test5(vector<int>{2, 3, 4});
Vector<int, 3> test6(vector<int>{-1, 3, -2});
Vector<int, 3> test7 = test5 - test6;
assert(test5.coord.x == 2);
assert(test5.coord.y == 3);
assert(test5.coord.z == 4);
assert(test6.coord.x == -1);
assert(test6.coord.y == 3);
assert(test6.coord.z == -2);
assert(test7.coord.x == 3);
assert(test7.coord.y == 0);
assert(test7.coord.z == 6);
assert((test7 * 3).coord.x == 9);
assert((test7 * 3).coord.y == 0);
assert((test7 * 3).coord.z == 18);
assert((Vector<int, 3>(vector<int>{0, 1, 0}) *
Vector<int, 3>(vector<int>{1, 0, 0})) == 0);
assert(test5.norm() == sqrt(29));
assert((-test5).coord.x == -2);
assert((-test5).coord.y == -3);
assert((-test5).coord.z == -4);
assert(test5 == true);
Vector<int, 3> test8;
assert(test8 == false);
Vector<int, 3> test9 = test5 ^ test6;
assert(test9.coord.x == -18);
assert(test9.coord.y == 0);
assert(test9.coord.z == 9);
int tmp233[3] = {1, 2, 3};
Vector<int, 3> test10(tmp233);
assert(test10.coord.x == 1);
assert(test10.coord.y == 2);
assert(test10.coord.z == 3);
Vector<int, 3> test11(test10);
assert(test11.coord.x == 1);
assert(test11.coord.y == 2);
assert(test11.coord.z == 3);
return true;
}
bool Test::test_matrix(void) const {
Matrix<int> test1;
int arr[16] = {233};
size_t total = test1.to_arr(arr);
assert(total == 16);
assert(arr[0] == 0);
assert(arr[3] == 0);
assert(arr[5] == 0);
assert(arr[7] == 0);
assert(arr[8] == 0);
assert(arr[9] == 0);
assert(arr[15] == 0);
vector<vector<int>> tmp{{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};
Matrix<int> test2(tmp);
total = test2.to_arr(arr);
assert(total == 12);
assert(arr[0] == 1);
assert(arr[3] == 4);
assert(arr[5] == 6);
assert(arr[7] == 8);
assert(arr[8] == 9);
assert(arr[9] == 10);
assert(arr[11] == 12);
Matrix<int> test3 = test2.transpose();
total = test3.to_arr(arr);
assert(total == 12);
assert(arr[0] == 1);
assert(arr[3] == 2);
assert(arr[5] == 10);
assert(arr[7] == 7);
assert(arr[8] == 11);
assert(arr[9] == 4);
assert(arr[11] == 12);
int arr1[12] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};
Matrix<int> test4(3, 4, arr1);
total = test4.to_arr(arr);
assert(total == 12);
assert(arr[0] == 1);
assert(arr[3] == 4);
assert(arr[5] == 6);
assert(arr[7] == 8);
assert(arr[8] == 9);
assert(arr[9] == 10);
assert(arr[11] == 12);
Matrix<int> test5 = test4.transpose();
total = test5.to_arr(arr);
assert(total == 12);
assert(arr[0] == 1);
assert(arr[3] == 2);
assert(arr[5] == 10);
assert(arr[7] == 7);
assert(arr[8] == 11);
assert(arr[9] == 4);
assert(arr[11] == 12);
Matrix<int> test6(test2);
total = test6.to_arr(arr);
assert(total == 12);
assert(arr[0] == 1);
assert(arr[3] == 4);
assert(arr[5] == 6);
assert(arr[7] == 8);
assert(arr[8] == 9);
assert(arr[9] == 10);
assert(arr[11] == 12);
Matrix<int> test7 = test2 + test2;
total = test7.to_arr(arr);
assert(total == 12);
assert(arr[0] == 2);
assert(arr[3] == 8);
assert(arr[5] == 12);
assert(arr[7] == 16);
assert(arr[8] == 18);
assert(arr[9] == 20);
assert(arr[11] == 24);
test7 = test2 - test2;
total = test7.to_arr(arr);
assert(total == 12);
assert(arr[0] == 0);
assert(arr[3] == 0);
assert(arr[5] == 0);
assert(arr[7] == 0);
assert(arr[8] == 0);
assert(arr[9] == 0);
assert(arr[11] == 0);
test7 = test2 * test3;
total = test7.to_arr(arr);
assert(total == 9);
assert(arr[0] == 30);
assert(arr[3] == 70);
assert(arr[5] == 278);
assert(arr[7] == 278);
assert(arr[8] == 446);
test7 -= test7;
total = test7.to_arr(arr);
assert(total == 9);
assert(arr[0] == 0);
assert(arr[3] == 0);
assert(arr[5] == 0);
assert(arr[7] == 0);
assert(arr[8] == 0);
test2 *= test3;
total = test2.to_arr(arr);
assert(total == 9);
assert(arr[0] == 30);
assert(arr[3] == 70);
assert(arr[5] == 278);
assert(arr[7] == 278);
assert(arr[8] == 446);
int arr2[9] = {2, 3, 3, 3, 4, 2, -2, -2, 3};
Matrix<int> test8(3, 3, arr2);
Matrix<float> test9 = test8.inverse();
float arr3[16] = {233};
total = test9.to_arr(arr3);
assert(total == 9);
assert(arr3[0] == -16);
assert(arr3[3] == 13);
assert(arr3[5] == -5);
assert(arr3[7] == 2);
assert(arr3[8] == 1);
int arr4[16] = {1, 0, 0, 0, 2, 1, 0, 0, 3, 2, 1, 0, 4, 3, 2, 1};
Matrix<int> test10(4, 4, arr4);
Matrix<float> test11 = test10.inverse();
total = test11.to_arr(arr3);
assert(total == 16);
assert(arr3[0] == 1);
assert(arr3[3] == 0);
assert(arr3[5] == 1);
assert(arr3[7] == 0);
assert(arr3[8] == 1);
assert(arr3[15] == 1);
assert(arr3[14] == -2);
assert(arr3[12] == 0);
return true;
}
bool Test::test_line(void) const {
cout << "==========Test line==========" << endl;
TGAImage image(width, height, TGAImage::RGBA);
Geometry painter(image);
// 左右对角线
painter.line(0, 0, 1920, 1080, white);
painter.line(0, 1080, 1920, 0, white);
// 居中水平线
painter.line(0, 540, 1920, 540, white);
// 居中铅锤线
painter.line(960, 0, 960, 1080, white);
painter.save("test_line.tga");
return true;
}
bool Test::test_triangle(void) const {
cout << "==========Test triangle==========" << endl;
TGAImage image(width, height, TGAImage::RGBA);
Geometry painter(image);
painter.line(0, 0, 100, 100, white);
size_t a[] = {0, 0};
size_t b[] = {0, 540};
size_t c[] = {960, 0};
Vectors2 A(a);
Vectors2 B(b);
Vectors2 C(c);
painter.triangle(A, B, C, white);
painter.save("test_triangle.tga");
return true;
}
bool Test::test_fill(void) const {
cout << "==========Test fill==========" << endl;
TGAImage image(width, height, TGAImage::RGBA);
Geometry painter(image);
painter.line(0, 0, 100, 100, white);
painter.save("test_triangle.tga");
return true;
}
bool Test::test_2d(void) const {
test_line();
test_triangle();
// test_fill();
return true;
}
<file_sep>/src/include/model.h
// This file is a part of Simple-XX/SimpleRenderer
// (https://github.com/Simple-XX/SimpleRenderer).
//
// model.h for Simple-XX/SimpleRenderer.
#ifndef __MODEL_H__
#define __MODEL_H__
#include "vector"
#include "string"
#include "vector.hpp"
// 参考: http://read.pudn.com/downloads115/ebook/484936/OpenGL_wenjian.pdf
// v x y z
// 顶点坐标 v x坐标 y坐标 z坐标
// vt u v w
// 顶点在纹理图片中的对应点 vt 纹理图片对应的坐标
// vn x y z
// 顶点法向量 vn x分量 y分量 z分量
// f v/vt/vn v/vt/vn v/vt/vn
// f 顶点索引/纹理坐标索引/顶点法向量索引
// 面的法向量是由构成面的顶点对应的顶点法向量的做矢量和决定的(xyz的坐标分别相加再除以3得到的)
#define MAX 100
// 顶点
struct Vertex {
int draw;
// 顶点坐标
float x;
float y;
float z;
// 顶点对应的
float nx;
float ny;
float nz;
int colorIndex; // 颜色索引
int vertexlndex; // 顶点索引
int facets[90]; // 存面片数组
int facetsNum; // 面片数
int edges[60]; // 存顶点数组
int edgesNum; // 顶点数
};
// 面
// 颜色
struct ColorStruct {
int index; //颜色索引
float ra,ga,ba; // 环境光的各分量
float rd, gd, bd, ad; // 漫反射光的各分量
float rs, gs, bs; // 镜面反射光的各分量
float spec; // 镜面反射光的强度
};
// 材质
struct MaterialColor {
char name[100];
float ra,ga,ba; // 环境光的各分量
float rd, gd, bd, ad; // 漫反射光的各分量
float rs, gs, bs; // 镜面反射光的各分量
float spec; // 镜面反射光的强度
};
// 模型
struct ModelContext {
int faceCount; // 面的数量
int traggleFlag; // 三角形标注
Vertex vertexList[MAX]; // 模型中的顶点列表
int vertexCount; //顶点数量
Vertex lineList[MAX]; // 模型中的线列表
int lineCount; //线数量
Vertex lineStripList[MAX];
int lineStripCount;
int edgeList[MAX][2]; // 边界列表
int edgeCount; //边界数量
Vertex objVertexList[MAX]; // obj 文件中的顶点
int ovCount; //顶点序数
int onCount; //法向量序数
ColorStruct colorList[MAX]; // 模型中的颜色列表
int ColorCounr; //颜色数
// etc.
};
class Model {
private:
std::vector<Vectorf3> verts;
std::vector<std::vector<int>> faces;
public:
Model(const std::string &_filename);
~Model(void);
size_t nverts(void) const;
size_t nfaces(void) const;
Vectorf3 vert(int i) const;
std::vector<int> face(int _idx) const;
};
#endif /* __MODEL_H__ */
<file_sep>/src/include/renderer.h
// This file is a part of Simple-XX/SimpleRenderer
// (https://github.com/Simple-XX/SimpleRenderer).
//
// renderer.h for Simple-XX/SimpleRenderer.
#ifndef __RENDERER_H__
#define __RENDERER_H__
#include "vector"
#include "common.h"
#include "model.h"
#include "vector.hpp"
#include "geometry.h"
// 负责渲染模型到指定画布
class Renderer {
private:
// 要渲染的模型
const Model &model;
// 着色器?
// 绘制像素
Geometry &painter;
// 光照
Vectorf3 light_dir = Vectorf3(0, 0, -1);
// z-buffer 缓冲
float *zbuffer;
// 大小
size_t width;
size_t height;
// 由 obj 坐标转换为屏幕坐标
size_t get_x(float _x) const;
size_t get_y(float _y) const;
protected:
public:
Renderer(Geometry &_painter2, const Model &_model);
~Renderer(void);
// 渲染
bool render(void);
bool render(void) const;
// 设置参数
bool set_light(const Vectorf3 &_light);
bool set_size(size_t _w, size_t _h);
// 读取参数
Vectorf3 get_light(void) const;
Vectors2 get_size(void) const;
// 保存
bool save(const std::string &_filename = "output.tga") const;
// 直线
bool line(void) const;
// 带 zbuffer 的直线
bool line_zbuffer();
// TODO: 升级成任意曲线
// 圆
bool circle(void) const;
// 填充圆
bool fill_circle(void) const;
// 带 zbuffer 的圆
bool fill_circle_zbuffer(void);
// 填充三角
bool fill_triangle(void) const;
// 带 zbuffer 的三角
bool fill_triangle_zbuffer(void);
};
#endif /* __RENDER_H__ */
<file_sep>/src/main.cpp
// This file is a part of Simple-XX/SimpleRenderer
// (https://github.com/Simple-XX/SimpleRenderer).
//
// main.cpp for Simple-XX/SimpleRenderer.
#include "common.h"
#include "geometry.h"
#include "image.h"
#include "iostream"
#include "model.h"
#include "renderer.h"
#include "test.h"
#include "vector.hpp"
using namespace std;
Test test;
int main(int argc, char **argv) {
string filename;
if (2 == argc) {
filename = argv[1];
}
else {
filename = "../../src/obj/african_head.obj";
}
Model model(filename);
TGAImage image(width, height, TGAImage::RGBA);
Geometry painter(image);
Renderer render = Renderer(painter, model);
render.render();
render.save();
// test.test_vector();
// test.test_matrix();
return 0;
}
<file_sep>/CMakeLists.txt
# This file is a part of Simple-XX/SimpleRenderer (https://github.com/Simple-XX/SimpleRenderer).
#
# CMakeLists.txt for Simple-XX/SimpleRenderer.
# Set minimum cmake version
cmake_minimum_required(VERSION 3.10)
project(SimpleRenderer LANGUAGES CXX)
if(${SimpleRenderer_SOURCE_DIR} STREQUAL ${SimpleRenderer_BINARY_DIR})
message(FATAL_ERROR "In-source builds not allowed. Please make a new directory (called a build directory) and run CMake from there.")
endif()
# Set debug
set(CMAKE_BUILD_TYPE DEBUG)
# Set C gnu11
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
# Set kernel name
set(RendererName renderer)
set(SimpleRenderer_SOURCE_CODE_DIR ${SimpleRenderer_SOURCE_DIR}/src)
add_subdirectory(${SimpleRenderer_SOURCE_CODE_DIR})
<file_sep>/src/include/vector.hpp
// This file is a part of Simple-XX/SimpleRenderer
// (https://github.com/Simple-XX/SimpleRenderer).
//
// vector.hpp for Simple-XX/SimpleRenderer.
#ifndef __VECTOR_HPP__
#define __VECTOR_HPP__
#include "assert.h"
#include "iostream"
#include "math.h"
#include "stdarg.h"
#include "vector"
template <class T, size_t N = 3>
class Vector {
private:
public:
union {
T vect[N];
struct {
T x;
T y;
T z;
} coord;
};
Vector(void);
Vector(const T *const _vect);
Vector(const Vector<T, N> &_vector);
Vector(const std::vector<T> &_vect);
Vector(const T _x, const T _y);
Vector(const T _x, const T _y, const T _z);
~Vector(void);
// 向量不为零向量
operator bool(void) const;
// 向量比较
bool operator==(const Vector<T, N> &_v) const;
bool operator!=(const Vector<T, N> &_v) const;
bool operator>(const Vector<T, N> &_v) const;
bool operator>=(const Vector<T, N> &_v) const;
bool operator<(const Vector<T, N> &_v) const;
bool operator<=(const Vector<T, N> &_v) const;
// 向量取反
Vector<T, N> operator-(void) const;
// 范数
float norm(void) const;
// 单位向量
Vector<float, N> unit(void) const;
// 赋值
Vector<T, N> &operator=(const Vector<T, N> &_v);
// 向量和
Vector<T, N> operator+(const Vector<T, N> &_v) const;
// 向量自加
Vector<T, N> &operator+=(const Vector<T, N> &_v);
// 向量差
Vector<T, N> operator-(const Vector<T, N> &_v) const;
// 向量自减
Vector<T, N> &operator-=(const Vector<T, N> &_v);
// 向量数乘
Vector<T, N> operator*(const T _t) const;
// 向量自乘
Vector<T, N> &operator*=(const T _t);
// 向量点积
T operator*(const Vector<T, N> &_v) const;
// 向量叉积
Vector<T, N> operator^(const Vector<T, N> &_v) const;
// 向量投影
// 下标访问
T &operator[](size_t _idx);
};
template <class T, size_t N>
Vector<T, N>::Vector(void) {
coord.x = 0;
coord.y = 0;
coord.z = 0;
return;
}
template <class T, size_t N>
Vector<T, N>::Vector(const T *const _vect) {
coord.x = _vect[0];
coord.y = _vect[1];
if (N == 3) {
coord.z = _vect[2];
}
return;
}
template <class T, size_t N>
Vector<T, N>::Vector(const Vector<T, N> &_vector) : coord(_vector.coord) {
return;
}
template <class T, size_t N>
Vector<T, N>::Vector(const std::vector<T> &_vect) {
coord.x = _vect.at(0);
coord.y = _vect.at(1);
if (N == 3) {
coord.z = _vect.at(2);
}
return;
}
template <class T, size_t N>
Vector<T, N>::Vector(const T _x, const T _y) {
assert(N == 2);
coord.x = _x;
coord.y = _y;
return;
}
template <class T, size_t N>
Vector<T, N>::Vector(const T _x, const T _y, const T _z) {
assert(N == 3);
coord.x = _x;
coord.y = _y;
coord.z = _z;
return;
}
template <class T, size_t N>
Vector<T, N>::~Vector(void) {
return;
}
template <class T, size_t N>
Vector<T, N>::operator bool(void) const {
bool res = false;
if (coord.x != 0 || coord.y != 0 || coord.z != 0) {
res = true;
}
return res;
}
template <class T, size_t N>
bool Vector<T, N>::operator==(const Vector<T, N> &_v) const {
bool res = true;
if (coord.x != _v.coord.x || coord.y != _v.coord.y ||
coord.z != _v.coord.z) {
res = false;
}
return res;
}
template <class T, size_t N>
bool Vector<T, N>::operator!=(const Vector<T, N> &_v) const {
bool res = false;
if (coord.x != _v.coord.x || coord.y != _v.coord.y ||
coord.z != _v.coord.z) {
res = true;
}
return res;
}
template <class T, size_t N>
bool Vector<T, N>::operator>(const Vector<T, N> &_v) const {
bool res = true;
if (coord.x <= _v.coord.x || coord.y <= _v.coord.y ||
coord.z <= _v.coord.z) {
res = false;
}
return res;
}
template <class T, size_t N>
bool Vector<T, N>::operator>=(const Vector<T, N> &_v) const {
bool res = true;
if (coord.x < _v.coord.x || coord.y < _v.coord.y || coord.z < _v.coord.z) {
res = false;
}
return res;
}
template <class T, size_t N>
bool Vector<T, N>::operator<(const Vector<T, N> &_v) const {
bool res = true;
if (coord.x >= _v.coord.x || coord.y >= _v.coord.y ||
coord.z >= _v.coord.z) {
res = false;
}
return res;
}
template <class T, size_t N>
bool Vector<T, N>::operator<=(const Vector<T, N> &_v) const {
bool res = true;
if (coord.x > _v.coord.x || coord.y > _v.coord.y || coord.z > _v.coord.z) {
res = false;
}
return res;
}
template <class T, size_t N>
Vector<T, N> Vector<T, N>::operator-(void) const {
T tmp[N];
tmp[0] = -coord.x;
tmp[1] = -coord.y;
if (N == 3) {
tmp[2] = -coord.z;
}
return Vector<T, N>(tmp);
}
template <class T, size_t N>
float Vector<T, N>::norm(void) const {
float res = 0;
res += coord.x * coord.x;
res += coord.y * coord.y;
res += coord.z * coord.z;
res = sqrt(res);
return res;
}
template <class T, size_t N>
Vector<float, N> Vector<T, N>::unit(void) const {
float tmp[N];
float norm = this->norm();
tmp[0] = coord.x / norm;
tmp[1] = coord.y / norm;
if (N == 3) {
tmp[2] = coord.z / norm;
}
return Vector<float, N>(tmp);
}
template <class T, size_t N>
Vector<T, N> &Vector<T, N>::operator=(const Vector<T, N> &_v) {
coord = _v.coord;
return *this;
}
template <class T, size_t N>
Vector<T, N> Vector<T, N>::operator+(const Vector<T, N> &_v) const {
T tmp[N];
tmp[0] = coord.x + _v.coord.x;
tmp[1] = coord.y + _v.coord.y;
if (N == 3) {
tmp[2] = coord.z + _v.coord.z;
}
return Vector<T, N>(tmp);
}
template <class T, size_t N>
Vector<T, N> &Vector<T, N>::operator+=(const Vector<T, N> &_v) {
coord.x += _v.coord.x;
coord.y += _v.coord.y;
if (N == 3) {
coord.z += _v.coord.z;
}
return *this;
}
template <class T, size_t N>
Vector<T, N> Vector<T, N>::operator-(const Vector<T, N> &_v) const {
T tmp[N];
tmp[0] = coord.x - _v.coord.x;
tmp[1] = coord.y - _v.coord.y;
if (N == 3) {
tmp[2] = coord.z - _v.coord.z;
}
return Vector<T, N>(tmp);
}
template <class T, size_t N>
Vector<T, N> &Vector<T, N>::operator-=(const Vector<T, N> &_v) {
coord.x -= _v.coord.x;
coord.y -= _v.coord.y;
if (N == 3) {
coord.z -= _v.coord.z;
}
return *this;
}
template <class T, size_t N>
Vector<T, N> Vector<T, N>::operator*(const T _t) const {
T tmp[N];
tmp[0] = coord.x * _t;
tmp[1] = coord.y * _t;
if (N == 3) {
tmp[2] = coord.z * _t;
}
return Vector<T, N>(tmp);
}
template <class T, size_t N>
Vector<T, N> &Vector<T, N>::operator*=(const T _t) {
coord.x *= _t;
coord.y *= _t;
if (N == 3) {
coord.z *= _t;
}
return *this;
}
template <class T, size_t N>
T Vector<T, N>::operator*(const Vector<T, N> &_v) const {
T res = 0;
res += coord.x * _v.coord.x;
res += coord.y * _v.coord.y;
if (N == 3) {
res += coord.z * _v.coord.z;
}
return res;
}
template <class T, size_t N>
Vector<T, N> Vector<T, N>::operator^(const Vector<T, N> &_v) const {
assert(N == 3);
T tmp[N];
tmp[0] = coord.y * _v.coord.z - coord.z * _v.coord.y;
tmp[1] = coord.z * _v.coord.x - coord.x * _v.coord.z;
tmp[2] = coord.x * _v.coord.y - coord.y * _v.coord.x;
return Vector<T, N>(tmp);
}
template <class T, size_t N>
T &Vector<T, N>::operator[](size_t _idx) {
return vect[_idx];
}
// 输出
template <class T, size_t N>
std::ostream &operator<<(std::ostream &_os, const Vector<T, N> &_v) {
_os << "(" << _v.coord.x << ", " << _v.coord.y;
if (N == 3) {
_os << ", " << _v.coord.z;
}
_os << ")";
return _os;
}
typedef Vector<size_t, 2> Vectors2;
typedef Vector<float, 2> Vectorf2;
typedef Vector<float, 3> Vectorf3;
typedef Vector<float, 4> Vectorf4;
#endif /* __VECTOR_HPP__ */
<file_sep>/devlog/devlog20200829.md
# devlog20200829
跟着教程开始写
L1 部分绘图的结果是反的,用 800 减一下就好
# devlog20200831
实现向量计算
实现 Bresenham 直线算法
重构部分代码,隐藏 main 中大部分细节
准备绘制三角形
# devlog20200901
三角形绘制完成
完成光照处理
重构
添加了一些三维操作
重构
# devlog20200904
不小心把文件 rm 掉了重来一遍吧。。写了半天的向量优化和矩阵全没了艹
心态崩了,过几天再写吧
TODO:
将 vector 的私有变量变为公有
完善矩阵操作
测试
# devlog20200917
缓过劲了,继续
添加 clang-format
优化向量
# devlog20200918
矩阵操作
现在的模版写法导致矩阵乘法很难写。。还在寻求解决方案
将模版参数减少为一个
# devlog20200919
高斯消元法求逆矩阵,效率太低了,换成 LU 法
# devlog20200923
终于把基本操作完善了。。勉强可以用,效率很低。
# devlog20200924
obj 文件的定义:https://en.wikipedia.org/wiki/Wavefront_.obj_file
添加计时功能
二维:求出 z 相对 x 的变化率,直接计算即可 $z=z_0 + {{z_1-z_0}\over{x_1-x_0}} \times {\Delta x} $
三维:根据平面的一般方程可得 $z={{Ax+By+D}\over{C}}$
出现问题:有些图形不能正确

可能的原因:精度,算法
# devlog20200925
<file_sep>/src/renderer.cpp
// This file is a part of Simple-XX/SimpleRenderer
// (https://github.com/Simple-XX/SimpleRenderer).
//
// renderer.cpp for Simple-XX/SimpleRenderer.
#include "iostream"
#include "limits"
#include "common.h"
#include "renderer.h"
using namespace std;
size_t Renderer::get_x(float _x) const {
return (_x + 1.) * width / 3.;
}
size_t Renderer::get_y(float _y) const {
return height - (_y + 1.) * height / 3.;
}
Renderer::Renderer(Geometry &_painter, const Model &_model)
: model(_model), painter(_painter) {
width = painter.get_width();
height = painter.get_height();
zbuffer = new float[width * height];
for (size_t i = 0; i < width * height; i++) {
zbuffer[i] = -std::numeric_limits<float>::max();
}
return;
}
Renderer::~Renderer(void) {
delete zbuffer;
return;
}
bool Renderer::render(void) {
// line_zbuffer();
fill_triangle_zbuffer();
// fill_circle_zbuffer();
return true;
}
bool Renderer::render(void) const {
// line();
fill_triangle();
// fill_circle();
return true;
}
bool Renderer::set_light(const Vectorf3 &_light) {
light_dir = _light;
return true;
}
bool Renderer::set_size(size_t _w, size_t _h) {
width = _w;
height = _h;
return true;
}
Vectorf3 Renderer::get_light(void) const {
return light_dir;
}
Vectors2 Renderer::get_size(void) const {
return Vectors2(width, height);
}
bool Renderer::save(const std::string &_filename) const {
return painter.save(_filename);
}
bool Renderer::line(void) const {
// 所有面
for (size_t i = 0; i < model.nfaces(); i++) {
// 取出一个面
vector<int> face = model.face(i);
// 处理 x y 坐标
for (size_t j = 0; j < 3; j++) {
Vectorf3 v0 = model.vert(face.at(j));
Vectorf3 v1 = model.vert(face.at((j + 1) % 3));
size_t x0 = get_x(v0.coord.x);
size_t y0 = get_y(v0.coord.y);
size_t x1 = get_x(v1.coord.x);
size_t y1 = get_y(v1.coord.y);
painter.line(x0, y0, x1, y1, white);
}
}
return true;
}
bool Renderer::circle(void) const {
painter.circle(mid_width, mid_height, 50, white);
return true;
}
bool Renderer::line_zbuffer(void) {
for (size_t i = 0; i < model.nfaces(); i++) {
vector<int> face = model.face(i);
for (size_t j = 0; j < 3; j++) {
Vectorf3 v0 = model.vert(face.at(j));
Vectorf3 v1 = model.vert(face.at((j + 1) % 3));
size_t x0 = get_x(v0.coord.x);
size_t y0 = get_y(v0.coord.y);
size_t x1 = get_x(v1.coord.x);
size_t y1 = get_y(v1.coord.y);
float z0 = v0.coord.z;
float z1 = v1.coord.z;
painter.line(x0, y0, z0, x1, y1, z1, zbuffer, white);
}
}
return true;
}
bool Renderer::fill_triangle(void) const {
for (size_t i = 0; i < model.nfaces(); i++) {
std::vector<int> face = model.face(i);
Vectors2 screen_coords[3];
Vectorf3 world_coords[3];
for (size_t j = 0; j < 3; j++) {
Vectorf3 v = model.vert(face[j]);
screen_coords[j].coord.x = get_x(v.coord.x);
screen_coords[j].coord.y = get_y(v.coord.y);
world_coords[j] = model.vert(face[j]);
}
Vectorf3 n = (world_coords[2] - world_coords[0]) ^
(world_coords[1] - world_coords[0]);
float intensity = light_dir * n.unit();
if (intensity > 0) {
painter.triangle(screen_coords[0], screen_coords[1],
screen_coords[2],
TGAColor(intensity * 255, intensity * 255,
intensity * 255, 255));
}
}
return true;
}
bool Renderer::fill_triangle_zbuffer(void) {
for (size_t i = 0; i < model.nfaces(); i++) {
std::vector<int> face = model.face(i);
Vectorf3 screen_coords[3];
Vectorf3 world_coords[3];
for (size_t j = 0; j < 3; j++) {
Vectorf3 v = model.vert(face[j]);
screen_coords[j] =
Vectorf3(get_x(v.coord.x), get_y(v.coord.y), v.coord.z);
world_coords[j] = v;
}
Vectorf3 n = (world_coords[2] - world_coords[0]) ^
(world_coords[1] - world_coords[0]);
float intensity = light_dir * n.unit();
if (intensity > 0) {
painter.triangle(screen_coords[0], screen_coords[1],
screen_coords[2], zbuffer,
TGAColor(intensity * 255, intensity * 255,
intensity * 255, 255));
}
}
return true;
}
bool Renderer::fill_circle(void) const {
return true;
}
bool Renderer::fill_circle_zbuffer(void) {
return true;
}
<file_sep>/src/include/image.h
// This file is a part of Simple-XX/SimpleRenderer
// (https://github.com/Simple-XX/SimpleRenderer). Based on
// https://github.com/ssloy/tinyrenderer
//
// image.h for Simple-XX/SimpleRenderer.
#ifndef __IMAGE_H__
#define __IMAGE_H__
#include "cstdint"
#include "fstream"
#include "vector"
#pragma pack(push, 1)
struct TGA_Header {
std::uint8_t idlength{};
std::uint8_t colormaptype{};
std::uint8_t datatypecode{};
std::uint16_t colormaporigin{};
std::uint16_t colormaplength{};
std::uint8_t colormapdepth{};
std::uint16_t x_origin{};
std::uint16_t y_origin{};
std::uint16_t width{};
std::uint16_t height{};
std::uint8_t bitsperpixel{};
std::uint8_t imagedescriptor{};
};
#pragma pack(pop)
struct TGAColor {
std::uint8_t bgra[4] = {0, 0, 0, 0};
std::uint8_t bytespp = {0};
TGAColor() = default;
TGAColor(const std::uint8_t _R, const std::uint8_t _G,
const std::uint8_t _B, const std::uint8_t _A = 255);
TGAColor(const std::uint8_t _v);
TGAColor(const std::uint8_t *_p, const std::uint8_t _bpp);
std::uint8_t &operator[](const int _i);
TGAColor operator*(const float _intensity) const;
};
class TGAImage {
protected:
std::vector<std::uint8_t> data;
size_t width;
size_t height;
int bytespp;
bool load_rle_data(std::ifstream &_in);
bool unload_rle_data(std::ofstream &_out) const;
public:
enum Format { GRAYSCALE = 1, RGB = 3, RGBA = 4 };
TGAImage();
TGAImage(const size_t _w, const size_t _h, const int _bpp);
bool read_tga_file(const std::string _filename);
bool write_tga_file(const std::string _filename, const bool _vflip = true,
const bool _rle = true) const;
void flip_horizontally();
void flip_vertically();
void scale(const int _w, const int _h);
TGAColor get(const size_t _x, const size_t _y) const;
void set(const size_t _x, const size_t _y, const TGAColor &_c);
size_t get_width() const;
size_t get_height() const;
int get_bytespp();
std::uint8_t *buffer();
void clear();
};
#endif /* __IMAGE_H__ */
<file_sep>/src/CMakeLists.txt
# This file is a part of Simple-XX/SimpleRenderer (https://github.com/Simple-XX/SimpleRenderer).
#
# CMakeLists.txt for Simple-XX/SimpleRenderer.
# Set CXX flags for debug
if (CMAKE_BUILD_TYPE STREQUAL DEBUG)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -g -ggdb -Wall -Wextra")
endif ()
if (CMAKE_BUILD_TYPE STREQUAL RELEASE)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wextra -Werror")
endif ()
# Set common flags
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -O0")
message(STATUS "CMAKE_CXX_FLAGS is ${CMAKE_CXX_FLAGS}")
# Set include dir
include_directories(${SimpleRenderer_SOURCE_CODE_DIR}/include)
aux_source_directory(${SimpleRenderer_SOURCE_CODE_DIR} cxx_src)
# Link
add_executable(${RendererName}
${cxx_src})
<file_sep>/src/image.cpp
// This file is a part of Simple-XX/SimpleRenderer
// (https://github.com/Simple-XX/SimpleRenderer).
// Based on https://github.com/ssloy/tinyrenderer
// tga.cpp for Simple-XX/SimpleRenderer.
#include "iostream"
#include "cstring"
#include "image.h"
TGAColor::TGAColor(const uint8_t _R, const uint8_t _G, const uint8_t _B,
const uint8_t _A)
: bgra{_B, _G, _R, _A}, bytespp(4) {
return;
}
TGAColor::TGAColor(const uint8_t _v) : bgra{_v, 0, 0, 0}, bytespp(1) {
return;
}
TGAColor::TGAColor(const uint8_t *_p, const uint8_t _bpp)
: bgra{0, 0, 0, 0}, bytespp(_bpp) {
for (uint8_t i = 0; i < _bpp; i++) {
bgra[i] = _p[i];
}
return;
}
uint8_t &TGAColor::operator[](const int _i) {
return bgra[_i];
}
TGAColor TGAColor::operator*(const float _intensity) const {
TGAColor res = *this;
float clamped = std::max((float)0., std::min(_intensity, (float)1.));
for (size_t i = 0; i < 4; i++) {
res.bgra[i] = bgra[i] * clamped;
}
return res;
}
TGAImage::TGAImage() : data(), width(0), height(0), bytespp(0) {
return;
}
TGAImage::TGAImage(const size_t _w, const size_t _h, const int _bpp)
: data(_w * _h * _bpp, 0), width(_w), height(_h), bytespp(_bpp) {
return;
}
bool TGAImage::read_tga_file(const std::string _filename) {
std::ifstream in;
in.open(_filename, std::ios::binary);
if (!in.is_open()) {
std::cerr << "can't open file " << _filename << "\n";
in.close();
return false;
}
TGA_Header header;
in.read(reinterpret_cast<char *>(&header), sizeof(header));
if (!in.good()) {
in.close();
std::cerr << "an error occured while reading the header\n";
return false;
}
width = header.width;
height = header.height;
bytespp = header.bitsperpixel >> 3;
if (width <= 0 || height <= 0 ||
(bytespp != GRAYSCALE && bytespp != RGB && bytespp != RGBA)) {
in.close();
std::cerr << "bad bpp (or width/height) value\n";
return false;
}
int nbytes = bytespp * width * height;
data = std::vector<std::uint8_t>(nbytes, 0);
if (header.datatypecode == 3 || header.datatypecode == 2) {
in.read(reinterpret_cast<char *>(data.data()), nbytes);
if (!in.good()) {
in.close();
std::cerr << "an error occured while reading the data\n";
return false;
}
}
else if (header.datatypecode == 10 || header.datatypecode == 11) {
if (!load_rle_data(in)) {
in.close();
std::cerr << "an error occured while reading the data\n";
return false;
}
}
else {
in.close();
std::cerr << "unknown file format " << (int)header.datatypecode << "\n";
return false;
}
if (!(header.imagedescriptor & 0x20)) {
flip_vertically();
}
if (header.imagedescriptor & 0x10) {
flip_horizontally();
}
std::cerr << width << "x" << height << "/" << bytespp * 8 << "\n";
in.close();
return true;
}
bool TGAImage::load_rle_data(std::ifstream &_in) {
int pixelcount = width * height;
int currentpixel = 0;
int currentbyte = 0;
TGAColor colorbuffer;
do {
std::uint8_t chunkheader = 0;
chunkheader = _in.get();
if (!_in.good()) {
std::cerr << "an error occured while reading the data\n";
return false;
}
if (chunkheader < 128) {
chunkheader++;
for (int i = 0; i < chunkheader; i++) {
_in.read(reinterpret_cast<char *>(colorbuffer.bgra), bytespp);
if (!_in.good()) {
std::cerr << "an error occured while reading the header\n";
return false;
}
for (int t = 0; t < bytespp; t++)
data[currentbyte++] = colorbuffer.bgra[t];
currentpixel++;
if (currentpixel > pixelcount) {
std::cerr << "Too many pixels read\n";
return false;
}
}
}
else {
chunkheader -= 127;
_in.read(reinterpret_cast<char *>(colorbuffer.bgra), bytespp);
if (!_in.good()) {
std::cerr << "an error occured while reading the header\n";
return false;
}
for (int i = 0; i < chunkheader; i++) {
for (int t = 0; t < bytespp; t++) {
data[currentbyte++] = colorbuffer.bgra[t];
}
currentpixel++;
if (currentpixel > pixelcount) {
std::cerr << "Too many pixels read\n";
return false;
}
}
}
} while (currentpixel < pixelcount);
return true;
}
bool TGAImage::write_tga_file(const std::string _filename, const bool _vflip,
const bool _rle) const {
std::uint8_t developer_area_ref[4] = {0, 0, 0, 0};
std::uint8_t extension_area_ref[4] = {0, 0, 0, 0};
std::uint8_t footer[18] = {'T', 'R', 'U', 'E', 'V', 'I', 'S', 'I', 'O',
'N', '-', 'X', 'F', 'I', 'L', 'E', '.', '\0'};
std::ofstream out;
out.open(_filename, std::ios::binary);
if (!out.is_open()) {
std::cerr << "can't open file " << _filename << "\n";
out.close();
return false;
}
TGA_Header header;
header.bitsperpixel = bytespp << 3;
header.width = width;
header.height = height;
header.datatypecode =
(bytespp == GRAYSCALE ? (_rle ? 11 : 3) : (_rle ? 10 : 2));
header.imagedescriptor =
_vflip ? 0x00 : 0x20; // top-left or bottom-left origin
out.write(reinterpret_cast<const char *>(&header), sizeof(header));
if (!out.good()) {
out.close();
std::cerr << "can't dump the tga file\n";
return false;
}
if (!_rle) {
out.write(reinterpret_cast<const char *>(data.data()),
width * height * bytespp);
if (!out.good()) {
std::cerr << "can't unload raw data\n";
out.close();
return false;
}
}
else {
if (!unload_rle_data(out)) {
out.close();
std::cerr << "can't unload rle data\n";
return false;
}
}
out.write(reinterpret_cast<const char *>(developer_area_ref),
sizeof(developer_area_ref));
if (!out.good()) {
std::cerr << "can't dump the tga file\n";
out.close();
return false;
}
out.write(reinterpret_cast<const char *>(extension_area_ref),
sizeof(extension_area_ref));
if (!out.good()) {
std::cerr << "can't dump the tga file\n";
out.close();
return false;
}
out.write(reinterpret_cast<const char *>(footer), sizeof(footer));
if (!out.good()) {
std::cerr << "can't dump the tga file\n";
out.close();
return false;
}
out.close();
return true;
}
// TODO: it is not necessary to break a raw chunk for two equal pixels (for the
// matter of the resulting size)
bool TGAImage::unload_rle_data(std::ofstream &_out) const {
const std::uint8_t max_chunk_length = 128;
int npixels = width * height;
int curpix = 0;
while (curpix < npixels) {
int chunkstart = curpix * bytespp;
int curbyte = curpix * bytespp;
std::uint8_t run_length = 1;
bool raw = true;
while (curpix + run_length < npixels && run_length < max_chunk_length) {
bool succ_eq = true;
for (int t = 0; succ_eq && t < bytespp; t++) {
succ_eq = (data[curbyte + t] == data[curbyte + t + bytespp]);
}
curbyte += bytespp;
if (1 == run_length) {
raw = !succ_eq;
}
if (raw && succ_eq) {
run_length--;
break;
}
if (!raw && !succ_eq)
break;
run_length++;
}
curpix += run_length;
_out.put(raw ? run_length - 1 : run_length + 127);
if (!_out.good()) {
std::cerr << "can't dump the tga file\n";
return false;
}
_out.write(reinterpret_cast<const char *>(data.data() + chunkstart),
(raw ? run_length * bytespp : bytespp));
if (!_out.good()) {
std::cerr << "can't dump the tga file\n";
return false;
}
}
return true;
}
TGAColor TGAImage::get(const size_t _x, const size_t _y) const {
if (!data.size() || _x >= width || _y >= height) {
return {};
}
return TGAColor(data.data() + (_x + _y * width) * bytespp, bytespp);
}
void TGAImage::set(size_t _x, size_t _y, const TGAColor &_c) {
if (!data.size() || _x >= width || _y >= height) {
return;
}
memcpy(data.data() + (_x + _y * width) * bytespp, _c.bgra, bytespp);
}
int TGAImage::get_bytespp() {
return bytespp;
}
size_t TGAImage::get_width() const {
return width;
}
size_t TGAImage::get_height() const {
return height;
}
void TGAImage::flip_horizontally() {
if (!data.size()) {
return;
}
size_t half = width >> 1;
for (size_t i = 0; i < half; i++) {
for (size_t j = 0; j < height; j++) {
TGAColor c1 = get(i, j);
TGAColor c2 = get(width - 1 - i, j);
set(i, j, c2);
set(width - 1 - i, j, c1);
}
}
return;
}
void TGAImage::flip_vertically() {
if (!data.size()) {
return;
}
int bytes_per_line = width * bytespp;
std::vector<std::uint8_t> line(bytes_per_line, 0);
int half = height >> 1;
for (int j = 0; j < half; j++) {
int l1 = j * bytes_per_line;
int l2 = (height - 1 - j) * bytes_per_line;
std::copy(data.begin() + l1, data.begin() + l1 + bytes_per_line,
line.begin());
std::copy(data.begin() + l2, data.begin() + l2 + bytes_per_line,
data.begin() + l1);
std::copy(line.begin(), line.end(), data.begin() + l2);
}
return;
}
std::uint8_t *TGAImage::buffer() {
return data.data();
}
void TGAImage::clear() {
data = std::vector<std::uint8_t>(width * height * bytespp, 0);
return;
}
void TGAImage::scale(int _w, int _h) {
if (_w <= 0 || _h <= 0 || !data.size()) {
return;
}
std::vector<std::uint8_t> tdata(_w * _h * bytespp, 0);
int nscanline = 0;
int oscanline = 0;
int erry = 0;
int nlinebytes = _w * bytespp;
int olinebytes = width * bytespp;
for (size_t j = 0; j < height; j++) {
size_t errx = width - _w;
int nx = -bytespp;
int ox = -bytespp;
for (size_t i = 0; i < width; i++) {
ox += bytespp;
errx += _w;
while (errx >= width) {
errx -= width;
nx += bytespp;
memcpy(tdata.data() + nscanline + nx,
data.data() + oscanline + ox, bytespp);
}
}
erry += _h;
oscanline += olinebytes;
while (erry >= (int)height) {
if (erry >= (int)height << 1) {
// it means we jump over a scanline
memcpy(tdata.data() + nscanline + nlinebytes,
tdata.data() + nscanline, nlinebytes);
}
erry -= height;
nscanline += nlinebytes;
}
}
data = tdata;
width = _w;
height = _h;
return;
}
<file_sep>/src/include/common.h
// This file is a part of Simple-XX/SimpleRenderer
// (https://github.com/Simple-XX/SimpleRenderer).
//
// common.h for Simple-XX/SimpleRenderer.
#ifndef __COMMON_H__
#define __COMMON_H__
#include "image.h"
const TGAColor black = TGAColor(0, 0, 0, 255);
const TGAColor white = TGAColor(255, 255, 255, 255);
const TGAColor red = TGAColor(255, 0, 0, 255);
const int width = 1920;
const int height = 1080;
const int mid_width = width / 2;
const int mid_height = height / 2;
#endif /* __COMMON_H__ */
<file_sep>/run.sh
# This file is a part of Simple-XX/SimpleRenderer (https://github.com/Simple-XX/SimpleRenderer).
#
# setup.sh for Simple-XX/SimpleRenderer.
#!/bin/bash
# shell 执行出错时终止运行
set -e
# 输出实际执行内容
# set -x
# 重新编译
mkdir -p ./build/
rm -rf ./build/*
cd ./build
cmake ..
make
cd ./bin
./renderer
open ./output.tga
<file_sep>/src/model.cpp
// This file is a part of SimpleXX/SimpleRenderer
// (https://github.com/SimpleXX/SimpleRenderer).
// Based on https://github.com/ssloy/tinyrenderer
// model.cpp for SimpleXX/SimpleRenderer.
#include "iostream"
#include "fstream"
#include "sstream"
#include "model.h"
using namespace std;
Model::Model(const string &_filename) : verts(), faces() {
std::ifstream in;
in.open(_filename, std::ifstream::in);
if (in.fail()) {
return;
}
std::string line;
while (!in.eof()) {
std::getline(in, line);
std::istringstream iss(line.c_str());
char trash;
if (!line.compare(0, 2, "v ")) {
iss >> trash;
std::vector<float> tmp;
for (int i = 0; i < 3; i++) {
float s;
iss >> s;
tmp.push_back(s);
}
Vectorf3 v(tmp);
verts.push_back(v);
}
else if (!line.compare(0, 2, "f ")) {
std::vector<int> f;
int itrash, idx;
iss >> trash;
while (iss >> idx >> trash >> itrash >> trash >> itrash) {
// in wavefront obj all indices start at 1, not zero
idx--;
f.push_back(idx);
}
faces.push_back(f);
}
}
std::cerr << "# v# " << verts.size() << " f# " << faces.size() << std::endl;
return;
}
Model::~Model() {
return;
}
size_t Model::nverts() const {
return verts.size();
}
size_t Model::nfaces() const {
return faces.size();
}
std::vector<int> Model::face(int _idx) const {
return faces.at(_idx);
}
Vectorf3 Model::vert(int _i) const {
return verts.at(_i);
}
<file_sep>/src/include/matrix.hpp
// This file is a part of Simple-XX/SimpleRenderer
// (https://github.com/Simple-XX/SimpleRenderer).
//
// matrix.hpp for Simple-XX/SimpleRenderer.
#ifndef __MATRIX_HPP__
#define __MATRIX_HPP__
#include "vector"
#include "iomanip"
template <class T>
class Matrix {
private:
std::vector<std::vector<T>> mat;
size_t rows;
size_t cols;
// 矩阵求行列式
T det(void) const;
// 矩阵求余子式
T minor(const size_t _r, const size_t _c) const;
// 矩阵求代数余子式
T cofactor(const size_t _r, const size_t _c) const;
public:
Matrix(size_t _rows = 4, size_t _cols = 4);
Matrix(size_t _rows, size_t _cols, const T *const _mat);
Matrix(const std::vector<std::vector<T>> &_mat);
Matrix(const Matrix<T> &_matrix);
~Matrix(void);
// 赋值
Matrix<T> &operator=(const Matrix<T> &_matrix);
// 矩阵间加法
Matrix<T> operator+(const Matrix<T> &_matrix) const;
// 矩阵间自加
Matrix<T> &operator+=(const Matrix<T> &_matrix);
// 矩阵之间的减法运算
Matrix<T> operator-(const Matrix<T> &_matrix) const;
// 矩阵之间自减运算
Matrix<T> &operator-=(const Matrix<T> &_matrix);
// 矩阵与整数乘法
Matrix<T> operator*(const T _v);
// 矩阵间乘法
Matrix<T> operator*(const Matrix<T> &_matrix) const;
// 矩阵与整数自乘
Matrix<T> &operator*=(const T _v);
// 矩阵间自乘
Matrix<T> &operator*=(const Matrix<T> &_matrix);
// 矩阵相等
bool operator==(const Matrix<T> &_matrix) const;
// 访问矩阵行/列
std::vector<T> &operator[](const size_t _idx);
// 获取行数
size_t get_rows(void) const;
// 获取列数
size_t get_cols(void) const;
// 矩阵转置
Matrix<T> transpose(void) const;
// 矩阵求逆
Matrix<float> inverse(void) const;
// 转换为数组
size_t to_arr(T *_arr) const;
// 转换为向量
std::vector<std::vector<T>> to_vector(void) const;
// PLU 分解,返回分解好的矩阵,参数用于获取主元表
Matrix<float> PLU(std::vector<size_t> &_p);
// 矩阵求余子式矩阵
Matrix<T> minor(void) const;
// 矩阵求代数余子式矩阵
Matrix<T> cofactor(void) const;
// 矩阵求伴随矩阵
Matrix<T> adjugate(void) const;
};
template <class T>
Matrix<float> Matrix<T>::PLU(std::vector<size_t> &_p) {
std::vector<std::vector<float>> tmp(rows, std::vector<float>(cols, 0));
// 转换为 float 类型
for (size_t i = 0; i < rows; i++) {
for (size_t j = 0; j < cols; j++) {
tmp.at(i).at(j) = (float)mat.at(i).at(j);
}
}
// 对于非方阵,选取较小的
size_t n = std::min(rows, cols);
// 初始化置换矩阵 _p
_p = std::vector<size_t>(n, 0);
for (size_t i = 0; i < n; i++) {
_p.at(i) = i;
}
// 如果主元所在列的绝对值最大值不是当前行,进行行交换
for (size_t i = 0; i < n; i++) {
T imax = 0;
for (size_t j = i; j < n; j++) {
if (imax < std::abs(tmp.at(j).at(i))) {
imax = std::abs(tmp.at(j).at(i));
// 交换行
if (i != j) {
std::swap(tmp.at(i), tmp.at(j));
// 记录 _p
_p.at(i) = j;
_p.at(j) = i;
}
}
}
}
// 选主元完成
// L
// for (size_t i = n - 1; i >= 0; i--) {
// // 变为单位下三角矩阵
// // ii 归一化
// if (tmp.at(i).at(i) != 1) {
// T ii = tmp.at(i).at(i);
// for (size_t j = n - 1; j >= 0; j--) {
// assert(j < 0);
// tmp.at(i).at(j) /= ii;
// }
// }
// return Matrix<double>(tmp);
// }
// U
for (size_t i = 0; i < n; i++) {
// 变为上三角矩阵
// 首先确定主元
float ii = tmp.at(i).at(i);
// 下面一行-主元行*(行列/主元)
for (size_t j = i + 1; j < n; j++) {
for (size_t k = 0; k < n; k++) {
float scale = tmp.at(j).at(k) / ii;
tmp.at(j).at(k) -= tmp.at(i).at(k) * scale;
}
}
// return Matrix<double>(tmp);
}
return Matrix<float>(tmp);
}
template <class T>
T Matrix<T>::det(void) const {
assert(rows == cols);
assert(rows != 0);
T res = 0;
if (rows == 1) {
res = mat.at(0).at(0);
}
else if (rows == 2) {
res = mat.at(0).at(0) * mat.at(1).at(1) -
mat.at(0).at(1) * mat.at(1).at(0);
}
else if (rows == 3) {
res = mat.at(0).at(0) * mat.at(1).at(1) * mat.at(2).at(2) +
mat.at(1).at(0) * mat.at(2).at(1) * mat.at(0).at(2) +
mat.at(2).at(0) * mat.at(0).at(1) * mat.at(1).at(2) -
mat.at(1).at(0) * mat.at(0).at(1) * mat.at(2).at(2) -
mat.at(2).at(0) * mat.at(1).at(1) * mat.at(0).at(2) -
mat.at(0).at(0) * mat.at(2).at(1) * mat.at(1).at(2);
}
else if (rows == 4) {
res = mat.at(0).at(0) * mat.at(1).at(1) * mat.at(2).at(2) *
mat.at(3).at(3) +
mat.at(0).at(0) * mat.at(2).at(1) * mat.at(3).at(2) *
mat.at(1).at(3) +
mat.at(0).at(0) * mat.at(3).at(1) * mat.at(1).at(2) *
mat.at(2).at(3) +
mat.at(1).at(0) * mat.at(0).at(1) * mat.at(3).at(2) *
mat.at(2).at(3) +
mat.at(1).at(0) * mat.at(3).at(1) * mat.at(2).at(2) *
mat.at(0).at(3) +
mat.at(1).at(0) * mat.at(2).at(1) * mat.at(0).at(2) *
mat.at(3).at(3) +
mat.at(2).at(0) * mat.at(3).at(1) * mat.at(0).at(2) *
mat.at(1).at(3) +
mat.at(2).at(0) * mat.at(0).at(1) * mat.at(1).at(2) *
mat.at(3).at(3) +
mat.at(2).at(0) * mat.at(1).at(1) * mat.at(3).at(2) *
mat.at(0).at(3) +
mat.at(3).at(0) * mat.at(2).at(1) * mat.at(1).at(2) *
mat.at(0).at(3) +
mat.at(3).at(0) * mat.at(1).at(1) * mat.at(0).at(2) *
mat.at(2).at(3) +
mat.at(3).at(0) * mat.at(0).at(1) * mat.at(2).at(2) *
mat.at(1).at(3) -
mat.at(0).at(0) * mat.at(1).at(1) * mat.at(3).at(2) *
mat.at(2).at(3) -
mat.at(0).at(0) * mat.at(2).at(1) * mat.at(1).at(2) *
mat.at(3).at(3) -
mat.at(0).at(0) * mat.at(3).at(1) * mat.at(2).at(2) *
mat.at(1).at(3) -
mat.at(1).at(0) * mat.at(0).at(1) * mat.at(2).at(2) *
mat.at(3).at(3) -
mat.at(1).at(0) * mat.at(3).at(1) * mat.at(0).at(2) *
mat.at(2).at(3) -
mat.at(1).at(0) * mat.at(2).at(1) * mat.at(3).at(2) *
mat.at(0).at(3) -
mat.at(2).at(0) * mat.at(3).at(1) * mat.at(1).at(2) *
mat.at(0).at(3) -
mat.at(2).at(0) * mat.at(0).at(1) * mat.at(3).at(2) *
mat.at(1).at(3) -
mat.at(2).at(0) * mat.at(1).at(1) * mat.at(0).at(2) *
mat.at(3).at(3) -
mat.at(3).at(0) * mat.at(2).at(1) * mat.at(0).at(2) *
mat.at(1).at(3) -
mat.at(3).at(0) * mat.at(1).at(1) * mat.at(2).at(2) *
mat.at(0).at(3) -
mat.at(3).at(0) * mat.at(0).at(1) * mat.at(1).at(2) *
mat.at(2).at(3);
}
return res;
}
template <class T>
T Matrix<T>::minor(const size_t _r, const size_t _c) const {
std::vector<std::vector<T>> tmp(rows - 1, std::vector<T>(cols - 1, 0));
for (size_t i = 0; i < rows - 1; i++) {
for (size_t j = 0; j < cols - 1; j++) {
size_t idx_r = i;
size_t idx_c = j;
if (i >= _r) {
idx_r += 1;
}
if (j >= _c) {
idx_c += 1;
}
tmp.at(i).at(j) = mat.at(idx_r).at(idx_c);
}
}
// 计算行列式 tmp 的值
T res = Matrix<T>(tmp).det();
return res;
}
template <class T>
Matrix<T> Matrix<T>::minor(void) const {
std::vector<std::vector<T>> tmp(rows, std::vector<T>(cols, 0));
for (size_t i = 0; i < rows; i++) {
for (size_t j = 0; j < cols; j++) {
tmp.at(i).at(j) = minor(i, j);
}
}
return Matrix<T>(tmp);
}
template <class T>
T Matrix<T>::cofactor(const size_t _r, const size_t _c) const {
assert(std::is_signed<T>::value);
return minor(_r, _c) * ((_r + _c) % 2 ? -1 : 1);
}
template <class T>
Matrix<T> Matrix<T>::cofactor(void) const {
std::vector<std::vector<T>> tmp(rows, std::vector<T>(cols, 0));
for (size_t i = 0; i < rows; i++) {
for (size_t j = 0; j < cols; j++) {
tmp.at(i).at(j) = cofactor(i, j);
}
}
return Matrix<T>(tmp);
}
template <class T>
Matrix<T> Matrix<T>::adjugate(void) const {
return cofactor().transpose();
}
template <class T>
Matrix<T>::Matrix(size_t _rows, size_t _cols)
: mat(std::vector<std::vector<T>>(_rows, std::vector<T>(_cols, 0))),
rows(_rows), cols(_cols) {
for (size_t i = 0; i < rows; i++) {
mat.at(i).at(i) = 1;
}
return;
}
template <class T>
Matrix<T>::Matrix(size_t _rows, size_t _cols, const T *const _mat)
: mat(std::vector<std::vector<T>>(_rows, std::vector<T>(_cols, 0))),
rows(_rows), cols(_cols) {
for (size_t i = 0; i < rows; i++) {
for (size_t j = 0; j < cols; j++) {
mat.at(i).at(j) = _mat[i * cols + j];
}
}
return;
}
template <class T>
Matrix<T>::Matrix(const std::vector<std::vector<T>> &_mat)
: mat(_mat), rows(_mat.size()), cols(_mat.at(0).size()) {
return;
}
template <class T>
Matrix<T>::Matrix(const Matrix<T> &_matrix)
: mat(_matrix.mat), rows(_matrix.rows), cols(_matrix.cols) {
return;
}
template <class T>
Matrix<T>::~Matrix(void) {
return;
}
template <class T>
Matrix<T> &Matrix<T>::operator=(const Matrix<T> &_matrix) {
mat = _matrix.to_vector();
return *this;
}
template <class T>
Matrix<T> Matrix<T>::operator+(const Matrix<T> &_matrix) const {
std::vector<std::vector<T>> tmp(rows, std::vector<T>(cols, 0));
for (size_t i = 0; i < rows; i++) {
for (size_t j = 0; j < cols; j++) {
tmp.at(i).at(j) = mat.at(i).at(j) + _matrix.to_vector().at(i).at(j);
}
}
return Matrix<T>(tmp);
}
template <class T>
Matrix<T> &Matrix<T>::operator+=(const Matrix<T> &_matrix) {
for (size_t i = 0; i < rows; i++) {
for (size_t j = 0; j < cols; j++) {
mat.at(i).at(j) += _matrix.to_vector().at(i).at(j);
}
}
return *this;
}
template <class T>
Matrix<T> Matrix<T>::operator-(const Matrix<T> &_matrix) const {
std::vector<std::vector<T>> tmp(rows, std::vector<T>(cols, 0));
for (size_t i = 0; i < rows; i++) {
for (size_t j = 0; j < cols; j++) {
tmp.at(i).at(j) = mat.at(i).at(j) - _matrix.to_vector().at(i).at(j);
}
}
return Matrix<T>(tmp);
}
template <class T>
Matrix<T> &Matrix<T>::operator-=(const Matrix<T> &_matrix) {
for (size_t i = 0; i < rows; i++) {
for (size_t j = 0; j < cols; j++) {
mat.at(i).at(j) -= _matrix.to_vector().at(i).at(j);
}
}
return *this;
}
template <class T>
Matrix<T> Matrix<T>::operator*(const T _v) {
std::vector<std::vector<T>> tmp(rows, std::vector<T>(cols, 0));
for (size_t i = 0; i < rows; i++) {
for (size_t j = 0; j < cols; j++) {
tmp.at(i).at(j) = mat.at(i).at(j) * _v;
}
}
return Matrix<T>(tmp);
}
template <class T>
Matrix<T> &Matrix<T>::operator*=(const T _v) {
for (size_t i = 0; i < rows; i++) {
for (size_t j = 0; j < cols; j++) {
mat.at(i).at(j) *= _v;
}
}
return *this;
}
template <class T>
Matrix<T> Matrix<T>::operator*(const Matrix<T> &_matrix) const {
assert(cols == _matrix.rows);
std::vector<std::vector<T>> tmp(rows, std::vector<T>(_matrix.cols, 0));
for (size_t i = 0; i < rows; i++) {
for (size_t j = 0; j < _matrix.cols; j++) {
for (size_t k = 0; k < cols; k++) {
tmp.at(i).at(j) += mat.at(i).at(k) * _matrix.mat.at(k).at(j);
}
}
}
return Matrix<T>(tmp);
}
template <class T>
Matrix<T> &Matrix<T>::operator*=(const Matrix<T> &_matrix) {
assert(cols == _matrix.rows);
std::vector<std::vector<T>> tmp(rows, std::vector<T>(_matrix.cols, 0));
for (size_t i = 0; i < rows; i++) {
for (size_t j = 0; j < _matrix.cols; j++) {
for (size_t k = 0; k < cols; k++) {
tmp.at(i).at(j) += mat.at(i).at(k) * _matrix.mat.at(k).at(j);
}
}
}
mat = tmp;
cols = _matrix.cols;
return *this;
}
template <class T>
bool Matrix<T>::operator==(const Matrix<T> &_matrix) const {
bool res = true;
for (size_t i = 0; i < rows; i++) {
for (size_t j = 0; j < cols; j++) {
if (_matrix.get_rows() != rows || _matrix.get_cols() != cols) {
res = false;
break;
}
if (mat.at(i).at(j) != _matrix.to_vector().at(i).at(j)) {
res = false;
break;
}
}
}
return res;
}
template <class T>
std::vector<T> &Matrix<T>::operator[](const size_t _idx) {
assert(_idx >= 0 && _idx < rows);
return mat.at(_idx);
}
template <class T>
size_t Matrix<T>::get_rows(void) const {
return rows;
}
template <class T>
size_t Matrix<T>::get_cols(void) const {
return cols;
}
template <class T>
Matrix<T> Matrix<T>::transpose(void) const {
std::vector<std::vector<T>> tmp(cols, std::vector<T>(rows, 0));
for (size_t i = 0; i < rows; i++) {
for (size_t j = 0; j < cols; j++) {
tmp.at(j).at(i) = to_vector().at(i).at(j);
}
}
return Matrix<T>(tmp);
}
// TODO: 换成 LU 分解法
template <class T>
Matrix<float> Matrix<T>::inverse(void) const {
assert(rows == cols);
std::vector<std::vector<float>> tmp(rows, std::vector<float>(cols, 0));
T d = det();
if (d == 0) {
return Matrix<float>(tmp);
}
Matrix<T> adj = adjugate();
for (size_t i = 0; i < rows; i++) {
for (size_t j = 0; j < cols; j++) {
tmp.at(i).at(j) = adj.mat.at(i).at(j) * (1. / d);
}
}
return Matrix<float>(tmp);
}
template <class T>
size_t Matrix<T>::to_arr(T *_arr) const {
for (size_t i = 0; i < rows; i++) {
for (size_t j = 0; j < cols; j++) {
_arr[i * cols + j] = to_vector().at(i).at(j);
}
}
return rows * cols;
}
template <class T>
std::vector<std::vector<T>> Matrix<T>::to_vector(void) const {
return mat;
}
// 输出
template <class T>
std::ostream &operator<<(std::ostream &_os, const Matrix<T> &_mat) {
_os << "[";
for (size_t i = 0; i < _mat.get_rows(); i++) {
if (i != 0) {
_os << "\n";
_os << " ";
}
for (size_t j = 0; j < _mat.get_cols(); j++) {
_os << std::setw(7) << std::setprecision(4)
<< _mat.to_vector().at(i).at(j);
if (j != _mat.get_cols() - 1) {
_os << " ";
}
}
}
_os << std::setw(4) << "]";
return _os;
}
typedef Matrix<float> Matrixf4;
#endif /* __MATRIX_HPP__ */
<file_sep>/src/geometry.cpp
// This file is a part of Simple-XX/SimpleRenderer
// (https://github.com/Simple-XX/SimpleRenderer).
//
// geometry.cpp for Simple-XX/SimpleRenderer.
#include "iostream"
#include "vector"
#include "geometry.h"
using namespace std;
// 推导过程见
bool Geometry::is_barycentric(const Vectors2 &_vertex1,
const Vectors2 &_vertex2,
const Vectors2 &_vertex3,
const Vectors2 &_p) const {
// 边向量
Vectors2 edge1 = (_vertex3 - _vertex1);
Vectors2 edge2 = (_vertex2 - _vertex1);
// 到点 P 的向量
Vectors2 edge3 = (_p - _vertex1);
float v1v1 = edge1 * edge1;
float v1v2 = edge1 * edge2;
float v1v3 = edge1 * edge3;
float v2v2 = edge2 * edge2;
float v2v3 = edge2 * edge3;
float deno = (v1v1 * v2v2) - (v1v2 * v1v2);
float u = ((v2v2 * v1v3) - (v1v2 * v2v3)) / deno;
if (u < 0. || u > 1.) {
return false;
}
float v = ((v1v1 * v2v3) - (v1v2 * v1v3)) / deno;
if (v < 0. || v > 1.) {
return false;
}
if (u + v >= 1.) {
return false;
}
return true;
}
bool Geometry::is_barycentric(const Vectorf3 &_vertex1,
const Vectorf3 &_vertex2,
const Vectorf3 &_vertex3,
const Vectorf3 &_p) const {
// 边向量
Vectorf3 edge1 = (_vertex3 - _vertex1);
Vectorf3 edge2 = (_vertex2 - _vertex1);
// 到点 P 的向量
Vectorf3 edge3 = (_p - _vertex1);
float v1v1 = edge1 * edge1;
float v1v2 = edge1 * edge2;
float v1v3 = edge1 * edge3;
float v2v2 = edge2 * edge2;
float v2v3 = edge2 * edge3;
float deno = (v1v1 * v2v2) - (v1v2 * v1v2);
float u = ((v2v2 * v1v3) - (v1v2 * v2v3)) / deno;
if (u < 0. || u > 1.) {
return false;
}
float v = ((v1v1 * v2v3) - (v1v2 * v1v3)) / deno;
if (v < 0. || v > 1.) {
return false;
}
if (u + v >= 1.) {
return false;
}
return true;
}
Vectors2 Geometry::get_min(const Vectors2 &_vertex1, const Vectors2 &_vertex2,
const Vectors2 &_vertex3) const {
size_t x = min(_vertex1.coord.x, min(_vertex2.coord.x, _vertex3.coord.x));
size_t y = min(_vertex1.coord.y, min(_vertex2.coord.y, _vertex3.coord.y));
return Vectors2(x, y);
}
Vectors2 Geometry::get_max(const Vectors2 &_vertex1, const Vectors2 &_vertex2,
const Vectors2 &_vertex3) const {
size_t x = max(_vertex1.coord.x, max(_vertex2.coord.x, _vertex3.coord.x));
size_t y = max(_vertex1.coord.y, max(_vertex2.coord.y, _vertex3.coord.y));
return Vectors2(x, y);
}
Vectorf3 Geometry::get_min(const Vectorf3 &_vertex1, const Vectorf3 &_vertex2,
const Vectorf3 &_vertex3) const {
size_t x = min(_vertex1.coord.x, min(_vertex2.coord.x, _vertex3.coord.x));
size_t y = min(_vertex1.coord.y, min(_vertex2.coord.y, _vertex3.coord.y));
size_t z = min(_vertex1.coord.z, min(_vertex2.coord.z, _vertex3.coord.z));
return Vectorf3(x, y, z);
}
Vectorf3 Geometry::get_max(const Vectorf3 &_vertex1, const Vectorf3 &_vertex2,
const Vectorf3 &_vertex3) const {
float x = max(_vertex1.coord.x, max(_vertex2.coord.x, _vertex3.coord.x));
float y = max(_vertex1.coord.y, max(_vertex2.coord.y, _vertex3.coord.y));
float z = max(_vertex1.coord.z, max(_vertex2.coord.z, _vertex3.coord.z));
return Vectorf3(x, y, z);
}
Vectorf3 Geometry::normal(const Vectorf3 &_vertex1, const Vectorf3 &_vertex2,
const Vectorf3 &_vertex3) const {
Vectorf3 edge1 = (_vertex3 - _vertex1);
Vectorf3 edge2 = (_vertex2 - _vertex1);
return edge1 ^ edge2;
}
float Geometry::get_z(const Vectorf3 &_vertex1, const Vectorf3 &_vertex2,
const Vectorf3 &_vertex3, size_t _x, size_t _y) const {
Vectorf3 abc = normal(_vertex1, _vertex2, _vertex3);
float d =
-(abc.coord.x * _vertex1.coord.x + abc.coord.y * _vertex1.coord.y +
abc.coord.z * _vertex1.coord.z);
float res = -(abc.coord.x * _x + abc.coord.y * _y + d) / abc.coord.z;
return res;
}
Geometry::Geometry(TGAImage &_image, const string &_filename)
: image(_image), filename(_filename) {
for (size_t w = 0; w < image.get_width(); w++) {
for (size_t h = 0; h < image.get_height(); h++) {
image.set(w, h, color_bg);
}
}
return;
}
Geometry::~Geometry(void) {
return;
}
size_t Geometry::get_width(void) const {
return image.get_width();
}
size_t Geometry::get_height(void) const {
return image.get_height();
}
bool Geometry::save(string _filename) const {
return image.write_tga_file(_filename);
}
// 在给定 _image 上按照 _x0, _y0, _x1, _y1 给出的坐标绘制直线,颜色由 _color
// 指定
// [(_x0, _y0), (_x1, _y1)) 左上角为原点
void Geometry::line(size_t _x0, size_t _y0, size_t _x1, size_t _y1,
const TGAColor &_color) const {
// 斜率大于 1
bool steep = false;
if (abs((int)(_x0 - _x1)) < abs((int)(_y0 - _y1))) {
swap(_x0, _y0);
swap(_x1, _y1);
steep = true;
}
// 终点 x 坐标在起点 左边
if (_x0 > _x1) {
swap(_x0, _x1);
swap(_y0, _y1);
}
int de = 0;
int dy2 = (_y1 - _y0) << 1;
int dx2 = (_x1 - _x0) << 1;
size_t y = _y0;
for (size_t x = _x0; x <= _x1; x++) {
if (steep == true) {
image.set(y, image.get_height() - x, _color);
}
else {
image.set(x, image.get_height() - y, _color);
}
de += abs(dy2);
if (de > 1) {
y += (_y1 > _y0 ? 1 : -1);
de -= dx2;
}
}
return;
}
void Geometry::line(Vectors2 _v0, Vectors2 _v1, const TGAColor &_color) const {
line(_v0.coord.x, _v0.coord.y, _v1.coord.x, _v1.coord.y, _color);
return;
}
void Geometry::line(Vectors2 *_vertexes, const TGAColor &_color) const {
line(_vertexes[0].coord.x, _vertexes[0].coord.y, _vertexes[1].coord.x,
_vertexes[1].coord.y, _color);
return;
}
void Geometry::line(float _x0, float _y0, float _z0, float _x1, float _y1,
float _z1, float *_zbuffer, const TGAColor &_color) {
// 斜率大于 1
bool steep = false;
if (abs(_x0 - _x1) < abs(_y0 - _y1)) {
swap(_x0, _y0);
swap(_x1, _y1);
steep = true;
}
// 终点 x 坐标在起点 左边
if (_x0 > _x1) {
swap(_x0, _x1);
swap(_y0, _y1);
}
int de = 0;
float dy2 = (_y1 - _y0) * 2;
float dx2 = (_x1 - _x0) * 2;
float y = _y0;
float z = _z0;
float dz = (_z1 - _z0) / (_x1 - _x0);
size_t idx = 0;
for (float x = _x0; x <= _x1; x++) {
idx = (size_t)(x + y * image.get_height());
if (steep == true) {
if (_zbuffer[idx] < z) {
image.set(y, image.get_height() - x, _color);
_zbuffer[idx] = z;
}
}
else {
if (_zbuffer[idx] < z) {
image.set(x, image.get_height() - y, _color);
_zbuffer[idx] = z;
}
}
de += abs(dy2);
if (de > 1) {
y += (_y1 > _y0 ? 1 : -1);
de -= dx2;
}
z = _z0 + dz * (x - _x0);
}
return;
}
void Geometry::line(Vectorf3 _v0, Vectorf3 _v1, float *_zbuffer,
const TGAColor &_color) {
line(_v0.coord.x, _v0.coord.y, _v0.coord.z, _v1.coord.x, _v1.coord.y,
_v1.coord.z, _zbuffer, _color);
return;
}
void Geometry::line(Vectorf3 *_vertexes, float *_zbuffer,
const TGAColor &_color) {
line(_vertexes[0].coord.x, _vertexes[0].coord.y, _vertexes[0].coord.z,
_vertexes[1].coord.x, _vertexes[1].coord.y, _vertexes[1].coord.z,
_zbuffer, _color);
return;
}
// 绘制三角形,_vertex1 _vertex2 _vertex3 为三个顶点
void Geometry::triangle(const Vectors2 &_vertex1, const Vectors2 &_vertex2,
const Vectors2 &_vertex3,
const TGAColor &_color) const {
// 遍历平行四边形,如果在三角形内则填充
Vectors2 min = get_min(_vertex1, _vertex2, _vertex3);
Vectors2 max = get_max(_vertex1, _vertex2, _vertex3);
Vectors2 p;
for (p.coord.x = min.coord.x; p.coord.x <= max.coord.x; p.coord.x++) {
for (p.coord.y = min.coord.y; p.coord.y <= max.coord.y; p.coord.y++) {
if (is_barycentric(_vertex1, _vertex2, _vertex3, p) == true) {
image.set(p.coord.x, image.get_height() - p.coord.y, _color);
}
}
}
return;
}
void Geometry::triangle(const Vectors2 *_vertexes,
const TGAColor &_color) const {
triangle(_vertexes[0], _vertexes[1], _vertexes[2], _color);
return;
}
void Geometry::triangle(const Vectorf3 &_vertex1, const Vectorf3 &_vertex2,
const Vectorf3 &_vertex3, float *_zbuffer,
const TGAColor &_color) const {
Vectorf3 min = get_min(_vertex1, _vertex2, _vertex3);
Vectorf3 max = get_max(_vertex1, _vertex2, _vertex3);
Vectorf3 p;
size_t idx = 0;
float z = 0;
for (p.coord.x = min.coord.x; p.coord.x <= max.coord.x; p.coord.x++) {
for (p.coord.y = min.coord.y; p.coord.y <= max.coord.y; p.coord.y++) {
if (is_barycentric(_vertex1, _vertex2, _vertex3, p) == true) {
idx = (size_t)(p.coord.x + p.coord.y * image.get_height());
z = get_z(_vertex1, _vertex2, _vertex3, p.coord.x, p.coord.y);
if (_zbuffer[idx] < z) {
_zbuffer[idx] = z;
image.set(p.coord.x, image.get_height() - p.coord.y,
_color);
}
}
}
}
return;
}
void Geometry::triangle(const Vectorf3 *_vertexes, float *_zbuffer,
const TGAColor &_color) {
triangle(_vertexes[0], _vertexes[1], _vertexes[2], _zbuffer, _color);
return;
}
void Geometry::circle(size_t _x0, size_t _y0, float _r, TGAColor _color) const {
assert(_r > 0);
size_t x = 0;
size_t y = _r;
// 起点(0,R)
// 下一点中点(1,R-0.5)
// d=1*1+(R-0.5)*(R-0.5)-R*R=1.25-R
// d只参与整数运算,所以小数部分可省略
int d = 1 - _r;
while (y > x) // y>x即第一象限的第1区八分圆
{
image.set(x + _x0, image.get_height() - (y + _y0), _color);
image.set(y + _x0, image.get_height() - (x + _y0), _color);
image.set(-x + _x0, image.get_height() - (y + _y0), _color);
image.set(-y + _x0, image.get_height() - (x + _y0), _color);
image.set(-x + _x0, image.get_height() - (-y + _y0), _color);
image.set(-y + _x0, image.get_height() - (-x + _y0), _color);
image.set(x + _x0, image.get_height() - (-y + _y0), _color);
image.set(y + _x0, image.get_height() - (-x + _y0), _color);
if (d < 0) {
d = d + 2 * x + 3;
}
else {
d = d + 2 * (x - y) + 5;
y--;
}
x++;
}
return;
}
void Geometry::circle(size_t _x0, size_t _y0, float _r, float *_zbuffer,
const TGAColor &_color) const {
assert(_r > 0);
size_t x = 0;
size_t y = _r;
// 起点(0,R)
// 下一点中点(1,R-0.5)
// d=1*1+(R-0.5)*(R-0.5)-R*R=1.25-R
// d 只参与整数运算,所以小数部分可省略
int d = 1 - _r;
// y > x 即第一象限的第1区八分圆
while (y > x) {
image.set(x + _x0, image.get_height() - (y + _y0), _color);
image.set(y + _x0, image.get_height() - (x + _y0), _color);
image.set(-x + _x0, image.get_height() - (y + _y0), _color);
image.set(-y + _x0, image.get_height() - (x + _y0), _color);
image.set(-x + _x0, image.get_height() - (-y + _y0), _color);
image.set(-y + _x0, image.get_height() - (-x + _y0), _color);
image.set(x + _x0, image.get_height() - (-y + _y0), _color);
image.set(y + _x0, image.get_height() - (-x + _y0), _color);
if (d < 0) {
d = d + 2 * x + 3;
}
else {
d = d + 2 * (x - y) + 5;
y--;
}
x++;
}
_zbuffer = _zbuffer;
return;
}
| 8fbb2603be4623128086f728f20a73ff3a1b99be | [
"CMake",
"Markdown",
"C",
"C++",
"Shell"
] | 19 | C++ | assassindesign/SimpleRenderer | 1c0b75af7cfb920a7861c1928657d1f1a3a81c1a | 16bcba4013825d4e20e3a5ffbc95dcbac402fefa |
refs/heads/master | <repo_name>dragankoprena/picassolLib<file_sep>/settings.gradle
rootProject.name='demoLibForPicaso'
include ':app'
include ':picasolib'
<file_sep>/picasolib/src/main/java/com/comtrade/picasolib/PicassoLib.kt
package com.comtrade.picasolib
import android.widget.ImageView
import com.comtrade.libraryb.LibraryB
import com.squareup.picasso.Picasso
object PicassoLib {
fun load(url: String, imageView: ImageView) {
Picasso.get()
.load(url)
.resize(50, 50)
.centerCrop()
.into(imageView)
}
fun helloFromLibB() = LibraryB.hello()
} | a063604fe544899525283294ac330b9e4e1866b3 | [
"Kotlin",
"Gradle"
] | 2 | Gradle | dragankoprena/picassolLib | fbccdf8baf819e8429ae2483fc65a5e2c47ffa87 | 6200ef5bebd61186f1b0a5f7db8e5d459d9f4f36 |
refs/heads/master | <file_sep>/**
* Callback for currentRasterProbe field
* "currentRasterProbe" object represents data for raster in raster probe
* @module
* @memberof stateUpdate
*/
const getUpdateCurrentRasterProbe = ({ components }) => {
const updateCurrentRasterProbe = function updateCurrentRasterProbe() {
const {
currentRasterProbe,
} = this.props();
const {
layout,
rasterProbe,
} = components;
layout
.config({
rasterProbeOpen: currentRasterProbe !== null,
})
.updateRasterProbe();
rasterProbe
.config({
currentRasterProbe,
})
.update();
};
return updateCurrentRasterProbe;
};
export default getUpdateCurrentRasterProbe;
<file_sep>/**
* Module controls url parameters
* @module url
*/
import rasterMethods from '../rasterProbe/rasterMethods';
const privateProps = new WeakMap();
const paramFields = [
'language',
'overlay',
'center',
'zoom',
'bearing',
'year',
];
const privateMethods = {
init() {
const props = privateProps.get(this);
props.urlParams = new URLSearchParams(window.location.search);
const {
urlParams,
} = props;
paramFields.forEach((param) => {
if (urlParams.has(param)) {
props[param] = urlParams.get(param);
}
});
},
};
class UrlParams {
constructor(config) {
const {
init,
} = privateMethods;
privateProps.set(this, {
language: 'en',
center: null,
zoom: null,
bearing: null,
overlay: null,
rasterData: null,
year: 1960,
timeout: null,
});
this.config(config);
init.call(this);
this.update();
}
config(config) {
Object.assign(privateProps.get(this), config);
return this;
}
get(field) {
const props = privateProps.get(this);
const { rasterData } = props;
const { getRasterFromSSID } = rasterMethods;
if (field === 'overlay' && props[field] !== null) {
return getRasterFromSSID({
rasterData,
SS_ID: props[field],
});
} else if (field === 'center' && props[field] !== null) {
const coords = props[field].split(',');
return new mapboxgl.LngLat(coords[1], coords[0]);
}
return props[field];
}
update() {
const props = privateProps.get(this);
const { urlParams, timeout } = props;
paramFields.forEach((param) => {
if (props[param] !== null) {
urlParams.set(param, props[param]);
} else if (urlParams.has(param) && props[param] === null) {
urlParams.delete(param);
}
});
if (timeout !== null) {
clearTimeout(timeout);
}
props.timeout = setTimeout(() => {
props.timeout = null;
window.history.replaceState({}, '', `?${decodeURIComponent(urlParams.toString())}`);
}, 250);
}
}
export default UrlParams;
<file_sep>/**
* Module initializes application state
* Application state represents properties shared between components
* @module initState
*/
import State from '../state/state';
import rasterMethods from '../rasterProbe/rasterMethods';
const initState = function initState() {
const { urlParams } = this.components;
const startOverlay = urlParams.get('overlay');
const center = urlParams.get('center');
const zoom = urlParams.get('zoom');
const bearing = urlParams.get('bearing');
const initialLocation = center === null && zoom === null && bearing === null ?
null :
{
center,
zoom,
bearing,
};
const startView = initialLocation === null ? 'intro' : 'map';
const state = new State({
year: parseInt(urlParams.get('year'), 10),
sidebarOpen: false,
footerOpen: startView === 'map',
allRasterOpen: false,
registerOpen: false,
sidebarView: 'legend',
footerView: 'views',
view: startView,
mapLoaded: false,
componentsInitialized: false,
textSearch: null,
clickSearch: null,
areaSearchActive: false,
areaSearch: null,
currentLayers: null,
currentOverlay: startOverlay,
currentView: null,
currentLocation: initialLocation,
currentRasterProbe: null,
highlightedFeature: null,
highlightedLayer: null,
mouseEventsDisabled: false,
transitionsDisabled: false,
mobile: null,
language: urlParams.get('language'),
screenSize: [window.innerWidth, window.innerHeight],
overlayOpacity: 1,
});
state.getAvailableLayers = function getAvailableLayers(data) {
const year = this.get('year');
const { layers } = data;
const newLayers = layers.map((group) => {
const newGroup = Object.assign({}, group);
newGroup.layers = group.layers.filter(d =>
d.startYear <= year &&
d.endYear >= year)
.map((layer) => {
const newLayer = Object.assign({}, layer);
newLayer.features = layer.features.filter(d =>
d.years.some(e =>
e[0] <= year &&
e[1] >= year) &&
d.style !== undefined);
return newLayer;
})
.filter(layer => layer.features.length > 0);
return newGroup;
})
.filter(group => group.layers.length > 0);
return newLayers;
};
state.getAvailableRasters = function getAvailableRasters(data) {
const year = this.get('year');
const availableRasters = new Map();
data.rasters.forEach((val, key) => {
availableRasters.set(key, data.rasters.get(key)
.filter(d => d.FirstYear <= year &&
d.LastYear >= year));
});
return availableRasters;
};
state.getAllAvailableLayers = function getAllAvailableLayers(data) {
const availableViews = this.getAvailableRasters(data)
.get('views');
const viewsLayer = {
sourceLayer: 'ViewConesPoint',
status: true,
};
const availableLayers = this.getAvailableLayers(data)
.reduce((accumulator, group) => [...accumulator, ...group.layers], [])
.map(layer => ({
sourceLayer: layer.sourceLayer,
status: true,
}));
if (availableViews.length > 0) {
return [
viewsLayer,
...availableLayers,
];
}
return availableLayers;
};
state.getLayersToClear = function getLayersToClear(fields) {
return fields.reduce((accumulator, field) => {
if (state.get(field) !== null) {
/* eslint-disable no-param-reassign */
accumulator[field] = null;
/* eslint-enable no-param-reassign */
}
return accumulator;
}, {});
};
state.getAutoFooterView = function getAutoFooterView(data) {
const {
getRasterDataByCategory,
} = rasterMethods;
const rasterData = this.getAvailableRasters(data);
const rasterDataByCategory = getRasterDataByCategory({ rasterData });
if (rasterDataByCategory.length === 0) {
return 'views';
} else if (rasterData.get(this.get('footerView')).length === 0) {
return rasterDataByCategory[0].key;
}
return state.get('footerView');
};
state.getOrientation = function getOrientation() {
const width = this.get('screenSize')[0];
if (width > 700) {
return 'desktop';
} else if (width >= 415 && width <= 700) {
return 'mobileLandscape';
}
return 'mobile';
};
state.set('mobile', state.getOrientation() === 'mobile');
state.set('currentLayers', state.getAllAvailableLayers(this.data));
state.set(
'footerView',
state.getAutoFooterView(this.data),
);
this.components.state = state;
};
export default initState;
<file_sep>/**
* Module comprises methods related to raster manipulation and raster metadata
* @module rasterMethods
*/
import 'whatwg-fetch';
const rasterMethods = {
getScaledCircleDim({ width, height, maxDim }) {
if (width > height) {
return {
height: maxDim,
width: width * (maxDim / height),
};
}
return {
height: height * (maxDim / width),
width: maxDim,
};
},
getScaledCircleDimFromMetadata({
metadata,
maxDim,
}) {
const { getScaledCircleDim } = rasterMethods;
const { width, height } = metadata;
return getScaledCircleDim({ width, height, maxDim });
},
getScaledDim({
width,
height,
maxWidth,
maxHeight,
}) {
const scaledHeight = height * (maxWidth / width);
const heightLimited = maxHeight !== undefined && scaledHeight > maxHeight;
return {
width: heightLimited ? maxWidth * (maxHeight / scaledHeight) : maxWidth,
height: heightLimited ? maxHeight : scaledHeight,
};
},
getScaledDimFromMetadata({ metadata, maxWidth, maxHeight }) {
const { getScaledDim } = rasterMethods;
const { width, height } = metadata;
return getScaledDim({
width,
height,
maxWidth,
maxHeight,
});
},
getImageUrl(metadata) {
return `https://pilotplan.s3.amazonaws.com/images/${metadata.retrieveLink}/`;
},
getMetadata({ data }, callback) {
return callback({
height: 1200,
width: 1200,
retrieveLink: `SSID${data.SS_ID}`,
});
},
getSharedShelfURL({ currentRasterProbe }, callback) {
window.fetch(`https://library.artstor.org/api/v1/metadata?object_ids=${currentRasterProbe.SSC_ID}&openlib=true`, { credentials: 'include' })
.then(res => res.text())
.then((text) => {
const json = JSON.parse(text);
callback(`https://library.artstor.org/#/asset/${json.metadata[0].object_id}`);
});
},
addSharedShelfLinkToSelection({
currentRasterProbe,
cachedSharedShelfURLs,
selection,
}) {
const {
getSharedShelfURL,
} = rasterMethods;
selection.on('click', () => {
window.open(`https://library.artstor.org/#/asset/${currentRasterProbe.SSC_ID}`, '_blank');
});
},
setRasterBackground({ selection, url }) {
selection
.styles({
'background-image': `url("${url}")`,
'background-size': 'cover',
});
},
setBackgroundFromMetadata({
metadata,
scaledDim,
selection,
resizeContainer = false,
}) {
const {
getImageUrl,
setRasterBackground,
} = rasterMethods;
let url = getImageUrl(metadata);
if (scaledDim.width <= 130 || scaledDim.height <= 130) {
url += 'thumb.jpg';
} else if (scaledDim.width <= 400 || scaledDim.height <= 400) {
url += 'medium.jpg';
} else {
url += 'full.jpg';
}
setRasterBackground({
url,
selection,
});
if (resizeContainer) {
selection
.styles({
width: `${scaledDim.width}px`,
height: `${scaledDim.height}px`,
});
}
},
setBackgroundToContainerWidth({
cachedMetadata,
selection,
currentRasterProbe,
resizeContainer,
maxHeight,
maxWidth,
}) {
const {
setBackgroundFromMetadata,
getScaledDimFromMetadata,
} = rasterMethods;
const { getMetadata } = rasterMethods;
if (cachedMetadata.has(currentRasterProbe.SS_ID)) {
const metadata = cachedMetadata.get(currentRasterProbe.SS_ID);
const scaledDim = getScaledDimFromMetadata({
maxWidth,
metadata,
maxHeight,
});
setBackgroundFromMetadata({
metadata,
scaledDim,
selection,
resizeContainer,
});
} else {
getMetadata({ data: currentRasterProbe }, (metadata) => {
const scaledDim = getScaledDimFromMetadata({
maxWidth,
metadata,
maxHeight,
});
setBackgroundFromMetadata({
metadata,
scaledDim,
selection,
resizeContainer,
});
});
}
},
setEachRasterBackground({
images,
cachedMetadata,
maxDim,
spinner = false,
}) {
const {
getMetadata,
setBackgroundFromMetadata,
getScaledCircleDimFromMetadata,
} = rasterMethods;
images.each(function addData(d) {
const selection = d3.select(this);
if (cachedMetadata.has(d.SS_ID)) {
const metadata = cachedMetadata.get(d.SS_ID);
const scaledDim = getScaledCircleDimFromMetadata({
metadata,
maxDim,
});
setBackgroundFromMetadata({
metadata,
scaledDim,
selection,
});
} else {
if (spinner) {
selection
.append('i')
.attr('class', 'icon-spinner animate-spin');
}
getMetadata({ data: d }, (metadata) => {
const scaledDim = getScaledCircleDimFromMetadata({
metadata,
maxDim,
});
cachedMetadata.set(d.SS_ID, metadata);
setBackgroundFromMetadata({
metadata,
scaledDim,
selection,
});
if (spinner) {
selection.selectAll('.icon-spinner').remove();
}
});
}
});
},
getRasterCategories({ rasterData }) {
const rasterCategories = [];
rasterData.forEach((val, key) => {
rasterCategories.push(key);
});
return rasterCategories;
},
getRasterDataByCategory({ rasterData }) {
const data = [];
rasterData.forEach((values, key) => {
if (values.length > 0) {
data.push({
values,
key,
});
}
});
return data;
},
getFlattenedRasterData({ rasterData }) {
const data = [];
rasterData.forEach((values, key) => {
values.forEach((value) => {
const valueCopy = Object.assign({}, value);
valueCopy.category = key;
data.push(valueCopy);
});
});
return data;
},
getRasterFromSSID({ rasterData, SS_ID }) {
const { getFlattenedRasterData } = rasterMethods;
const flattenedRaster = getFlattenedRasterData({ rasterData });
return flattenedRaster.find(d => d.SS_ID === SS_ID);
},
onRasterClick({ rasterData, state }) {
const getId = d => (d === null ? null : d.SS_ID);
const currentView = state.get('currentView');
const currentOverlay = state.get('currentOverlay');
if (rasterData.type === 'overlay') {
if (getId(currentOverlay) === getId(rasterData)) {
state.update({
currentOverlay: null,
currentRasterProbe: currentView === null ? null : currentView,
});
} else {
state.update({
currentOverlay: rasterData,
currentRasterProbe: currentView === null ? rasterData : currentView,
});
}
} else if (rasterData.type === 'view') {
if (getId(currentView) === getId(rasterData)) {
state.update({
currentView: null,
currentRasterProbe: null,
});
} else {
state.update({
currentView: rasterData,
currentRasterProbe: rasterData,
});
}
}
},
};
export default rasterMethods;
<file_sep>/**
* Module comprises methods related to slider tooltip
* @module timelineTooltipMethods
* @memberof timeline
*/
import Timeline from './timeline';
import erasMethods from '../eras/erasMethods';
const getTooltipMethods = ({ privateProps, privateMethods }) => ({
initTooltip() {
const props = privateProps.get(this);
const {
detectionTrack,
outerContainer,
tooltip,
svg,
} = props;
if (!tooltip) return;
const { setTooltipPosition } = privateMethods;
props.tooltipWidth = 400;
const { tooltipWidth } = props;
const tooltipMargin = 45;
props.svgPosition = svg.node().getBoundingClientRect();
const { svgPosition } = props;
detectionTrack
.on('mouseover', () => {
props.tooltipContainer = outerContainer.append('div')
.attr('class', 'slider__tooltip-container')
.styles({
position: 'absolute',
width: `${tooltipWidth}px`,
top: `${svgPosition.y - (tooltipMargin / 2) - 10}px`,
height: `${svgPosition.height + tooltipMargin}px`,
});
props.tooltipYear = props.tooltipContainer
.append('div')
.attr('class', 'slider__tooltip-year')
.text('YEAR');
props.tooltipEra = props.tooltipContainer
.append('div')
.attr('class', 'slider__tooltip-era')
.text('ERA');
})
.on('mousemove', () => {
const { x } = d3.event;
setTooltipPosition.call(this, { x });
})
.on('mouseout', () => {
const { tooltipContainer } = privateProps.get(this);
if (tooltipContainer === undefined) return;
tooltipContainer.remove();
});
},
setTooltipPosition({ x }) {
const {
tooltipContainer,
tooltipWidth,
scale,
svgPosition,
tooltipYear,
eras,
language,
tooltipEra,
uniqueYears,
} = privateProps.get(this);
const {
getCurrentEra,
} = erasMethods;
const year = Math.round(scale.invert(x - svgPosition.left));
const currentEra = getCurrentEra({ year, eras });
if (currentEra === undefined) return;
tooltipContainer
.styles({
left: `${x - (tooltipWidth / 2)}px`,
});
tooltipYear.text(Timeline.getUniqueYear(year, uniqueYears));
tooltipEra.text(currentEra[language]);
},
});
export default getTooltipMethods;
<file_sep>npm run views
# No local roads buildings, or parcels
tippecanoe -Z 8 -z 11 -pf -pk -ab -ai -f -o data/tiles/allzooms.mbtiles \
-x osm_id -x Shape_Leng -x Shape_Area -x layer -x Date -x Address -x SHAPE_Le_1 -x Shape_Leng -x SHAPE_Area -x Notes -x Join_Count -x TARGET_FID -x OBJECTID -x Height -x alturaapro -x ano -x Title \
-j '{ "RoadsLine": ["!in", "SubType", "Collector", "Local", "Service"] }' \
data/geojson/geography/BoundariesPoly.json \
data/geojson/geography/BuiltDomainPoly.json \
data/geojson/geography/InfrastructureLine.json \
data/geojson/geography/OpenSpacesPoly.json \
data/geojson/geography/RoadsLine.json \
data/geojson/geography/SectorsPoly.json \
data/geojson/geography/WaterBodiesPoly.json \
data/geojson/geography/WatersLine.json
# Adding in buildings
tippecanoe -Z 12 -z 12 -pf -pk -ab -ai -f -o data/tiles/BuildingsPoly.mbtiles \
-x osm_id -x Shape_Leng -x Shape_Area -x layer -x Date -x Address -x SHAPE_Le_1 -x Shape_Leng -x SHAPE_Area -x Notes -x Join_Count -x TARGET_FID -x OBJECTID -x Height -x alturaapro -x ano -x Title \
-j '{ "RoadsLine": ["!in", "SubType", "Collector", "Local", "Service"] }' \
data/geojson/geography/BoundariesPoly.json \
data/geojson/geography/BuildingsPoly.json \
data/geojson/geography/BuiltDomainPoly.json \
data/geojson/geography/InfrastructureLine.json \
data/geojson/geography/OpenSpacesPoly.json \
data/geojson/geography/RoadsLine.json \
data/geojson/geography/SectorsPoly.json \
data/geojson/geography/WaterBodiesPoly.json \
data/geojson/geography/WatersLine.json
# Removing filter to add local roads
tippecanoe -Z 13 -z 17 -pf -pk -ab -ai -f -o data/tiles/LocalRoads.mbtiles \
-x osm_id -x Shape_Leng -x Shape_Area -x layer -x Date -x Address -x SHAPE_Le_1 -x Shape_Leng -x SHAPE_Area -x Notes -x Join_Count -x TARGET_FID -x OBJECTID -x Height -x alturaapro -x ano -x Title \
data/geojson/geography/BoundariesPoly.json \
data/geojson/geography/BuildingsPoly.json \
data/geojson/geography/BuiltDomainPoly.json \
data/geojson/geography/InfrastructureLine.json \
data/geojson/geography/OpenSpacesPoly.json \
data/geojson/geography/RoadsLine.json \
data/geojson/geography/SectorsPoly.json \
data/geojson/geography/WaterBodiesPoly.json \
data/geojson/geography/WatersLine.json
tippecanoe -Z 9 -z 17 -pf -pk -r1 -pk -pf -f -o data/tiles/ViewCones.mbtiles data/geojson/geography/ViewConesPoint.json
tile-join -pk -f -o data/tiles/pilot.mbtiles data/tiles/allzooms.mbtiles data/tiles/BuildingsPoly.mbtiles data/tiles/LocalRoads.mbtiles data/tiles/ViewCones.mbtiles
mapbox-tile-copy data/tiles/pilot.mbtiles "s3://pilotplan/tiles/{z}/{x}/{y}?timeout=10000"<file_sep>const fs = require('fs');
const path = require('path');
const _ = require('underscore');
const turf = require('@turf/helpers');
const getBBox = require('@turf/bbox').default;
const config = {};
let uniqueYears = [];
let loaded = 0;
let total = 0;
function getYears(features) {
let years = _.union(
features.map(f => f.properties.FirstYear),
features.map(f => f.properties.LastYear),
);
years = years.filter(y => y !== 8888);
return years.sort();
}
function getFeaturesByYear(features, year) {
return features.filter(f => f.properties.FirstYear <= year && f.properties.LastYear >= year);
}
function getExtents(features) {
const collection = turf.featureCollection(features);
return getBBox(collection);
}
function processFeatures(features, name, layer) {
const years = getYears(features);
const extents = {};
years.forEach((y) => {
extents[y] = getExtents(getFeaturesByYear(features, y));
});
if (!config[layer]) config[layer] = {};
config[layer][name] = extents;
uniqueYears = _.union(uniqueYears, years).sort();
}
function writeStatic(f) {
fs.readFile(path.join(__dirname, '../data/geojson/geography', f), (err2, data) => {
const layer = f.replace(/\.json$/, '');
const { features } = JSON.parse(data);
const subs = _.groupBy(features, feat => feat.properties.SubType);
_.each(subs, (fArray, name) => {
processFeatures(fArray, name, layer);
});
loaded += 1;
if (loaded === total) {
fs.writeFile(path.join(__dirname, '../src/data/extents.json'), JSON.stringify(config, null, 2), () => {
console.log('EXTENTS FILE WRITTEN');
uniqueYears = _.union(uniqueYears, [new Date().getFullYear()]).sort();
if (_.last(uniqueYears) !== Date.getFullYear()) uniqueYears.push(Date.getFullYear());
fs.writeFile(path.join(__dirname, '../src/data/years.json'), JSON.stringify(uniqueYears, null, 2), () => {
console.log('YEARS FILE WRITTEN');
});
});
}
});
}
fs.readdir(path.join(__dirname, '../data/geojson/geography'), (err, files) => {
total = files.length;
files.forEach(writeStatic);
});
<file_sep>const fs = require('fs');
const getBBox = require('@turf/bbox').default;
const _ = require('underscore');
const processFile = (fileName) => {
const path = 'data/geojson/visual/';
fs.readFile(`${path}${fileName}`, (err, dataRaw) => {
if (err) throw err;
const data = JSON.parse(dataRaw);
const cleanData = data.features.map((feature) => {
let record = Object.assign({}, feature.properties);
record = _.pick(record, [
'Creator',
'SS_ID',
'Notes',
'SSC_ID',
'FirstYear',
'LastYear',
'Title',
'CreditLine',
'Repository',
]);
record.bounds = getBBox(feature);
return record;
});
fs.writeFile(`src/data/${fileName.replace('Poly', '')}`, JSON.stringify(cleanData), 'utf8', (err2) => {
if (err2) throw err;
console.log(`written file ${fileName.replace('Poly', '')}`);
});
});
};
processFile('AerialExtentsPoly.json');
processFile('MapExtentsPoly.json');
processFile('PlanExtentsPoly.json');
<file_sep>"""Deal with raster transparency and convert to MBTiles for uploading"""
import argparse
import os
import re
from string import Template
from shutil import copyfile
from osgeo import gdal
import rasterio
PARSER = argparse.ArgumentParser()
PARSER.add_argument('file', nargs='?')
PARSER.add_argument('--fixed')
PARSER.add_argument('--nodata', type=int)
PARSER.add_argument('--dev')
ARGS = PARSER.parse_args()
PATH = 'data/geotiff/'
def raster_bands(tif, sub):
if re.search(r"\.tif$", tif):
tif_file = PATH + sub + tif
print('Reading raster', tif_file)
src = gdal.Open(tif_file)
ras = rasterio.open(tif_file)
if ARGS.nodata:
val = ARGS.nodata
else:
val = ras.read(1)[0][0]
if (src.RasterCount == 4 or (val != 0 and val != 255)) and ras.dtypes[0] == 'uint8':
print('4 correct bands found')
copyfile(tif_file, PATH + 'converted/' + tif)
project_raster(tif)
elif src.RasterCount == 1 or src.RasterCount == 3 or src.RasterCount == 4:
print('Using ' + str(val) + ' for no data')
gdal_string = Template("""gdal_translate -b 1 ${f} -a_nodata none ${path}converted/red.tif &&
gdal_translate -b ${b2} ${f} -a_nodata none ${path}converted/green.tif &&
gdal_translate -b ${b3} ${f} -a_nodata none ${path}converted/blue.tif &&
echo Calculating file mask
gdal_calc.py -A ${path}converted/red.tif -B ${path}converted/green.tif -C ${path}converted/blue.tif --outfile=${path}converted/mask.tif --calc="logical_and(A!=${nodata},B!=${nodata},C!=${nodata})*255" --NoDataValue=0 &&
echo Merging files
gdal_merge.py -separate -ot Byte -o ${path}converted/${tif} ${path}converted/red.tif ${path}converted/green.tif ${path}converted/blue.tif ${path}converted/mask.tif &&
echo Cleaning up
rm ${path}converted/red.tif &&
rm ${path}converted/green.tif &&
rm ${path}converted/blue.tif &&
rm ${path}converted/mask.tif""")
if src.RasterCount == 1:
print('1 band raster found')
os.system(gdal_string.substitute(f=tif_file, b2='1', b3='1', nodata=str(val),
path=PATH, tif=tif))
project_raster(tif)
elif src.RasterCount >= 3:
print('3+ band raster found')
os.system(gdal_string.substitute(f=tif_file, b2='2', b3='3', nodata=str(val),
path=PATH, tif=tif))
project_raster(tif)
else:
print(tif_file + ' has wrong number of bands!')
def project_raster(tif):
basename = re.sub(r"\.tif$", '', tif)
if ARGS.dev:
basename += 'dev'
if ARGS.fixed:
mb_string = Template("""echo Converting to MBTiles &&
gdal2mbtiles --no-fill-borders --min-resolution 9 --max-resolution 17\
${path}converted/${base}_merc.tif ${path}converted/${base}.mbtiles""")
else:
mb_string = Template("""gdal2tiles.py -r antialias -s "EPSG:4326"\
--processes 12 -w none ${path}converted/${tif} ${path}converted/${base}""")
os.system(mb_string.substitute(path=PATH, tif=tif, base=basename))
if ARGS.file:
FILES = ARGS.file.replace(PATH, '').split('/')
raster_bands(FILES[1], FILES[0] + '/')
# os.system('find data/geotiff/converted/ -type f ! -name ".gitignore" -delete')
else:
for subdir in os.listdir(PATH):
if subdir[0] != '.' and subdir != 'converted':
subdir += '/'
for t in os.listdir(PATH + subdir):
raster_bands(t, subdir)
<file_sep>/**
* Callback for mapLoaded field
* "mapLoaded" boolean represents if the map has initially loaded
* @module
* @memberof stateUpdate
*/
const getUpdateMapLoaded = ({ components }) => {
const updateMapLoaded = function updateMapLoaded() {
const { mapLoaded } = this.props();
const { views, layout } = components;
views.config({ mapLoaded });
layout.config({ mapLoaded }).updateMapLoaded();
};
return updateMapLoaded;
};
export default getUpdateMapLoaded;
<file_sep>/**
* Module initializes url component
* @module initURL
*/
import UrlParams from '../url/url';
const initURL = function initURL() {
this.components.urlParams = new UrlParams({
rasterData: this.data.rasters,
});
};
export default initURL;
<file_sep>/**
* Callback for areaSearchActive field
* "areaSearchActive" boolean field indicates if area search button has been clicked
* but search has not yet been performed
* @module
* @memberof stateUpdate
*/
const getUpdateAreaSearchActive = ({ components }) => {
const updateAreaSearchActive = function updateAreaSearchActive() {
const {
areaSearchActive,
} = this.props();
const {
layout,
atlas,
} = components;
layout
.config({
areaSearchActive,
})
.updateAreaSearch();
layout.removeHintProbe();
atlas
.config({
areaSearchActive,
})
.updateAreaSearch();
};
return updateAreaSearchActive;
};
export default getUpdateAreaSearchActive;
<file_sep>/**
* Module comprises pure functions related to raster probe
* @module rasterProbeMethods
* @memberof rasterProbe
*/
import rasterMethods from './rasterMethods';
import TimelineSlider from '../timeline/timelineSlider';
const localMethods = {
clearImage({
rasterProbeImageContainer,
}) {
rasterProbeImageContainer
.style('background-image', 'none');
},
setImageClickListener({
rasterProbeImageContainer,
onImageClick,
}) {
rasterProbeImageContainer
.on('click', onImageClick);
},
toggleOverlayControls({
rasterProbeControlsContainer,
currentRasterProbe,
}) {
if (currentRasterProbe === null) return;
rasterProbeControlsContainer
.classed('raster-probe__overlay-controls--hidden', currentRasterProbe.type === 'view');
},
setOverlayCloseButtonListener({
onOverlayCloseClick,
rasterProbeCloseOverlayButton,
}) {
rasterProbeCloseOverlayButton
.on('click', onOverlayCloseClick);
},
};
const rasterProbeMethods = {
updateTitle({
rasterProbeTitleContainer,
currentRasterProbe,
}) {
rasterProbeTitleContainer
.text(currentRasterProbe.Title);
},
updateImage({
currentRasterProbe,
cachedMetadata,
rasterProbeImageContainer,
onImageClick,
mobile,
rasterProbeInnerContainer,
}) {
const {
clearImage,
setImageClickListener,
} = localMethods;
const {
setBackgroundToContainerWidth,
} = rasterMethods;
clearImage({ rasterProbeImageContainer });
setImageClickListener({
rasterProbeImageContainer,
onImageClick,
});
const padding = parseFloat(rasterProbeInnerContainer
.style('padding-left')
.replace('px', ''));
setBackgroundToContainerWidth({
selection: rasterProbeImageContainer,
cachedMetadata,
currentRasterProbe,
resizeContainer: true,
maxHeight: mobile ? 150 : 400,
maxWidth: mobile ? window.innerWidth - (padding * 2) : 410,
});
},
setCloseButtonListener({
rasterProbeCloseButton,
onCloseClick,
}) {
rasterProbeCloseButton
.on('click', onCloseClick);
},
updateCredits({
selection,
currentRasterProbe,
}) {
let creditsHTML = '';
const hasValue = value => value !== '' && value !== undefined && value !== null;
if (hasValue(currentRasterProbe.Creator)) {
creditsHTML += `
<div class="raster-probe__credits-row">${currentRasterProbe.Creator}</div>
`;
}
if (hasValue(currentRasterProbe.Date) || hasValue(currentRasterProbe.CreditLine)) {
creditsHTML += `
<div class="raster-probe__credits-row">
${hasValue(currentRasterProbe.Date) ? currentRasterProbe.Date : ''}
${hasValue(currentRasterProbe.CreditLine) ? `[${currentRasterProbe.CreditLine}]` : ''}</div>
`;
}
selection
.html(creditsHTML);
},
resizeProbe({
rasterProbeContainer,
rasterProbeInnerContainer,
rasterProbeImageContainer,
}) {
const formatPadding = padding => parseInt(padding.replace('px', ''), 10);
const imageWidth = rasterProbeImageContainer.node().getBoundingClientRect().width;
const newWidth =
imageWidth +
formatPadding(rasterProbeInnerContainer.style('padding-left')) +
formatPadding(rasterProbeInnerContainer.style('padding-right'));
rasterProbeContainer
.style('width', `${newWidth}px`);
},
updateOverlayControls({
rasterProbeCloseOverlayButton,
onOverlayCloseClick,
rasterProbeControlsContainer,
currentRasterProbe,
}) {
const {
toggleOverlayControls,
setOverlayCloseButtonListener,
} = localMethods;
toggleOverlayControls({
rasterProbeControlsContainer,
currentRasterProbe,
});
setOverlayCloseButtonListener({
onOverlayCloseClick,
rasterProbeCloseOverlayButton,
});
},
drawSlider({
onSliderDrag,
overlayOpacity,
rasterProbeSliderContainer,
}) {
rasterProbeSliderContainer.select('svg').remove();
const { width } = rasterProbeSliderContainer
.node()
.getBoundingClientRect();
const slider = new TimelineSlider({
container: rasterProbeSliderContainer,
currentValue: overlayOpacity,
tooltip: false,
axisOn: false,
backgroundTrackAttrs: {
rx: 8,
ry: 8,
},
activeTrackAttrs: {
rx: 8,
ry: 8,
},
handleAttrs: {
rx: 7,
ry: 7,
},
trackHeight: 8,
handleHeight: 14,
handleWidth: 14,
padding: { left: 0, right: 2 },
valueRange: [0, 1],
stepSections: [{
increment: 1,
years: [0, 1],
}],
onDragEnd: onSliderDrag,
size: {
width,
height: 14,
},
handleDetail: false,
opacitySlider: true,
});
return slider;
},
};
export default rasterProbeMethods;
<file_sep>/**
* Module comprises pure functions related to the atlas module
* @module atlasMethods
* @memberof atlas
*/
import { tilesets, hillshades } from '../config/config';
import getProbeConfig from '../dataProbe/dataProbeGetConfig';
import atlasClickSearchMethods from './atlasClickSearchMethods';
const atlasMethods = {
getCurrentLocation({
mbMap,
}) {
const center = mbMap.getCenter();
const zoom = mbMap.getZoom();
const bearing = mbMap.getBearing();
return { center, zoom, bearing };
},
getLayerStyle({
layer,
year,
}) {
if (!('filter' in layer)) return layer;
const newLayer = Object.assign({}, layer);
newLayer.filter = layer.filter.map((f) => {
if (f[0] === 'all') {
return f.map((d, i) => {
if (i === 0) return d;
const copyFilter = [...d];
if (copyFilter[1] === 'FirstYear' || copyFilter[1] === 'LastYear') {
copyFilter[2] = year;
}
return copyFilter;
});
} else if (f[1] === 'FirstYear' || f[1] === 'LastYear') {
const copyFilter = [...f];
copyFilter[2] = year;
return copyFilter;
}
return f;
});
return newLayer;
},
getLayerOpacities({
mbMap,
}) {
return mbMap.getStyle().layers.reduce((accumulator, layer) => {
/* eslint-disable no-param-reassign */
if (layer.type === 'fill') {
const opacity = mbMap.getPaintProperty(layer.id, 'fill-opacity');
accumulator[layer.id] = opacity === undefined ? 1 : opacity;
} else if (layer.type === 'line') {
const opacity = mbMap.getPaintProperty(layer.id, 'line-opacity');
accumulator[layer.id] = opacity === undefined ? 1 : opacity;
} else {
accumulator[layer.id] = 1;
}
return accumulator;
/* eslint-enable no-param-reassign */
}, {});
},
getLayerFills({
mbMap,
}) {
return mbMap.getStyle().layers.reduce((accumulator, layer) => {
/* eslint-disable no-param-reassign */
let fill;
if (layer.type === 'fill') {
fill = mbMap.getPaintProperty(layer.id, 'fill-color');
} else if (layer.type === 'line') {
fill = mbMap.getPaintProperty(layer.id, 'line-color');
}
accumulator[layer.id] = fill;
return accumulator;
/* eslint-enable no-param-reassign */
}, {});
},
getCurrentStyle({
style,
year,
}) {
const { getLayerStyle } = atlasMethods;
const styleCopy = JSON.parse(JSON.stringify(style));
styleCopy.layers = styleCopy.layers.map(layer => getLayerStyle({ layer, year }));
return styleCopy;
},
getCurrentStyleFromMap({
mbMap,
year,
}) {
const { getCurrentStyle } = atlasMethods;
return getCurrentStyle({
style: mbMap.getStyle(),
year,
});
},
updateTileSet(style) {
const updatedSource = style;
if (/[?&]dev=true/.test(window.location.search)) {
updatedSource.sources.composite.url = tilesets.dev;
updatedSource.sources[hillshades.prod].url = hillshades.dev;
}
return updatedSource;
},
getMap({
viewshedsGeo,
initApp,
style,
getLanguage,
translations,
getCurrentView,
setCancelClickSearch,
getRasterData,
onViewClick,
onMove,
dataProbe,
onLayerSourceData,
onFeatureSourceData,
onReturnToSearch,
}) {
const {
addConeToMap,
removeCone,
getCurrentLocation,
} = atlasMethods;
const { removePulse } = atlasClickSearchMethods;
let coneFeature;
const mbMap = new mapboxgl.Map({
minZoom: 8,
maxZoom: 17,
maxBounds: [[-49.6726203, -17.0908045], [-46.4447028, -12.9291031]],
logoPosition: 'bottom-right',
container: 'map',
style,
preserveDrawingBuffer: true,
attributionControl: true,
})
.on('moveend', () => {
const currentLocation = getCurrentLocation({ mbMap });
onMove(currentLocation);
})
.on('movestart', () => {
removePulse();
})
.on('load', () => {
initApp();
})
.on('sourcedata', () => {
onLayerSourceData();
onReturnToSearch();
onFeatureSourceData();
})
.on('mouseover', 'viewconespoint', (d) => {
coneFeature = viewshedsGeo.features.find(cone =>
cone.properties.SS_ID === d.features[0].properties.SS_ID);
const offset = 15;
const probeConfig = getProbeConfig({
data: coneFeature.properties,
position: {
left: d.point.x + offset,
bottom: (window.innerHeight - d.point.y) + offset,
width: 200,
},
clickText: translations['click-for-details'][getLanguage()],
});
dataProbe
.config(probeConfig)
.draw();
const currentView = getCurrentView();
if (currentView !== null &&
currentView.SS_ID !== coneFeature.properties.SS_ID) {
const viewCone = viewshedsGeo.features.find(cone =>
cone.properties.SS_ID === currentView.SS_ID);
addConeToMap({
coneFeature: {
type: 'FeatureCollection',
features: [coneFeature, viewCone],
},
mbMap,
});
} else {
addConeToMap({
coneFeature,
mbMap,
});
}
})
.on('mouseout', 'viewconespoint', () => {
const currentView = getCurrentView();
dataProbe.remove();
removeCone({ mbMap });
if (currentView !== null) {
const viewCone = viewshedsGeo.features.find(cone =>
cone.properties.SS_ID === currentView.SS_ID);
addConeToMap({
mbMap,
coneFeature: viewCone,
});
}
})
.on('click', 'viewconespoint', () => {
const views = getRasterData().get('views');
const newView = views.find(d => d.SS_ID === coneFeature.properties.SS_ID);
onViewClick(newView);
setCancelClickSearch();
});
return mbMap;
},
addConeToMap({
coneFeature,
mbMap,
}) {
if (mbMap.getLayer('viewshed-feature') !== undefined) {
mbMap.removeLayer('viewshed-feature');
}
const existingSource = mbMap.getSource('viewshed');
if (existingSource === undefined) {
mbMap.addSource('viewshed', {
type: 'geojson',
data: coneFeature,
});
} else {
existingSource.setData(coneFeature);
}
mbMap.addLayer({
id: 'viewshed-feature',
type: 'fill',
source: 'viewshed',
layout: {},
paint: {
'fill-color': 'white',
'fill-opacity': 0.5,
},
});
},
removeCone({
mbMap,
}) {
const existingLayer = mbMap.getLayer('viewshed-feature');
if (existingLayer === undefined) return;
mbMap.removeLayer('viewshed-feature');
},
updateYear({
year,
mbMap,
}) {
const {
getLayerStyle,
} = atlasMethods;
const styleCopy = JSON.parse(JSON.stringify(mbMap.getStyle()));
styleCopy.layers = styleCopy.layers.map(layer => getLayerStyle({ layer, year }));
mbMap.setStyle(styleCopy);
},
getMapLayers(mbMap) {
return mbMap
.getStyle()
.layers
.map(d => mbMap.getLayer(d.id));
},
getSourceLayers(mbMap) {
const sources = mbMap
.getStyle()
.layers
.map(d => d['source-layer'])
.filter(d => d !== undefined);
return [...new Set(sources)];
},
};
export default atlasMethods;
<file_sep>/**
* Module comprises methods related to timeline axis
* @module timelineSliderAxis
* @memberof timeline
*/
const axisMethods = ({ privateProps, privateMethods }) => ({
initAxis() {
const {
drawAxisGroup,
setAxisGenerator,
updateAxis,
} = privateMethods;
const { axisOn } = privateProps.get(this);
if (!axisOn) return;
drawAxisGroup.call(this);
setAxisGenerator.call(this);
updateAxis.call(this);
},
drawAxisGroup() {
const props = privateProps.get(this);
const {
trackHeight,
svg,
size,
} = props;
const { height } = size;
props.axisGroup = svg.append('g')
.attrs({
transform: `translate(0, ${(height / 2) - (trackHeight / 2)})`,
class: 'slider__axis',
});
},
setAxisGenerator() {
const props = privateProps.get(this);
const {
scale,
stepSections,
mobile,
} = props;
const { isLabeledTick } = privateMethods;
const tickValues = [1900, 1915, 1930, 1945];
const span2 = stepSections[1];
const increment2 = 5;
const numTicks2 = Math.round((span2.years[1] - span2.years[0]) / increment2);
const startValSeg2 = 1950;
for (let i = 1;
i < numTicks2;
i += 1
) {
tickValues.push(Math.round(startValSeg2 + ((i + 1) * increment2)));
}
props.axis = d3.axisBottom(scale)
.tickValues(tickValues)
.tickFormat(d => (isLabeledTick({ value: d, breakpoint: stepSections[0].years[1] }) && !mobile ? d : ''));
},
isLabeledTick({ value, breakpoint }) {
if (value > breakpoint) {
return value % 10 === 0;
}
return [1900, 1930].includes(value);
},
updateAxis() {
const props = privateProps.get(this);
const {
axisGroup,
axis,
axisOn,
stepSections,
} = props;
const { isLabeledTick } = privateMethods;
if (!axisOn) return;
axisGroup
.call(axis);
axisGroup
.selectAll('.tick')
.each(function setMinorTick(d) {
const tick = d3.select(this).select('line');
if (!isLabeledTick({ value: d, breakpoint: stepSections[0].years[1] })) {
tick.attr('y2', 10);
}
});
},
});
export default axisMethods;
<file_sep>/**
* Module initializes rasterProbe component
* @module initRasterProbe
*/
import RasterProbe from '../rasterProbe/rasterProbe';
const initRasterProbe = function initRasterProbe() {
const { state } = this.components;
this.components.rasterProbe = new RasterProbe({
cachedMetadata: this.cachedMetadata,
currentView: state.get('currentView'),
currentOverlay: state.get('currentOverlay'),
overlayOpacity: state.get('overlayOpacity'),
mobile: state.get('mobile'),
onCloseClick() {
const currentRasterProbe = state.get('currentRasterProbe');
const { type } = currentRasterProbe;
if (type === 'view') {
state.update({
currentView: null,
currentRasterProbe: null,
});
} else if (type === 'overlay') {
state.update({
currentRasterProbe: null,
});
}
},
onOverlayCloseClick() {
state.update({
currentOverlay: null,
currentRasterProbe: null,
});
},
onSliderDrag(newOpacity) {
state.update({
overlayOpacity: newOpacity,
});
},
});
};
export default initRasterProbe;
<file_sep>/**
* Initializes components, sets callbacks for changes to application state
* @module index
*/
import setStateEvents from './stateUpdate/stateUpdate';
import initState from './initComponents/initState';
import initData from './initComponents/initData';
import initURL from './initComponents/initURL';
import initAtlas from './initComponents/initAtlas';
import initSidebar from './initComponents/initSidebar';
import initFooter from './initComponents/initFooter';
import initViews from './initComponents/initViews';
import initIntro from './initComponents/initIntro';
import initEras from './initComponents/initEras';
import initLayout from './initComponents/initLayout';
import initTimeline from './initComponents/initTimeline';
import initRasterProbe from './initComponents/initRasterProbe';
require('../scss/index.scss');
const app = {
components: {},
data: null,
cachedMetadata: new Map(),
init() {
initData((cleanedData) => {
this.data = cleanedData;
this.initURL();
this.initState();
this.setStateEvents();
this.initAtlas();
this.initViews();
this.initIntro();
this.initEras();
this.initLayout();
});
},
initURL,
initState,
initViews,
initIntro,
initEras,
initAtlas,
initLayout,
initComponents() {
const {
state,
} = this.components;
setTimeout(() => {
d3.select('.mapboxgl-ctrl-attrib')
.styles({
opacity: 1,
})
.html(`
<a href="https://www.mapbox.com/about/maps/" target="_blank">© Mapbox</a>
<a class="mapbox-improve-map" href="https://www.mapbox.com/feedback/?owner=axismaps&id=cjlxzhuj652652smt1jf50bq5&access_token=<KEY>" target="_blank">Improve this map</a>
<a href="https://www.digitalglobe.com/" target="_blank">© DigitalGlobe</a>
`);
}, 1000);
initTimeline.call(this);
initRasterProbe.call(this);
initFooter.call(this);
initSidebar.call(this);
state.update({ componentsInitialized: true });
},
setStateEvents() {
setStateEvents({ components: this.components, data: this.data });
},
listenForResize() {
const { state } = this.components;
d3.select(window).on('resize', () => {
state.update({ screenSize: [window.innerWidth, window.innerHeight] });
});
},
};
app.init();
<file_sep>const fs = require('fs');
const path = require('path');
const _ = require('underscore');
const config = {};
let loaded = 0;
let total = 0;
function getProps(json) {
return json.features.map(f => f.properties);
}
function getStyleInfo() {
fs.readFile(path.join(__dirname, '../src/data/style.json'), (err, data) => {
const json = JSON.parse(data);
_.each(config, (l, name) => {
const layer = l;
let unmatch = true;
const styles = _.filter(json.layers, lay => lay['source-layer'] === name);
_.each(layer.features, (f, fname) => {
const feature = f;
const id = _.find(styles, (s) => {
const filter = _.flatten(s.filter);
return _.some(filter, f1 => f1 === fname);
});
if (id) {
feature.style = id.id;
unmatch = false;
}
});
if (unmatch && styles.length === 1) {
layer.style = styles[0].id;
}
});
fs.writeFile(path.join(__dirname, '../src/data/config.json'), JSON.stringify(config, null, 2), () => {
console.log('FILE WRITTEN');
});
});
}
function extendYears(years, first, last) {
if (years) {
const y = years;
let i = 0;
for (i; i < y.length; i += 1) {
if ((y[i][0] <= first + 1 && y[i][1] >= first - 1) || (y[i][0] <= last + 1 && y[i][1] >= last - 1)) {
y[i][0] = Math.min(y[i][0], first);
y[i][1] = Math.max(y[i][1], last);
break;
}
}
if (i === y.length) {
y.push([first, last]);
}
return _.sortBy(y, a => a[0]);
}
return [[first, last]];
}
function writeStatic(f) {
fs.readFile(path.join(__dirname, '../data/geojson/geography', f), (err2, data) => {
const name = f.replace(/\.json$/, '');
const json = JSON.parse(data);
const props = getProps(json);
const layer = {};
layer.features = {};
layer.group = name === 'WatersLine' || name === 'WaterBodiesPoly' || name === 'OpenSpacesPoly' ? 'Landscape' : 'Urbanism';
layer.icon = json.features[0].geometry.type === 'LineString' ? 'line.svg' : 'poly.svg';
// Fake translation for now
layer.en = name;
layer.pr = name;
props.forEach((p) => {
layer.startYear = layer.startYear ? Math.min(layer.startYear, p.FirstYear) : p.FirstYear;
layer.endYear = layer.endYear ? Math.max(layer.endYear, p.LastYear) : p.LastYear;
if (p.SubType) {
const sub = p.SubType;
if (!layer.features[sub]) layer.features[sub] = {};
// Fake translation for now
layer.features[sub].en = sub;
layer.features[sub].pr = sub;
layer.features[sub].years = extendYears(layer.features[sub].years, p.FirstYear, p.LastYear);
}
});
config[name] = layer;
loaded += 1;
if (loaded === total) getStyleInfo();
});
}
fs.readdir(path.join(__dirname, '../data/geojson/geography'), (err, files) => {
total = files.length;
files.forEach(writeStatic);
});
<file_sep>/**
* Module initializes sidebar component
* @module initSidebar
*/
import Sidebar from '../sidebar/sidebar';
import rasterMethods from '../rasterProbe/rasterMethods';
const initSidebar = function initSidebar() {
const { state } = this.components;
const { onRasterClick } = rasterMethods;
this.components.sidebar = new Sidebar({
mobile: state.get('mobile'),
highlightedFeature: state.get('highlightedFeature'),
highlightedLayer: state.get('highlightedLayer'),
sidebarOpen: state.get('sidebarOpen'),
layerStyles: this.components.atlas.getStyle().layers,
availableLayers: state.getAvailableLayers(this.data),
legendSwatches: this.data.legendSwatches,
viewLayersOn: state.getAvailableRasters(this.data).get('views').length > 0,
cachedMetadata: this.cachedMetadata,
translations: this.data.translations,
language: state.get('language'),
view: state.get('sidebarView'),
onSearchReturn() {
if (!state.get('mobile')) {
state.update({ highlightedFeature: null });
}
},
onLayerClick(layer) {
const currentLayers = state.get('currentLayers');
const layerIndex = currentLayers.map(d => d.sourceLayer)
.indexOf(layer.sourceLayer);
const newLayers = [
...currentLayers.slice(0, layerIndex),
{ sourceLayer: layer.sourceLayer, status: !currentLayers[layerIndex].status },
...currentLayers.slice(layerIndex + 1),
];
const stateToUpdate = { currentLayers: newLayers };
state.update(stateToUpdate);
},
onRasterClick(rasterData) {
onRasterClick({ rasterData, state });
},
onTextInput(val) {
state.update({ textSearch: val });
},
onLayerHighlightClick(newLayer) {
const currentHighlightedLayer = state.get('highlightedLayer');
const stateToUpdate = {};
const highlight = currentHighlightedLayer === null ||
currentHighlightedLayer.dataLayer !== newLayer.dataLayer;
if (highlight) {
Object.assign(stateToUpdate, { highlightedLayer: newLayer });
} else {
Object.assign(stateToUpdate, { highlightedLayer: null });
}
if (state.get('mobile') && highlight) {
Object.assign(stateToUpdate, { sidebarOpen: false });
}
state.update(stateToUpdate);
},
onFeatureClick(feature) {
const oldFeature = state.get('highlightedFeature');
const highlight = oldFeature === null ||
feature.id !== oldFeature.id;
const stateToUpdate = {};
if (highlight) {
Object.assign(stateToUpdate, { highlightedFeature: feature });
} else {
Object.assign(stateToUpdate, { highlightedFeature: null });
}
if (state.get('mobile') && highlight) {
Object.assign(stateToUpdate, { sidebarOpen: false });
}
state.update(stateToUpdate);
},
});
};
export default initSidebar;
<file_sep>/**
* Module comprises functions related to data manipulation
* @module data
*/
import { eras } from '../config/config';
/**
* Parses all initial async data
* @param {Object} rawData
* @return {Object} clean, processed data
* @memberof data
*/
export const cleanData = (rawData) => {
const [
rawLayers,
rawViewsheds,
rawAerials,
rawMaps,
rawPlans,
rawExtents,
rawYears,
rawTranslations,
rawLegendSwatches,
] = rawData;
const layerGroups = [
'Views',
'Landscape',
'Urbanism',
];
const layers = layerGroups
.map((group) => {
const groupRecord = {
group,
layers: Object.keys(rawLayers)
.filter(groupKey => rawLayers[groupKey].group === group)
.map((groupKey) => {
const layerRecord = Object.assign({}, rawLayers[groupKey]);
layerRecord.sourceLayer = groupKey;
layerRecord.features = Object.keys(layerRecord.features)
.map((featureKey) => {
const featureRecord = Object.assign({}, layerRecord.features[featureKey]);
featureRecord.dataLayer = featureKey;
return featureRecord;
});
return layerRecord;
}),
};
return groupRecord;
});
const views = rawViewsheds.features.map((d) => {
const record = Object.assign({}, d.properties);
record.type = 'view';
return record;
});
const processOverlay = data => data.map((d) => {
const record = Object.assign({}, d);
record.type = 'overlay';
return record;
});
const translations = rawTranslations
.reduce((accumulator, d) => {
const { en, pr } = d;
/* eslint-disable no-param-reassign */
accumulator[`${d.id}`] = { en, pr };
/* eslint-enable no-param-reassign */
return accumulator;
}, {});
const erasWithTranslations = eras.map(d => Object.assign({}, d, translations[d.id]));
const rasters = new Map();
rasters.set('views', views);
rasters.set('maps', processOverlay(rawMaps));
rasters.set('plans', processOverlay(rawPlans));
rasters.set('aerials', processOverlay(rawAerials));
const data = {
layers,
viewshedsGeo: rawViewsheds,
rasters,
translations,
eras: erasWithTranslations,
extents: rawExtents,
years: rawYears,
legendSwatches: rawLegendSwatches,
};
return data;
};
/**
* Returns unique, non-empty non-raster search results from all non-rasters
* @param {Array} nonRasters non-raster search results
* @return {Array} unique, non-empty results
* @memberof data
*/
export const formatNonRasterResults = nonRasters =>
[...new Set(nonRasters.map(d => d.sourceLayer))]
.map(sourceLayer => ({
sourceLayer,
features: nonRasters
.filter(d => d.sourceLayer === sourceLayer)
.filter(d => d.properties.Name !== ''),
}))
.filter(d => d.features.length > 0);
/**
* Returns unique, non-empty raster search results from all rasters
* @param {Array} rasters raster search results
* @return {Array} unique, non-empty results
* @memberof data
*/
export const formatRasterResults = rasters =>
[...new Set(rasters.map(d => d.category))]
.map(category => ({
category,
features: rasters
.filter(d => d.category === category),
}))
.filter(d => d.features.length > 0);
/**
* Returns raster search results from raw results
* @memberof data
* @param {Array} features results from vector tile query
* @return {Array} raster result features
*/
export const getRasterResults = features =>
features.filter(d => Object.prototype.hasOwnProperty.call(d.properties, 'SS_ID') &&
d.source !== 'viewshed');
/**
* Returns non-raster search results from raw results
* @memberof data
* @param {Array} features results from vector tile query
* @return {Array} non-raster search results
*/
export const getNonRasterResults = features =>
features.filter(d =>
!Object.prototype.hasOwnProperty.call(d.properties, 'SS_ID') &&
Object.prototype.hasOwnProperty.call(d.properties, 'Name') &&
(d.geometry.type.includes('String') ||
d.geometry.type.includes('Polygon')) &&
d.source !== 'highlighted');
<file_sep>const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
module.exports = {
entry: ['babel-polyfill', './src/js/index.js'],
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
},
watch: false,
mode: 'production',
module: {
rules: [
{
test: /\.js$/,
exclude: [/node_modules/],
loader: 'babel-loader',
query: {
presets: ['env'],
},
},
{
test: /\.scss$/,
use: [
MiniCssExtractPlugin.loader,
'css-loader',
'sass-loader',
],
},
{
test: /\.(jpg|png|woff|woff2|eot|ttf|svg)$/,
loader: 'url-loader?limit=100000',
},
],
},
plugins: [
new MiniCssExtractPlugin({ filename: 'styles.css' }),
new HtmlWebpackPlugin({
template: path.join(__dirname, 'src/html/index.html'),
filename: path.join(__dirname, 'dist/index.html'),
}),
new CopyWebpackPlugin([
{
from: 'src/data/*',
to: 'data',
flatten: true,
},
]),
],
};
<file_sep>/**
* Callback for year field
* "year" integer represents map year
* @module
* @memberof stateUpdate
*/
import rasterMethods from '../rasterProbe/rasterMethods';
const getUpdateYear = ({
components,
data,
}) => {
const updateYear = function updateYear() {
const {
timeline,
atlas,
sidebar,
footer,
eras,
layout,
urlParams,
} = components;
const {
year,
footerView,
componentsInitialized,
} = this.props();
const {
getRasterDataByCategory,
} = rasterMethods;
const rasterData = this.getAvailableRasters(data);
const rasterDataByCategory = getRasterDataByCategory({ rasterData });
atlas
.config({
year,
rasterData,
})
.updateYear();
eras
.config({
year,
})
.updateEra();
urlParams
.config({
year,
})
.update();
if (!componentsInitialized) {
if (rasterDataByCategory.length === 0) {
this.set('footerView', 'views');
} else if (rasterData.get(footerView).length === 0) {
this.set('footerView', rasterDataByCategory[0].key);
}
return;
}
const currentEra = eras.getCurrentEra();
layout
.config({
currentEra,
year,
})
.updateEra();
timeline
.config({
year,
})
.updateYear();
footer
.config({
year,
rasterData,
})
.updateRasterData();
const availableLayers = this.getAvailableLayers(data);
sidebar
.config({
viewLayersOn: this.getAvailableRasters(data).get('views').length > 0,
availableLayers,
})
.updateAvailableLayers();
atlas.config({ availableLayers });
const stateToUpdate = {
currentLayers: this.getAllAvailableLayers(data),
};
const sidebarView = sidebar.getView();
if (sidebarView === 'textSearch') {
Object.assign(stateToUpdate, { textSearch: sidebar.getSearchText() });
} else if (sidebarView === 'clickSearch') {
sidebar
.clearSearch();
}
{
const currentFooterCategory = this.getAutoFooterView(data);
if (footerView !== currentFooterCategory) {
Object.assign(stateToUpdate, { footerView: currentFooterCategory });
}
}
const layersToClear = this.getLayersToClear([
'currentOverlay',
'highlightedFeature',
'currentRasterProbe',
'currentView',
'highlightedLayer',
]);
Object.assign(stateToUpdate, layersToClear);
this.update(stateToUpdate);
};
return updateYear;
};
export default getUpdateYear;
<file_sep>/**
* Module comprises pubic methods for the atlas module (Atlas class prototype)
* @module atlasPublicMethods
* @memberof atlas
*/
import { getNonRasterResults } from '../data/data';
import rasterMethods from '../rasterProbe/rasterMethods';
import generalMethods from './atlasMethods';
const getPublicMethods = ({ privateProps }) => ({
config(config) {
Object.assign(privateProps.get(this), config);
return this;
},
getStyle() {
const { mbMap } = privateProps.get(this);
return mbMap.getStyle();
},
textSearch(value) {
const {
mbMap,
rasterData,
year,
} = privateProps.get(this);
const { getSourceLayers } = generalMethods;
const { getFlattenedRasterData } = rasterMethods;
const flattenedRasterData = getFlattenedRasterData({ rasterData });
const sourceLayers = getSourceLayers(mbMap);
const queriedFeatures = sourceLayers.reduce((accumulator, sourceLayer) => {
const results = mbMap.querySourceFeatures('composite', {
sourceLayer,
filter: [
'all',
['<=', 'FirstYear', year],
['>=', 'LastYear', year],
],
});
const resultsWithSource = results.map((d) => {
const record = Object.assign({}, d.toJSON(), { sourceLayer });
return record;
});
return [...accumulator, ...resultsWithSource];
}, []);
const rasterResults = flattenedRasterData
.filter(d => d.Title.toLowerCase().includes(value.toLowerCase()));
const nonRasterResults = getNonRasterResults(queriedFeatures)
.filter(d => d.properties.Name.toLowerCase().includes(value.toLowerCase()));
return {
raster: rasterResults,
nonRaster: nonRasterResults,
};
},
getMapExportLink() {
const { mbMap } = privateProps.get(this);
return mbMap.getCanvas().toDataURL('image/png');
},
getContext() {
const { mbMap } = privateProps.get(this);
return mbMap.getCanvas().getContext('webgl');
},
getCanvas() {
const { mbMap } = privateProps.get(this);
return mbMap.getCanvas();
},
setSearchLocation() {
const props = privateProps.get(this);
const { mbMap } = props;
const {
getCurrentLocation,
} = generalMethods;
props.searchLocation = getCurrentLocation({ mbMap });
},
});
export default getPublicMethods;
<file_sep>/**
* Module for raster probe and raster lightbox
* @module rasterProbe
*/
import { selections } from '../config/config';
import rasterProbeMethods from './rasterProbeMethods';
import lightboxMethods from './rasterProbeLightboxMethods';
const privateProps = new WeakMap();
const privateMethods = {
init() {
const {
rasterProbeCloseButton,
onCloseClick,
} = privateProps.get(this);
const {
setCloseButtonListener,
} = rasterProbeMethods;
setCloseButtonListener({
rasterProbeCloseButton,
onCloseClick,
});
},
drawProbe() {
const props = privateProps.get(this);
const {
currentRasterProbe,
rasterProbeTitleContainer,
cachedMetadata,
cachedSharedShelfURLs,
rasterProbeImageContainer,
rasterProbeControlsContainer,
rasterProbeCloseOverlayButton,
rasterProbeCreditsContainer,
rasterProbeContainer,
rasterProbeSliderContainer,
rasterProbeInnerContainer,
onOverlayCloseClick,
lightboxOuterContainer,
lightboxContentContainer,
lightboxImageContainer,
lightboxMetadataContainer,
lightboxCreditsContainer,
lightboxSharedShelfButton,
lightboxCloseButton,
onSliderDrag,
overlayOpacity,
mobile,
} = props;
const {
updateTitle,
updateImage,
updateCredits,
updateOverlayControls,
resizeProbe,
drawSlider,
} = rasterProbeMethods;
const {
initLightbox,
closeLightbox,
} = lightboxMethods;
if (currentRasterProbe === null) {
closeLightbox({ lightboxOuterContainer });
return;
}
updateTitle({
rasterProbeTitleContainer,
currentRasterProbe,
});
updateImage({
currentRasterProbe,
cachedMetadata,
rasterProbeImageContainer,
mobile,
rasterProbeInnerContainer,
onImageClick: () => {
initLightbox({
currentRasterProbe,
lightboxOuterContainer,
lightboxContentContainer,
lightboxImageContainer,
lightboxMetadataContainer,
lightboxCreditsContainer,
lightboxSharedShelfButton,
lightboxCloseButton,
cachedMetadata,
mobile,
cachedSharedShelfURLs,
});
},
});
resizeProbe({
rasterProbeContainer,
rasterProbeInnerContainer,
rasterProbeImageContainer,
});
updateCredits({
selection: rasterProbeCreditsContainer,
currentRasterProbe,
});
updateOverlayControls({
rasterProbeCloseOverlayButton,
rasterProbeControlsContainer,
currentRasterProbe,
onOverlayCloseClick,
});
if (currentRasterProbe.type === 'view') return;
props.slider = drawSlider({
onSliderDrag,
overlayOpacity,
rasterProbeSliderContainer,
});
},
};
class RasterProbe {
constructor(config) {
const {
rasterProbeTitleContainer,
rasterProbeImageContainer,
rasterProbeOverlayControlContainer,
rasterProbeCloseButton,
rasterProbeControlsContainer,
rasterProbeCloseOverlayButton,
rasterProbeCreditsContainer,
rasterProbeContainer,
rasterProbeSliderContainer,
rasterProbeInnerContainer,
lightboxOuterContainer,
lightboxContentContainer,
lightboxImageContainer,
lightboxMetadataContainer,
lightboxCreditsContainer,
lightboxSharedShelfButton,
lightboxCloseButton,
} = selections;
privateProps.set(this, {
rasterProbeTitleContainer,
rasterProbeImageContainer,
rasterProbeOverlayControlContainer,
rasterProbeCloseButton,
rasterProbeControlsContainer,
rasterProbeCloseOverlayButton,
rasterProbeCreditsContainer,
rasterProbeContainer,
rasterProbeInnerContainer,
rasterProbeSliderContainer,
lightboxOuterContainer,
lightboxContentContainer,
lightboxImageContainer,
lightboxMetadataContainer,
lightboxCreditsContainer,
lightboxSharedShelfButton,
lightboxCloseButton,
currentRasterProbe: null,
onCloseClick: null,
onOverlayCloseClick: null,
cachedMetadata: null,
cachedSharedShelfURLs: new Map(),
});
const {
init,
} = privateMethods;
this.config(config);
init.call(this);
}
config(config) {
Object.assign(privateProps.get(this), config);
return this;
}
update() {
const {
drawProbe,
} = privateMethods;
drawProbe.call(this);
}
updateSlider() {
const props = privateProps.get(this);
const {
slider,
overlayOpacity,
} = props;
if (slider === undefined || slider === null) return;
slider
.config({ currentValue: overlayOpacity })
.update();
}
}
export default RasterProbe;
<file_sep>/**
* Module comprises methods related to both intro eras dropdown
* @module introEraDropdown
* @memberof intro
*/
import setDropdownListeners from './introDropdownBase';
import { selections } from '../config/config';
const privateProps = new WeakMap();
const privateMethods = {
init() {
const props = privateProps.get(this);
const {
introJumpButtonContainer,
introJumpDropdownContainer,
} = props;
setDropdownListeners({
buttonContainer: introJumpButtonContainer,
dropdownContainer: introJumpDropdownContainer,
getTimer: () => props.timer,
setTimer: (newTimer) => {
props.timer = newTimer;
},
});
this.update();
},
setContent({
eras,
introJumpDropdownContent,
onClick,
language,
}) {
introJumpDropdownContent
.selectAll('.intro__jump-dropdown-item')
.remove();
introJumpDropdownContent
.selectAll('.intro__jump-dropdown-item')
.data(eras)
.enter()
.append('div')
.attr('class', 'intro__jump-dropdown-item')
.text(d => d[language])
.on('click', onClick);
},
setTitleText({
introJumpButtonText,
translations,
language,
}) {
introJumpButtonText
.text(translations['jump-to-era'][language]);
},
};
class EraDropdown {
constructor(config) {
const {
introJumpButtonContainer,
introJumpDropdownContainer,
introJumpDropdownContent,
introJumpButtonText,
} = selections;
const {
init,
} = privateMethods;
privateProps.set(this, {
introJumpButtonContainer,
introJumpDropdownContainer,
introJumpDropdownContent,
introJumpButtonText,
onClick: null,
language: null,
translations: null,
eras: null,
timer: null,
});
this.config(config);
init.call(this);
}
config(config) {
Object.assign(privateProps.get(this), config);
return this;
}
update() {
const {
eras,
introJumpDropdownContent,
introJumpButtonText,
language,
onClick,
translations,
} = privateProps.get(this);
const {
setContent,
setTitleText,
} = privateMethods;
setTitleText({
introJumpButtonText,
translations,
language,
});
setContent({
eras,
introJumpDropdownContent,
onClick,
language,
});
return this;
}
}
export default EraDropdown;
<file_sep>/**
* Callbacks that fire on changes to application state
* @module stateUpdate
*/
import getUpdateYear from './stateUpdateYear';
import getUpdateView from './stateUpdateView';
import getUpdateTextSearch from './stateUpdateTextSearch';
import getUpdateLanguage from './stateUpdateLanguage';
import getStateUpdateCurrentLocation from './stateUpdateCurrentLocation';
import getUpdateClickSearch from './stateUpdateClickSearch';
import getAreaSearch from './stateUpdateAreaSearch';
import getUpdateHighlightedLayer from './stateUpdateHighlightedLayer';
import getUpdateAllRasterOpen from './stateUpdateAllRasterOpen';
import getUpdateTransitionsDisabled from './stateUpdateTransitionsDisabled';
import getUpdateScreenSize from './stateUpdateScreenSize';
import getUpdateSidebarOpen from './stateUpdateSidebarOpen';
import getUpdateFooterOpen from './stateUpdateFooterOpen';
import getUpdateCurrentLayers from './stateUpdateCurrentLayers';
import getUpdateAreaSearchActive from './stateUpdateAreaSearchActive';
import getUpdateHighlightedFeature from './stateUpdateHighlightedFeature';
import getUpdateCurrentOverlay from './stateUpdateCurrentOverlay';
import getUpdateCurrentView from './stateUpdateCurrentView';
import getUpdateCurrentRasterProbe from './stateUpdateCurrentRasterProbe';
import getUpdateFooterView from './stateUpdateFooterView';
import getUpdateMouseEventsDisabled from './stateUpdateMouseEventsDisabled';
import getUpdateMapLoaded from './stateUpdateMapLoaded';
import getUpdateOverlayOpacity from './stateUpdateOverlayOpacity';
import getUpdateRegisterOpen from './stateUpdateRegisterOpen';
const setStateEvents = ({ components, data }) => {
const { state } = components;
state.registerCallbacks({
highlightedLayer: getUpdateHighlightedLayer({ components }),
year: getUpdateYear({ data, components }),
view: getUpdateView({ components }),
language: getUpdateLanguage({ data, components }),
currentLocation: getStateUpdateCurrentLocation({ components }),
textSearch: getUpdateTextSearch({ components }),
clickSearch: getUpdateClickSearch({ components }),
transitionsDisabled: getUpdateTransitionsDisabled({ components }),
screenSize: getUpdateScreenSize({ components }),
sidebarOpen: getUpdateSidebarOpen({ components }),
footerOpen: getUpdateFooterOpen({ components }),
currentLayers: getUpdateCurrentLayers({ components }),
areaSearch: getAreaSearch({ components }),
areaSearchActive: getUpdateAreaSearchActive({ components }),
highlightedFeature: getUpdateHighlightedFeature({ components }),
currentOverlay: getUpdateCurrentOverlay({ components }),
currentView: getUpdateCurrentView({ components }),
currentRasterProbe: getUpdateCurrentRasterProbe({ components }),
footerView: getUpdateFooterView({ components, data }),
allRasterOpen: getUpdateAllRasterOpen({ components }),
mouseEventsDisabled: getUpdateMouseEventsDisabled({ components }),
mapLoaded: getUpdateMapLoaded({ components }),
overlayOpacity: getUpdateOverlayOpacity({ components }),
registerOpen: getUpdateRegisterOpen({ components }),
});
};
export default setStateEvents;
<file_sep>/**
* Module for sidebar--layers menu, search results, text search input
* @module sidebar
*/
import searchMethods from './sidebarSearch';
import getSidebarMethods from './sidebarGetPrivateMethods';
import { selections } from '../config/config';
const privateProps = new WeakMap();
const privateMethods = getSidebarMethods(privateProps);
class Sidebar {
constructor(config) {
const {
sidebarContainer,
sidebarContentContainer,
searchReturnContainer,
textSearchReturnButton,
textSearchReturnButtonMobile,
searchInput,
resultsContainer,
rasterResultsContainer,
nonRasterResultsContainer,
sidebarViewshedLayerBlock,
sidebarViewshedLayerRow,
sidebarViewshedLayerIconContainer,
sidebarToggleButtonText,
} = selections;
const {
init,
} = privateMethods;
privateProps.set(this, {
sidebarContainer,
sidebarContentContainer,
searchReturnContainer,
textSearchReturnButton,
textSearchReturnButtonMobile,
searchInput,
resultsContainer,
rasterResultsContainer,
nonRasterResultsContainer,
sidebarViewshedLayerBlock,
sidebarViewshedLayerRow,
sidebarViewshedLayerIconContainer,
sidebarToggleButtonText,
cachedSwatches: new Map(),
view: null,
previousView: null,
results: null,
availableLayers: null,
viewLayerOn: true,
highlightedFeature: null,
highlightedLayer: null,
});
this.config(config);
privateProps.get(this).previousView = config.view;
init.call(this);
}
config(config) {
Object.assign(privateProps.get(this), config);
return this;
}
updateAvailableLayers() {
const {
setViewLayerVisibility,
drawLayerGroups,
drawLayers,
drawFeatures,
} = privateMethods;
setViewLayerVisibility.call(this);
drawLayerGroups.call(this);
drawLayers.call(this);
drawFeatures.call(this);
}
updateCurrentLayers() {
const {
currentLayers,
layers,
sidebarViewshedLayerRow,
} = privateProps.get(this);
const updateCheck = ({ check, sourceLayer }) => {
if (!currentLayers.map(d => d.sourceLayer).includes(sourceLayer)) return;
check.property('checked', currentLayers.find(dd => dd.sourceLayer === sourceLayer).status);
};
updateCheck({
check: sidebarViewshedLayerRow.select('.sidebar__layer-checkbox'),
sourceLayer: 'ViewConesPoint',
});
layers.each(function checkBox(d) {
const row = d3.select(this);
const check = row.select('.sidebar__layer-checkbox');
updateCheck({ check, sourceLayer: d.sourceLayer });
});
}
updateHighlightedFeature() {
const {
sidebarContentContainer,
highlightedFeature,
nonRasterResultsContainer,
} = privateProps.get(this);
const isHighlightedFeature = (d) => {
if (highlightedFeature === null) {
return false;
}
const isFullLayer = feature => Object.prototype.hasOwnProperty.call(feature, 'dataLayer');
if (isFullLayer(d) && isFullLayer(highlightedFeature)) {
return d.dataLayer === highlightedFeature.dataLayer;
} else if (!isFullLayer(d) && !isFullLayer(highlightedFeature)) {
return d.id === highlightedFeature.id;
}
return false;
};
sidebarContentContainer
.selectAll('.sidebar__feature-button')
.classed('sidebar__feature-button--highlighted', isHighlightedFeature);
nonRasterResultsContainer
.selectAll('.sidebar__results-button')
.classed('sidebar__results-button--highlighted', isHighlightedFeature);
}
updateHighlightedLayer() {
const {
sidebarContentContainer,
highlightedLayer,
} = privateProps.get(this);
const isHighlightedLayer = (d) => {
if (highlightedLayer === null) {
return false;
}
return d.dataLayer === highlightedLayer.dataLayer;
};
sidebarContentContainer
.selectAll('.sidebar__feature-button')
.classed('sidebar__feature-button--highlighted', isHighlightedLayer);
}
updateResults() {
const props = privateProps.get(this);
const {
view,
previousView,
nonRasterResultsContainer,
rasterResultsContainer,
results,
onFeatureClick,
onRasterClick,
cachedMetadata,
translations,
language,
} = props;
const {
setSidebarClass,
} = privateMethods;
const {
drawRasterSearchResults,
drawNonRasterSearchResults,
} = searchMethods;
if (previousView === 'legend' && view === 'legend') return;
setSidebarClass.call(this);
drawRasterSearchResults({
language,
translations,
onRasterClick,
container: rasterResultsContainer,
results: results === null ? [] : results.raster,
onFeatureClick,
cachedMetadata,
});
drawNonRasterSearchResults({
language,
translations,
container: nonRasterResultsContainer,
results: results === null ? [] : results.nonRaster,
onFeatureClick,
});
props.previousView = view;
}
getView() {
return privateProps.get(this).view;
}
getSearchText() {
const {
searchInput,
} = privateProps.get(this);
return searchInput.node().value;
}
clearSearch() {
const props = privateProps.get(this);
const {
onSearchReturn,
} = props;
const {
setSidebarClass,
setSidebarToLegend,
clearTextInput,
} = privateMethods;
setSidebarToLegend.call(this);
clearTextInput.call(this);
setSidebarClass.call(this);
onSearchReturn();
}
updateLanguage() {
const {
clearContent,
drawContent,
clearResults,
setToggleButtonText,
} = privateMethods;
clearContent.call(this);
drawContent.call(this);
clearResults.call(this);
setToggleButtonText.call(this);
}
}
export default Sidebar;
<file_sep>npm run build
aws s3 sync dist/ s3://pilotplan.org --delete
aws cloudfront create-invalidation --distribution-id E1OA4SOYLJP856 --paths /\*<file_sep>/**
* Callback for highlightedLayer field
* "highlightedLayer" object represents data for currently selected (isolated) layer
* @module
* @memberof stateUpdate
*/
const getUpdateHighlightedLayer = ({
components,
}) => {
const updateHighlightedLayer = function updateHighlightedLayer() {
const {
atlas,
sidebar,
} = components;
const { highlightedLayer } = this.props();
sidebar.config({ highlightedLayer }).updateHighlightedLayer();
atlas.config({ highlightedLayer }).updateHighlightedLayer();
};
return updateHighlightedLayer;
};
export default getUpdateHighlightedLayer;
<file_sep>/**
* Callback for transitionsDisabled field
* "transitionsDisabled" boolean represents if menu transitions are disabled
* @module
* @memberof stateUpdate
*/
const getUpdateTransitionsDisabled = ({
components,
}) => {
const updateTransitionsDisabled = function updateTransitionsDisabled() {
const { transitionsDisabled } = this.props();
const { layout } = components;
layout
.config({
transitionsDisabled,
})
.toggleTransitions();
};
return updateTransitionsDisabled;
};
export default getUpdateTransitionsDisabled;
<file_sep>/**
* Module comprises function for getting data probe config object
* @module dataProbeGetConfig
* @memberof dataProbe
*/
const getProbeConfig = function getProbeConfig({
data,
position,
clickText,
selection,
leader = false,
}) {
let html = [
data.Title !== '' ? data.Title : data.Creator,
data.FirstYear === data.LastYear ? data.FirstYear : `${data.FirstYear} - ${data.LastYear}`,
].reduce((accumulator, value) => {
if (value !== '' && value !== undefined) {
const row = `
<div class="data-probe__row">${value}</div>
`;
return accumulator + row;
}
return accumulator;
}, '');
const text = clickText !== undefined ? clickText : 'Click to view on map';
html += `<div class="data-probe__row data-probe__click-row">${text}</div>`;
const getPos = () => {
const imagePos = selection.node().getBoundingClientRect();
const imageLeft = imagePos.left;
const imageWidth = imagePos.width;
const probeWidth = 200;
return {
left: imageLeft + ((imageWidth / 2) - (probeWidth / 2)),
bottom: (window.innerHeight - imagePos.top) + 10,
width: probeWidth,
};
};
const pos = position !== undefined ? position :
getPos();
return {
pos,
html,
leader,
};
};
export default getProbeConfig;
<file_sep>/**
* Callback for highlightedFeature field
* "highlightedFeature" object represents data for search feature highlighted on map / sidebar
* @module
* @memberof stateUpdate
*/
const getUpdateHighlightedFeature = ({ components }) => {
const updateHighlightedFeature = function updateHighlightedFeature() {
const {
highlightedFeature,
mobile,
} = this.props();
const {
atlas,
sidebar,
layout,
} = components;
atlas
.config({
highlightedFeature,
})
.updateHighlightedFeature();
sidebar
.config({
highlightedFeature,
})
.updateHighlightedFeature();
if (mobile) {
layout
.config({
highlightedFeature,
})
.updateHighlightedFeature();
}
};
return updateHighlightedFeature;
};
export default getUpdateHighlightedFeature;
<file_sep>/**
* Module comprises pure functions for eras module (animated eras menu)
* @module erasMethods
* @memberof eras
*/
const erasMethods = {
setStepperListeners({
erasStepperLeftButton,
erasStepperRightButton,
updateYear,
getYear,
eras,
setAnimationDirection,
mouseEventsDisabled,
}) {
const { getCurrentEra } = erasMethods;
const getEraIndex = () => {
const year = getYear();
const currentEra = getCurrentEra({ year, eras });
return eras.findIndex(era => era.dates[0] === currentEra.dates[0]);
};
erasStepperLeftButton
.on('click', () => {
mouseEventsDisabled(true);
const eraIndex = getEraIndex();
let newEra;
if (eraIndex === 0) {
[newEra] = eras.slice(-1);
} else {
newEra = eras[eraIndex - 1];
}
setAnimationDirection('right');
updateYear(newEra.dates[0]);
});
erasStepperRightButton
.on('click', () => {
mouseEventsDisabled(true);
const eraIndex = getEraIndex();
let newEra;
if (eraIndex === eras.length - 1) {
[newEra] = eras;
} else {
newEra = eras[eraIndex + 1];
}
setAnimationDirection('left');
updateYear(newEra.dates[0]);
});
},
getCurrentEra({ year, eras }) {
return eras.find(era =>
year >= era.dates[0] &&
year <= era.dates[1]);
},
updateEra({
currentEra,
animationDirection,
erasTitleContainer,
mouseEventsDisabled,
view,
language,
}) {
if (view !== 'eras') {
d3.select('.eras__title')
.text(currentEra[language]);
return;
}
const getOffset = (selection) => {
const titleWidth = selection.node().getBoundingClientRect().width;
const pageWidth = window.innerWidth;
return ((titleWidth + pageWidth) / 2) * (animationDirection === 'right' ? 1 : -1);
};
erasTitleContainer
.style('left', '0px')
.transition()
.duration(750)
.style('left', `${getOffset(d3.select('.eras__title'))}px`)
.on('end', () => {
mouseEventsDisabled(false);
erasTitleContainer.remove();
});
const newTitleContainer = d3.select('.eras__title-outer')
.append('div')
.attr('class', 'eras__title-container')
.styles({
left: '0px',
opacity: 0,
});
const newTitle = newTitleContainer.append('div')
.attr('class', 'eras__title')
.text(currentEra[language]);
const newOffset = getOffset(newTitle);
newTitleContainer
.style('left', `${-newOffset}px`)
.style('opacity', 1);
newTitleContainer
.transition()
.duration(750)
.style('left', '0px');
},
updateDates({
currentEra,
animationDirection,
titleOuterContainer,
titleTextContainer,
titleInnerContainer,
view,
}) {
if (view !== 'eras') {
d3.select('.eras__stepper-years')
.text(`${currentEra.datesDisplay[0]} - ${currentEra.datesDisplay[1]}`);
return;
}
const getOffset = (selection) => {
const titleWidth = selection.node().getBoundingClientRect().width;
const containerWidth = titleOuterContainer.node().getBoundingClientRect().width;
return ((titleWidth + containerWidth) / 2) * (animationDirection === 'right' ? 1 : -1);
};
titleInnerContainer
.style('left', '0px')
.transition()
.duration(750)
.style('left', `${getOffset(titleTextContainer)}px`)
.on('end', () => {
titleInnerContainer.remove();
});
const newTitleContainer = titleOuterContainer
.append('div')
.attr('class', 'eras__stepper-years-inner')
.styles({
left: '0px',
opacity: 0,
});
const newTitle = newTitleContainer.append('div')
.attr('class', 'eras__stepper-years')
.text(`${currentEra.datesDisplay[0]} - ${currentEra.datesDisplay[1]}`);
const newOffset = getOffset(newTitle);
newTitleContainer
.style('left', `${-newOffset}px`)
.style('opacity', 1);
newTitleContainer
.transition()
.duration(750)
.style('left', '0px');
},
getTitleContainer() {
return d3.select('.eras__title');
},
};
export default erasMethods;
<file_sep>/**
* Callback for currentOverlay field
* "currentOverlay" object represents data for overlay toggled on map
* @module
* @memberof stateUpdate
*/
const getUpdateCurrentOverlay = ({ components }) => {
const updateCurrentOverlay = function updateCurrentOverlay() {
const {
currentOverlay,
overlayOpacity,
} = this.props();
const {
atlas,
layout,
urlParams,
} = components;
layout
.config({
overlayOn: currentOverlay !== null,
})
.updateOverlay();
atlas
.config({
currentOverlay,
})
.updateOverlay();
urlParams
.config({
overlay: currentOverlay !== null ? currentOverlay.SS_ID : null,
})
.update();
if (overlayOpacity !== 1 && currentOverlay !== null) {
this.update({ overlayOpacity: 1 });
}
};
return updateCurrentOverlay;
};
export default getUpdateCurrentOverlay;
<file_sep>/**
* Module comprises public update methods for the atlas module (Atlas class prototype)
* @module atlasPublicUpdateMethods
* @memberof atlas
*/
import getBBox from '@turf/bbox';
import clickSearchMethods from './atlasClickSearchMethods';
import highlightMethods from './atlasHighlightMethods';
import generalMethods from './atlasMethods';
import getZoom from './atlasGetZoom';
const getAtlasUpdateMethods = ({
privateProps,
privateMethods,
}) => {
const updateMethods = {
updateCurrentLayers() {
const {
mbMap,
currentLayers,
} = privateProps.get(this);
const { layers } = mbMap.getStyle();
layers
.filter(layer => layer.id !== 'satellite')
.forEach((layer) => {
const visible = mbMap.getLayoutProperty(layer.id, 'visibility') === 'visible';
const currentLayer = currentLayers
.find(d => d.sourceLayer === layer['source-layer']);
const toggled = currentLayer === undefined ? true : currentLayer.status;
if (visible && !toggled) {
mbMap.setLayoutProperty(layer.id, 'visibility', 'none');
} else if (!visible && toggled) {
mbMap.setLayoutProperty(layer.id, 'visibility', 'visible');
}
});
},
updateAreaSearch() {
const {
areaSearchActive,
mbMap,
mapContainer,
clickSearch,
} = privateProps.get(this);
const {
initClickSearchListener,
disableClickSearchListener,
toggleMapAreaSearchMode,
} = clickSearchMethods;
toggleMapAreaSearchMode({
mapContainer,
areaSearchActive,
});
if (areaSearchActive) {
disableClickSearchListener({
mbMap,
clickSearch,
});
mbMap.dragPan.disable();
} else {
initClickSearchListener({
mbMap,
clickSearch,
});
mbMap.dragPan.enable();
}
},
updateHighlightedLayer() {
const props = privateProps.get(this);
const {
highlightedLayer,
mbMap,
layerOpacities,
layerFills,
year,
extentsData,
onLayerSourceData,
highlightLoadingTimer,
toggleOverlayFade,
} = props;
const {
getLayerBounds,
} = highlightMethods;
const { layers } = mbMap.getStyle();
if (highlightedLayer === null) {
if (highlightLoadingTimer !== null) {
clearTimeout(highlightLoadingTimer);
}
layers.forEach((layer) => {
let opacityField;
let fillField;
if (layer.type === 'fill') {
opacityField = 'fill-opacity';
fillField = 'fill-color';
} else if (layer.type === 'line') {
opacityField = 'line-opacity';
fillField = 'line-color';
} else if (layer.type === 'symbol') {
opacityField = 'text-opacity';
}
if (opacityField !== undefined) {
mbMap.setPaintProperty(layer.id, opacityField, layerOpacities[layer.id]);
if (fillField && layerFills[layer.id]) {
mbMap.setPaintProperty(layer.id, fillField, layerFills[layer.id]);
}
}
props.highlightLayerLoading = false;
});
toggleOverlayFade(false);
return;
}
props.highlightLayerLoading = true;
props.highlightFeatureLoading = false;
const newBounds = getLayerBounds({
year,
highlightedFeature: highlightedLayer,
extentsData,
});
const newZoom = getZoom({
mbMap,
bounds: newBounds,
highlightedFeature: highlightedLayer,
padding: 0,
});
const rendered = mbMap.queryRenderedFeatures({
layers: [highlightedLayer.style],
});
if (rendered.length === 0) {
mbMap.easeTo({
bearing: 0,
zoom: newZoom,
center: newBounds.getCenter(),
duration: 1500,
});
}
onLayerSourceData();
},
updateHighlightedFeature() {
const {
clearHighlightedFeature,
getHighlightedGeoJSON,
} = highlightMethods;
const props = privateProps.get(this);
const {
mbMap,
highlightedFeature,
year,
onReturnToSearch,
searchLocation,
} = props;
const { zoomToAndHighlightFeature } = privateMethods;
clearHighlightedFeature(mbMap);
if (highlightedFeature === null) return;
const highlightedFeatureJSON = getHighlightedGeoJSON({
highlightedFeature,
year,
mbMap,
});
if (highlightedFeatureJSON.features.length > 0) {
props.highlightedFeatureJSON = highlightedFeatureJSON;
zoomToAndHighlightFeature({ props });
} else {
props.highlightLayerLoading = false;
props.searchLocationLoading = true;
onReturnToSearch();
mbMap.easeTo(searchLocation);
}
},
updateOverlayOpacity() {
const props = privateProps.get(this);
const {
mbMap,
overlayOpacity,
} = props;
mbMap.setPaintProperty('overlay-layer', 'raster-opacity', overlayOpacity);
},
updateOverlay() {
const props = privateProps.get(this);
const {
currentOverlay,
mbMap,
overlayOpacity,
} = props;
if (mbMap.getSource('overlay') !== undefined) {
mbMap.removeLayer('overlay-layer');
mbMap.removeSource('overlay');
}
if (currentOverlay === null) return;
const dev = /[?&]dev=true/.test(window.location.search) ? 'dev' : '';
const sourceUrl = `https://pilotplan.s3.amazonaws.com/SSID${currentOverlay.SS_ID}${dev}/{z}/{x}/{y}.png`;
mbMap.addSource(
'overlay',
{
type: 'raster',
tiles: [sourceUrl],
scheme: 'tms',
},
);
mbMap.addLayer({
id: 'overlay-layer',
type: 'raster',
source: 'overlay',
paint: {
'raster-opacity': overlayOpacity,
},
}, 'viewconespoint');
const bounds = new mapboxgl.LngLatBounds([
currentOverlay.bounds.slice(0, 2),
currentOverlay.bounds.slice(2, 4),
]);
mbMap.fitBounds(bounds);
},
updateView() {
const props = privateProps.get(this);
const {
currentView,
mbMap,
viewshedsGeo,
} = props;
const {
addConeToMap,
removeCone,
} = generalMethods;
if (currentView === null) {
removeCone({ mbMap });
} else {
const coneFeature = viewshedsGeo.features.find(d =>
d.properties.SS_ID === currentView.SS_ID);
addConeToMap({
coneFeature,
mbMap,
});
const bbox = getBBox(coneFeature);
mbMap.fitBounds(bbox, { padding: 100 });
}
},
resizeMap() {
const { mbMap } = privateProps.get(this);
mbMap.resize();
},
updateYear() {
const {
updateYear,
} = privateMethods;
updateYear.call(this);
},
};
return updateMethods;
};
export default getAtlasUpdateMethods;
<file_sep>/**
* Module initializes timeline component
* @module initTimeline
*/
import Timeline from '../timeline/timeline';
import { yearRange } from '../config/config';
const initTimeline = function initTimeline() {
const { state } = this.components;
this.components.timeline = new Timeline({
mobile: state.get('mobile'),
language: state.get('language'),
eras: this.data.eras,
uniqueYears: this.data.years,
year: state.get('year'),
updateYear(newYear) {
state.update({ year: Math.round(newYear) });
},
yearRange,
stepSections: [
{
years: [yearRange[0], 1955],
increment: 2,
},
{
years: [1955, yearRange[1]],
increment: 1,
},
],
});
};
export default initTimeline;
<file_sep>/**
* Module comprises pure functions for displaying the 'show all' raster screen
* (raster thumbnail lightbox)
* @module footerAllRasterMethods
* @memberof footer
*/
import rasterMethods from '../rasterProbe/rasterMethods';
import getProbeConfig from '../dataProbe/dataProbeGetConfig';
import { footerCategoryIcons } from '../config/config';
const {
setEachRasterBackground,
getRasterDataByCategory,
} = rasterMethods;
const allRasterMethods = {
setAllRasterBackgroundClick({
allRasterInnerContainer,
allRasterOuterContainer,
onAllRasterCloseClick,
}) {
allRasterOuterContainer.on('click', onAllRasterCloseClick);
allRasterInnerContainer.on('click', () => {
d3.event.stopPropagation();
});
},
setAllRasterCloseButton({
allRasterCloseButton,
onAllRasterCloseClick,
}) {
allRasterCloseButton.on('click', onAllRasterCloseClick);
},
drawAllRasterCategories({
rasterData,
allRasterContentContainer,
}) {
const data = getRasterDataByCategory({ rasterData });
const allRasterSections = allRasterContentContainer
.selectAll('.allraster__section')
.data(data, d => d.key);
const newSections = allRasterSections
.enter()
.append('div')
.attr('class', 'allraster__section');
allRasterSections.exit().remove();
return {
newAllRasterSections: newSections,
allRasterSections: newSections.merge(allRasterSections),
};
},
drawAllRasterTitles({
newAllRasterSections,
}) {
const titles = newAllRasterSections
.append('div')
.attr('class', 'allraster__title');
const titleTextBlock = titles
.append('div')
.attr('class', 'allraster__title-text-block');
titleTextBlock.append('i')
.attr('class', d => footerCategoryIcons[d.key]);
titleTextBlock
.append('div')
.attr('class', 'allraster__title-text')
.text(d => d.key);
},
drawAllRasterImageBlocks({
newAllRasterSections,
}) {
return newAllRasterSections
.append('div')
.attr('class', 'allraster__image-block');
},
drawAllRasterImages({
allRasterSections,
onRasterClick,
cachedMetadata,
onAllRasterCloseClick,
dataProbe,
mobile,
}) {
allRasterSections.each(function drawRasters(d) {
const block = d3.select(this).select('.allraster__image-block');
const images = block.selectAll('.footer__image')
.data(d.values, dd => dd.SS_ID);
const newImages = images
.enter()
.append('div')
.attr('class', 'footer__image allraster__image')
.classed('allraster__image--mobile', mobile)
.on('click', (dd) => {
onRasterClick(dd);
onAllRasterCloseClick();
})
.on('mouseover', function drawProbe(dd) {
if (mobile) return;
const config = getProbeConfig({
selection: d3.select(this),
data: dd,
leader: true,
});
dataProbe
.config(config)
.draw();
})
.on('mouseout', () => {
if (mobile) return;
dataProbe.remove();
});
setEachRasterBackground({
images: newImages,
cachedMetadata,
maxDim: mobile ? 90 : 130,
spinner: true,
});
images.exit().remove();
});
},
scrollToCategory({
category,
getAllRasterSections,
allRasterInnerContainer,
}) {
/* eslint-disable no-param-reassign */
const sections = getAllRasterSections();
allRasterInnerContainer
.node()
.scrollTop = 0;
const positions = {};
sections.each(function getPosition(d) {
positions[d.key] = this.getBoundingClientRect();
});
allRasterInnerContainer
.node()
.scrollTop = positions[category].top - 20;
/* eslint-enable no-param-reassign */
},
};
export default allRasterMethods;
<file_sep>/**
* Module comprises pure functions for display of footer (raster filmstrip)
* @module footerMethods
* @memberof footer
*/
import rasterMethods from '../rasterProbe/rasterMethods';
import getProbeConfig from '../dataProbe/dataProbeGetConfig';
import { footerCategoryIcons } from '../config/config';
const footerMethods = {
drawRasters({
rasterData,
imagesContainer,
onRasterClick,
footerView,
cachedMetadata,
dataProbe,
}) {
const {
setEachRasterBackground,
} = rasterMethods;
const images = imagesContainer.selectAll('.footer__image')
.data(rasterData.get(footerView), d => d.SS_ID);
const newImages = images
.enter()
.append('div')
.attr('class', 'footer__image')
.on('click', onRasterClick)
.on('mouseover', function drawProbe(d) {
const config = getProbeConfig({
data: d,
selection: d3.select(this),
leader: true,
});
dataProbe
.config(config)
.draw();
})
.on('mouseout', () => {
dataProbe.remove();
});
setEachRasterBackground({
images: newImages,
maxDim: 130,
cachedMetadata,
spinner: true,
});
images.exit().remove();
return newImages.merge(images);
},
drawToggleRasters({
rasterData,
footerToggleRastersContainer,
cachedMetadata,
}) {
const {
getFlattenedRasterData,
setEachRasterBackground,
} = rasterMethods;
const toggleRasterData = getFlattenedRasterData({ rasterData }).slice(0, 3);
const images = footerToggleRastersContainer
.selectAll('.footer__toggle-image')
.data(toggleRasterData, d => d.SS_ID);
const newImages = images
.enter()
.append('div')
.attr('class', 'footer__toggle-image');
images.exit().remove();
setEachRasterBackground({
images: newImages,
maxDim: 20,
cachedMetadata,
});
},
drawCategoryButtons({
rasterCategories,
container,
onClick,
}) {
return container
.selectAll('.footer__category')
.data(rasterCategories)
.enter()
.append('div')
.attr('class', 'footer__category')
.html(d => `<i class="${footerCategoryIcons[d]}"></i>`)
.on('click', onClick);
},
drawMobileCategoryButtons({
container,
rasterCategories,
onClick,
}) {
return container
.selectAll('.footer__category')
.data(rasterCategories)
.enter()
.append('div')
.attr('class', 'mobileFooter__category')
.html(d => `<i class="${footerCategoryIcons[d]}"></i>`)
.on('click', onClick);
},
};
export default footerMethods;
<file_sep>for f in $1*.shp;\
do mapshaper $f field-types=FirstYear:number,LastYear:number -o data/geojson/$(basename "$f" .shp).json;\
done
mv data/geojson/AerialExtentsPoly.json data/geojson/visual/AerialExtentsPoly.json
mv data/geojson/BasemapExtentsPoly.json data/geojson/visual/BasemapExtentsPoly.json
mv data/geojson/MapExtentsPoly.json data/geojson/visual/MapExtentsPoly.json
mv data/geojson/PlanExtentsPoly.json data/geojson/visual/PlanExtentsPoly.json
mv data/geojson/ViewConesPoly.json data/geojson/visual/ViewConesPoly.json
mv data/geojson/*.json data/geojson/geography/<file_sep>/**
* Module comprises function that returns zoom level for given bounds and min zoom
* @module atlasGetZoom
* @memberof atlas
*/
const getZoom = ({
mbMap,
bounds,
highlightedFeature,
padding = 0,
}) => {
const {
width,
height,
} = mbMap.getContainer()
.getBoundingClientRect();
const minLat = bounds.getSouth();
const maxLat = bounds.getNorth();
const maxLng = bounds.getEast();
const minLng = bounds.getWest();
/* eslint-disable no-mixed-operators */
/**
* best zoom level based on map width
* @private
*/
const zoom1 = Math.log(360.0 / 256.0 * (width - (2 * padding)) / (maxLng - minLng)) / Math.log(2);
/**
* best zoom level based on map height
* @private
*/
const zoom2 =
Math.log(180.0 / 256.0 * (height - (2 * padding)) / (maxLat - minLat)) / Math.log(2);
/* eslint-enable no-mixed-operators */
const newZoom = ((zoom1 < zoom2) ? zoom1 : zoom2) - 0.3;
const minZoom = mbMap.getLayer(highlightedFeature.style).minzoom;
if (minZoom !== undefined) {
if (minZoom > newZoom) return minZoom;
}
return newZoom;
};
export default getZoom;
<file_sep>/**
* Callback for currentLocation field
* "currentLocation" object contains map location info--bearing, center, zoom
* @module
* @memberof stateUpdate
*/
const getStateUpdateCurrentLocation = ({
components,
}) => function updateCurrentLocation() {
const { currentLocation } = this.props();
const {
urlParams,
views,
layout,
atlas,
} = components;
const { center, bearing, zoom } = currentLocation;
if (!views.mapViewInitialized()) return;
const style = atlas.getStyle();
urlParams
.config({
center: `${center.lat},${center.lng}`,
zoom,
bearing,
})
.update();
layout
.config({
rotated: bearing !== style.bearing ||
Math.abs(style.center[0] - center.lng) > 0.0001 ||
Math.abs(style.center[1] - center.lat) > 0.0001 ||
zoom !== style.zoom,
zoomedOut: zoom < 11,
})
.updateLocation();
};
export default getStateUpdateCurrentLocation;
<file_sep>/**
* Callback for view field
* "view" string represents map screen--intro, eras, map
* @module
* @memberof stateUpdate
*/
const getUpdateView = ({
components,
}) => {
const updateView = function updateView() {
const {
view,
} = this.props();
const {
views,
sidebar,
eras,
languageDropdown,
} = components;
views
.config({ view })
.updateView();
eras
.config({ view });
if (view === 'intro') {
languageDropdown.update();
}
if (!this.get('componentsInitialized')) return;
const layersToClear = this.getLayersToClear([
'currentOverlay',
'currentRasterProbe',
'currentView',
'highlightedFeature',
'allRasterOpen',
]);
if (sidebar !== undefined && sidebar.getView() !== 'legend') {
sidebar.clearSearch();
}
this.update({ transitionsDisabled: true });
this.update(Object.assign({
footerOpen: true,
sidebarOpen: false,
}, layersToClear));
this.update({ transitionsDisabled: false });
};
return updateView;
};
export default getUpdateView;
<file_sep>/**
* Module comprises methods related to slider
* @module timelineSliderBase
* @memberof timeline
*/
const getSliderBase = ({ privateProps }) => ({
setScale() {
const props = privateProps.get(this);
const {
valueRange,
stepSections,
} = props;
const domain = stepSections.length === 2 ?
[valueRange[0], stepSections[0].years[1], valueRange[1]] :
valueRange;
props.scale = d3.scaleLinear()
.domain(domain);
const { scale } = props;
props.handleScale = d3.scaleLinear()
.domain(scale.domain());
},
updateScale() {
const {
size,
padding,
handleWidth,
scale,
handleScale,
stepSections,
} = privateProps.get(this);
const domain = scale.domain();
if (stepSections.length === 2) {
const increments1 = stepSections[0].increment;
const increments2 = stepSections[1].increment;
const steps1 = (domain[1] - domain[0]) / increments1;
const steps2 = (domain[2] - domain[0]) / increments2;
const pctWayThrough = steps1 / (steps1 + steps2);
const startPoint = padding.left + (handleWidth / 2);
const endPoint = size.width - padding.right - (handleWidth / 2);
const midPoint = (endPoint - startPoint) * pctWayThrough;
scale
.range([startPoint, midPoint, endPoint]);
} else if (stepSections.length === 1) {
scale
.range([padding.left + (handleWidth / 2), size.width - padding.right - (handleWidth / 2)]);
}
handleScale.range(scale.range());
},
updateScaleValueRange() {
const {
valueRange,
scale,
handleScale,
} = privateProps.get(this);
scale.domain(valueRange);
handleScale.domain(scale.domain());
},
drawSvg() {
const props = privateProps.get(this);
const { container } = props;
props.svg = container.append('svg');
},
updateSvgSize() {
const {
size,
svg,
} = privateProps.get(this);
svg.styles({
width: `${size.width}px`,
height: `${size.height}px`,
});
},
drawDetectionTrack() {
const props = privateProps.get(this);
const {
size,
svg,
} = props;
props.detectionTrack = svg.append('g')
.append('line')
.attrs({
class: 'track_overlay',
'stroke-width': size.height,
opacity: '0',
stroke: 'red',
'pointer-events': 'stroke',
cursor: 'pointer',
transform: `translate(${0},${size.height / 2})`,
})
.on('mousemove', () => {
const {
handle,
handleHeight,
} = privateProps.get(this);
if (handle === undefined) return;
const handleBBox = handle.node().getBBox();
const svgBBox = props.svg.node().getBoundingClientRect();
const handlePos = {
x: svgBBox.left + handleBBox.x,
y: svgBBox.top + handleBBox.y,
};
const { x, y } = d3.event;
handle.classed(
'slider__handle--hover',
x >= handlePos.x &&
x <= handlePos.x + handleHeight &&
y >= handlePos.y &&
y <= handlePos.y + handleHeight,
);
});
},
updateDetectionTrack() {
const {
detectionTrack,
scale,
} = privateProps.get(this);
detectionTrack.attrs({
x1: scale.range()[0],
x2: scale.range().slice(-1)[0],
});
},
drawBackgroundTrack() {
const props = privateProps.get(this);
const {
svg,
size,
padding,
trackHeight,
backgroundTrackAttrs,
} = props;
const defaultAttrs = {
class: 'slider__track slider__background-track',
x: padding.left,
y: (size.height / 2) - (trackHeight / 2),
height: trackHeight,
'pointer-events': 'none',
rx: 3,
ry: 3,
};
const overrideAttrs = backgroundTrackAttrs !== undefined ? backgroundTrackAttrs : {};
props.backgroundTrack = svg.append('rect')
.attrs(Object.assign(defaultAttrs, overrideAttrs));
},
updateBackgroundTrack() {
const {
backgroundTrack,
scale,
} = privateProps.get(this);
backgroundTrack
.attrs({
x: scale.range()[0],
width: scale.range()[scale.range().length - 1] - scale.range()[0],
});
},
drawActiveTrack() {
const props = privateProps.get(this);
const {
svg,
size,
padding,
trackHeight,
activeTrackAttrs,
} = props;
const defaultAttrs = {
class: 'slider__track slider__active-track',
x: padding.left,
y: (size.height / 2) - (trackHeight / 2),
height: trackHeight,
'pointer-events': 'none',
rx: 3,
ry: 3,
opacity: 0,
};
const overrideAttrs = activeTrackAttrs !== undefined ? activeTrackAttrs : {};
props.activeTrack = svg.append('rect')
.attrs(Object.assign(defaultAttrs, overrideAttrs));
},
drawHighlightedRange() {
const props = privateProps.get(this);
const {
svg,
trackHeight,
size,
} = props;
props.highlightedRangeBar = svg.append('rect')
.attrs({
class: 'slider__highlighted-range',
y: (size.height / 2) - (trackHeight / 2),
'pointer-events': 'none',
height: trackHeight,
opacity: 0,
});
const highlightedRangeEndProps = {
class: 'slider__highlighted-range-end',
cy: size.height / 2,
r: trackHeight / 2,
opacity: 0,
};
props.highlightedRangeLeftEnd = svg
.append('circle')
.attrs(highlightedRangeEndProps);
props.highlightedRangeRightEnd = svg
.append('circle')
.attrs(highlightedRangeEndProps);
},
});
export default getSliderBase;
<file_sep>/**
* Callback for footerOpen field
* "footerOpen" boolean represents open / close status of footer
* @module
* @memberof stateUpdate
*/
const getUpdateFooterOpen = ({ components }) => {
const updateFooterOpen = function updateFooterOpen() {
const {
footerOpen,
} = this.props();
const {
layout,
} = components;
layout
.config({
footerOpen,
})
.updateFooter();
};
return updateFooterOpen;
};
export default getUpdateFooterOpen;
<file_sep>/**
* Callback for when screen is resized
* @module
* @memberof stateUpdate
*/
const getUpdateScreenSize = ({ components }) => {
const updateScreenSize = function updateScreenSize() {
const {
timeline,
} = components;
timeline
.updateScreenSize();
};
return updateScreenSize;
};
export default getUpdateScreenSize;
<file_sep>/**
* Module initializes views component
* @module initViews
*/
import Views from '../views/views';
const initViews = function initViews() {
const { state } = this.components;
this.components.views = new Views({
view: state.get('view'),
initialize: {
map: () => {
this.initComponents();
this.listenForResize();
},
},
mapLoaded: state.get('mapLoaded'),
});
this.components.views.updateView();
};
export default initViews;
<file_sep>/**
* Module controls classes and callbacks related to toggling map views
* @module views
*/
import { selections } from '../config/config';
const privateProps = new WeakMap();
const privateMethods = {
updateClass({
outerContainer,
view,
views,
}) {
Object.keys(views)
.forEach((key) => {
outerContainer.classed(views[key].className, key === view);
});
},
};
class Views {
constructor(config) {
const {
outerContainer,
} = selections;
privateProps.set(this, {
outerContainer,
view: 'map',
views: {
map: {
className: 'outer-container--map',
initialized: false,
},
intro: {
className: 'outer-container--intro',
initialized: false,
},
eras: {
className: 'outer-container--eras',
initialized: false,
},
},
});
this.config(config);
}
config(config) {
Object.assign(privateProps.get(this), config);
return this;
}
updateView() {
const props = privateProps.get(this);
const {
initialize,
view,
views,
outerContainer,
mapLoaded,
} = props;
const {
updateClass,
} = privateMethods;
updateClass({
outerContainer,
view,
views,
});
if (!views[view].initialized &&
Object.prototype.hasOwnProperty.call(initialize, view) &&
mapLoaded) {
initialize[view]();
}
views[view].initialized = true;
}
mapViewInitialized() {
return privateProps.get(this)
.views
.map
.initialized;
}
}
export default Views;
<file_sep>const fs = require('fs');
const path = require('path');
const mbxStyles = require('@mapbox/mapbox-sdk/services/styles');
require('dotenv').config();
console.log('env', process.env);
const stylesClient = mbxStyles({ accessToken: process.env.MAPBOX_ACCESS_TOKEN });
stylesClient.getStyle({ styleId: process.env.MAPBOX_STYLE })
.send()
.then((response) => {
const style = response.body;
fs.writeFile(path.join(__dirname, '../src/data/style.json'), JSON.stringify(style, null, 2), () => {
console.log('NEW STYLE WRITTEN');
});
});
<file_sep>/**
* Module comprises private methods for the layout module
* @module layoutPrivateMethods
* @memberof layout
*/
const getPrivateMethods = ({ privateProps }) => ({
initAreaButton() {
const {
areaSearchButton,
onAreaButtonClick,
} = privateProps.get(this);
areaSearchButton.on('click', onAreaButtonClick);
},
initOverlayButton() {
const {
overlayButtonContainer,
onOverlayButtonClick,
} = privateProps.get(this);
overlayButtonContainer
.on('click', onOverlayButtonClick);
},
initErasButton() {
const {
erasButtonContainer,
onErasButtonClick,
} = privateProps.get(this);
erasButtonContainer
.on('click', onErasButtonClick);
},
initBackToIntroButton() {
const {
erasBackButton,
onBackButtonClick,
} = privateProps.get(this);
erasBackButton
.on('click', onBackButtonClick);
},
updateFooter({ outerContainer, footerOpen }) {
outerContainer.classed('footer-open', footerOpen);
},
setErasButtonText() {
const {
currentEra,
erasButtonText,
language,
translations,
} = privateProps.get(this);
erasButtonText
.text(`${translations['back-to-text'][language]} ${currentEra[language]}`);
},
initMenuTransitions() {
const {
sidebarContainer,
footerContainer,
transitionSpeed,
} = privateProps.get(this);
sidebarContainer
.style('transition', `width ${transitionSpeed}ms`);
footerContainer
.style('transition', `height ${transitionSpeed}ms width ${transitionSpeed}ms`);
},
initSidebarToggleButton() {
const {
sidebarToggleButton,
sidebarToggleButtonMobile,
onSidebarToggleClick,
} = privateProps.get(this);
sidebarToggleButton
.on('click', onSidebarToggleClick);
sidebarToggleButtonMobile
.on('touchstart', onSidebarToggleClick);
},
initCloseSidebarButton() {
const {
sidebarCloseButtonMobile,
onSidebarToggleClick,
} = privateProps.get(this);
sidebarCloseButtonMobile
.on('click', onSidebarToggleClick);
},
initRegisterButton() {
const {
headerRegisterButton,
toggleRegisterScreen,
} = privateProps.get(this);
headerRegisterButton
.on('click', () => {
toggleRegisterScreen(true);
});
},
initRegisterScreen() {
const {
registerOuterContainer,
toggleRegisterScreen,
registerInnerContainer,
registerCancelButton,
registerSubmitButton,
} = privateProps.get(this);
registerOuterContainer
.on('click', () => {
toggleRegisterScreen(false);
});
registerCancelButton
.on('click', () => {
toggleRegisterScreen(false);
});
registerSubmitButton
.on('click', () => {
toggleRegisterScreen(false);
});
registerInnerContainer
.on('click', () => {
d3.event.stopPropagation();
});
},
initSocialMediaButtons() {
const {
headerFacebookButton,
headerTwitterButton,
headerDownloadButton,
getCanvas,
language,
translations,
} = privateProps.get(this);
const map = this;
headerDownloadButton
.on('click', function exportMap() {
const {
width,
height,
} = getCanvas().getBoundingClientRect();
const { year } = privateProps.get(map);
const canvas = document.createElement('canvas');
canvas.height = height;
canvas.width = width;
const titleHeight = 50;
const context = canvas.getContext('2d');
context.drawImage(getCanvas(), 0, 0, width, height);
context.fillStyle = 'rgba( 230, 230, 230, 0.8 )';
context.fillRect(0, 0, width, titleHeight);
context.fillStyle = '#666';
context.fillRect(0, titleHeight - 1, width, 1);
context.font = "100 30px 'Helvetica Neue', Helvetica, Arial, sans-serif";
context.fillText(translations.h1[language], 20, 35);
context.font = "bold 20px 'Helvetica Neue', Helvetica, Arial, sans-serif";
context.fillText(year, width - 100, 35);
const url = canvas.toDataURL('image/png');
d3.select(this).attr('href', url);
});
headerTwitterButton
.attr(
'href',
`https://twitter.com/intent/tweet?text=pilotPlan&url=${encodeURIComponent(window.location.href)}`,
);
headerFacebookButton
.attr(
'href',
`https://www.facebook.com/sharer/sharer.php?&u=${encodeURIComponent(window.location.href)}`,
);
},
initMobileDataProbe() {
const {
dataProbeMobileCloseButton,
onMobileProbeClose,
} = privateProps.get(this);
dataProbeMobileCloseButton
.on('click', onMobileProbeClose);
},
setHintProbeLanguage() {
const {
hintProbeText,
translations,
language,
} = privateProps.get(this);
hintProbeText
.text(translations['probe-hint-text'][language]);
},
setAreaProbeLanguage() {
const {
areaSearchText,
language,
translations,
} = privateProps.get(this);
areaSearchText
.text(translations['probe-area-text'][language]);
},
setRegisterButtonLanguage() {
const {
headerRegisterButtonText,
language,
translations,
} = privateProps.get(this);
headerRegisterButtonText
.text(translations.Register[language]);
},
setErasBackButtonText() {
const {
erasBackButtonText,
language,
translations,
} = privateProps.get(this);
erasBackButtonText
.text(`${translations['back-to-text'][language]} ${translations.start[language]}`);
},
});
export default getPrivateMethods;
<file_sep>/**
* Callback for footerView field
* "footerView" string represents currently toggled footer raster category
* This probably doesn't need to be its own state field. Could be local state in Footer module
* @module
* @memberof stateUpdate
*/
const getUpdateFooterView = ({ components }) => {
const updateFooterView = function updateFooterView() {
const {
footerView,
} = this.props();
const {
footer,
} = components;
footer
.config({
footerView,
})
.updateRasterData();
};
return updateFooterView;
};
export default getUpdateFooterView;
<file_sep>/**
* Module comprises functions related to atlas click search
* @module atlasClickSearchMethods
* @memberof atlas
*/
import {
getRasterResults,
getNonRasterResults,
} from '../data/data';
let pulsing = false;
let pulseTimer = null;
const atlasClickSearchMethods = {
setClickSearch({
onClickSearch,
mbMap,
setClickSearchProp,
getCancelClickSearch,
removeCancelClickSearch,
getYear,
getFlattenedRasterData,
outerContainer,
}) {
const { getClickSearch } = atlasClickSearchMethods;
const clickSearch = getClickSearch({
outerContainer,
onClickSearch,
getCancelClickSearch,
removeCancelClickSearch,
getYear,
getFlattenedRasterData,
mbMap,
});
setClickSearchProp(clickSearch);
},
addPulse({ e, outerContainer }) {
const { removePulse } = atlasClickSearchMethods;
const { x, y } = e.point;
const size = 60;
if (pulseTimer !== null) {
clearTimeout(pulseTimer);
removePulse();
}
pulsing = true;
outerContainer
.append('img')
.attrs({
class: 'atlas__pulse',
src: `img/pulse.gif?a=${Math.random()}`,
})
.styles({
position: 'absolute',
'pointer-events': 'none',
left: `${x - (size / 2)}px`,
top: `${y - (size / 2)}px`,
});
pulseTimer = setTimeout(() => {
pulseTimer = null;
removePulse();
}, 450);
},
removePulse() {
if (!pulsing) return;
d3.selectAll('.atlas__pulse').remove();
pulsing = false;
},
getClickSearch({
outerContainer,
onClickSearch,
getYear,
getFlattenedRasterData,
getCancelClickSearch,
removeCancelClickSearch,
mbMap,
}) {
const {
addPulse,
} = atlasClickSearchMethods;
return (e) => {
if (getCancelClickSearch()) {
removeCancelClickSearch();
return;
}
addPulse({ e, outerContainer });
const year = getYear();
const flattenedRasterData = getFlattenedRasterData();
const bbox = [[e.point.x - 5, e.point.y - 5], [e.point.x + 5, e.point.y + 5]];
const features = mbMap.queryRenderedFeatures(bbox, {
filter: [
'all',
['<=', 'FirstYear', year],
['>=', 'LastYear', year],
],
});
const rasterFeatures = getRasterResults(features)
.map(d => flattenedRasterData.find(dd => dd.SS_ID === d.properties.SS_ID));
const nonRasterFeatures = getNonRasterResults(features);
onClickSearch({
raster: rasterFeatures,
nonRaster: nonRasterFeatures,
});
};
},
initClickSearchListener({
mbMap,
clickSearch,
}) {
mbMap.on('click', clickSearch);
},
disableClickSearchListener({
mbMap,
clickSearch,
}) {
mbMap.off('click', clickSearch);
},
toggleMapAreaSearchMode({
mapContainer,
areaSearchActive,
}) {
mapContainer.classed('map--area-search', areaSearchActive);
},
};
export default atlasClickSearchMethods;
<file_sep>/**
* Module comprises functions related to atlas area search
* @module atlasAreaSearchMethods
* @memberof atlas
*/
import {
getRasterResults,
getNonRasterResults,
} from '../data/data';
const getAreaSearchMethods = ({
getAreaSearchActive,
canvas,
mbMap,
getYear,
onAreaSearch,
getFlattenedRasterData,
mobile,
}) => {
const localState = {
start: null,
current: null,
box: null,
};
const areaMouseMethods = {
getMousePos(e) {
const rect = canvas.getBoundingClientRect();
if (!mobile) {
return new mapboxgl.Point(
e.clientX - rect.left - canvas.clientLeft,
e.clientY - rect.top - canvas.clientTop,
);
}
const touch = e.touches[0];
return new mapboxgl.Point(
touch.clientX,
touch.clientY,
);
},
onMouseDown(e) {
const {
onMouseMove,
onMouseUp,
getMousePos,
} = areaMouseMethods;
if (!getAreaSearchActive()) return;
localState.start = getMousePos(e);
if (!mobile) {
document.addEventListener('mousemove', onMouseMove);
document.addEventListener('mouseup', onMouseUp);
} else {
document.addEventListener('touchmove', onMouseMove);
document.addEventListener('touchend', onMouseUp);
}
},
onMouseMove(e) {
const {
getMousePos,
} = areaMouseMethods;
const { start } = localState;
const current = getMousePos(e);
localState.current = current;
if (localState.box === null || localState.box === undefined) {
localState.box = d3.select('#map')
.append('div')
.attr('class', 'search-box');
}
const { box } = localState;
const minX = Math.min(start.x, current.x);
const maxX = Math.max(start.x, current.x);
const minY = Math.min(start.y, current.y);
const maxY = Math.max(start.y, current.y);
const pos = `translate(${minX}px,${minY}px)`;
box.styles({
transform: pos,
WebkitTransform: pos,
width: `${maxX - minX}px`,
height: `${maxY - minY}px`,
})
.classed('search-box--hidden', false);
},
onMouseUp() {
const {
onMouseMove,
onMouseUp,
} = areaMouseMethods;
const {
box,
start,
current,
} = localState;
const flattenedRasterData = getFlattenedRasterData();
if (!mobile) {
document.removeEventListener('mousemove', onMouseMove);
document.removeEventListener('mouseup', onMouseUp);
} else {
document.removeEventListener('touchmove', onMouseMove);
document.removeEventListener('touchend', onMouseUp);
}
box.classed('search-box--hidden', true);
const bbox = [start, current];
const features = mbMap.queryRenderedFeatures(bbox, {
filter: [
'all',
['<=', 'FirstYear', getYear()],
['>=', 'LastYear', getYear()],
],
});
const rasterFeatures = getRasterResults(features)
.map(d => flattenedRasterData.find(dd => dd.SS_ID === d.properties.SS_ID));
const nonRasterFeatures = getNonRasterResults(features);
onAreaSearch({
raster: rasterFeatures,
nonRaster: nonRasterFeatures,
});
},
};
return areaMouseMethods;
};
export default getAreaSearchMethods;
<file_sep>/**
* Module comprises pure functions related to displaying search results on sidebar
* @module sidebarSearch
* @memberof sidebar
*/
import rasterMethods from '../rasterProbe/rasterMethods';
const searchMethods = {
listenForText({
searchInput,
onTextInput,
}) {
searchInput.on('input', function getValue() {
const val = d3.select(this).node().value;
onTextInput(val);
});
},
clearResults({
rasterResultsContainer,
nonRasterResultsContainer,
}) {
rasterResultsContainer.selectAll('div').remove();
nonRasterResultsContainer.selectAll('div').remove();
},
drawRasterSearchResults({
translations,
container,
results,
onRasterClick,
cachedMetadata,
language,
}) {
const {
drawSearchResultGroups,
drawRasterResultRows,
} = searchMethods;
const groups = drawSearchResultGroups({
language,
translations,
container,
results,
isRaster: true,
});
drawRasterResultRows({
onRasterClick,
groups,
cachedMetadata,
});
},
drawNonRasterSearchResults({
translations,
container,
results,
onFeatureClick,
language,
}) {
const {
drawSearchResultGroups,
drawNonRasterResultsRows,
} = searchMethods;
const groups = drawSearchResultGroups({
language,
translations,
container,
results,
});
drawNonRasterResultsRows({
groups,
onFeatureClick,
});
},
drawSearchResultGroups({
language,
translations,
container,
results,
isRaster = false,
}) {
const groups = container.selectAll('.sidebar__results-group')
.data(results, d => (isRaster ? d.category : d.sourceLayer));
groups.exit().remove();
const newGroups = groups
.enter()
.append('div')
.attr('class', 'sidebar__results-group');
newGroups.append('div')
.attr('class', 'sidebar__layer-group-title')
.text(d => (isRaster ? translations.ViewConesPoly[language] :
translations[d.sourceLayer][language]));
newGroups.append('div')
.attr('class', 'sidebar__result-rows');
return newGroups.merge(groups);
},
drawRasterResultRows({
groups,
onRasterClick,
cachedMetadata,
}) {
const { setEachRasterBackground } = rasterMethods;
groups.each(function drawLayers(d) {
const rows = d3.select(this)
.select('.sidebar__result-rows')
.selectAll('.sidebar__raster-results-row')
.data(d.features, dd => dd.SS_ID);
rows.exit().remove();
const newRows = rows.enter()
.append('div')
.attr('class', 'sidebar__raster-results-row')
.on('click', onRasterClick);
const imageRows = newRows
.append('div')
.attr('class', 'sidebar__results-image-row');
const newImages = imageRows
.append('div')
.attr('class', 'sidebar__raster-image');
setEachRasterBackground({
images: newImages,
cachedMetadata,
maxDim: 130,
spinner: true,
});
imageRows
.append('div')
.attr('class', 'sidebar__raster-title')
.text(dd => dd.Title);
});
},
drawNonRasterResultsRows({
groups,
onFeatureClick,
}) {
groups.each(function drawLayers(d) {
const uniqueFeatures = [...new Set(d.features.map(dd => dd.properties.Name))]
.map(id => d.features.find(dd => dd.properties.Name === id));
const rows = d3.select(this)
.select('.sidebar__result-rows')
.selectAll('.sidebar__results-row')
.data(uniqueFeatures, dd => dd.properties.Name);
rows.exit().remove();
const newRows = rows.enter()
.append('div')
.attr('class', 'sidebar__results-row');
const buttonRows = newRows
.append('div')
.attr('class', 'sidebar__results-button-row');
buttonRows
.append('div')
.attr('class', 'sidebar__results-button')
.text(dd => dd.properties.Name)
.on('click', onFeatureClick);
});
},
setSearchReturnListener({
searchReturnContainer,
textSearchReturnButton,
clearSearch,
}) {
searchReturnContainer
.on('click', clearSearch);
textSearchReturnButton
.on('click', clearSearch);
},
};
export default searchMethods;
<file_sep>/* imagineRio Cone Collector */
/* -------------------------*/
/* Config Vars */
/* -------------------------*/
let maxAngleAllowed = 170;
let tooltips = {
firstPoint: 'Click map to place Focal point of Visual',
secondPoint: 'Click map to place one side of the view cone',
thirdPoint: 'Click map to place the other side of the view cone',
fourthPoint: 'Click map to place the curve control point',
edit: {
subtext: 'Click cancel to remove the cone and start again.',
text: 'Drag markers to adjust the visual cone.'
}
};
/* -------------------------*/
/* Vars and Intialization */
/* -------------------------*/
let metaserver = 'https://beirut.axismaps.io';
let tileserver = 'https://beirut.axismaps.io/tiles/';
let year;
let maxYear = 2017;
let tiles = {};
let shown = {};
/* General Map */
let leafletMap = L.map('map', {
center: [29.717, -95.402],
zoom: 16,
minZoom: 15,
maxZoom: 18,
doubleClickZoom: false
});
let base = L.tileLayer(tileserver + year + '/{z}/{x}/{y}.png').addTo(leafletMap);
/* Slider */
let pipValues = _.range(1900, 2025, 25);
pipValues.push(maxYear);
let slider = noUiSlider.create(document.querySelector('.slider'), {
start: [1900],
connect: false,
step: 1,
range: {
min: [1900],
max: [2017]
},
pips: {
mode: 'values',
filter: (val) => {
if (val === maxYear) return 1;
else if (val === 2000) return 0;
else if (val % 50) {
if (val % 25) return 0;
else return 2;
} else return 1;
},
values: pipValues,
density: 2
},
tooltips: true,
format: {
to: (value) => value,
from: (value) => parseInt(value)
}
});
slider.on('set', (y) => {
updateYear(y[0]);
});
/* Leaflet Draw */
let editableLayer = new L.FeatureGroup();
let nonEditableLayer = new L.FeatureGroup();
leafletMap.addLayer(editableLayer);
leafletMap.addLayer(nonEditableLayer);
let drawControl = new L.Control.Draw({
draw: false,
edit: {
edit: false,
featureGroup: editableLayer,
remove: false
}
});
leafletMap.addControl(drawControl);
/* Sidebar */
// Set form submit location
document.querySelector('.sidebar--form').setAttribute('action', metaserver + '/collector/');
let requiredInputs = document.querySelectorAll('.required');
for (let i = 0; i < requiredInputs.length; i++) {
requiredInputs[i].addEventListener('change', function () {
checkForm();
});
}
// Submit Event
document.querySelector('.sidebar--submit').addEventListener('click', function (e) {
//e.preventDefault();
let formEl = document.querySelector('.sidebar--form');
let request = new XMLHttpRequest();
request.open('POST', metaserver + '/collector/', true);
// Success
request.addEventListener('load', function () {
document.querySelector('.success-message').classList.add('show');
setTimeout(function () {
document.querySelector('.success-message').classList.remove('show');
}, 3000);
cancelEditing();
newCone();
// Clear form
document.querySelectorAll('.sidebar--input, .sidebar--textarea').forEach(function (input) {
input.value = '';
});
// Return submit button back to disabled state
document.querySelector('.sidebar--submit').classList.add('disabled');
});
// Error
request.addEventListener('error', function (e) {
document.querySelector('.error-message > .message-response').textContent = e.responseText || 'There was an error submitting the viewcone to the server.';
document.querySelector('.error-message').classList.add('show');
setTimeout(function () {
document.querySelector('.error-message').classList.remove('show');
}, 3000);
});
var formData = new FormData(formEl);
var object = {};
formData.forEach(function(value, key){
object[key] = value;
});
request.send(JSON.stringify(object));
});
// Cancel event
document.querySelector('.sidebar--cancel').addEventListener('click', function (e) {
e.preventDefault();
cancelEditing();
newCone();
// Clear form
document.querySelectorAll('.sidebar--input, .sidebar--textarea').forEach(function (input) {
input.value = '';
});
});
/* -------------------------*/
/* Functions */
/* -------------------------*/
/* General Functions */
function updateYear(y) {
if (year == y) return false;
year = y;
loadTiles();
}
function mapLoading(show) {
if (show && document.querySelector('.loading') == null) {
let loading = document.createElement('div');
loading.classList.add('loading');
document.querySelector('.map').appendChild(loading);
leafletMap.dragging.disable();
leafletMap.touchZoom.disable();
leafletMap.doubleClickZoom.disable();
leafletMap.scrollWheelZoom.disable();
} else if (show === false) {
document.querySelector('.loading').remove();
leafletMap.dragging.enable();
leafletMap.touchZoom.enable();
leafletMap.doubleClickZoom.enable();
leafletMap.scrollWheelZoom.enable();
}
}
/* Tile functions */
function loadTiles() {
mapLoading(true);
if (tiles[year]) {
leafletMap.addLayer(tiles[year].setOpacity(0));
} else {
var t = L.tileLayer(tileserver + year + '/all/{z}/{x}/{y}.png')
.addTo(leafletMap)
.setOpacity(0)
.on('load', function () {
showTiles(this);
});
tiles[year] = t;
}
}
function showTiles(tile) {
if (!_.isEqual(shown.tiles, tile)) {
if (shown.tiles) leafletMap.removeLayer(tileFadeOut(shown.tiles));
shown.tiles = tileFadeIn(tile);
}
}
function tileFadeOut(tileOut) {
var i = 1;
var timer = setInterval(function () {
i -= 0.1;
if (i <= 0) clearInterval(timer);
tileOut.setOpacity(Math.max(0, i));
}, 50);
return tileOut;
}
function tileFadeIn(tileIn) {
var i = 0;
var timer = setInterval(function () {
i += 0.1;
if (i >= 1) {
clearInterval(timer);
mapLoading(false);
}
tileIn.setOpacity(Math.min(1, i));
}, 50);
return tileIn;
}
/* Leaflet Draw Functions */
let tooling;
let editing;
let genericIcon = L.divIcon({ className: 'cone-guidepoint', iconSize: 10 });
let majorPoints = [];
let line1;
let line2;
let line3;
let finalCone;
leafletMap.on('draw:canceled', function (e) {
cancelEditing();
newCone();
});
function newCone() {
let firstPointIcon = L.divIcon({ className: 'cone-point', iconSize: 10 });
// Set tooltip text
L.drawLocal.draw.handlers.marker.tooltip.start = tooltips.firstPoint;
tooling = new L.Draw.Marker(leafletMap, { icon: firstPointIcon });
tooling.enable();
leafletMap.on('draw:created', firstPointCreated);
}
function cancelEditing() {
// Clear cones
editableLayer.clearLayers();
nonEditableLayer.clearLayers();
if (tooling) tooling.disable();
tooling = null;
if (editing) editing.disable();
editing = null;
leafletMap.off('draw:created');
leafletMap.off('mousemove');
}
function firstPointCreated(e) {
// Add point
editableLayer.addLayer(e.layer);
majorPoints[0] = e.layer.getLatLng();
e.layer.dependentLayers = ['line1', 'line2', 'finalCone']; // for easier access during editing stage
e.layer.pointIndex = 0;
tooling.disable();
// Turn off old events
leafletMap.off('draw:created');
// Set tooltip text
L.drawLocal.draw.handlers.marker.tooltip.start = tooltips.secondPoint;
// Start new point
tooling = new L.Draw.Marker(leafletMap, { icon: genericIcon });
tooling.enable();
// Draw line between points
line1 = L.polyline([], { className: 'cone-guideline' }).addTo(nonEditableLayer);
// New events
leafletMap.on('mousemove', (e) => updateLine(line1, e.latlng));
leafletMap.on('draw:created', secondPointCreated);
}
function secondPointCreated(e) {
// Add point
editableLayer.addLayer(e.layer);
majorPoints[1] = e.layer.getLatLng();
e.layer.dependentLayers = ['line1', 'finalCone']; // for easier access during editing stage
e.layer.pointIndex = 1;
tooling.disable();
// Turn off old events
leafletMap.off('draw:created');
leafletMap.off('mousemove');
// Set tooltip text
L.drawLocal.draw.handlers.marker.tooltip.start = tooltips.thirdPoint;
// Start new point
tooling = new L.Draw.Marker(leafletMap, { icon: genericIcon });
tooling.enable();
// Draw line between points
line2 = L.polyline([], { className: 'cone-guideline' }).addTo(nonEditableLayer);
// New events
leafletMap.on('mousemove', (e) => {
updateLine(line2, e.latlng);
tooling._marker.setLatLng(snapSidePoint(e.layerPoint, majorPoints[1], line2));
});
leafletMap.on('draw:created', thirdPointCreated);
}
function thirdPointCreated(e) {
// Add point
editableLayer.addLayer(e.layer);
majorPoints[2] = e.layer.getLatLng();
e.layer.dependentLayers = ['line2', 'finalCone']; // for easier access during editing stage
e.layer.pointIndex = 2;
tooling.disable();
// Turn off old events
leafletMap.off('draw:created');
leafletMap.off('mousemove');
// Set tooltip text
L.drawLocal.draw.handlers.marker.tooltip.start = tooltips.fourthPoint;
// Start new point
tooling = new L.Draw.Marker(leafletMap, { icon: genericIcon });
tooling.enable();
// Draw invisble line between point 0 and halfwayPoint - used for snapping
let halfwayPoint = L.latLng((majorPoints[1].lat - majorPoints[2].lat) / 2 + majorPoints[2].lat, (majorPoints[1].lng - majorPoints[2].lng) / 2 + majorPoints[2].lng);
line3 = L.polyline([], { className: 'cone-guideline--invisible' }).addTo(nonEditableLayer);
updateLine(line3, halfwayPoint);
// Draw polygon between points
finalCone = L.polygon([], { className: 'cone-guidepolygon' }).addTo(nonEditableLayer);
// New events
leafletMap.on('mousemove', (e) => {
let snappedPoint = snapFourthPoint(e.layerPoint);
tooling._marker.setLatLng(snappedPoint);
updatePolygon(snappedPoint);
});
leafletMap.on('draw:created', fourthPointCreated);
}
function fourthPointCreated(e) {
// Add point
editableLayer.addLayer(e.layer);
majorPoints[3] = e.layer.getLatLng();
e.layer.dependentLayers = ['line3', 'finalCone']; // for easier access during editing stage
e.layer.pointIndex = 3;
tooling.disable();
// Update form
checkForm();
// Turn off old events
leafletMap.off('draw:created');
leafletMap.off('mousemove');
// Set tooltip text
L.drawLocal.edit.handlers.edit.tooltip.subtext = tooltips.edit.subtext;
L.drawLocal.edit.handlers.edit.tooltip.text = tooltips.edit.text;
// Start editing
editing = new L.EditToolbar.Edit(leafletMap, { featureGroup: editableLayer });
editing.enable();
editableLayer.eachLayer(function (layer) {
layer.on('drag', function (e) {
let dependentLayers = e.target.dependentLayers;
let layerPoint = leafletMap.latLngToLayerPoint(e.latlng);
// update point location
majorPoints[e.target.pointIndex] = e.target.getLatLng();
// update any lines affected
let newLinePoint = e.target.pointIndex ? e.target.getLatLng() : null;
if (dependentLayers.indexOf('line1') >= 0) {
updateLine(line1, newLinePoint);
// snapPoint and update markers accordingly
let snappedPoint = snapSidePoint(layerPoint, majorPoints[2], line1);
editing._featureGroup.eachLayer(function (l) {
if (l.pointIndex === 1) l.setLatLng(snappedPoint); // update visible marker
});
line1._latlngs[1] = snappedPoint; // update line
majorPoints[1] = snappedPoint; // update majorPoints to snapped version
}
if (dependentLayers.indexOf('line2') >= 0) {
updateLine(line2, newLinePoint);
// snapPoint and update markers accordingly
let snappedPoint = snapSidePoint(layerPoint, majorPoints[1], line2);
editing._featureGroup.eachLayer(function (l) {
if (l.pointIndex === 2) l.setLatLng(snappedPoint); // update visible marker
});
line2._latlngs[1] = snappedPoint; // update line
majorPoints[2] = snappedPoint; // update majorPoints to snapped version
}
// Update curve point based on the movement of the two lines
if (dependentLayers.indexOf('line1') || dependentLayers.indexOf('line2')) {
let halfwayPoint = L.latLng((majorPoints[1].lat - majorPoints[2].lat) / 2 + majorPoints[2].lat, (majorPoints[1].lng - majorPoints[2].lng) / 2 + majorPoints[2].lng);
updateLine(line3, halfwayPoint);
// snapPoint and update markers accordingly
let snappedPoint = snapFourthPoint(leafletMap.latLngToLayerPoint(majorPoints[3]));
editing._featureGroup.eachLayer(function (l) {
if (l.pointIndex === 3) l.setLatLng(snappedPoint); // update visible marker
});
line3._latlngs[1] = snappedPoint; // update line
majorPoints[3] = snappedPoint; // update majorPoints to snapped version
}
if (dependentLayers.indexOf('line3') >= 0) {
let halfwayPoint = L.latLng((majorPoints[1].lat - majorPoints[2].lat) / 2 + majorPoints[2].lat, (majorPoints[1].lng - majorPoints[2].lng) / 2 + majorPoints[2].lng);
updateLine(line3, halfwayPoint);
// snapPoint and update markers accordingly
let snappedPoint = snapFourthPoint(leafletMap.latLngToLayerPoint(e.latlng));
e.target.setLatLng(snappedPoint); // update visible marker
line3._latlngs[1] = snappedPoint; // update line
majorPoints[3] = snappedPoint; // update majorPoints to snapped version
}
// update the cone polygon
if (dependentLayers.indexOf('finalCone') >= 0) {
updatePolygon();
}
});
});
}
function updateLine(line, midPoint) {
if (!midPoint) midPoint = line.getLatLngs()[1]; // if no midPoint, then updated point was majorPoints[0]
let c = getMapEdgePoint(leafletMap.latLngToLayerPoint(majorPoints[0]), leafletMap.latLngToLayerPoint(midPoint));
let previousLineLatLngs = line.getLatLngs();
line.setLatLngs([majorPoints[0], midPoint, leafletMap.layerPointToLatLng(c)]);
// Don't allow the line to extend beyond a given angle
if (line1 && line2 && getAngle(line1, line2) > maxAngleAllowed) line.setLatLngs(previousLineLatLngs);
}
function snapSidePoint(mousePoint, equivalentPoint, line) {
let point0 = leafletMap.latLngToLayerPoint(majorPoints[0]);
let point1 = leafletMap.latLngToLayerPoint(equivalentPoint);
let dist = Math.sqrt(Math.pow(point1.x - point0.x, 2) + Math.pow(point1.y - point0.y, 2));
let pointAlongLine = findPointAlongLine(line, dist);
let pointToUse = mousePoint;
if (mousePoint.distanceTo(pointAlongLine) <= 10 || getAngle(line1, line2) > maxAngleAllowed) pointToUse = pointAlongLine;
return leafletMap.layerPointToLatLng(pointToUse);
}
function snapFourthPoint(mousePoint) {
const line3LLs = line3.getLatLngs();
let point0 = leafletMap.latLngToLayerPoint(line3LLs[0]);
let point1 = leafletMap.latLngToLayerPoint(line3LLs[2]);
let snappedPoint = L.LineUtil.closestPointOnSegment(mousePoint, point0, point1);
let pointToUse = mousePoint;
if (mousePoint.distanceTo(snappedPoint) <= 10) pointToUse = snappedPoint;
let pointToUseLL = leafletMap.layerPointToLatLng(pointToUse);
if (isLeft(majorPoints[1], majorPoints[2], majorPoints[0]) === isLeft(majorPoints[1], majorPoints[2], pointToUseLL)) pointToUseLL = line3LLs[1];
if (isLeft(majorPoints[0], majorPoints[1], line3LLs[1]) !== isLeft(majorPoints[0], majorPoints[1], pointToUseLL)) pointToUseLL = line3LLs[1];
if (isLeft(majorPoints[0], majorPoints[2], line3LLs[1]) !== isLeft(majorPoints[0], majorPoints[2], pointToUseLL)) pointToUseLL = line3LLs[1];
return pointToUseLL;
}
// assumes that line[0] is the beginning point of distance
function findPointAlongLine(line, distance) {
let line0Point = leafletMap.latLngToLayerPoint(line.getLatLngs()[0]);
let line1Point = leafletMap.latLngToLayerPoint(line.getLatLngs()[1]);
let originVector = [line1Point.x - line0Point.x, line1Point.y - line0Point.y];
let unitVectorDenominator = Math.sqrt(Math.pow(originVector[0], 2) + Math.pow(originVector[1], 2));
let unitVector = [originVector[0] / unitVectorDenominator, originVector[1] / unitVectorDenominator];
let distanceVector = [distance * unitVector[0], distance * unitVector[1]];
return L.point(line0Point.x + distanceVector[0], line0Point.y + distanceVector[1]);
}
function updatePolygon(curvePoint) {
if (!curvePoint) curvePoint = majorPoints[3];
let newPoints = [[majorPoints[0].lat, majorPoints[0].lng]].concat(generateCurvePoints([majorPoints[1], curvePoint, majorPoints[2]]));
finalCone.setLatLngs(newPoints);
savePolygonToForm();
}
function getMapEdgePoint(a, b) {
let length = Math.sqrt(Math.pow(a.x - b.x, 2) + Math.pow(a.y - b.y, 2));
let c = {};
c.x = b.x + (b.x - a.x) / length * window.outerWidth;
c.y = b.y + (b.y - a.y) / length * window.outerWidth;
return c;
}
function getAngle(l1, l2) {
let l1Points = l1.getLatLngs().map((ll) => leafletMap.latLngToLayerPoint(ll));
let l2Points = l2.getLatLngs().map((ll) => leafletMap.latLngToLayerPoint(ll));
let angle1 = Math.atan2(l1Points[0].y - l1Points[1].y, l1Points[0].x - l1Points[1].x);
let angle2 = Math.atan2(l2Points[0].y - l2Points[1].y, l2Points[0].x - l2Points[1].x);
let returnAngle = Math.round(Math.abs(angle1 - angle2) * 180 / Math.PI);
return returnAngle > 180 ? 360 - returnAngle : returnAngle;
}
function isLeft(a, b, c) {
return ((b.lng - a.lng) * (c.lat - a.lat) - (b.lat - a.lat) * (c.lng - a.lng)) > 0;
}
function generateCurvePoints(ptsArray) {
let tension = 0.5;
let numOfSegments = 32;
let _pts;
let result = [];
let pl = ptsArray.length;
// clone array so we don't change the original content
_pts = _.flatten(ptsArray.map((pt) => [pt.lng, pt.lat]));
// Add control point
let halfwayPoint1 = [(ptsArray[0].lng - majorPoints[0].lng) / 2 + majorPoints[0].lng, (ptsArray[0].lat - majorPoints[0].lat) / 2 + majorPoints[0].lat];
let point01Dist = [ptsArray[1].lng - ptsArray[0].lng, ptsArray[1].lat - ptsArray[0].lat];
_pts.unshift(halfwayPoint1[1] - point01Dist[1]);
_pts.unshift(halfwayPoint1[0] - point01Dist[0]);
// Add second control point
let halfwayPoint2 = [(ptsArray[2].lng - majorPoints[0].lng) / 2 + majorPoints[0].lng, (ptsArray[2].lat - majorPoints[0].lat) / 2 + majorPoints[0].lat];
let point12Dist = [ptsArray[1].lng - ptsArray[2].lng, ptsArray[1].lat - ptsArray[2].lat];
_pts.push(halfwayPoint2[0] - point12Dist[0], halfwayPoint2[1] - point12Dist[1]);
// 1. loop goes through point array
// 2. loop goes through each segment between the two points + one point before and after
for (let i = 2; i < (_pts.length - 4); i += 2) {
let p0 = _pts[i];
let p1 = _pts[i + 1];
let p2 = _pts[i + 2];
let p3 = _pts[i + 3];
// calc tension vectors
let t1x = (p2 - _pts[i - 2]) * tension;
let t2x = (_pts[i + 4] - p0) * tension;
let t1y = (p3 - _pts[i - 1]) * tension;
let t2y = (_pts[i + 5] - p1) * tension;
for (let t = 0; t <= numOfSegments; t++) {
// calc step
let st = t / numOfSegments;
let pow2 = Math.pow(st, 2);
let pow3 = pow2 * st;
let pow23 = pow2 * 3;
let pow32 = pow3 * 2;
// calc cardinals
let c1 = pow32 - pow23 + 1;
let c2 = pow23 - pow32;
let c3 = pow3 - 2 * pow2 + st;
let c4 = pow3 - pow2;
// calc x and y cords with common control vectors
let x = c1 * p0 + c2 * p2 + c3 * t1x + c4 * t2x;
let y = c1 * p1 + c2 * p3 + c3 * t1y + c4 * t2y;
// store points in array
result.push([y, x]);
}
}
return result;
}
function savePolygonToForm() {
document.getElementById('form-polygon-data').value = JSON.stringify(finalCone.toGeoJSON());
document.getElementById('form-point-lat').value = majorPoints[0].lat;
document.getElementById('form-point-lon').value = majorPoints[0].lng;
checkForm();
}
function checkForm() {
let modifiedCount = 0
// check form
let required = document.querySelectorAll('.required');
for (let i = 0; i < required.length; i++) {
if (required[i].value !== '') modifiedCount += 1;
}
// check polygon is drawn
if (majorPoints[3]) modifiedCount += 1;
if (modifiedCount === 5) {
document.querySelector('.sidebar--submit').classList.remove('disabled');
}
}
/* -------------------------*/
/* Start */
/* -------------------------*/
slider.set(1950);
newCone();
<file_sep>/**
* Module initializes atlas component
* @module initAtlas
*/
import Atlas from '../atlas/atlas';
const initAtlas = function initAtlas() {
const { state } = this.components;
this.components.atlas = new Atlas({
extentsData: this.data.extents,
mobile: state.get('mobile'),
overlayOpacity: state.get('overlayOpacity'),
initialLocation: state.get('currentLocation'),
viewshedsGeo: this.data.viewshedsGeo,
highlightedFeature: state.get('highlightedFeature'),
highlightedLayer: state.get('highlightedLayer'),
availableLayers: this.components.state.getAvailableLayers(this.data),
currentLayers: state.get('currentLayers'),
currentOverlay: state.get('currentOverlay'),
currentView: state.get('currentView'),
rasterData: state.getAvailableRasters(this.data),
year: state.get('year'),
layerNames: this.data.layerNames,
/**
* Some components need to be initialized only after map (vector tiles) have loaded
* @private
*/
onLoad: () => {
if (state.get('view') === 'map') {
this.initComponents();
this.listenForResize();
}
state.update({ mapLoaded: true });
},
onClickSearch(features) {
state.update({ clickSearch: features });
},
onAreaSearch(features) {
state.update({ areaSearchActive: false, areaSearch: features });
},
onViewClick(newView) {
state.update({
currentView: newView,
currentRasterProbe: newView,
});
},
onMove(currentLocation) {
state.update({
currentLocation,
});
},
toggleOverlayFade(toggle) {
const overlayOn = state.get('currentOverlay') !== null;
if (overlayOn) {
if (toggle) {
state.update({ overlayOpacity: 0.1 });
} else {
state.update({ overlayOpacity: 1 });
}
}
},
toggleMouseEventsDisabled(toggle) {
state.update({ mouseEventsDisabled: toggle });
},
translations: this.data.translations,
language: state.get('language'),
});
};
export default initAtlas;
<file_sep>/**
* Module comprises methods related to slider
* @module timelineSlider
* @memberof timeline
*/
import Timeline from './timeline';
import getSliderBase from './timelineSliderBase';
import getSliderAxis from './timelineSliderAxis';
import getTooltipMethods from './timelineTooltipMethods';
const privateProps = new WeakMap();
const privateMethods = {
init() {
const {
setScale,
updateScale,
drawSvg,
updateSvgSize,
drawDetectionTrack,
updateDetectionTrack,
drawBackgroundTrack,
updateBackgroundTrack,
drawActiveTrack,
drawHighlightedRange,
drawHandle,
initAxis,
updateSliderPosition,
setDrag,
initTooltip,
} = privateMethods;
setScale.call(this);
updateScale.call(this);
drawSvg.call(this);
updateSvgSize.call(this);
drawDetectionTrack.call(this);
updateDetectionTrack.call(this);
drawBackgroundTrack.call(this);
updateBackgroundTrack.call(this);
drawActiveTrack.call(this);
drawHighlightedRange.call(this);
initAxis.call(this);
drawHandle.call(this);
updateSliderPosition.call(this);
setDrag.call(this);
initTooltip.call(this);
return this;
},
drawHandle() {
const props = privateProps.get(this);
const {
svg,
handleHeight,
handleWidth,
handleAttrs,
handleDetail,
} = props;
props.handle = svg
.append('g');
props.handle
.append('rect')
.attrs(Object.assign({
class: 'slider__handle',
width: handleWidth,
height: handleHeight,
y: 0,
x: 0,
rx: 3,
ry: 3,
}, handleAttrs));
const lineHeight = 20;
if (!handleDetail) return;
props.handle
.append('line')
.attrs({
class: 'slider__line',
x1: handleWidth / 2,
x2: handleWidth / 2,
y1: (handleHeight / 2) - (lineHeight / 2),
y2: (handleHeight / 2) + (lineHeight / 2),
});
},
setHandlePosition() {
const props = privateProps.get(this);
const {
handleScale,
handle,
currentValue,
handleWidth,
size,
handleHeight,
} = props;
handle
.attr('transform', `translate(${handleScale(currentValue) - (handleWidth / 2)}, ${(size.height / 2) - (handleHeight / 2)})`);
},
setActiveTrackPosition() {
const props = privateProps.get(this);
const {
handleScale,
activeTrack,
currentValue,
valueRange,
handleHeight,
} = props;
const width = (handleScale(currentValue) - handleScale(valueRange[0])) + (handleHeight);
if (width < 0) return;
activeTrack.attr('width', width);
},
updateSliderPosition() {
const {
setHandlePosition,
setActiveTrackPosition,
} = privateMethods;
setHandlePosition.call(this);
setActiveTrackPosition.call(this);
},
setDrag() {
const props = privateProps.get(this);
const {
scale,
detectionTrack,
onDragEnd,
tooltip,
mobile,
uniqueYears,
opacitySlider,
} = props;
const { setTooltipPosition } = privateMethods;
detectionTrack.call(d3.drag()
.on('start.interrupt', () => {
detectionTrack.interrupt();
})
.on('start drag', () => {
const { valueRange, svgPosition } = props;
const sliderValue = scale.invert(d3.event.x);
if (tooltip && !mobile) {
setTooltipPosition.call(this, { x: d3.event.x + svgPosition.left });
}
let newValue;
if (sliderValue >= valueRange[0] && sliderValue <= valueRange[1]) {
newValue = sliderValue;
} else if (sliderValue < valueRange[0]) {
/* eslint-disable prefer-destructuring */
newValue = valueRange[0];
} else if (sliderValue > valueRange[1]) {
newValue = valueRange[1];
/* eslint-enable prefer-destructuring */
}
if (opacitySlider) {
onDragEnd(newValue);
} else {
onDragEnd(Timeline.getUniqueYear(newValue, uniqueYears));
}
}));
},
};
const baseMethods = getSliderBase({ privateProps, privateMethods });
const axisMethods = getSliderAxis({ privateProps, privateMethods });
const tooltipMethods = getTooltipMethods({ privateProps, privateMethods });
Object.assign(privateMethods, baseMethods, axisMethods, tooltipMethods);
class TimelineSlider {
constructor(config) {
privateProps.set(this, {
dragging: false,
tooltip: false,
axisOn: true,
handleDetail: true,
trackHeight: 5,
handleHeight: 20,
highlightColor: 'black',
activeTrackAttrs: {},
handleAttrs: {},
highlightedRange: undefined,
});
this.config(config);
privateMethods.init.call(this);
}
config(config) {
Object.assign(privateProps.get(this), config);
return this;
}
update() {
const {
updateSliderPosition,
} = privateMethods;
updateSliderPosition.call(this);
}
updateHighlightedRange() {
const {
highlightedRange,
handleScale,
highlightedRangeBar,
highlightColor,
valueRange,
highlightedRangeLeftEnd,
highlightedRangeRightEnd,
} = privateProps.get(this);
if (highlightedRange !== undefined) {
const width = handleScale(highlightedRange[1]) - handleScale(highlightedRange[0]);
const atStart = highlightedRange[0] === valueRange[0];
const atEnd = highlightedRange[1] === valueRange[1];
const bigEnough = width >= (handleScale.range()[1] - handleScale.range()[0]) / 2;
highlightedRangeBar
.attrs({
x: handleScale(highlightedRange[0]),
width,
opacity: 1,
fill: highlightColor,
});
highlightedRangeLeftEnd
.attrs({
cx: handleScale(highlightedRange[0]),
fill: highlightColor,
opacity: atStart && bigEnough ? 1 : 0,
});
highlightedRangeRightEnd
.attrs({
cx: handleScale(highlightedRange[1]),
fill: highlightColor,
opacity: atEnd && bigEnough ? 1 : 0,
});
} else {
[
highlightedRangeBar,
highlightedRangeLeftEnd,
highlightedRangeRightEnd,
].forEach(el => el.attr('opacity', 0));
}
}
getScale() {
const { scale } = privateProps.get(this);
return scale;
}
getHandleScale() {
const { handleScale } = privateProps.get(this);
return handleScale;
}
getSvg() {
const { svg } = privateProps.get(this);
return svg;
}
getSize() {
return privateProps.get(this).size;
}
getTrackHeight() {
return privateProps.get(this).trackHeight;
}
updateDimensions() {
const {
updateScale,
updateSvgSize,
updateBackgroundTrack,
updateDetectionTrack,
updateAxis,
} = privateMethods;
updateScale.call(this);
updateSvgSize.call(this);
updateBackgroundTrack.call(this);
updateDetectionTrack.call(this);
updateAxis.call(this);
this.update();
}
updateValueRange() {
const {
updateScaleValueRange,
} = privateMethods;
updateScaleValueRange.call(this);
}
}
export default TimelineSlider;
<file_sep>/**
* Module comprises public methods for the layout module
* @module layoutPublicMethods
* @memberof layout
*/
const getPublicMethods = ({ privateProps, privateMethods }) => ({
config(config) {
const props = privateProps.get(this);
props.previousEra = props.currentEra;
Object.assign(privateProps.get(this), config);
return this;
},
updateHighlightedFeature() {
const {
outerContainer,
highlightedFeature,
dataProbeMobileTitle,
dataProbeMobileContent,
} = privateProps.get(this);
outerContainer
.classed('outer-container--highlighted', highlightedFeature !== null);
if (highlightedFeature == null) return;
dataProbeMobileTitle
.text(highlightedFeature.properties.Name);
const start = highlightedFeature.properties.FirstYear;
const end = highlightedFeature.properties.LastYear === 8888 ?
new Date().getFullYear() :
highlightedFeature.properties.LastYear;
const creator = highlightedFeature.properties.Creator;
let content = '';
const addContentRow = (text) => {
content += `
<div class="mobile-probe__content-row">
${text}
</div>
`;
};
if (creator !== '') {
addContentRow(`Creator: ${creator}`);
}
addContentRow(`Mapped: ${start} - ${end}`);
dataProbeMobileContent
.html(content);
},
updateRasterProbe() {
const {
outerContainer,
rasterProbeOpen,
} = privateProps.get(this);
outerContainer.classed('raster-probe-on', rasterProbeOpen);
},
updateOverlay() {
const {
outerContainer,
overlayOn,
} = privateProps.get(this);
outerContainer.classed('overlay-on', overlayOn);
},
updateSidebar() {
const {
outerContainer,
sidebarOpen,
} = privateProps.get(this);
outerContainer.classed('sidebar-open', sidebarOpen);
},
updateLocation() {
const {
outerContainer,
sidebarContainer,
zoomedOut,
rotated,
} = privateProps.get(this);
outerContainer.classed('rotated', rotated);
sidebarContainer.classed('sidebar--zoom-hint', zoomedOut);
},
removeSidebarToggleLabel() {
const props = privateProps.get(this);
const {
sidebarToggleHelpContainer,
sidebarOpened,
} = props;
if (sidebarOpened) return;
props.sidebarOpen = true;
sidebarToggleHelpContainer.remove();
},
updateFooter() {
const {
outerContainer,
footerOpen,
} = privateProps.get(this);
const { updateFooter } = privateMethods;
updateFooter({ outerContainer, footerOpen });
},
updateAreaSearch() {
const {
probeButtonsContainer,
areaSearchActive,
} = privateProps.get(this);
probeButtonsContainer.classed('probe-buttons-container--area-search', areaSearchActive);
},
updateAllRaster() {
const {
allRasterOpen,
outerContainer,
} = privateProps.get(this);
outerContainer.classed('allraster-open', allRasterOpen);
},
updateEra() {
const {
currentEra,
previousEra,
language,
} = privateProps.get(this);
const { setErasButtonText } = privateMethods;
if (previousEra[language] === currentEra[language]) return;
setErasButtonText.call(this);
},
toggleMouseEvents() {
const { outerContainer, mouseEventsDisabled } = privateProps.get(this);
outerContainer.classed('mouse-disabled', mouseEventsDisabled);
},
toggleTransitions() {
const { outerContainer, transitionsDisabled } = privateProps.get(this);
outerContainer.classed('transitions-disabled', transitionsDisabled);
},
removeHintProbe() {
const props = privateProps.get(this);
const {
hintProbeContainer,
hintProbeContainerMobile,
hintProbeOn,
} = props;
if (!hintProbeOn) return;
hintProbeContainer.remove();
hintProbeContainerMobile.remove();
props.hintProbeOn = false;
},
updateLanguage() {
const {
setHintProbeLanguage,
setAreaProbeLanguage,
setRegisterButtonLanguage,
setErasButtonText,
setErasBackButtonText,
} = privateMethods;
setHintProbeLanguage.call(this);
setAreaProbeLanguage.call(this);
setRegisterButtonLanguage.call(this);
setErasButtonText.call(this);
setErasBackButtonText.call(this);
},
updateRegisterScreen() {
const {
registerOpen,
registerOuterContainer,
} = privateProps.get(this);
registerOuterContainer
.classed('register__outer--on', registerOpen);
},
updateMapLoaded() {
const {
loadingScreenContainer,
mapLoaded,
} = privateProps.get(this);
if (mapLoaded) {
loadingScreenContainer
.style('opacity', 1)
.transition()
.duration(750)
.style('opacity', 0)
.remove();
}
},
updateMobile() {
const {
outerContainer,
mobile,
} = privateProps.get(this);
outerContainer
.classed('outer-container--desktop', !mobile)
.classed('outer-container--mobile', mobile);
},
});
export default getPublicMethods;
<file_sep>/**
* Callback for overlayOpacity field
* "overlayOpacity" float represents opacity of map overlay
* @module
* @memberof stateUpdate
*/
const getUpdateOverlayOpacity = ({ components }) => {
const updateOverlayOpacity = function updateOverlayOpacity() {
const { overlayOpacity } = this.props();
const {
rasterProbe,
atlas,
} = components;
rasterProbe
.config({
overlayOpacity,
})
.updateSlider();
atlas
.config({
overlayOpacity,
})
.updateOverlayOpacity();
};
return updateOverlayOpacity;
};
export default getUpdateOverlayOpacity;
<file_sep>const fs = require('fs');
const path = require('path');
const _ = require('underscore');
fs.readFile(path.join(__dirname, '../data/geojson/visual/ViewConesPoly.json'), 'utf8', (err, data) => {
const points = JSON.parse(data);
const polys = JSON.parse(data);
const csv = [];
points.features = points.features.map((p) => {
const feature = p;
feature.geometry.type = 'Point';
feature.geometry.coordinates = [
parseFloat(p.properties.Longitude),
parseFloat(p.properties.Latitude),
];
feature.properties = _.pick(p.properties, ['SS_ID', 'FirstYear', 'LastYear']);
return feature;
});
points.features = points.features.filter(p =>
p.geometry.coordinates[0] && p.geometry.coordinates[1]);
polys.features = polys.features.map((p) => {
const feature = p;
const props = _.omit(p.properties, ['StyleName', 'ScaleRank', 'Latitude', 'Longitude', 'Shape_Leng', 'Shape_Area']);
csv.push(props);
feature.properties = props;
return feature;
});
fs.writeFileSync(path.join(__dirname, '../data/geojson/geography/ViewConesPoint.json'), JSON.stringify(points));
fs.writeFileSync(path.join(__dirname, '../src/data/ViewConesPoly.json'), JSON.stringify(polys));
fs.writeFileSync(path.join(__dirname, '../dist/data/ViewConesPoly.json'), JSON.stringify(polys));
});
<file_sep>/**
* Module loads and parses static data
* @module initData
*/
import { cleanData } from '../data/data';
const loadData = (callback) => {
Promise.all([
d3.json('data/config.json'),
d3.json('data/ViewConesPoly.json'),
d3.json('data/AerialExtents.json'),
d3.json('data/MapExtents.json'),
d3.json('data/PlanExtents.json'),
d3.json('data/extents.json'),
d3.json('data/years.json'),
d3.csv('data/translations.csv'),
d3.csv('img/legend/legend.csv'),
]).then((rawData) => {
const data = cleanData(rawData);
callback(data);
});
};
export default loadData;
<file_sep>/**
* Module initializes footer component
* @module initFooter
*/
import Footer from '../footer/footer';
import rasterMethods from '../rasterProbe/rasterMethods';
const initFooter = function initFooter() {
const { state } = this.components;
const { onRasterClick } = rasterMethods;
this.components.footer = new Footer({
translations: this.data.translations,
language: state.get('language'),
year: state.get('year'),
mobile: state.get('mobile'),
footerView: state.get('footerView'),
rasterData: state.getAvailableRasters(this.data),
cachedMetadata: this.cachedMetadata,
onCategoryClick(newCategory) {
const currentView = state.get('footerView');
if (newCategory === currentView) return;
state.update({ footerView: newCategory });
},
onRasterClick(rasterData) {
onRasterClick({ rasterData, state });
},
onAllRasterCloseClick() {
state.update({ allRasterOpen: false });
},
onAllRasterClick() {
state.update({ allRasterOpen: true });
},
onToggleClick(toggle) {
state.update({ footerOpen: toggle === undefined ? !state.get('footerOpen') : toggle });
},
});
};
export default initFooter;
<file_sep>/**
* Callback for language field
* "language" string represents current map language
* @module
* @memberof stateUpdate
*/
const getUpdateLanguage = ({
components,
}) => {
const updateLanguage = function updateLanguage() {
const { language } = this.props();
const {
urlParams,
languageDropdown,
eraDropdown,
intro,
eras,
sidebar,
layout,
footer,
atlas,
} = components;
urlParams.config({ language }).update();
languageDropdown.config({ language }).update();
eraDropdown.config({ language }).update();
intro.config({ language }).update();
eras.config({ language }).updateLanguage();
sidebar.config({ language }).updateLanguage();
layout.config({ language }).updateLanguage();
footer.config({ language }).updateLanguage();
atlas.config({ language });
};
return updateLanguage;
};
export default getUpdateLanguage;
<file_sep>/**
* Module comprises functions related to atlas feature highlighting
* @module atlasHighlightMethods
* @memberof atlas
*/
import union from '@turf/union';
import { colors } from '../config/config';
const atlasHighlightMethods = {
getHighlightedGeoJSON({
highlightedFeature,
year,
mbMap,
}) {
const features = mbMap.querySourceFeatures('composite', {
sourceLayer: highlightedFeature.sourceLayer,
layers: [highlightedFeature.style],
filter: [
'all',
['<=', 'FirstYear', year],
['>=', 'LastYear', year],
['==', 'Name', highlightedFeature.properties.Name],
],
});
if (features.length === 0) {
return {
type: 'FeatureCollection',
features,
};
}
if (highlightedFeature.geometry.type.includes('Polygon')) {
return {
type: 'FeatureCollection',
features: [features.reduce((accumulator, feature) =>
union(accumulator, feature))],
};
}
return {
type: 'FeatureCollection',
features,
};
},
getLayerBounds({
year,
highlightedFeature,
extentsData,
}) {
const extentsForLayer =
extentsData[highlightedFeature.sourceLayer][highlightedFeature.dataLayer];
const years = Object.keys(extentsForLayer).map(d => parseInt(d, 10));
const closestYear = years.reduce((accumulator, d) => {
if (d <= year && d > accumulator) {
return d;
}
return accumulator;
});
const featureExtent = extentsForLayer[String(closestYear)];
const sw = new mapboxgl.LngLat(featureExtent[0], featureExtent[1]);
const ne = new mapboxgl.LngLat(featureExtent[2], featureExtent[3]);
return new mapboxgl.LngLatBounds(sw, ne);
},
clearHighlightedFeature(mbMap) {
const polyLayers = [
'highlighted-feature-fill',
'highlighted-feature-outline-top',
'highlighted-feature-outline-bottom',
];
const lineLayers = [
'highlighted-feature-outline-top',
'highlighted-feature-outline-bottom',
];
const existingHighlighted = mbMap.getSource('highlighted');
const existingPoly = mbMap.getLayer('highlighted-feature-fill');
const existingOutline = mbMap.getLayer('highlighted-feature-outline-top');
if (existingHighlighted !== undefined) {
if (existingPoly !== undefined) {
polyLayers.forEach((layer) => {
mbMap.removeLayer(layer);
});
} else if (existingOutline !== undefined) {
lineLayers.forEach((layer) => {
mbMap.removeLayer(layer);
});
}
}
},
drawHighlightedFeature({
highlightedFeature,
mbMap,
year,
geoJSON,
}) {
const existingHighlighted = mbMap.getSource('highlighted');
if (highlightedFeature === null) return;
let featureJSON;
const notEntireLayer = !Object.prototype.hasOwnProperty.call(highlightedFeature, 'dataLayer');
if (notEntireLayer && geoJSON === undefined) {
featureJSON = {
type: 'FeatureCollection',
features: mbMap.querySourceFeatures('composite', {
sourceLayer: highlightedFeature.sourceLayer,
layers: [highlightedFeature.style],
filter: [
'all',
['<=', 'FirstYear', year],
['>=', 'LastYear', year],
['==', '$id', highlightedFeature.id],
],
}),
};
} else if (geoJSON !== undefined) {
featureJSON = geoJSON;
} else {
featureJSON = {
type: 'FeatureCollection',
features: mbMap.querySourceFeatures('composite', {
sourceLayer: highlightedFeature.sourceLayer,
layers: [highlightedFeature.style],
filter: [
'all',
['<=', 'FirstYear', year],
['>=', 'LastYear', year],
['==', 'SubType', highlightedFeature.dataLayer],
],
}),
};
}
if (existingHighlighted === undefined) {
mbMap.addSource('highlighted', {
type: 'geojson',
data: featureJSON,
});
} else {
existingHighlighted.setData(featureJSON);
}
const fillLayer = {
id: 'highlighted-feature-fill',
type: 'fill',
source: 'highlighted',
layout: {},
paint: {
'fill-color': colors.highlightColor,
'fill-opacity': 0.2,
},
};
const outlineLayerTop = {
id: 'highlighted-feature-outline-top',
type: 'line',
source: 'highlighted',
layout: {
'line-join': 'round',
},
paint: {
'line-width': 2,
'line-color': '#eee',
},
};
const outlineLayerBottom = {
id: 'highlighted-feature-outline-bottom',
type: 'line',
source: 'highlighted',
layout: {
'line-join': 'round',
},
paint: {
'line-width': 8,
'line-color': colors.highlightColor,
'line-opacity': 0.5,
},
};
const isPolygon = feature => feature.geometry.type === 'Polygon' || feature.geometry.type === 'MultiPolygon';
if (featureJSON.features.length === 0) return;
if (featureJSON.type === 'FeatureCollection') {
if (isPolygon(featureJSON.features[0])) {
mbMap.addLayer(fillLayer);
}
mbMap.addLayer(outlineLayerBottom);
mbMap.addLayer(outlineLayerTop);
} else {
if (isPolygon(featureJSON)) {
mbMap.addLayer(fillLayer);
}
mbMap.addLayer(outlineLayerBottom);
mbMap.addLayer(outlineLayerTop);
}
},
updateLuminosity(
mbMap,
layerId,
paintProp,
) {
let hsl = mbMap.getPaintProperty(layerId, paintProp);
if (hsl) {
if (Array.isArray(hsl)) hsl = hsl[hsl.length - 1];
const nums = hsl.match(/\d+\.?\d*/gm);
if (nums.length === 3 || nums.length === 4) {
nums[2] = Math.min(parseInt(nums[2], 10) + 20, 100);
const bright = `hsl(${nums[0]}, ${nums[1]}%, ${nums[2]}%)`;
mbMap.setPaintProperty(layerId, paintProp, bright);
}
}
},
};
export default atlasHighlightMethods;
<file_sep>/**
* Callback for allRasterOpen field
* "allRasterOpen "boolean field determines whether "show all" raster screen is on or not
* @module
* @memberof stateUpdate
*/
const getUpdateAllRasterOpen = ({
components,
}) => {
const updateAllRasterOpen = function updateAllRasterOpen() {
const {
allRasterOpen,
} = this.props();
const {
layout,
footer,
} = components;
layout
.config({
allRasterOpen,
})
.updateAllRaster();
footer
.config({
allRasterOpen,
})
.updateAllRaster();
};
return updateAllRasterOpen;
};
export default getUpdateAllRasterOpen;
| c9a126acf421da4114d55efcfef0d936168a1fef | [
"JavaScript",
"Python",
"Shell"
] | 64 | JavaScript | axismaps/pilotplan | a59b1d7cd5c207d6b648f43eedc496b9fe747344 | e1825848055ee868676ab2dd78716144a2df18a8 |
refs/heads/master | <repo_name>xwhboy/AsyncImageLoader<file_sep>/README.md
# AsyncImageLoader
图片缓存 异步加载
<file_sep>/src/com/example/asyncimageloader/Images.java
package com.example.asyncimageloader;
public class Images {
public final static String[] imageThumbUrls = new String[] {
"http://pica.nipic.com/2007-11-09/200711912453162_2.jpg",
"http://pica.nipic.com/2007-11-09/200711912453162_2.jpg",
"http://pica.nipic.com/2007-11-09/200711912453162_2.jpg",
"http://pica.nipic.com/2007-11-09/200711912453162_2.jpg",
"http://pica.nipic.com/2007-11-09/200711912453162_2.jpg",
"http://pica.nipic.com/2007-11-09/200711912453162_2.jpg",
"http://pica.nipic.com/2007-11-09/200711912453162_2.jpg",
"http://pica.nipic.com/2007-11-09/200711912453162_2.jpg",
"http://pica.nipic.com/2007-11-09/200711912453162_2.jpg",
"http://pica.nipic.com/2007-11-09/200711912453162_2.jpg",
"http://pica.nipic.com/2007-11-09/200711912453162_2.jpg",
"http://pica.nipic.com/2007-11-09/200711912453162_2.jpg",
"http://pica.nipic.com/2007-11-09/200711912453162_2.jpg",
"http://pica.nipic.com/2007-11-09/200711912453162_2.jpg",
"http://pica.nipic.com/2007-11-09/200711912453162_2.jpg",
"http://pica.nipic.com/2007-11-09/200711912453162_2.jpg",
"http://pica.nipic.com/2007-11-09/200711912453162_2.jpg",
"http://pica.nipic.com/2007-11-09/200711912453162_2.jpg",
"http://pica.nipic.com/2007-11-09/200711912453162_2.jpg",
"http://pica.nipic.com/2007-11-09/200711912453162_2.jpg",
"http://pica.nipic.com/2007-11-09/200711912453162_2.jpg",
"http://pica.nipic.com/2007-11-09/200711912453162_2.jpg",
"http://pica.nipic.com/2007-11-09/200711912453162_2.jpg",
"http://pica.nipic.com/2007-11-09/200711912453162_2.jpg",
"http://pica.nipic.com/2007-11-09/200711912453162_2.jpg",
"http://pica.nipic.com/2007-11-09/200711912453162_2.jpg",
"http://pica.nipic.com/2007-11-09/200711912453162_2.jpg",
"http://pica.nipic.com/2007-11-09/200711912453162_2.jpg",
"http://pica.nipic.com/2007-11-09/200711912453162_2.jpg",
"http://pica.nipic.com/2007-11-09/200711912453162_2.jpg",
"http://pica.nipic.com/2007-11-09/200711912453162_2.jpg",
"http://pica.nipic.com/2007-11-09/200711912453162_2.jpg",
"http://pica.nipic.com/2007-11-09/200711912453162_2.jpg",
"http://pica.nipic.com/2007-11-09/200711912453162_2.jpg",
"http://pica.nipic.com/2007-11-09/200711912453162_2.jpg",
"http://pica.nipic.com/2007-11-09/200711912453162_2.jpg",
"http://pica.nipic.com/2007-11-09/200711912453162_2.jpg",
"http://pica.nipic.com/2007-11-09/200711912453162_2.jpg",
"http://pica.nipic.com/2007-11-09/200711912453162_2.jpg",
"http://pica.nipic.com/2007-11-09/200711912453162_2.jpg",
"http://pica.nipic.com/2007-11-09/200711912453162_2.jpg"
};
}
| 3b65206b7acdd3f2f398f4c4d90e80f46f02cb3f | [
"Markdown",
"Java"
] | 2 | Markdown | xwhboy/AsyncImageLoader | 65a818b66fa31025e00cb06e7aedc63b03358801 | c057da8a67fbe3dfe05c48f9da09e14c0129498d |
refs/heads/master | <file_sep>using System;
using System.IO;
using System.Collections.Generic;
using SyntaxHighlighter;
namespace MainProgram
{
class MainProgram
{
public static void Main (string[] args)
{
Keyword[] keywords = readKeywordsFromTextFile ("../../csharpkeywordlist.txt");
Highlighter h = new Highlighter (keywords);
bool quit = false;
int lineNumber = 0;
while (!quit) {
string line = Console.ReadLine ();
Line l;
l.lineNumber = lineNumber;
l.text = line;
LineData d = LineParser.ParseLine (l);
d = h.HighlightLine (d);
for (int i = 0; i < d.words.Length; i++) {
Console.SetCursorPosition (d.words [i].x, d.words [i].y);
ConsoleColor color = (ConsoleColor)Enum.Parse(typeof(ConsoleColor),d.words [i].color.ToString());
Console.ForegroundColor = color;
Console.Write (d.words [i].text);
}
Console.SetCursorPosition (0, lineNumber+1);
lineNumber++;
}
}
public static Keyword[] readKeywordsFromTextFile(string path) {
string[] rawLines = File.ReadAllLines (path);
List<Line> lines = new List<Line> ();
for (int i = 0; i < rawLines.Length; i++) {
Line l;
l.lineNumber = i;
l.text = rawLines [i];
lines.Add (l);
}
List<LineData> lineDatas = new List<LineData> ();
for (int i = 0; i < lines.Count; i++) {
lineDatas.Add (LineParser.ParseLine (lines [i]));
}
Keyword[] keywords = new Keyword[lineDatas.Count];
for (int i = 0; i < lineDatas.Count; i++) {
keywords [i].word = lineDatas [i].words [0].text;
keywords [i].color = (HighlightColor)Enum.Parse(typeof(HighlightColor),lineDatas [i].words [1].text);
}
return keywords;
}
}
}
<file_sep>// DON'T CHANGE THIS
// THIS IS GENERATED FILE
// WHEN YOU WANT TO ADD NEW COLOR
// USE GenerateHighlightColor PROJECTnamespace SyntaxHighlighter{
/// <summary>
/// Basic colors for Highlighting
/// </summary>
namespace SyntaxHighlighter {
public enum HighlightColor {
Gray = 0xd3d3d3,
Black = 0x000000,
Test = 0x0b1621,
Blue = 0x0000FF,
Cyan = 0x00FFFF,
Green = 0x00FF00,
Magenta = 0xFF00FF,
Yellow = 0xFFFF00,
Red = 0xFF0000,
White = 0xFFFFFF,
}
}
<file_sep>using System;
namespace SyntaxHighlighter {
/// <summary>
/// RGB Class for Custom Colors
/// </summary>
public class RGB {
// Name of color
string name;
// Red value of color
int r;
// Green value of color
int g;
// Blue value of color
int b;
/// <summary>
/// Initializes a new instance of the RGB Class.
/// </summary>
/// <param name="name">The name of color.</param>
/// <param name="r">The red value of color.</param>
/// <param name="g">The green value of color.</param>
/// <param name="b">The blue value of color.</param>
public RGB (string name, int r, int g, int b) {
this.name = name;
this.r = r;
this.g = g;
this.b = b;
}
/// <summary>
/// Gets the name of color.
/// </summary>
/// <returns>The name of color</returns>
public string GetName() {
return name;
}
/// <summary>
/// Gets the red value of color.
/// </summary>
/// <returns>The red value of color.</returns>
public int GetRed() {
return r;
}
/// <summary>
/// Gets the green value of color.
/// </summary>
/// <returns>The green value of color.</returns>
public int GetGreen() {
return g;
}
/// <summary>
/// Gets the blue value of color.
/// </summary>
/// <returns>The blue value of color.</returns>
public int GetBlue() {
return b;
}
/// <summary>
/// Gets the hexadecimal value of color
/// </summary>
/// <returns>The hexadecimal value.</returns>
public string GetHex() {
// It's basic RGB to Hex formula
return string.Format ("0x{0:x6}", (r << 16) + (g << 8) + b);
}
}
}
<file_sep>namespace SyntaxHighlighter
{
/// <summary>
/// Contains 'seperated' line text, line x position, line y position and line color
/// </summary>
public struct Word {
public string text;
public int x;
public int y;
public HighlightColor color;
}
}
<file_sep>namespace SyntaxHighlighter
{
/// <summary>
/// Keyword data
/// </summary>
public struct Keyword {
public string word;
public HighlightColor color;
}
}
<file_sep>using System;
using System.Collections.Generic;
namespace SyntaxHighlighter
{
/// <summary>
/// This class basically seperates lines to LineData.
/// </summary>
public class LineParser {
/// <summary>
/// Seperates the line to words, finds x, y.
/// </summary>
public static LineData ParseLine(Line line) {
// Line data to return
LineData rData;
// List of words
List<Word> rWords = new List<Word> ();
// Word start index (word x position)
int wStart = 0;
// Word length
int wLen = 0;
// Loop through every character
for (int i = 0; i < line.text.Length; i++) {
// If is this before last character
if (i == line.text.Length - 1) {
// Last word of line
Word w;
w.text = line.text.Substring (wStart, wLen + 1);
w.x = wStart;
w.y = line.lineNumber;
w.color = HighlightColor.White;
rWords.Add (w);
wStart += wLen + 1;
wLen = 0;
}
// Current character is a blank space that means word is ended
if (line.text [i] == ' ') {
// Create word same as up except one thing
Word w;
w.text = line.text.Substring (wStart, wLen);
w.x = wStart;
w.y = line.lineNumber;
w.color = HighlightColor.White;
rWords.Add (w);
wStart += wLen + 1;
wLen = 0;
} else {
// Otherwise add 1 to word length
wLen++;
}
}
// Convert list to array
rData.words = rWords.ToArray();
return rData;
}
}
}
<file_sep>namespace SyntaxHighlighter {
/// <summary>
/// Line Struct
/// </summary>
public struct Line {
public int lineNumber;
public string text;
}
}<file_sep>using System;
using System.IO; // For streamreader, streamwriter and filestream..
using SyntaxHighlighter;
using System.Text; // For string builder.
namespace GenerateHighlightColor
{
class MainClass
{
public static string title = "HIGHLIGHT COLOR GENERATOR";
// It's just a simple program for testing i'll convert this to code generator.
/// <summary>
/// The entry point of the program, where the program control starts and ends.
/// </summary>
/// <param name="args">The command-line arguments.</param>
public static void Main (string[] args)
{
Console.Title = title;
bool quit = false;
while (!quit) {
RGB color = TakeInput ();
// [WARNING] This file location is for my pc. I'm using linux. And it can be confuse you. Change with your location. [WARNING]
InsertIntoFile ("../../../SyntaxHighlighter/HighlightColor.cs", color.GetName() + " = " + color.GetHex() + ",", 10);
Console.WriteLine ("If you want exit type '0'");
Console.WriteLine ("If you want generate one more color type '1'");
int value;
// Basic input control etc. etc..
if (int.TryParse (Console.ReadLine (), out value)) {
if (value == 0) {
quit = true;
} else if (value == 1) {
Console.Clear ();
continue;
} else {
Console.WriteLine ("You entered invalid choice.!");
quit = true;
}
}
}
}
/// <summary>
/// Inserts into file with specified lineNumber
/// </summary>
/// <param name="path">Path of file</param>
/// <param name="data">Data to write</param>
/// <param name="linenumber">Line number</param>
public static void InsertIntoFile(string path, string data, int linenumber) {
// For a new result
StringBuilder result = new StringBuilder ();
// File stream for write and read
FileStream fs = new FileStream (path, FileMode.Open, FileAccess.ReadWrite);
// Current line number
int lines = 0;
using (StreamReader sr = new StreamReader(fs)) {
// Current line
string line;
// While current line is not null
while((line = sr.ReadLine()) != null) {
// If current line number equals wanted line number
if(lines == linenumber-1) {
// Append the new result
result.Append(data);
// Append a seperator
result.Append("|");
}
// And write other things
result.Append(line);
result.Append ("|");
// Increase current line number
lines++;
}
}
string fullstr = result.ToString ();
// Seperate with seperator
string[] text = fullstr.Split ('|');
// Write new data to a file
using (StreamWriter sw = new StreamWriter (path)) {
for(int i = 0; i < text.Length; i++) {
string item = text [i].Trim ();
sw.WriteLine (item);
Console.WriteLine (item);
}
}
}
/// <summary>
/// Take the input and created new RGB color
/// </summary>
/// <returns>RGB Color</returns>
public static RGB TakeInput() {
// Set cursor position and write title
Console.SetCursorPosition (Console.WindowWidth / 2 - title.Length/2 - 1, Console.WindowHeight / 2 - 5);
Console.WriteLine (title);
// Take name of color from user
Console.WriteLine ("Please Enter;");
Console.Write ("Name of color: ");
string color = Console.ReadLine ();
// Take red value from user
Console.Write ("Red value of color: ");
int red;
int.TryParse (Console.ReadLine (), out red);
// Take green value from user
Console.Write ("Green value of color: ");
int green;
int.TryParse (Console.ReadLine (), out green);
// Take blue value from user
Console.Write ("Blue value of color: ");
int blue;
int.TryParse (Console.ReadLine (), out blue);
// Create new RGB color with taken inputs
RGB rgb = new RGB (color, red, green, blue);
// Return it.
return rgb;
}
}
}
<file_sep>using System;
namespace SyntaxHighlighter
{
/// <summary>
/// Main highlighter class
/// </summary>
public class Highlighter {
// List of keywords for highlighting
public Keyword[] keywords;
// Constructor
public Highlighter(Keyword[] _keywords) {
this.keywords = _keywords;
}
/// <summary>
/// That function takes a data parameter and finds if line contains one of keywords
/// if it finds keyword, change the color of word.
/// </summary>
/// <param name="lineData">Line data.</param>
public LineData HighlightLine(LineData lineData) {
// For loop every word in line
for (int i = 0; i < lineData.words.Length; i++) {
// For loop every keyword
for(int j = 0; j < keywords.Length; j++) {
// If word is a keyword
if (lineData.words [i].text == keywords [j].word) {
// Change word color to keyword color
lineData.words [i].color = keywords [j].color;
break;
} else {
// Word color for not a keyword
lineData.words [i].color = HighlightColor.White;
}
}
}
return lineData;
}
}
}
<file_sep>namespace SyntaxHighlighter
{
/// <summary>
/// Line Data for Lines
/// </summary>
public struct LineData {
public Word[] words;
}
}
| 5fd0a8a8f7e4651d9ccc3e06ea4a6c624fe8d782 | [
"C#"
] | 10 | C# | batinevirgen/SyntaxHighlighter | 3dde88daef26a76c0a2d1388d003ddc5d7cf5f03 | 7f911ebd2b14c33cf22f323b217822608a4468c1 |
refs/heads/master | <repo_name>TcheL/OpenAny<file_sep>/opan
#!/bin/bash
#===============================================================================
# opan: open an any-type file on Linux system.
#
# Author: <NAME> Email: <EMAIL>
# Copyright (C) <NAME>, 2017. All Rights Reserved.
#===============================================================================
# file-open tools defination.
explorer=xdg-open
editor=vim
ncdump=ncdump
mdview=typora
pdfview=evince
picview=eog
tartool=tar
# function to print help information.
function print_help_info() {
printf '\nUsage: opan [-h] | [ file [options] ]\n'
printf ' [-h ]: print this help information.\n'
printf ' [file ]: name of the file to open.\n'
printf ' [options]: options to pass to the invoked file-open tool.\n\n'
exit $1
}
#====================== handle with command line arguments =====================
# if no argument:
if [ "$*" == '' ]; then
$explorer `pwd`
printf ">> $explorer ./\n"
exit 0
fi
# if want to print help info:
if [ "$1" == '-h' -o "$1" == '--help' ]; then
print_help_info 0
fi
# get file type:
if [ -d "$1" ]; then
tool=$explorer
elif [ -f "$1" ]; then
file=${1##*/}
pref=${file%.*}
suff=${file##*.}
case $suff in
'txt' | 'log' | 'conf' | 'dat' | 'inc' | 'cpt' )
tool=$editor ;;
'c' | 'cpp' | 'cc' | 'h' | 'hpp' )
tool=$editor ;;
'f' | 'for' | 'f90' | 'F' | 'FOR' | 'F90' | 'nml' )
tool=$editor ;;
'cu' )
tool=$editor ;;
'm' )
tool=$editor ;;
'py' | 'pyf' )
tool=$editor ;;
'sh' | 'bat' )
tool=$editor ;;
'tex' | 'sty' | 'bib' )
tool=$editor ;;
'pbs' | 'lsf' )
tool=$editor ;;
'json' )
tool=$editor ;;
'yml' )
tool=$editor ;;
'html' )
tool=$editor ;;
'pdf' | 'eps' | 'ps' )
tool=$pdfview ;;
'png' | 'jpg' | 'gif' | 'tif' )
tool=$picview ;;
'tar' | 'tgz' | 'gz' | 'bz2' )
tool=$tartool ;;
'md' )
tool=$mdview ;;
'nc' | 'grd' )
tool=$ncdump ;;
* )
if [ "$suff" == "$file" ]; then
# if no dot in the filename:
tool=$editor
elif [ -z "$pref" ]; then
# for hidden files:
tool=$editor
else
printf "Error at `pwd`:\n"
printf " $suff: I don't know this file-type.\n"
exit 1
fi
esac
else
printf "Error at `pwd`:\n"
printf " $1: No such file or directory.\n"
exit 2
fi
# pass other arguments:
ops="${@:2}"
# test file readability:
if [ ! -r "$1" ]; then
printf "Error at `pwd`:\n"
printf " $1: Not readable for me.\n"
exit 3
else
if [ "$ops" ]; then
printf ">> $tool $ops $1\n"
$tool $ops "$1"
else
printf ">> $tool $1\n"
$tool "$1"
fi
fi
<file_sep>/README.md
# OpenAny
A bash script used to open a type-arbitrary file on Linux.
## License
[The MIT License](http://tchel.mit-license.org)
## Usage
You can get help information as follows:
```shell
[user@A ~]$ opan -h
Usage: opan [-h] | [ file [options] ]
[-h ]: print this help information.
[file ]: name of the file to open.
[options]: options to pass to the invoked file-open tool.
```
If you want to open any file, just run `$ opan filename`, __opan__ will automatically detect file type according to file extension, and select a binding tool to open the file _filename_.
So far, __opan__ supports:
| file extension | invoked tool |
| ------------------------------------ | ------------ |
| .txt, .log, .conf, .dat, .inc, .cpt | vim |
| .c, .cpp, .cc, .h, .hpp | vim |
| .f, .for, .f90, .F, .FOR, .F90, .nml | vim |
| .cu | vim |
| .m | vim |
| .py, .pyf | vim |
| .sh, .bat | vim |
| .tex, .sty, .bib | vim |
| .pbs, .lsf | vim |
| .json | vim |
| .yml | vim |
| .html | vim |
| .pdf, .eps, .ps | evince |
| .png, .jpg, .gif, .tif | eog |
| .tar, .tgz, .gz, .bz2 | tar |
| .md | typora |
| .nc | ncdump |
## Author
<NAME>, <<EMAIL>>, USTC

| 9b62050f1513f6b5276d5f595d883bd885e8655e | [
"Markdown",
"Shell"
] | 2 | Shell | TcheL/OpenAny | 17182492dee34a4ad3496387cd5d43452fb8ba47 | bf0991d5709c2ffb425a986555c04b3cfec32ae5 |
refs/heads/master | <repo_name>alisiahkoohi/JUDI.jl<file_sep>/src/Python/test_rho.py
from __future__ import print_function
import numpy as np
import psutil, os, gc
from numpy.random import randint
from sympy import solve, cos, sin
from sympy import Function as fint
from devito.logger import set_log_level
from devito import Eq, Function, TimeFunction, Dimension, Operator, clear_cache
from PySource import RickerSource, PointSource, Receiver
from PyModel import Model
from checkpoint import DevitoCheckpoint, CheckpointOperator
from pyrevolve import Revolver
import matplotlib.pyplot as plt
from JAcoustic_codegen import forward_modeling, adjoint_born
# Model
shape = (101, 101)
spacing = (10., 10.)
origin = (0., 0.)
# Velocity
v = np.empty(shape, dtype=np.float32)
v[:, :51] = 1.5
v[:, 51:] = 1.5
v0 = np.empty(shape, dtype=np.float32)
v0[:, :] = 1.5
# Density
rho = np.empty(shape, dtype=np.float32)
rho[:, :51] = 1.0
rho[:, 51:] = 2.0
rho0 = np.empty(shape, dtype=np.float32)
rho0[:, :] = 1.0
# Set up model structures
model = Model(shape=shape, origin=origin, spacing=spacing, vp=v, rho=rho)
model0 = Model(shape=shape, origin=origin, spacing=spacing, vp=v0, rho=rho0)
# Time axis
t0 = 0.
tn = 1000.
dt = model.critical_dt
nt = int(1 + (tn-t0) / dt)
time = np.linspace(t0,tn,nt)
# Source
f0 = 0.010
src = RickerSource(name='src', grid=model.grid, f0=f0, time=time)
src.coordinates.data[0,:] = np.array(model.domain_size) * 0.5
src.coordinates.data[0,-1] = 20.
# Receiver for observed data
rec_t = Receiver(name='rec_t', grid=model.grid, npoint=101, ntime=nt)
rec_t.coordinates.data[:, 0] = np.linspace(0, model.domain_size[0], num=101)
rec_t.coordinates.data[:, 1] = 20.
# Observed data
dobs, utrue = forward_modeling(model, src.coordinates.data, src.data, rec_t.coordinates.data)
##################################################################################################################
# Receiver for predicted data
rec = Receiver(name='rec', grid=model0.grid, npoint=101, ntime=nt)
rec.coordinates.data[:, 0] = np.linspace(0, model0.domain_size[0], num=101)
rec.coordinates.data[:, 1] = 20.
# Save wavefields
d0, u0 = forward_modeling(model, src.coordinates.data, src.data, rec.coordinates.data, save=True, dt=dt)
#g = adjoint_born(model0, rec.coordinates.data, dpred_data[:] - dobs.data[:], u=u0, dt=dt)
plt.figure(); plt.imshow(d0, vmin=-1, vmax=1)
plt.figure(); plt.imshow(np.transpose(model.rho.data))
plt.figure(); plt.imshow(np.transpose(model.m.data))
plt.show()
<file_sep>/src/Python/test_3D.py
from __future__ import print_function
import numpy as np
import psutil, os, gc
from numpy.random import randint
from sympy import solve, cos, sin
from sympy import Function as fint
from devito.logger import set_log_level
from devito import Eq, Function, TimeFunction, Dimension, Operator, clear_cache
from PySource import RickerSource, PointSource, Receiver
from PyModel import Model
from checkpoint import DevitoCheckpoint, CheckpointOperator
from pyrevolve import Revolver
import matplotlib.pyplot as plt
from JAcoustic_codegen import forward_modeling, adjoint_born
# Model
shape = (101, 101, 51)
spacing = (10., 10., 10.)
origin = (0., 0., 0.)
v = np.empty(shape, dtype=np.float32)
v[:, :, :51] = 1.5
v[:, :, 51:] = 2.5
v0 = np.empty(shape, dtype=np.float32)
v0[:, :, :] = 1.5
model = Model(shape=shape, origin=origin, spacing=spacing, vp=v)
model0 = Model(shape=shape, origin=origin, spacing=spacing, vp=v0)
# Time axis
t0 = 0.
tn = 1000.
dt = model.critical_dt
nt = int(1 + (tn-t0) / dt)
time = np.linspace(t0,tn,nt)
# Source
f0 = 0.010
src = RickerSource(name='src', grid=model.grid, f0=f0, time=time)
src.coordinates.data[0,:] = np.array(model.domain_size) * 0.5
src.coordinates.data[0,-1] = 20.
# Receiver for observed data
rec_t = Receiver(name='rec_t', grid=model.grid, npoint=101, ntime=nt)
rec_t.coordinates.data[:, 0] = np.linspace(0, model.domain_size[0], num=101)
rec_t.coordinates.data[:, 1] = 20.
# Observed data
dobs, uTrue = forward_modeling(model, src.coordinates.data, src.data, rec_t.coordinates.data)
##################################################################################################################
# Receiver for predicted data
rec = Receiver(name='rec', grid=model0.grid, npoint=101, ntime=nt)
rec.coordinates.data[:, 0] = np.linspace(0, model0.domain_size[0], num=101)
rec.coordinates.data[:, 1] = 20.
# Save wavefields
dpred_data, u0 = forward_modeling(model0, src.coordinates.data, src.data, rec.coordinates.data, save=True, dt=dt)
f1 = .5*np.linalg.norm(dpred_data[:] - dobs.data[:])**2
g1 = adjoint_born(model0, rec.coordinates.data, dpred_data[:] - dobs.data[:], u=u0, dt=dt)
# Checkpointing
op_predicted = forward_modeling(model0, src.coordinates.data, src.data, rec.coordinates.data, op_return=True, dt=dt)
f2, g2 = adjoint_born(model0, rec.coordinates.data, dobs.data, op_forward=op_predicted, dt=dt, is_residual=False)
print('Error f: ', np.linalg.norm(f1 - f2))
print('Error g: ', np.linalg.norm(g1 - g2))
<file_sep>/src/Python/adjoint_test_F.py
from __future__ import print_function
import numpy as np
import psutil, os, gc
from numpy.random import randint
from sympy import solve, cos, sin
from sympy import Function as fint
from devito.logger import set_log_level
from devito import Eq, Function, TimeFunction, Dimension, Operator, clear_cache
from PySource import RickerSource, PointSource, Receiver
from PyModel import Model
from checkpoint import DevitoCheckpoint, CheckpointOperator
from pyrevolve import Revolver
import matplotlib.pyplot as plt
from JAcoustic_codegen import forward_modeling, adjoint_modeling
import time
# Model
shape = (301, 301)
spacing = (10., 10.)
origin = (0., 0.)
v1 = np.empty(shape, dtype=np.float32)
v1[:, :51] = 1.5
v1[:, 51:] = 3.5
# Density
rho = np.empty(shape, dtype=np.float32)
rho[:, :51] = 1.0
rho[:, 51:] = 2.0
# Set up model structures
model1 = Model(shape=shape, origin=origin, spacing=spacing, vp=v1, rho=rho)
def smooth10(vel, shape):
if np.isscalar(vel):
return .9 * vel * np.ones(shape, dtype=np.float32)
out = np.copy(vel)
nz = shape[-1]
for a in range(5, nz-6):
if len(shape) == 2:
out[:, a] = np.sum(vel[:, a - 5:a + 5], axis=1) / 10
else:
out[:, :, a] = np.sum(vel[:, :, a - 5:a + 5], axis=2) / 10
return out
# Smooth background model
v2 = np.empty(shape, dtype=np.float32)
v2[:, :41] = 1.5
v2[:, 41:71] = 2.5
v2[:, 71:] = 4.5
model2 = Model(shape=shape, origin=origin, spacing=spacing, vp=v2, rho=rho)
# Time axis
t0 = 0.
tn = 1000.
dt = model2.critical_dt
nt = int(1 + (tn-t0) / dt)
time_axis = np.linspace(t0,tn,nt)
# Source
f1 = 0.008
src1 = RickerSource(name='src', grid=model1.grid, f0=f1, time=time_axis)
src1.coordinates.data[0,:] = np.array(model1.domain_size) * 0.5
src1.coordinates.data[0,-1] = 20.
f2 = 0.012
src2 = RickerSource(name='src', grid=model2.grid, f0=f2, time=time_axis)
src2.coordinates.data[0,:] = np.array(model2.domain_size) * 0.5
src2.coordinates.data[0,-1] = 20.
# Receiver for observed data
rec_t = Receiver(name='rec_t', grid=model1.grid, npoint=401, ntime=nt)
rec_t.coordinates.data[:, 0] = np.linspace(100, 900, num=401)
rec_t.coordinates.data[:, 1] = 20.
# Test data and source
d_hat, _ = forward_modeling(model1, src1.coordinates.data, src1.data, rec_t.coordinates.data, dt=dt)
q_hat = src2.data
# Forward
d0, _ = forward_modeling(model2, src2.coordinates.data, src2.data, rec_t.coordinates.data, dt=dt)
# Adjoint
q0 = adjoint_modeling(model2, src2.coordinates.data, rec_t.coordinates.data, d_hat, dt=dt)
# Adjoint test
a = np.dot(d_hat.flatten(), d0.flatten())
b = np.dot(q_hat.flatten(), q0.flatten())
print("Adjoint test F")
print("Difference: ", a - b)
print("Relative error: ", a/b - 1)
<file_sep>/src/Python/adjoint_test_J.py
from __future__ import print_function
import numpy as np
import psutil, os, gc
from numpy.random import randint
from sympy import solve, cos, sin
from sympy import Function as fint
from devito.logger import set_log_level
from devito import Eq, Function, TimeFunction, Dimension, Operator, clear_cache
from PySource import RickerSource, PointSource, Receiver
from PyModel import Model
from checkpoint import DevitoCheckpoint, CheckpointOperator
from pyrevolve import Revolver
import matplotlib.pyplot as plt
from JAcoustic_codegen import forward_modeling, forward_born, adjoint_born, forward_freq_modeling, adjoint_freq_born
import time
# Model
shape = (301, 301)
spacing = (10., 10.)
origin = (0., 0.)
v = np.empty(shape, dtype=np.float32)
v[:, :51] = 1.5
v[:, 51:] = 4.5
# Density
rho = np.empty(shape, dtype=np.float32)
rho[:, :51] = 1.0
rho[:, 51:] = 1.5
def smooth10(vel, shape):
if np.isscalar(vel):
return .9 * vel * np.ones(shape, dtype=np.float32)
out = np.copy(vel)
nz = shape[-1]
for a in range(5, nz-6):
if len(shape) == 2:
out[:, a] = np.sum(vel[:, a - 5:a + 5], axis=1) / 10
else:
out[:, :, a] = np.sum(vel[:, :, a - 5:a + 5], axis=2) / 10
return out
# Set up model structures
rho0 = smooth10(rho, shape)
model = Model(shape=shape, origin=origin, spacing=spacing, vp=v, rho=rho0)
# Smooth background model
v0 = smooth10(v, shape)
dm = (1/v)**2 - (1/v0)**2
model0 = Model(shape=shape, origin=origin, spacing=spacing, vp=v0, dm=dm, rho=rho0)
# Constant background model
v_const = np.empty(shape, dtype=np.float32)
v_const[:,:] = 1.5
dm_const = (1/v)**2 - (1/v_const)**2
model_const = Model(shape=shape, origin=origin, spacing=spacing, vp=v_const, rho=rho0, dm=dm_const)
# Time axis
t0 = 0.
tn = 1400.
dt = model.critical_dt
nt = int(1 + (tn-t0) / dt)
time_axis = np.linspace(t0,tn,nt)
# Source
f0 = 0.010
src = RickerSource(name='src', grid=model.grid, f0=f0, time=time_axis)
src.coordinates.data[0,:] = np.array(model.domain_size) * 0.5
src.coordinates.data[0,-1] = 20.
# Receiver for observed data
rec_t = Receiver(name='rec_t', grid=model.grid, npoint=401, ntime=nt)
rec_t.coordinates.data[:, 0] = np.linspace(100, 900, num=401)
rec_t.coordinates.data[:, 1] = 20.
# Linearized data
print("Forward J")
t1 = time.time()
dD_hat = forward_born(model_const, src.coordinates.data, src.data, rec_t.coordinates.data, isic=False, dt=dt)
dm_hat = model0.dm.data
t2 = time.time()
print(t2 - t1)
# Forward
print("Forward J")
t1 = time.time()
dD = forward_born(model0, src.coordinates.data, src.data, rec_t.coordinates.data, isic=True, dt=dt)
t2 = time.time()
print(t2 - t1)
# Adjoint
print("Adjoint J")
d0, u0 = forward_modeling(model0, src.coordinates.data, src.data, rec_t.coordinates.data, dt=dt, save=True)
t1 = time.time()
dm = adjoint_born(model0, rec_t.coordinates.data, dD_hat.data, u0, isic=True, dt=dt)
t2 = time.time()
print(t2 - t1)
# Adjoint test
a = np.dot(dD_hat.flatten(), dD.flatten())
b = np.dot(dm_hat.flatten(), dm.flatten())
print("Adjoint test J")
print("Difference: ", a - b)
print("Relative error: ", a/b - 1)
<file_sep>/Manifest.toml
# This file is machine-generated - editing it directly is not advised
[[AbstractFFTs]]
deps = ["LinearAlgebra"]
git-tree-sha1 = "380e36c66edfa099cd90116b24c1ce8cafccac40"
uuid = "621f4979-c628-5d54-868e-fcf4e3e8185c"
version = "0.4.1"
[[Base64]]
uuid = "2a0f44e3-6c83-55bd-87e4-b1978d98bd5f"
[[BinDeps]]
deps = ["Compat", "Libdl", "SHA", "URIParser"]
git-tree-sha1 = "12093ca6cdd0ee547c39b1870e0c9c3f154d9ca9"
uuid = "9e28174c-4ba2-5203-b857-d8d62c4213ee"
version = "0.8.10"
[[BinaryProvider]]
deps = ["Libdl", "Logging", "SHA"]
git-tree-sha1 = "c7361ce8a2129f20b0e05a89f7070820cfed6648"
uuid = "b99e7846-7c00-51b0-8f62-c81ae34c0232"
version = "0.5.6"
[[Blosc]]
deps = ["BinaryProvider", "CMakeWrapper", "Compat", "Libdl"]
git-tree-sha1 = "71fb23581e1f0b0ae7be8ccf0ebfb3600e23ca41"
uuid = "a74b3585-a348-5f62-a45c-50e91977d574"
version = "0.5.1"
[[CMake]]
deps = ["BinDeps"]
git-tree-sha1 = "c67a8689dc5444adc5eb2be7d837100340ecba11"
uuid = "631607c0-34d2-5d66-819e-eb0f9aa2061a"
version = "1.1.2"
[[CMakeWrapper]]
deps = ["BinDeps", "CMake", "Libdl", "Parameters", "Test"]
git-tree-sha1 = "16d4acb3d37dc05b714977ffefa8890843dc8985"
uuid = "d5fb7624-851a-54ee-a528-d3f3bac0b4a0"
version = "0.2.3"
[[CSTParser]]
deps = ["Tokenize"]
git-tree-sha1 = "c69698c3d4a7255bc1b4bc2afc09f59db910243b"
uuid = "00ebfdb7-1f24-5e51-bd34-a7502290713f"
version = "0.6.2"
[[Compat]]
deps = ["Base64", "Dates", "DelimitedFiles", "Distributed", "InteractiveUtils", "LibGit2", "Libdl", "LinearAlgebra", "Markdown", "Mmap", "Pkg", "Printf", "REPL", "Random", "Serialization", "SharedArrays", "Sockets", "SparseArrays", "Statistics", "Test", "UUIDs", "Unicode"]
git-tree-sha1 = "84aa74986c5b9b898b0d1acaf3258741ee64754f"
uuid = "34da2185-b29b-5c13-b0c7-acf172513d20"
version = "2.1.0"
[[Conda]]
deps = ["JSON", "VersionParsing"]
git-tree-sha1 = "9a11d428dcdc425072af4aea19ab1e8c3e01c032"
uuid = "8f4d0f93-b110-5947-807f-2305c1781a2d"
version = "1.3.0"
[[DSP]]
deps = ["FFTW", "LinearAlgebra", "Polynomials", "Random", "Reexport", "SpecialFunctions", "Statistics"]
git-tree-sha1 = "fd5dc811fc47f8c31274712d887c466bea0841c8"
uuid = "717857b8-e6f2-59f4-9121-6e50c889abd2"
version = "0.6.0"
[[DataStructures]]
deps = ["InteractiveUtils", "OrderedCollections"]
git-tree-sha1 = "f94423c68f2e47db0d6f626a26d4872266e0ec3d"
uuid = "864edb3b-99cc-5e75-8d2d-829cb0a9cfe8"
version = "0.17.2"
[[Dates]]
deps = ["Printf"]
uuid = "ade2ca70-3891-5945-98fb-dc099432e06a"
[[DelimitedFiles]]
deps = ["Mmap"]
uuid = "8bb1440f-4735-579b-a4ab-409b98df4dab"
[[Dierckx]]
deps = ["BinaryProvider", "Libdl", "Random", "Test"]
git-tree-sha1 = "27a74763c20938a814da26f31a9e8408d16fec44"
uuid = "39dd38d3-220a-591b-8e3c-4c3a8c710a94"
version = "0.4.1"
[[Distributed]]
deps = ["Random", "Serialization", "Sockets"]
uuid = "8ba89e20-285c-5b6f-9357-94700520ee1b"
[[DistributedArrays]]
deps = ["Distributed", "LinearAlgebra", "Primes", "Random", "Serialization", "SparseArrays", "Statistics"]
git-tree-sha1 = "b9cde03fd283e49ea09911297067b2f872f84c2d"
uuid = "aaf54ef3-cdf8-58ed-94cc-d582ad619b94"
version = "0.6.4"
[[FFTW]]
deps = ["AbstractFFTs", "BinaryProvider", "Conda", "Libdl", "LinearAlgebra", "Reexport", "Test"]
git-tree-sha1 = "e1a479d3c972f20c9a70563eec740bbfc786f515"
uuid = "7a1cc6ca-52ef-59f5-83cd-3a7055c09341"
version = "0.3.0"
[[FileIO]]
deps = ["Pkg"]
git-tree-sha1 = "351f001a78aa1b7ad2696e386e110b5abd071c71"
uuid = "5789e2e9-d7fb-5bc7-8068-2c6fae9b9549"
version = "1.0.7"
[[HDF5]]
deps = ["BinaryProvider", "Blosc", "CMakeWrapper", "Libdl", "Mmap"]
git-tree-sha1 = "9f7e7eebd3cd46e541928ef6f1d5b992abd8d384"
uuid = "f67ccb44-e63f-5c2f-98bd-6dc0ccc4ba2f"
version = "0.12.3"
[[InplaceOps]]
deps = ["LinearAlgebra", "Test"]
git-tree-sha1 = "50b41d59e7164ab6fda65e71049fee9d890731ff"
uuid = "505f98c9-085e-5b2c-8e89-488be7bf1f34"
version = "0.3.0"
[[InteractiveUtils]]
deps = ["Markdown"]
uuid = "b77e0a4c-d291-57a0-90e8-8db25a27a240"
[[IterativeSolvers]]
deps = ["LinearAlgebra", "Printf", "Random", "RecipesBase", "SparseArrays", "Test"]
git-tree-sha1 = "5687f68018b4f14c0da54d402bb23eecaec17f37"
uuid = "42fd0dbc-a981-5370-80f2-aaf504508153"
version = "0.8.1"
[[JLD]]
deps = ["Compat", "FileIO", "HDF5", "LegacyStrings", "Profile", "Random"]
git-tree-sha1 = "95fd5d7f129918a75d0535aaaf5b8e235e6e0b0b"
uuid = "4138dd39-2aa7-5051-a626-17a0bb65d9c8"
version = "0.9.1"
[[JOLI]]
deps = ["Distributed", "DistributedArrays", "FFTW", "InplaceOps", "InteractiveUtils", "IterativeSolvers", "LinearAlgebra", "NFFT", "Nullables", "Printf", "Random", "SharedArrays", "SparseArrays", "Wavelets"]
git-tree-sha1 = "3990902c1a5700b3ad52237f97b81f9121991cb0"
repo-rev = "master"
repo-url = "https://github.com/slimgroup/JOLI.jl"
uuid = "bb331ad6-a1cf-11e9-23da-9bcb53c69f6f"
version = "0.7.0"
[[JSON]]
deps = ["Dates", "Mmap", "Parsers", "Unicode"]
git-tree-sha1 = "b34d7cef7b337321e97d22242c3c2b91f476748e"
uuid = "682c06a0-de6a-54ab-a142-c8b1cf79cde6"
version = "0.21.0"
[[LegacyStrings]]
deps = ["Compat"]
git-tree-sha1 = "d4b9bde2694c552fe579cc4462733f1ce08733fe"
uuid = "1b4a561d-cfcb-5daf-8433-43fcf8b4bea3"
version = "0.4.1"
[[LibGit2]]
uuid = "76f85450-5226-5b5a-8eaa-529ad045b433"
[[Libdl]]
uuid = "8f399da3-3557-5675-b5ff-fb832c97cbdb"
[[LinearAlgebra]]
deps = ["Libdl"]
uuid = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e"
[[Logging]]
uuid = "56ddb016-857b-54e1-b83d-db4d58db5568"
[[MacroTools]]
deps = ["CSTParser", "Compat", "DataStructures", "Test", "Tokenize"]
git-tree-sha1 = "d6e9dedb8c92c3465575442da456aec15a89ff76"
uuid = "1914dd2f-81c6-5fcd-8719-6d5c9610ff09"
version = "0.5.1"
[[Markdown]]
deps = ["Base64"]
uuid = "d6f4376e-aef5-505a-96c1-9c027394607a"
[[Mmap]]
uuid = "a63ad114-7e13-5084-954f-fe012c677804"
[[NFFT]]
deps = ["Distributed", "FFTW", "LinearAlgebra", "Random", "SparseArrays", "SpecialFunctions", "Test"]
git-tree-sha1 = "5678da0cbb2428a4b01403b5e555945191525bb0"
uuid = "efe261a4-0d2b-5849-be55-fc731d526b0d"
version = "0.4.0"
[[Nullables]]
deps = ["Compat"]
git-tree-sha1 = "ae1a63457e14554df2159b0b028f48536125092d"
uuid = "4d1e1d77-625e-5b40-9113-a560ec7a8ecd"
version = "0.0.8"
[[OrderedCollections]]
deps = ["Random", "Serialization", "Test"]
git-tree-sha1 = "c4c13474d23c60d20a67b217f1d7f22a40edf8f1"
uuid = "bac558e1-5e72-5ebc-8fee-abe8a469f55d"
version = "1.1.0"
[[Parameters]]
deps = ["OrderedCollections"]
git-tree-sha1 = "b62b2558efb1eef1fa44e4be5ff58a515c287e38"
uuid = "d96e819e-fc66-5662-9728-84c9c7592b0a"
version = "0.12.0"
[[Parsers]]
deps = ["Dates", "Test"]
git-tree-sha1 = "ef0af6c8601db18c282d092ccbd2f01f3f0cd70b"
uuid = "69de0a69-1ddd-5017-9359-2bf0b02dc9f0"
version = "0.3.7"
[[Pkg]]
deps = ["Dates", "LibGit2", "Markdown", "Printf", "REPL", "Random", "SHA", "UUIDs"]
uuid = "44cfe95a-1eb2-52ea-b672-e2afdf69b78f"
[[PolynomialRoots]]
deps = ["Test"]
git-tree-sha1 = "0ba43554d01a5f4d63e4ac51623d3d8595b7146e"
uuid = "3a141323-8675-5d76-9d11-e1df1406c778"
version = "0.2.0"
[[Polynomials]]
deps = ["LinearAlgebra", "SparseArrays", "Test"]
git-tree-sha1 = "62142bd65d3f8aeb2226ec64dd8493349147df94"
uuid = "f27b6e38-b328-58d1-80ce-0feddd5e7a45"
version = "0.5.2"
[[Primes]]
deps = ["Test"]
git-tree-sha1 = "ff1a2323cb468ec5f201838fcbe3c232266b1f95"
uuid = "27ebfcd6-29c5-5fa9-bf4b-fb8fc14df3ae"
version = "0.4.0"
[[Printf]]
deps = ["Unicode"]
uuid = "de0858da-6303-5e67-8744-51eddeeeb8d7"
[[Profile]]
deps = ["Printf"]
uuid = "9abbd945-dff8-562f-b5e8-e1ebf5ef1b79"
[[PyCall]]
deps = ["Conda", "Dates", "Libdl", "LinearAlgebra", "MacroTools", "Pkg", "Serialization", "Statistics", "Test", "VersionParsing"]
git-tree-sha1 = "6e5bac1b1faf3575731a6a5b76f638f2389561d3"
uuid = "438e738f-606a-5dbb-bf0a-cddfbfd45ab0"
version = "1.91.2"
[[REPL]]
deps = ["InteractiveUtils", "Markdown", "Sockets"]
uuid = "3fa0cd96-eef1-5676-8a61-b3b8758bbffb"
[[Random]]
deps = ["Serialization"]
uuid = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c"
[[RecipesBase]]
git-tree-sha1 = "7bdce29bc9b2f5660a6e5e64d64d91ec941f6aa2"
uuid = "3cdcf5f2-1ef4-517c-9805-6587b60abb01"
version = "0.7.0"
[[Reexport]]
deps = ["Pkg"]
git-tree-sha1 = "7b1d07f411bc8ddb7977ec7f377b97b158514fe0"
uuid = "189a3867-3050-52da-a836-e630ba90ab69"
version = "0.2.0"
[[SHA]]
uuid = "ea8e919c-243c-51af-8825-aaa63cd721ce"
[[SegyIO]]
deps = ["Distributed", "Printf", "Test"]
git-tree-sha1 = "329e1881c1afa0cdec51b91b6d383a569f8db62e"
repo-rev = "master"
repo-url = "https://github.com/slimgroup/SegyIO.jl"
uuid = "157a0f19-4d44-4de5-a0d0-07e2f0ac4dfa"
version = "0.7.1"
[[Serialization]]
uuid = "9e88b42a-f829-5b0c-bbe9-9e923198166b"
[[SharedArrays]]
deps = ["Distributed", "Mmap", "Random", "Serialization"]
uuid = "1a1011a3-84de-559e-8e89-a11a2f7dc383"
[[Sockets]]
uuid = "6462fe0b-24de-5631-8697-dd941f90decc"
[[SparseArrays]]
deps = ["LinearAlgebra", "Random"]
uuid = "2f01184e-e22b-5df5-ae63-d93ebab69eaf"
[[SpecialFunctions]]
deps = ["BinDeps", "BinaryProvider", "Libdl"]
git-tree-sha1 = "3bdd374b6fd78faf0119b8c5d538788dbf910c6e"
uuid = "276daf66-3868-5448-9aa4-cd146d93841b"
version = "0.8.0"
[[Statistics]]
deps = ["LinearAlgebra", "SparseArrays"]
uuid = "10745b16-79ce-11e8-11f9-7d13ad32a3b2"
[[Test]]
deps = ["Distributed", "InteractiveUtils", "Logging", "Random"]
uuid = "8dfed614-e22c-5e08-85e1-65c5234f0b40"
[[Tokenize]]
git-tree-sha1 = "dfcdbbfb2d0370716c815cbd6f8a364efb6f42cf"
uuid = "0796e94c-ce3b-5d07-9a54-7f471281c624"
version = "0.5.6"
[[URIParser]]
deps = ["Test", "Unicode"]
git-tree-sha1 = "6ddf8244220dfda2f17539fa8c9de20d6c575b69"
uuid = "30578b45-9adc-5946-b283-645ec420af67"
version = "0.4.0"
[[UUIDs]]
deps = ["Random", "SHA"]
uuid = "cf7118a7-6976-5b1a-9a39-7adc72f591a4"
[[Unicode]]
uuid = "4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5"
[[VersionParsing]]
deps = ["Compat"]
git-tree-sha1 = "c9d5aa108588b978bd859554660c8a5c4f2f7669"
uuid = "81def892-9a0e-5fdd-b105-ffc91e053289"
version = "1.1.3"
[[Wavelets]]
deps = ["Compat", "DSP", "Reexport"]
git-tree-sha1 = "4a53da1099523e7191ee5b95d6e5e32a88913b6d"
uuid = "29a6e085-ba6d-5f35-a997-948ac2efa89a"
version = "0.8.0"
<file_sep>/docker/Dockerfile
FROM python:3.6
# Install devito
RUN pip install --upgrade pip
RUN pip install --user git+https://github.com/opesci/devito.git@v3.2.0
# Devito requirements
ADD docker/devito_requirements.txt /app/devito_requirements.txt
RUN pip install --user -r /app/devito_requirements.txt && \
pip install --user jupyter
# Compiler and Devito environment variables
ENV DEVITO_ARCH="gcc"
ENV DEVITO_OPENMP="0"
ENV PYTHONPATH=/app/devito
# Required packages
RUN apt-get update && \
apt-get install -y gfortran && \
apt-get install -y hdf5-tools
# Install Julia
WORKDIR /julia
RUN wget "https://julialang-s3.julialang.org/bin/linux/x64/1.0/julia-1.0.2-linux-x86_64.tar.gz" && \
tar -xvzf julia-1.0.2-linux-x86_64.tar.gz && \
rm -rf julia-1.0.2-linux-x86_64.tar.gz && \
ln -s /julia/julia-1.0.2/bin/julia /usr/local/bin/julia
# Manually install unregistered packages and JUDI
RUN julia -e 'using Pkg; Pkg.clone("https://github.com/slimgroup/SegyIO.jl")' && \
julia -e 'using Pkg; Pkg.clone("https://github.com/slimgroup/JOLI.jl.git")' && \
julia -e 'using Pkg; Pkg.clone("https://github.com/slimgroup/JUDI.jl.git")'
RUN julia -e 'using Pkg; Pkg.add("NLopt")'
# Install and build IJulia
ENV JUPYTER="/root/.local/bin/jupyter"
RUN julia -e 'using Pkg; Pkg.add("IJulia")'
# Add JUDI examples
ADD ./data /app/judi/data
ADD ./test /app/judi/test
ADD ./examples /app/judi/examples
WORKDIR /app/judi/notebooks
EXPOSE 8888
CMD /root/.local/bin/jupyter-notebook --ip="*" --no-browser --allow-root
<file_sep>/src/Python/test.py
from __future__ import print_function
import numpy as np
import psutil, os, gc
from numpy.random import randint
from sympy import solve, cos, sin
from sympy import Function as fint
from devito.logger import set_log_level
from devito import Eq, Function, TimeFunction, Dimension, Operator, clear_cache
from PySource import RickerSource, PointSource, Receiver
from PyModel import Model
from checkpoint import DevitoCheckpoint, CheckpointOperator
from pyrevolve import Revolver
import matplotlib.pyplot as plt
from JAcoustic_codegen import forward_modeling, adjoint_born, adjoint_modeling, forward_born
from scipy import ndimage
# Model
shape = (101, 101)
spacing = (10., 10.)
origin = (0., 0.)
v = np.empty(shape, dtype=np.float32)
v[:, :51] = 1.5
v[:, 51:] = 5
v0 = ndimage.gaussian_filter(v, sigma=5)
#v0 = np.empty(shape, dtype=np.float32)
#v0[:, :] = 1.5
m = (1./v)**2
m0 = (1./v0)**2
dm = m - m0
model = Model(shape=shape, origin=origin, spacing=spacing, vp=v)
model0 = Model(shape=shape, origin=origin, spacing=spacing, vp=v0, dm=dm)
# Time axis
t0 = 0.
tn = 1000.
dt = model.critical_dt
nt = int(1 + (tn-t0) / dt)
time = np.linspace(t0,tn,nt)
# Source
f0 = 0.010
src = RickerSource(name='src', grid=model.grid, f0=f0, time=time)
src.coordinates.data[0,:] = np.array(model.domain_size) * 0.5
src.coordinates.data[0,-1] = 20.
# Receiver for observed data
rec_t = Receiver(name='rec_t', grid=model.grid, npoint=101, ntime=nt)
rec_t.coordinates.data[:, 0] = np.linspace(0, model.domain_size[0], num=101)
rec_t.coordinates.data[:, 1] = 20.
# Observed data
dobs, utrue = forward_modeling(model, src.coordinates.data, src.data, rec_t.coordinates.data)
#usave = forward_modeling(model, src.coordinates.data, src.data, rec_t.coordinates.data, save=True)[1]
#usub = forward_modeling(model, src.coordinates.data, src.data, rec_t.coordinates.data, save=True, tsub_factor=2)[1]
# adjoint modeling
#v = adjoint_modeling(model, None, rec_t.coordinates.data, dobs.data)
# forward born
#dlin = forward_born(model0, src.coordinates.data, src.data, rec_t.coordinates.data)
#disic = forward_born(model0, src.coordinates.data, src.data, rec_t.coordinates.data, isic=True)
# Receiver for predicted data
rec = Receiver(name='rec', grid=model0.grid, npoint=101, ntime=nt)
rec.coordinates.data[:, 0] = np.linspace(0, model0.domain_size[0], num=101)
rec.coordinates.data[:, 1] = 20.
dpred, u0 = forward_modeling(model0, src.coordinates.data, src.data, rec.coordinates.data, save=True, dt=dt, tsub_factor=2)
#g1 = adjoint_born(model0, rec.coordinates.data, disic, u=u0, dt=dt, isic=False)
# plt.imshow(np.transpose(g), vmin=-1e1, vmax=1e1); plt.show()
g1 = adjoint_born(model0, rec.coordinates.data, dpred - dobs, u=u0, dt=dt, isic=False)
op_predicted = forward_modeling(model0, src.coordinates.data, src.data, rec.coordinates.data, op_return=True, dt=dt)
f1, g2 = adjoint_born(model0, rec.coordinates.data, dobs, op_forward=op_predicted, dt=dt, is_residual=False)
print('Error: ', np.linalg.norm(g1 - g2))
##################################################################################################################
#
# # Receiver for predicted data
# rec = Receiver(name='rec', grid=model0.grid, npoint=101, ntime=nt)
# rec.coordinates.data[:, 0] = np.linspace(0, model0.domain_size[0], num=101)
# rec.coordinates.data[:, 1] = 20.
#
# # Save wavefields
# dpred_data, u0 = forward_modeling(model0, src.coordinates.data, src.data, rec.coordinates.data, save=True, dt=dt)
# g1 = adjoint_born(model0, rec.coordinates.data, dpred_data[:] - dobs.data[:], u=u0, dt=dt)
#
# # Checkpointing
# op_predicted = forward_modeling(model0, src.coordinates.data, src.data, rec.coordinates.data, op_return=True, dt=dt)
# f2, g2 = adjoint_born(model0, rec.coordinates.data, dobs.data, op_forward=op_predicted, dt=dt)
#
# print('Error: ', np.linalg.norm(g1 - g2))
<file_sep>/src/Python/timings_sigsbee.py
from __future__ import print_function
import numpy as np
from PySource import RickerSource
from PyModel import Model
from PySource import Receiver
from JAcoustic_codegen import forward_born, forward_freq_modeling, adjoint_freq_born, forward_modeling, adjoint_born
import time
import h5py
import matplotlib.pyplot as plt
# Load Sigsbee model
#sigsbee = h5py.File('/scratch/slim/shared/mathias-philipp/sigsbee2A/Sigsbee_LSRTM.h5','r+')
sigsbee = h5py.File('/data/pwitte3/sigsbee2A-shared/Sigsbee_LSRTM.h5','r+')
m0 = np.transpose(np.array(sigsbee['m0']))
dm = np.transpose(np.array(sigsbee['dm']))
# Model
shape = (3201, 1201)
spacing = (7.62, 7.62)
origin = (0., 0.)
model0 = Model(shape=shape, origin=origin, spacing=spacing, vp=np.sqrt(1/m0), dm=dm)
# Time axis
t0 = 0.
tn = 10000.
dt = model0.critical_dt
nt = int(1 + (tn-t0) / dt)
time_axis = np.linspace(t0,tn,nt)
# Source
f0 = 0.015
src = RickerSource(name='src', grid=model0.grid, f0=f0, time=time_axis)
src.coordinates.data[0,:] = np.array(4617.)
src.coordinates.data[0,-1] = 20.
# Receiver for observed data
rec_t = Receiver(name='rec_t', grid=model0.grid, npoint=1200, ntime=nt)
rec_t.coordinates.data[:, 0] = np.linspace(4717., 16617., num=1200)
rec_t.coordinates.data[:, 1] = 50.
# Compute LS-RTM gradient w/ on-the-fly DFTs
num_frequencies = [1, 2, 4, 8, 16, 32, 64, 128, 256]
timings = np.zeros(len(num_frequencies))
for j in range(len(num_frequencies)):
f = np.linspace(0.01, 0.01, num_frequencies[j]) # always use 10 Hz
t1 = time.time()
d0, ufr, ufi = forward_freq_modeling(model0, src.coordinates.data, src.data, rec_t.coordinates.data, freq=f, dt=dt, factor=8)
t2 = time.time()
print('Forward: ', t2 - t1)
t3 = time.time()
dm = adjoint_freq_born(model0, rec_t.coordinates.data, d0.data, f, ufr, ufi, isic=True, dt=dt, factor=8)
t4 = time.time()
print('Adjoint: ', t4 - t3)
print('Total: ', (t2 - t1) + (t4 - t3))
timings[j] = (t2 - t1) + (t4 - t3)
timings.dump('timing_sigsbee_frequencies.dat')
# Checkpointing
d0, _ = forward_modeling(model0, src.coordinates.data, src.data, rec_t.coordinates.data)
ta = time.time()
op_predicted = forward_modeling(model0, src.coordinates.data, src.data, rec_t.coordinates.data, op_return=True, dt=dt)
f1, g1 = adjoint_born(model0, rec_t.coordinates.data, d0.data, op_forward=op_predicted, dt=dt)
tb = time.time()
print('Optimal checkpointing: ', tb - ta)
timings_oc = np.array(tb - ta)
timings_oc.dump('timing_sigsbee_optimal_checkpointing.dat')
| b67dbc1fd409ce099380a9370e113dc502440d34 | [
"TOML",
"Python",
"Dockerfile"
] | 8 | Python | alisiahkoohi/JUDI.jl | f608b26aae139acd9ef73b01474524fe741cbf92 | 3f7508eaa4f7cd98f1caec0eeecc4a6b6c92b534 |
refs/heads/master | <file_sep>// <NAME>
// 18 December 2019
// Hello user!
// import things
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Hello extends JFrame implements ActionListener {
// begin gooui elements
JPanel[] panels = {new JPanel(), new JPanel(), new JPanel()};
JTextField[] tfs = {new JTextField("", 15), new JTextField("", 15)};
JLabel[] labels = {new JLabel("Name"), new JLabel("Message")};
JButton[] buttons = {new JButton("OK")};
// end gooui layouts
public static void main(String[] args) {
Hello window = new Hello(); // create new thingy
} // end main
public void actionPerformed(ActionEvent event) {
if (buttons[0] == event.getSource()) { // check for button in prep for future
if (! tfs[0].getText().equals("")) { // Don't want it to show up blank
tfs[1].setText("Hello, " + tfs[0].getText() + "!");
panels[1].setVisible(true); // magic appearing box
} // end if getText
} // end if button
} // end actionPerformed
public Hello() {
for (int i = 0; i < 2; i++) {
panels[i].add(labels[i]);
panels[i].add(tfs[i]);
} // less typing
buttons[0].addActionListener(this); // make button do something
panels[2].add(buttons[0]); // add button to last movable panel
panels[0].setLayout(new FlowLayout(FlowLayout.LEFT, 10, 10)); // make things look nice
panels[1].setLayout(new FlowLayout(FlowLayout.LEFT, 10, 0)); // make things look nicer
setSize(320, 150); // this seems like a good size
setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS)); // align everything
setTitle("Hello!");
for (JPanel panel : panels) { // technically not learned but it's so convenient
add(panel);
} // end for
panels[1].setVisible(false); // hide until needed
setVisible(true); // show frame
} // end constructor
} // end class
<file_sep>// <NAME>
// 25 October 2019
// Pounds to kg
import java.util.Scanner;
class Method2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Pounds: ");
double lb = input.nextDouble();
System.out.println(lb + " lb is " + lb2kg(lb) + " kg");
}
public static double lb2kg(double lb) {
return lb / 2.2;
}
}
<file_sep>// <NAME>
// 17 December 2019
// No panels yet
import java.awt.*;
import javax.swing.*;
public class FlowDemo extends JFrame {
public static void main(String[] args) {
FlowDemo window = new FlowDemo();
}
public FlowDemo() {
JPanel p1 = new JPanel();
FlowLayout f1 = new FlowLayout();
JButton[] buttons = {new JButton("Button 1"), new JButton("Button 2"), new JButton("Button 3"), new JButton("Long-Named Button 4"), new JButton("5")};
for (JButton button : buttons) {
p1.add(button);
}
p1.setLayout(f1);
add(p1);
setSize(640, 160);
setTitle("FlowLayoutDemo");
setLayout(f1);
setVisible(true);
}
}
<file_sep>// <NAME>
// 22 November 2019
// Reading from a file
import java.util.Scanner;
import java.io.*;
class IOFormativeB {
public static void main(String[] args) throws Exception {
File file = new File("formativeB.txt"); // setup file output
PrintWriter output = new PrintWriter(file);
Scanner finput = new Scanner(new File("formative.txt")); // setup file input
String tempholder = "";
while (finput.hasNext()) {
tempholder += finput.next() + "\n"; // add everything to one long string just in case input is over five lines long
}
String[] wArray = tempholder.split("\n"); // put into array
int eees = 0; // init holding var
for (int i = 0; i < wArray.length; i++) { // loop through every char
for (int j = 0; j < wArray[i].length(); j++) {
if (wArray[i].charAt(j) == 'e' || wArray[i].charAt(j) == 'E') {
eees++;
}
}
}
System.out.println("There is/are " + eees + " of the fifth letter of the English alphabet present.");
String tempString;
for (int i = 0; i < wArray.length - 1; i++) { // bubble sort
for (int j = 1; j < wArray.length - i; j++) {
if (wArray[j - 1].compareTo(wArray[j]) > 0) {
tempString = wArray[j - 1];
wArray[j - 1] = wArray[j];
wArray[j] = tempString;
}
}
}
for (int i = 0; i < wArray.length; i++) { // print sorted array to file
output.println(wArray[i]);
} // end for
output.close(); // close file handles
finput.close();
} // end main
} // end class<file_sep>// <NAME>
// 19 November 2019
// Write my name
import java.io.*;
class OutFile1 {
public static void main(String[] args) throws Exception {
File file1 = new File("file1");
PrintWriter output = new PrintWriter(file1);
output.println("<NAME>");
output.close();
}
}
<file_sep>// <NAME>
// 12 September 2019
// Var1
class Var1 {
public static void main(String[] args) {
int num = 5;
System.out.println(num);
}
}
<file_sep>// <NAME>
// 7 October 2019
// 0 to exit
import java.util.Scanner;
class Array7 {
public static void main(String[] args) {
// init variables
int times = 10; // everything relative is better
int broken = 0; // just in case user doesn't like us and quits
int[] integers = new int[times]; // no way to get around this because dynamic arrays don't exist
Scanner input = new Scanner(System.in);
for (int i = 0; i < times; i++) {
System.out.print("Number ('0' to continue): ");
integers[i] = input.nextInt();
broken++;
if (integers[i] == 0) {
broken--;
break;
}
}
// Positive numbers
System.out.println("Positive integers: ");
for (int i = 0; i < broken; i++) {
if (integers[i] > 0) {
System.out.println(integers[i]);
}
}
// I don't know how to optimise this but I'm sure it's possible
System.out.println("Negative integers: ");
for (int i = 0; i < broken; i++) {
if (integers[i] < 0) {
System.out.println(integers[i]);
}
}
}
}
<file_sep>// <NAME>
// 25 October 2019
// Heron formula thingy to find triangle area
// Algorithm
// create arrays for triangle lines
// create array for triangle lengths
// loop following:
// ask for triangle points
// pass triangle points through length formula into heron formula
// print heron formula
// ask for repetition
// if user doesn't want to repeat, leave
// distance function:
// take two points in array
// use distance formula on moodle to get a double
// return that
// heron function:
// accept array of triangle lengths
// solve for S as shown on moodle
// solve for area as shown on moodle
// return area, rounded
import java.util.Scanner;
import java.lang.Math;
class Method9 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
double[] p1 = new double[2];
double[] p2 = new double[2];
double[] p3 = new double[2];
double[] lengths = new double[3];
String repeat = "y";
do {
System.out.print("x1: ");
p1[0] = input.nextInt();
System.out.print("y1: ");
p1[1] = input.nextInt();
System.out.print("x2: ");
p2[0] = input.nextInt();
System.out.print("y2: ");
p2[1] = input.nextInt();
System.out.print("x3: ");
p3[0] = input.nextInt();
System.out.print("y3: ");
p3[1] = input.nextInt();
double a = distance(p1, p2);
double b = distance(p1, p3);
double c = distance(p2, p3);
System.out.println("Area = " + heron(a, b, c));
System.out.print("Repeat? (Y/n)");
repeat = input.next();
} while (! repeat.equals("n"));
}
public static double distance(double[] p1, double[] p2) {
return Math.sqrt((p1[1] - p1[0]) * (p1[1] - p1[0]) + (p2[1] - p2[0]) * (p2[1] - p2[0]));
}
public static double heron(double a, double b, double c) {
double S = (a + b + c) / 2;
return Math.round(Math.sqrt(S * (S - a) * (S - b) * (S - c)));
}
}
<file_sep>// <NAME>
// 25 October 2019
// Squares number
// Algorithm
// ask for input and store in variable
// function is defined as returning variable * variable
// pass variable through function and print result
import java.util.Scanner;
class Method5 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Number: ");
int number = input.nextInt();
System.out.println(number + " squared is " + squared(number));
}
public static int squared(int num) {
return num * num;
}
}
<file_sep>// <NAME>
// 19 November 2019
// Read and print file
import java.util.Scanner;
import java.io.File;
class InFile2 {
public static void main(String[] args) throws Exception {
File file = new File("file3");
Scanner input = new Scanner(file);
while (input.hasNextLine()) {
System.out.println(input.nextLine());
}
input.close();
}
}
<file_sep>// <NAME>
// 19 November 2019
// Read and print file
import java.util.Scanner;
import java.io.File;
class InFile3 {
public static void main(String[] args) throws Exception {
Scanner input = new Scanner(System.in);
System.out.print("Filename: ");
File file = new File(input.nextLine());
Scanner finput = new Scanner(file);
while (finput.hasNextLine()) {
System.out.println(finput.nextLine());
}
finput.close();
}
}
<file_sep>// <NAME>
// 19 November 2019
// write sorted number to file
import java.io.*;
import java.util.Scanner;
import java.util.Arrays;
class OutFile7 {
public static void main(String[] args) throws Exception {
Scanner input = new Scanner(System.in);
File file = new File("file7");
PrintWriter output = new PrintWriter(file);
int[] numArray = new int[15];
for (int i = 0; i < numArray.length; i++) {
System.out.print("Number (1-20): ");
numArray[i] = input.nextInt();
}
int tempswap = 0;
for (int i = 0; i < numArray.length; i++) {
for (int j = 1; j < numArray.length - i; j++) {
if (numArray[j - 1] > numArray[j]) {
tempswap = numArray[j - 1];
numArray[j - 1] = numArray[j];
numArray[j] = tempswap;
}
}
}
output.println(Arrays.toString(numArray));
output.close();
}
}
<file_sep>// <NAME>
// 14 November 2019
// print everything line by line
import java.util.Scanner;
class String5 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("String: ");
String string = input.nextLine();
for (int i = 0; i < string.length(); i++) {
System.out.println(string.charAt(i));
}
}
}
<file_sep>// <NAME>
// 14 November 2019
// lowerCamelCase converter from spaces
import java.util.Scanner;
class String8 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("String: ");
String string = input.nextLine();
String[] stringArray = string.split(" ");
stringArray[0] = stringArray[0].toLowerCase();
for (int i = 1; i < stringArray.length; i++) {
stringArray[i] = stringArray[i].substring(0, 1).toUpperCase() + stringArray[i].substring(1, stringArray[i].length()).toLowerCase();
}
for (int i = 0; i < stringArray.length; i++) {
System.out.print(stringArray[i]);
}
}
}
<file_sep>// <NAME>
// 20 September 2019
// Repeat name x times, with numbers
class For4 {
public static void main(String[] args) {
for (int i = 1; i < 11; i++) {
System.out.println(i + ". Daniel");
}
}
}
<file_sep>// <NAME>
// 7 October 2019
// Shame those who failed or compliment those who passed
import java.util.Scanner;
class Array5 {
public static void main(String[] args) {
int times = 10;
String[] firstnames = new String[times]; // Create empty arrays
String[] lastnames = new String[times];
int[] marks = new int[times];
Scanner input = new Scanner(System.in); // Set up input
for (int i = 0; i < times; i++) {
// Get names and marks
System.out.print("First name " + (i + 1) + ": ");
firstnames[i] = input.nextLine();
if (firstnames[i].equals("")) {
firstnames[i] = input.nextLine(); //Java dumb and doesn't see it again
}
System.out.print("Last name " + (i + 1) + ": ");
lastnames[i] = input.nextLine();
System.out.print("Mark " + (i + 1) + ": ");
marks[i] = input.nextInt();
}
System.out.print("List to see (PASS/fail): ");
String passFail = input.nextLine();
if ("".equals(passFail)) { // Java dumb and doesn't see it AGAIN
passFail = input.nextLine();
}
for (int i = 0; i < times; i++) {
if ("pass".equalsIgnoreCase(passFail) && marks[i] >= 50) {
System.out.println(lastnames[i] + ", " + firstnames[i] + " - " + marks[i] + "%");
} else if ("fail".equalsIgnoreCase(passFail) && marks[i] < 50) {
System.out.println(lastnames[i] + ", " + firstnames[i] + " - " + marks[i] + "%");
}
}
}
}
<file_sep>// <NAME>
// 31 October 2019
// Interest calculator
import java.util.Scanner;
class pMethod2 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Balance at beginning of year: ");
double balance = sc.nextDouble();
System.out.print("Current interest rate: ");
double currentInterest = sc.nextDouble();
interestBalance(balance, currentInterest);
}
public static void interestBalance(double bal, double i) {
System.out.println("Interest = " + bal * i);
System.out.println("New balance = " + (bal + bal * i));
}
}
<file_sep>// <NAME>
// 24 September 2019
// Word guessing but with statistics and repeated guessing
// Be able to get input from user
import java.util.Scanner;
class While9 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Make input user-friendly by telling them what to do
System.out.print("Word: ");
String word = input.nextLine();
// Initialise guessing variable
String guess = "There's no way anyone would possibly guess this it's a completely random string since Java doesn't like having this empty and yeah";
// Initialise counter variable
int counter = 0;
while (! word == guess) {
System.out.print("Guess: ");
guess = input.nextLine();
counter++;
}
System.out.println("The word was \"" + word + "\".");
System.out.println("You guessed it in " + counter + " guesses.");
}
}
<file_sep>// <NAME>
// 11 September 2019
// Outs
// Out1
// Comments are blue
// Reserved words are green
class Out {
public static void main(String[] args) {
System.out.println("12");
System.out.println("13");
System.out.println("14");
System.out.println("15");
// Out2
System.out.println("<NAME>");
// Out3
System.out.println("The area code for Toronto is " + 416);
// Out4
System.out.println(3*4);
// Out5
System.out.println(5%2);
// Out6
System.out.println("Hello");
System.out.println("Hello");
System.out.println("Hello");
System.out.println("Hello");
System.out.println("Hello");
System.out.println("Hello");
System.out.println("Hello");
System.out.println("Hello");
System.out.println("Hello");
System.out.println("Hello");
// Out7
}
}
<file_sep>// <NAME>
// 25 October 2019
// Find parallel slopes
// Algorithm
// Initialise two arrays, each holding four points
// ask user to fill up all arrays
// pass arrays to slope function, if they're equal output they're parallel
// slope function is formula on moodle
import java.util.Scanner;
import java.lang.Math;
class Method7 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] line1 = new int[4];
int[] line2 = new int[4];
String repeat = "y";
do {
System.out.println("Line 1:");
System.out.print("x1: ");
line1[0] = input.nextInt();
System.out.print("x2: ");
line1[1] = input.nextInt();
System.out.print("y1: ");
line1[2] = input.nextInt();
System.out.print("y2: ");
line1[3] = input.nextInt();
System.out.println("Line 2:");
System.out.print("x1: ");
line2[0] = input.nextInt();
System.out.print("x2: ");
line2[1] = input.nextInt();
System.out.print("y1: ");
line2[2] = input.nextInt();
System.out.print("y2: ");
line2[3] = input.nextInt();
if (slope(line1) == slope(line2)) {
System.out.println("The two lines are parallel.");
} else {
System.out.println("The two lines are not parallel.");
}
System.out.print("Repeat? (Y/n)");
repeat = input.next();
} while (! repeat.equals("n"));
}
public static double slope(int[] points) {
return (points[3] - points[2])/(points[1] - points[0]);
}
}
<file_sep>// <NAME>
// 28 November 2019
// Read from files
import java.util.Scanner;
import java.io.PrintWriter;
import java.io.File; // import required thingies
class IOTestB {
public static void main(String[] args) throws Exception {
Scanner in = new Scanner(System.in); // user input
System.out.print("Filename (e.g., file.txt): ");
Scanner fin = new Scanner(new File(in.nextLine())); // prompt for filename and create new scanner for that file
PrintWriter out = new PrintWriter("fileB.txt"); // setup output
String words = ""; // init blank string
while (fin.hasNextLine()) {
words += fin.nextLine() + " "; // add all words to long string separated by space
} // end while
String[] wordsArray = words.split(" "); // split words into array
int[] charCount = new int[wordsArray.length]; // create array to hold corresponding character count
char checkChar; // made purely to reduce the amount of words necessary for typing
for (int i = 0; i < wordsArray.length; i++) { // iterate through each word in array
for (int j = 0; j < wordsArray[i].length(); j++) { // iterate through each character in word
checkChar = wordsArray[i].charAt(j);
if (checkChar == 'r' || checkChar == 's' || checkChar == 't' || checkChar == 'n' || checkChar == 'a') {
charCount[i]++; // if characters exist increase corresponding count
} // end if
} // end j for
} // end i for
int tempInt; // declare temp variables for bubble sort
String tempString;
for (int i = 0; i < wordsArray.length - 1; i++) { // bubble sort
for (int j = 1; j < wordsArray.length - i; j++) {
if (charCount[j - 1] < charCount[j]) {
tempInt = charCount[j - 1]; // swap for both arrays since they're linked
charCount[j - 1] = charCount[j];
charCount[j] = tempInt;
tempString = wordsArray[j - 1];
wordsArray[j - 1] = wordsArray[j];
wordsArray[j] = tempString;
}
}
}
for (int i = 0; i < wordsArray.length; i++) {
System.out.println(wordsArray[i] + " - " + charCount[i] + " occurrence(s)"); // print out sorted array
out.println(wordsArray[i] + " "); // output sorted array
}
in.close();
fin.close();
out.close(); // close file handles
}
}
<file_sep>// <NAME>
// 4 November 2019
// Time unit converter
import java.util.Scanner;
class ExtraPractice1 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
}
public static double
<file_sep>import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
import java.io.IOException;
class dmoj_stack1 {
static StringTokenizer st;
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static String next() throws IOException{
while(st==null||!st.hasMoreTokens())
st = new StringTokenizer(br.readLine().trim());
return st.nextToken();
}
static int readInt() throws IOException{
return Integer.parseInt(next());
}
static String readLine() throws IOException{
return br.readLine().trim();
}
public static void main(String[] args) {
}
}
<file_sep>// <NAME>
// 11 October 2019
// Having fun with String arrays
import java.util.*;
class ArrayProcessing4 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String[] stringList = {"one","two","five","four","six","three"}; // initialise array
// swapping the two elements on the list
String temp = stringList[5];
stringList[5] = stringList[2];
stringList[2] = temp;
System.out.println(Arrays.toString(stringList));
// Ask user to switch things on list
System.out.print("Number (0-5): ");
int i = input.nextInt();
System.out.print("Number (0-5): ");
int j = input.nextInt();
// swapping the two elements on the list again but this time with variables
temp = stringList[j];
stringList[j] = stringList[i];
stringList[i] = temp;
System.out.println(Arrays.toString(stringList));
}
}
<file_sep>// <NAME>
// 24 September 2019
// For4 clone
// Be able to get input from user
import java.util.Scanner;
class While4 {
public static void main(String[] args) {
// Initialise counter variable in place of for loop
int counter = 1;
while (counter <= 10) {
System.out.println(counter + ". Daniel");
counter++;
}
}
}
<file_sep>// <NAME>
// 20 September 2019
// Repeat word x times, with numbers
import java.util.Scanner;
class For6 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Word: ");
String word = input.nextLine();
System.out.print("Times: ");
int times = input.nextInt();
for (int i = 1; i < times + 1; i++) {
System.out.println(i + ". " + word);
}
}
}
<file_sep>// <NAME>
// 11 October 2019
// Determine average of two marks for students
import java.util.*;
class ArrayProcessing2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in); // handle input
// initialise various arrays
int arrayLength = 10;
String[] nameList = new String[arrayLength];
float[] mathList = new float[arrayLength];
float[] scienceList = new float[arrayLength];
// ask user to input their marks
for (int i = 0; i < arrayLength; i++) {
System.out.print("Name: ");
do {
nameList[i] = input.nextLine();
} while ("".equals(nameList[i]));
System.out.print("Math mark: ");
mathList[i] = input.nextFloat();
System.out.print("Science mark: ");
scienceList[i] = input.nextFloat();
}
// Print averages
System.out.println("Averages:");
for (int i = 0; i < arrayLength; i++) {
System.out.println(nameList[i] + " - " + (mathList[i] + scienceList[i]) / 2.0 + "%");
}
}
}
<file_sep>// <NAME>
// 14 November 2019
// word remover
import java.util.Scanner;
class String9 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("String: ");
String string = input.nextLine();
System.out.print("Remove string: ");
String replacer = input.nextLine();
string = string.replaceAll(replacer + " ", "");
string = string.replaceAll(" " + replacer, "");
System.out.println(string);
}
}
<file_sep>// <NAME>
// 12 September 2019
// Var9
import java.util.Scanner;
class Var9 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("First name: ");
String fname = scan.nextLine();
System.out.print("Last name: ");
String lname = scan.nextLine();
System.out.println("Hello " + fname + " " + lname + "! How are you?");
}
}
<file_sep>// <NAME>
// 31 October 2019
// Rectangle generator
import java.util.Scanner;
class pMethod4 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Height: ");
int height = sc.nextInt();
System.out.print("Width: ");
int width = sc.nextInt();
System.out.print("Character: ");
char c = sc.next().charAt(0);
printRectangle(width, height, c);
}
public static void printRectangle(int width, int height, char c) {
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
System.out.print(c);
}
System.out.println();
}
}
}
<file_sep>// <NAME>
// 25 October 2019
// Centimetres to inches
// Algorithm
// ask for input and store in variable
// function is defined as returning variable / 2.54
// pass variable through function and print result
import java.util.Scanner;
class Method6 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Centimetres: ");
double cm = input.nextDouble();
System.out.println(cm + " cm is " + cm2i(cm) + "\"");
}
public static double cm2i(double cm) {
return cm / 2.54;
}
}
<file_sep>// <NAME>
// 19 November 2019
// Read and print file
import java.util.Scanner;
import java.util.Arrays;
import java.io.File;
class InFile7 {
public static void main(String[] args) throws Exception {
Scanner input = new Scanner(System.in);
File file = new File("file4");
Scanner finput = new Scanner(file);
String[] stringArray = finput.nextLine().replaceAll("\\[", "").replaceAll("\\]", "").replaceAll(",", "").split(" "); // me and my lazy code
int[] intArray = new int[stringArray.length];
for (int i = 0; i < stringArray.length; i++) {
intArray[i] = Integer.parseInt(stringArray[i]);
}
int tempswap = 0;
for (int i = 0; i < intArray.length; i++) {
for (int j = 1; j < intArray.length - i; j++) {
if (intArray[j - 1] > intArray[j]) {
tempswap = intArray[j - 1];
intArray[j - 1] = intArray[j];
intArray[j] = tempswap;
}
}
}
System.out.println(Arrays.toString(intArray));
finput.close();
}
}
<file_sep>// <NAME>
// 12 September 2019
// Scanner
import java.util.Scanner;
class Var8 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String principal = scan.nextLine();
int integer = scan.nextInt();
scan.nextInt()
}
}
<file_sep>// <NAME>
// 22 November 2019
// Writing to a file
import java.util.Scanner;
import java.io.*;
class IOFormativeA {
public static void main(String[] args) throws Exception {
File file = new File("formativeA.txt"); // setup file output
PrintWriter output = new PrintWriter(file);
Scanner input = new Scanner(System.in); // setup input
for (int i = 0; i < 5; i++) {
System.out.print("Name: ");
output.println(input.nextLine()); // output to file
} // end for
output.close();
input.close();
} // end main
} // end class<file_sep>// <NAME>
// 26 September 2019
// While5 clone 2
// Be able to get input from user
import java.util.Scanner;
class DoWhile6 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Ask for input nicely user friendly-y
System.out.print("Word: ");
String word = input.nextLine();
System.out.print("Times: ");
int repeat = input.nextInt();
// Initialise counter variable in place of for loop
int counter = 1;
do {
System.out.println(word);
counter++;
} while (counter <= repeat);
}
}
<file_sep>// <NAME>
// 12 September 2019
// Var7
import java.util.Scanner;
class Var7 {
public static void main(String[] args) {
System.out.print("Length: ");
Scanner scan = new Scanner(System.in);
double x = scan.nextDouble();
System.out.print("Width: ");
Scanner scan2 = new Scanner(System.in);
double y = scan.nextDouble();
double area = x * y;
double perimeter = 2 * (x + y);
System.out.println("Area = " + area);
System.out.println("Perimeter = " + perimeter);
}
}
<file_sep>// <NAME>
// 26 September 2019
// While4 clone
// Be able to get input from user
import java.util.Scanner;
class DoWhile4 {
public static void main(String[] args) {
// Initialise counter variable in place of for loop
int counter = 1;
do {
System.out.println(counter + ". Daniel");
counter++;
} while (counter <= 10);
}
}
<file_sep>// <NAME>
// 17 September 2019
// Sel8 but lower
import java.util.Scanner;
// Import module for interactivity
class Sel9 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Set up interactivity
System.out.print("Mark 1: ");
float mark1 = input.nextFloat();
System.out.print("Mark 2: ");
float mark2 = input.nextFloat();
if (mark1 < mark2) { // Make decision based on above input
System.out.println(mark1);
} else {
System.out.println(mark2);
}
}
}
<file_sep>// <NAME>
// 8 November 2019
// Online shop
import java.util.Scanner;
class OnlineShop {
static String[] names = new String[10]; // init base arrays
static double[] cost = new double[10];
static int[] stock = new int[10];
static int filled = 0;
/* uncommment to use
static String[] names = {"Microsoft Windows 10 Pro", "Solus 4", "Arch Linux 2019.11.01", "Ubuntu 18.04.2 LTS", "Microsoft Windows 7 Pro", "Microsoft Windows XP SP3", "Android 10", "macOS 10.15 Catalina", "Debian 10.1 Buster", "Android 8.1 Oreo"};
static double[] cost = {199.99, 0.0, 15.0, 3.0, 159.99, 29.99, 20.0, 129.99, 1.0, 60.0};
static int[] stock = {150, 2, 100, 1500, 5, 1, 50, 75, 3000, 10};
static int filled = 10;
*/
static int[] cart = new int[10]; // cart variable
static double[] taxprovters = {5, 12, 13, 15, 15, 5, 15, 5, 13, 15, 14.975, 11, 5}; // contains tax rates for provinces and territories
static String[] provters = {"Alberta", "British Columbia", "Manitoba", "New Brunswick", "Newfoundland", "Northwest Territories", "Nova Scotia", "Nunavut Territory", "Ontario", "Prince Edward Island", "Quebec", "Saskatchewan", "Yukon Territory"};
static double revenue = 0; // global revenue
static Scanner input = new Scanner(System.in); // global scanner
static double calcTax(double value, int area) {
double rate = taxprovters[area]; // just returning calculations
return value * rate / 100;
}
static void addProd() {
while (true) { // loop indefinitely until user quits
int chosenName = 0; // 0 to trigger loops
int chosenStock = -1; // negative to trigger loops
int holder = displayProd(); // everything returns int for what was originally navigational purposes
System.out.println((filled + 1) + ". Back"); // provide user with option to quit
System.out.println(); // make it look pretty
do { // didn't think of making dotrycatchwhile function
try {
System.out.print("Product # to add: ");
chosenName = input.nextInt() - 1; // align user input with array indexes
if (chosenName == filled) {
return; // leave method to return to main menu
} else if (chosenName > filled || chosenName < 0) {
error(1);
} // end if
} catch (Exception e) {
error(0);
} // end catch
} while (chosenName > filled || chosenName < 0);
do {
try {
System.out.print("Add count: ");
chosenStock = input.nextInt();
if (chosenStock > stock[chosenName] || chosenStock < 0) {
System.out.println("Cannot add " + chosenStock + " of " + names[chosenName] + " to cart. Try again."); // handle out of stock items here or overstocking instead of checkout since it's easier
} // end if
} catch (Exception e) {
error(0);
} // end catch
} while (chosenStock > stock[chosenName] || chosenStock < 0);
cart[chosenName] += chosenStock;
stock[chosenName] -= chosenStock; // add cart and reduce stock accordingly
System.out.println("Added " + chosenStock + " of " + names[chosenName] + " to cart."); // user confirmation message
System.out.println();
} // end big while
} // end addProd
static int updateInv() {
while (true) {
int chosenName = 0;
int chosenStock = -1;
double chosenPrice = -1;
int holder = displayInv();
if (filled < 10) { // handle both updating products and new products here
System.out.println((filled + 1) + ". New product");
System.out.println((filled + 2) + ". Back");
} else {
System.out.println((filled + 1) + ". Back");
}
System.out.println(); // make it look pretty
do {
try {
System.out.print("Product # to modify: ");
chosenName = input.nextInt() - 1;
if (chosenName == filled + 1) {
return 0; // leave method
} else if (chosenName == filled && filled == 10) {
return 0; // leave method when you can't add new products
} else if (chosenName > filled || chosenName < 0) {
error(1);
} // end if
} catch (Exception e) {
error(0);
} // end catch
} while (chosenName > filled || chosenName < 0);
input.nextLine(); // clear scanner
System.out.print("New product name: ");
names[chosenName] = input.nextLine(); // modify everything in one go to avoid extra clicks
do {
try {
System.out.print("New product price: ");
chosenPrice = input.nextDouble();
if (chosenPrice < 0) {
System.out.println("Cannot set price less than zero. Try again."); // print out helpful error
} //end if
} catch (Exception e) {
error(0);
} // end catch
} while (chosenPrice < 0);
cost[chosenName] = chosenPrice; // confirm and commit to global variable
do {
try {
System.out.print("New product stock: ");
chosenStock = input.nextInt();
if (chosenStock < 0) {
System.out.println("Cannot set total stock less than zero. Try again.");
} // end if
} catch (Exception e) {
error(0);
} // end catch
} while (chosenStock < 0);
stock[chosenName] = chosenStock;
if (chosenName == filled) {
filled++; // update total filled items
} // end if
} // end while
} // end updateInv
static int displayInv() {
for (int i = 0; i < filled; i++) { // simple for loop to iterate through everything
System.out.println((i + 1) + ". " + names[i] + " - $" + cost[i] + " - " + stock[i] + " in stock"); // formatted nicely
}
return 0; // everything was originally supposed to return int for navigational purposes
}
static int displayProd() {
for (int i = 0; i < filled; i++) {
if (stock[i] > 0) {
System.out.println((i + 1) + ". " + names[i] + " - $" + String.format("%.2f", cost[i]) + " - " + stock[i] + " available - " + cart[i] + " in cart"); // formatting
} else {
System.out.println((i + 1) + ". " + names[i] + " - $" + String.format("%.2f", cost[i]) + " - Out of stock - " + cart[i] + " in cart"); // make distinction from "0" and out of stock because I like it more
}
}
return 0;
}
static int showCart() {
for (int i = 0; i < cart.length; i++) {
if (cart[i] > 0) { // do not print if no item in that cart slot
System.out.println((i + 1) + ". " + names[i] + " - " + cart[i] + " in cart - $" + String.format("%.2f", (double) cost[i] * cart[i]) + " - $" + cost[i] + " ea"); // nicely formatted
}
}
System.out.println(); // nice newline for prettiness
return 0;
}
static String rngGreeting(int type) {
// 0 is hello manager, 1 is bye manager, 2 is hi customer, 3 is by customer
String[] hiManager = {"Manage " + rngName(), "Welcome back", "Fix stonks at " + rngName()};
String[] byeManager = {"We will see you soon!", "Good luck!", "See you tomorrow!"};
String[] hiCustomer = {"Welcome to " + rngName(), "Shop at " + rngName(), "Buy everything at " + rngName(), rngName()};
String[] byeCustomer = {"We hope to see you soon!", "Goodbye!", "Come back soon!"};
if (type == 0) {
return hiManager[(int)(Math.random() * hiManager.length)];
} else if (type == 1) {
return byeManager[(int)(Math.random() * byeManager.length)];
} else if (type == 2) {
return hiCustomer[(int)(Math.random() * hiCustomer.length)];
} else {
return byeCustomer[(int)(Math.random() * byeCustomer.length)];
}
} // end rngGreeting
static int checkout() {
int holder = showCart(); // get customer to look over their stuff
double subtotal = 0;
double tax = -1.0;
int location = -1; // holds province/territory
int discount = 0; // holds discount percentage
for (int i = 0; i < names.length; i++) {
subtotal += cart[i] * cost[i]; // add everything to subtotal
}
// randomly determine if they get a discount (1 in 5 chance)
if ((int) (Math.random() * 10) < 2) {
discount = (int) (Math.random() * 10) * 5; // it's a pretty big discount
System.out.println("Congratulations! You've won a " + discount + "% discount on your order, before tax!"); // tell user they got lucky
subtotal -= subtotal * discount / 100; // take their costs away
} // end if
System.out.println();
for (int i = 0; i < taxprovters.length; i++) {
System.out.println((i + 1) + ". " + provters[i]); // output list of provinces and options
}
System.out.println();
do {
try {
System.out.print("Yout province/territory #: ");
location = input.nextInt() - 1; // ask where they live
if (location < 0 || location > 12) {
error(1);
} else {
tax = calcTax(subtotal, location);
}
} catch (Exception e) {
error(0);
}
if (tax == -1) {
error(2); // if tax hasn't changed yell at them
}
} while (tax == -1);
// nicely formatted receipt
double total;
total = subtotal + tax;
if (discount != 0) {
System.out.println("Subtotal: $" + String.format("%.2f", subtotal/(1 - discount/100.0))); // output original price
System.out.println("Discount: " + discount + "% off ($" + String.format("%.2f", subtotal/(1 - discount/100.0) - subtotal) + " off)"); // remind user they got a discount
System.out.println("New subtotal: $" + String.format("%.2f", subtotal)); // output calculated price
} else {
System.out.println("Subtotal: $" + subtotal);
} // end else
System.out.println("Tax: $" + String.format("%.2f", tax) + " (" + taxprovters[location] + "%)");
System.out.println("Total: $" + String.format("%.2f",total));
System.out.println();
String yn = "p"; // picked random letter
do {
try {
System.out.print("Confirm? (y/N) ");
do { // clear scanner
yn = input.nextLine();
} while (yn.equals(""));
if (yn.toLowerCase().equals("n")) {
System.out.println("Transaction cancelled.");
System.out.println(); // just go back to main menu without touching cart
return 0;
} else if (yn.toLowerCase().equals("y")) {
for (int i = 0; i < names.length; i++) {
cart[i] = 0; // reset cart as order has been processed
}
revenue += subtotal; // transaction is non-returnable so we can safely add to revenue
System.out.println("Transaction complete.");
} else {
error(1);
yn = "p";
} // end else
} catch (Exception e) {
error(0);
} // end trycatch
} while (yn.equals("p"));
return 0;
} // end checkout
static String rngName() {
String[] storeNames = {"Osrus", "OS R'US", "A store"}; // various store names
return storeNames[(int)(Math.random() * 3)];
} // end rngname
static int displaySales() {
System.out.println("Revenue = $" + String.format("%.2f", revenue)); // format dollars like you would normally
System.out.println();
return 0;
}
static void error(int type) {
String[] errorarray = {"input", "option", "province/territory"}; // what things can be invalid
System.out.println("Error: Invalid " + errorarray[type] + ". Try again."); // lazy to type this out over and over again
if (type == 0) {
input.nextLine(); // clear scanner if input is invalid to be nice to more programs
}
System.out.println();
}
public static void main(String[] args) {
int menu = 1;
int option = 0;
while (true) {
while (menu == 0) { // main menu
try {
System.out.println();
System.out.println("Welcome to " + rngName());
System.out.println();
System.out.println("Who are you?");
System.out.println("1. Manager");
System.out.println("2. Customer");
System.out.println("3. I don't know and I want to get out"); // this is exit button
System.out.println();
System.out.print("Option #: ");
menu = input.nextInt();
if (menu > 3 || menu < 1) {
error(0);
menu = 0;
} else if (menu == 3) {
return; // leave main method
} // end if
} catch (Exception e) {
error(0);
}
} // end while
while (menu == 1) { // manager loop
System.out.println();
System.out.println("Manage " + rngName());
System.out.println();
System.out.println("1. Update inventory");
System.out.println("2. Display inventory");
System.out.println("3. Display revenue");
System.out.println("4. Return to main menu");
System.out.println();
do {
try {
System.out.print("Option #: ");
option = input.nextInt();
if (option < 1 || option > 4) {
error(1);
}
} catch (Exception e) {
error(1);
input.nextLine();
} // end catch
} while (option < 1 || option > 5);
if (option == 1) {
option = updateInv(); // add or modify stock/prices/names
} else if (option == 2) {
option = displayInv(); // just display special manager inventory view
} else if (option == 3) {
option = displaySales(); // prints revenue
} else if (option == 4) {
System.out.println(rngGreeting(1)); // goodbye manager
System.out.println();
menu = 0; // reset just in case things break
} // end if
option = 0;
} // end while
while (menu == 2) { // customer loop
System.out.println(); // looks nicer
System.out.println(rngGreeting(2)); // say hi nicely
System.out.println();
System.out.println("1. Product list");
System.out.println("2. Add items to cart");
System.out.println("3. Show cart");
System.out.println("4. Checkout");
System.out.println("5. Return to main menu");
System.out.println();
try {
System.out.print("Option #: ");
option = input.nextInt();
if (option < 1 || option > 5) {
error(1);
}
} catch (Exception e) {
error(0);
}
System.out.println();
if (option == 1) {
displayProd(); // customer only view of products probably is unnecessary but it was in my algorithm
} else if (option == 2) {
addProd(); // both display and add items to cart
} else if (option == 3) {
showCart();
} else if (option == 4) {
checkout(); // exit and pay
} else if (option == 5) {
System.out.println(rngGreeting(3)); // exit normally with nice message
menu = 0;
} // end if
} // end while
} // end big while
} // end main
} // end class
<file_sep>// <NAME>
// 12 September 2019
// Var3
import java.util.Scanner;
class Var3 {
public static void main(String[] args) {
System.out.println("Name:");
Scanner scan = new Scanner(System.in);
String name = scan.nextLine();
System.out.println("Age:");
int age = scan.nextInt();
System.out.println("Your name is " + name + " and you are " + age + " years old.");
}
}
<file_sep>// <NAME>
// 31 October 2019
// Triangle former
import java.util.Scanner;
class pMethod6 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Length 1: ");
int x = sc.nextInt();
System.out.print("Length 2: ");
int y = sc.nextInt();
System.out.print("Length 3: ");
int z = sc.nextInt();
calcTriangle(x, y, z);
}
public static void calcTriangle(int x, int y, int z) {
int largest = x;
int sum;
if (y > x && y > z) {
largest = y;
sum = x + z;
} else if (z > x) {
largest = z;
sum = x + y;
} else {
sum = y + z;
}
if (sum > largest) {
System.out.println("Triangle will be created.");
} else {
System.out.println("Triangle will not be created.");
}
}
}
<file_sep>// <NAME>
// 19 November 2019
// Write username array to file
import java.io.*;
import java.util.Scanner;
import java.util.Arrays;
class OutFile11 {
public static void main(String[] args) throws Exception {
Scanner input = new Scanner(System.in);
File file = new File("file11");
PrintWriter output = new PrintWriter(file);
String[] nameArray = new String[5];
for (int i = 0; i < nameArray.length; i++) {
System.out.print("Name: ");
nameArray[i] = input.nextLine();
}
output.println(Arrays.toString(nameArray));
output.close();
}
}
<file_sep>// <NAME>
// 4 October 2019
// Rock paper scissors
import java.util.Scanner;
import java.lang.Math;
class rps {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int userInput;
int compInput;
int score = 0;
String ynhandler;
System.out.println("Enter 1 for rock, 2 for paper, and 3 for scissors.");
while (true) {
System.out.print("Rock, paper, or scissors? (1/2/3) ");
userInput = input.nextInt();
compInput = (int) (Math.random() * 3 + 1);
// Tell user what they used
if (userInput == 1) {
System.out.println("You used rock!");
} else if (userInput == 2) {
System.out.println("You used paper!");
} else if (userInput == 3) {
System.out.println("You used scissor!");
} else {
System.out.println("You broke the game!");
break;
}
// Tell user what computer used
if (compInput == 1) {
System.out.println("Computer used rock!");
} else if (compInput == 2) {
System.out.println("Computer used paper!");
} else {
System.out.println("Computer used scissor!");
}
if (compInput == userInput) { // no need to check exact because ties
System.out.println("It doesn't affect foe PLAYER/COMPUTER... Tie!");
} else if (compInput - userInput == 1 || compInput - userInput == -2) { // this handles all computer win scenarios because math is cool
System.out.println("It's not very effective... PLAYER fainted! Player lost!");
} else {
System.out.println("It's super effective! COMPUTER fainted! You win!"); // because we don't need to handle dumb users
score += 1;
}
System.out.print("Play again? (Y/n)");
ynhandler = input.nextLine(); //there are two of these because Java doesn't understand things
ynhandler = input.nextLine();
if (ynhandler.equals("n")) {
System.out.println("You won " + score + " time(s).");
break;
}
}
}
}
<file_sep>// <NAME>
// 7 January 2020
// Thank you user!
// import things
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Scanner;
import java.io.PrintWriter;
import java.io.File;
public class ThankYou extends JFrame implements ActionListener {
JPanel[] panels = {new JPanel(), new JPanel()};
JButton ok = new JButton("OK");
JLabel[] labels = {new JLabel("Name ", JLabel.RIGHT), new JLabel("Email (optional) ", JLabel.RIGHT), new JLabel("Address (optional) ", JLabel.RIGHT), new JLabel("Message ", JLabel.RIGHT)};
JLabel[] blankLabels = {new JLabel(), new JLabel(), new JLabel(), new JLabel()};
JTextField[] tfs = {new JTextField(10), new JTextField(10), new JTextField(10), new JTextField(15)};
static File file = new File("hs.conf");
static PrintWriter output = new PrintWriter("hs.conf"); // crashses must be caught
public ThankYou() {
panels[1].setLayout(new GridLayout(5, 3));
panels[0].setLayout(new GridLayout(4, 3));
panels[0].add(labels[0]);
panels[0].add(tfs[0]);
panels[0].add(ok);
for (int i = 1; i < blankLabels.length; i++) {
panels[0].add(labels[i]);
panels[0].add(tfs[i]);
panels[0].add(blankLabels[i]);
}
ok.addActionListener(this);
for (JPanel panel : panels) {
add(panel);
}
setLayout(new FlowLayout());
setTitle("Tank you");
setSize(500, 500);
setVisible(true);
}
public void actionPerformed(ActionEvent event) {
if (event.getSource() == ok) {
if (! tfs[0].getText().equals("")) {
tfs[3].setText("Thank you, " + tfs[0].getText() + "!");
for (int i = 0; i < 3; i++) {
output.println(tfs[i].getText()); // resolve thing above first
}
output.println(); // need to resolve thing above first
}
}
}
public static void main(String[] args) {
ThankYou window = new ThankYou();
}
}
<file_sep>/*
* <NAME>
* 10 September 2019
* Hello world!
*/
class initial {
public static void main(String[] args) {
System.out.println("Hello world!");
}
}
// Comments are blue
// Reserved words are green
<file_sep>// <NAME>
// 19 November 2019
// Read and print file
import java.util.Scanner;
import java.util.Arrays;
import java.io.File;
class InFile10 {
public static void main(String[] args) throws Exception {
Scanner input = new Scanner(System.in);
File file = new File("file2");
Scanner finput = new Scanner(file);
int[] array = new int[10];
int sum = 0;
for (int i = 0; i < 10; i++) {
array[i] = finput.nextInt();
sum += array[i];
}
System.out.println(Arrays.toString(array));
System.out.println(sum);
finput.close();
}
}
<file_sep>// <NAME>
// 17 December 2019
// Fancy box thing
import javax.swing.*;
import java.awt.*;
public class AWTTest extends JFrame {
public static void main(String[] args) {
AWTTest window = new AWTTest();
}
public AWTTest() {
JPanel p1 = new JPanel();
JPanel p2 = new JPanel();
FlowLayout f1 = new FlowLayout();
JLabel l1 = new JLabel("Label1");
JTextField tf1 = new JTextField("TextField 1");
JButton[] buttons = {new JButton("Button 1"), new JButton("Button 2"), new JButton("Button 3")};
p1.add(l1);
p1.add(tf1);
for (JButton button : buttons) {
p2.add(button);
}
p1.setLayout(f1);
p2.setLayout(f1);
add(p1);
add(p2);
setLayout(f1);
setSize(320, 150);
setTitle("AWT Test");
setVisible(true);
}
}
<file_sep>// <NAME>
// 19 November 2019
// Write username array to file in alpha order
import java.io.*;
import java.util.Scanner;
import java.util.Arrays;
class OutFile12 {
public static void main(String[] args) throws Exception {
Scanner input = new Scanner(System.in);
File file = new File("file12");
PrintWriter output = new PrintWriter(file);
String[] nameArray = new String[5];
for (int i = 0; i < nameArray.length; i++) {
System.out.print("Name: ");
nameArray[i] = input.nextLine();
}
String tempswap;
for (int i = 0; i < nameArray.length; i++) {
for (int j = 1; j < nameArray.length - i; j++) {
if (nameArray[j - 1].compareTo(nameArray[j]) > 0) {
tempswap = nameArray[j - 1];
nameArray[j - 1] = nameArray[j];
nameArray[j] = tempswap;
}
}
}
output.println(Arrays.toString(nameArray));
output.close();
}
}
<file_sep>// <NAME>
// 31 October 2019
// Sorter
import java.util.Scanner;
class pMethod5 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Number 1: ");
int x = sc.nextInt();
System.out.print("Number 2: ");
int y = sc.nextInt();
System.out.print("Number 3: ");
int z = sc.nextInt();
sortNums(x, y, z);
}
public static void sortNums(int x, int y, int z) {
int smallest = x;
if (y < x && y < z) {
smallest = y;
} else if (z < x) {
smallest = z;
}
int largest = x;
if (y > x && y > z) {
largest = y;
} else if (z > x) {
largest = z;
}
System.out.println("Smallest = " + smallest);
System.out.println("Largest = " + largest);
}
}
<file_sep>// <NAME>
// 17 October 2019
// Sort user-input numbers
import java.util.Scanner;
import java.util.Arrays;
class Sort1 {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
int list[] = new int[5]; // setup array
for (int i = 0; i < 5; i++) { // setup standard input
System.out.print("Number: ");
list[i] = input.nextInt();
}
System.out.println("Numbers: "); // output unsorted array
System.out.println(Arrays.toString(list));
int tempswap = 0; // bubble sort template for future
for (int i = 0; i < list.length; i++) {
for (int j = 1; j < list.length - i; j++) {
if (list[j - 1] > list[j]) {
tempswap = list[j - 1];
list[j - 1] = list[j];
list[j] = tempswap;
}
}
}
System.out.println("Sorted Numbers: "); // output sorted array
System.out.println(Arrays.toString(list));
}
}
<file_sep>// <NAME>
// 19 November 2019
// write sorted numbers to array
import java.io.*;
import java.util.Scanner;
import java.util.Arrays;
class OutFile6 {
public static void main(String[] args) throws Exception {
Scanner input = new Scanner(System.in);
File file = new File("file6");
PrintWriter output = new PrintWriter(file);
int[] numArray = new int[10];
for (int i = 0; i < 10; i++) {
System.out.print("Number: ");
numArray[i] = input.nextInt();
}
for (int i = 0; i < 10; i++) {
if (numArray[i] > 50) {
output.println(numArray[i]);
}
}
output.close();
}
}
<file_sep>import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
import java.awt.event.*;//Adding the event since we will now be using an action listener
import java.io.*;
import java.util.*;
public class ChallengeTask extends JFrame implements ActionListener {
// Create some Panels
JPanel pan1;
JPanel pan2;
// Added some code
static final int MAX = 100;
String[] names; // arrays to store data that user enters
String[] emails;
String[] addresses;
int total; // number of records entered by the user
// declare GUI Components for panel 1
JLabel nameLabel;
JTextField nameField;
JLabel addressLabel;
JTextField addressField;
JLabel emailLabel;
JTextField emailField;
JButton addButton;
JLabel noMoreCanBeAddedLabel;
// declare GUI components for panel 2
JLabel nameTitle;
JLabel addressTitle;
JLabel emailTitle;
JLabel[] nameLabels;
JLabel[] addressLabels;
JLabel[] emailLabels;
// CONSTRUCTOR - Setup your GUI here
public ChallengeTask() {
setTitle("Challenge Task!"); // Create a window with a title
setSize(600, 450); // set the window size
// create relevant objects to store data
names = new String[MAX];
emails = new String[MAX];
addresses = new String[MAX];
// create components for pan1
pan1 = new JPanel();
pan1.setSize(800, 300);
nameLabel = new JLabel("Name: ", JLabel.RIGHT);
nameField = new JTextField(10);
addressLabel = new JLabel("Address: ", JLabel.RIGHT);
addressField = new JTextField(10);
emailLabel = new JLabel("Email: ", JLabel.RIGHT);
emailField = new JTextField(10);
addButton = new JButton("Add");
addButton.addActionListener(this); // Add an action listener to the
// button
noMoreCanBeAddedLabel = new JLabel("");
// Create some Layouts
BorderLayout frameLayout = new BorderLayout();
FlowLayout pan1Layout = new FlowLayout();
// Set the frame and both panel layouts
setLayout(frameLayout);// Setting layout for the whole frame
pan1.setLayout(pan1Layout);// Layout for Pan1
// Add all the components to panel 1 - this one is used for data entry
pan1.add(nameLabel);
pan1.add(nameField);
pan1.add(addressLabel);
pan1.add(addressField);
pan1.add(emailLabel);
pan1.add(emailField);
pan1.add(addButton);
pan1.add(noMoreCanBeAddedLabel);
// add the panels to the frame and display the window
add(BorderLayout.NORTH, pan1);
// create and initialize components for panel 2
GridLayout pan2Layout = new GridLayout(101, 3);
pan2 = new JPanel();
pan2.setLayout(pan2Layout);// Layout for Pan2
pan2.setAutoscrolls(true);
nameTitle = new JLabel("NAMES:", JLabel.CENTER);
addressTitle = new JLabel("ADDRESSES:", JLabel.CENTER);
emailTitle = new JLabel("EMAILS:", JLabel.CENTER);
// add title labels to panel 2
pan2.add(nameTitle);
pan2.add(addressTitle);
pan2.add(emailTitle);
// initialize all label arrays
nameLabels = new JLabel[100];
addressLabels = new JLabel[100];
emailLabels = new JLabel[100];
for (int i = 0; i < nameLabels.length; i++) {
nameLabels[i] = new JLabel("");
addressLabels[i] = new JLabel("");
emailLabels[i] = new JLabel("");
// add the labels to the panel
pan2.add(nameLabels[i]);
pan2.add(addressLabels[i]);
pan2.add(emailLabels[i]);
}
add(BorderLayout.CENTER, new JScrollPane(pan2)); // add a scroll bar to
// the panel
// load the data from file
loadInfoFromFile();
// add names to screen
displayLoadedData();
validate();
setVisible(true);
}
/**
* method to load data from file
*/
private void loadInfoFromFile() {
try {
File file = new File("personInfo.txt");
Scanner input = new Scanner(file);
while (input.hasNextLine()) {
String line = input.nextLine();
String[] values = line.split("-");
System.out.println(Arrays.toString(values));
names[total] = values[0];
addresses[total] = values[1];
emails[total] = values[2];
total++;
}
input.close();
} catch (IOException e) {
System.out.println("file does not exist!");
e.printStackTrace();
}
}
/**
* method to display data from the file
*/
private void displayLoadedData() {
for (int i = 0; i < total; i++) {
nameLabels[i].setText(names[i]);
nameLabels[i].setBorder(BorderFactory.createLineBorder(Color.BLACK));
addressLabels[i].setText(addresses[i]);
addressLabels[i].setBorder(BorderFactory.createLineBorder(Color.BLACK));
emailLabels[i].setText(emails[i]);
emailLabels[i].setBorder(BorderFactory.createLineBorder(Color.BLACK));
}
}
/**
* method to add new info to file
* @param name - name
* @param address - address
* @param email - email address
*/
private void addInfoToFile(String name, String address, String email) {
try {
FileWriter writer = new FileWriter("personInfo.txt", true);
PrintWriter output = new PrintWriter(writer);
output.println(name + "-" + address + "-" + email);
output.close();
} catch (IOException e) {
System.out.println("Error adding person to file...");
e.printStackTrace();
}
}
/**
* ACTION LISTENER - This method runs when an event occurs
* Code in here only runs when a user interacts with a component
* that has an action listener attached to it
*/
public void actionPerformed(ActionEvent event) {
String command = event.getActionCommand(); // find out the name of the
// component
// that was used
if (command.equals("Add")) { // if the OK button was pressed
System.out.println("add button pressed"); // display message in
// console(for testing)
if (total < 100) {
names[total] = nameField.getText();
addresses[total] = addressField.getText();
emails[total] = emailField.getText();
nameLabels[total].setText(names[total]);
addressLabels[total].setText(addresses[total]);
emailLabels[total].setText(emails[total]);
// add the info to the file
addInfoToFile(names[total], addresses[total], emails[total]);
total++;
} else {
noMoreCanBeAddedLabel.setText("No more entries can be added!");
}
} // no other conditions
}
/**
* Main method for launching the frame.
* @param args
*/
public static void main(String[] args) {
ChallengeTask frame1 = new ChallengeTask(); // Start the GUI
}
}
<file_sep>import javax.swing.*;//You need these two libraries to do the GUI stuff
import java.awt.*;
public class GUIExample1 extends JFrame //You are telling Java that this is a GUI application
{
// *** CREATE THE GUI COMPONENTS: Here we are only creating the following: Buttons, Labels, and Text field
JButton okButton = new JButton("OK"); //create a button
JLabel nameLabel = new JLabel("Name: ", JLabel.RIGHT); //create a label
JTextField nameField = new JTextField("Enter name here",20); //create a text field
// **********
// *** CONSTRUCTOR - Has the same name as the class and it runs once (when the program begins)
// This is were the GUI should be configured.
public GUIExample1() //This section adds the components on to the frame
{
setTitle("Hello World!"); //Set the window title or frame
setSize(640, 480); //Set the dimensions of
//Flow layout fills each row with the GUI components that you add and it will
//go to the next row when the previous row fills up
FlowLayout fl1 = new FlowLayout(); //used to organize window
setLayout(fl1); //organize the layout for the whole frame
add(okButton); // add the button to the frame
add(nameLabel); // add the label to the frame
add(nameField); // add the text field to the frame
setVisible(true); // display the gui on the screen
}
// **** This is the main method - It just starts the GUI
public static void main(String[] args) {
GUIExample1 frame1 = new GUIExample1(); //start the GUI!
}
}
<file_sep>// <NAME>
// 18 October 2019
// Completing array table
// | Number of items in array | Number of comparisions |
// | 5 | 10 |
// | 10 | 45 |
// | 20 | 190 |
// | n | (n^2 - n) / 2 |
<file_sep>// <NAME>
// 14 November 2019
// display random character in string
import java.util.Scanner;
class String7 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("String: ");
String string = input.nextLine();
// part a
System.out.println(string.replaceAll(" ", "").charAt((int) (Math.random() * string.length())));
// part b
String[] stringArray = string.split(" ");
System.out.println(stringArray[(int) (Math.random() * stringArray.length)]);
}
}
<file_sep>// <NAME>
// 17 September 2019
// Yell at user based on mark
import java.util.Scanner;
// Import module for interactivity
class Sel6 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Set up interactivity
System.out.print("Mark: ");
float mark = input.nextFloat();
// Grab mark
if (75 <= mark && mark <= 100) { // Make decision based on above input
System.out.println("Great");
} else if (mark >= 50 && mark <= 75) {
System.out.println("Pass");
} else if (0 <= mark && mark < 50) {
System.out.println("Fail");
} else {
System.out.println("Invalid");
}
}
}
<file_sep>// <NAME>
// 19 November 2019
// write marks to file
import java.io.*;
import java.util.Scanner;
import java.util.Arrays;
class OutFile8 {
public static void main(String[] args) throws Exception {
Scanner input = new Scanner(System.in);
File file = new File("file8");
PrintWriter output = new PrintWriter(file);
double temp = -1;
for (int i = 0; i < 10; i++) {
do {
try {
System.out.print("Mark: ");
temp = input.nextInt();
} catch (Exception e) {
System.out.println("Invalid input. Try again.");
temp = -1;
}
if (temp < 0 || temp > 100) {
System.out.println("Invalid input. Try again.");
}
} while (temp < 0 || temp > 100);
output.println(temp);
}
output.close();
}
}
<file_sep>// <NAME>
// 17 September 2019
// Ask for temperature and output based on response
import java.util.Scanner;
// Import module for interactivity
class Sel3 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Set up interactivity
System.out.print("Temperature: ");
float temp = input.nextFloat();
// Grab temperature
if (temp > 30) { // Make decision based on above input
System.out.println("hot");
} else if (temp >= 20) {
System.out.println("comfortable");
} else if (temp >= 10) {
System.out.println("cool");
} else {
System.out.println("cold");
}
}
}
<file_sep>// <NAME>
// 19 December 2019
// Hypotenuse calculator
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class HypotenuseCalculator extends JFrame implements ActionListener {
// make things
JPanel[] panels = {new JPanel(), new JPanel()};
JButton[] buttons = {new JButton("Submit")};
JLabel[] labels = {new JLabel("Side 1"), new JLabel("Side 2"), new JLabel("Hypotenuse")};
JTextField[] tfs = {new JTextField(), new JTextField(), new JTextField()};
public HypotenuseCalculator() {
// add things to panel
panels[0].setLayout(new GridLayout(3, 2));
for (int i = 0; i < 3; i++) {
panels[0].add(labels[i]);
panels[0].add(tfs[i]);
}
// add button to panel and manage button click
panels[1].add(buttons[0]);
buttons[0].addActionListener(this);
// add to main thing
for (JPanel panel : panels) {
add(panel);
}
// frame config
setTitle("Hypotenuse Calculator");
setLayout(new FlowLayout());
setSize(320, 200);
setVisible(true);
}
public void actionPerformed(ActionEvent event) {
if (event.getSource() == buttons[0]) {
double x = Double.parseDouble(tfs[0].getText());
double y = Double.parseDouble(tfs[1].getText());
double z = Math.sqrt(x*x + y*y);
tfs[2].setText("" + z);
}
return;
}
public static void main(String[] args) {
HypotenuseCalculator window = new HypotenuseCalculator();
}
}
| 50965012c500d00f668c9e83d9597647aa5b877e | [
"Java"
] | 59 | Java | potatoeggy/ICS3U | 6b9552880c121c6e5f4357ed76bda774c0ff05b0 | 981737d0ce580a5a0e34b864921751d69756ad0a |
refs/heads/master | <repo_name>CHDQ/netty<file_sep>/src/main/java/org/dq/netty/netty/udp/out/LogEventBroadCaster.java
package org.dq.netty.netty.udp.out;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.InetSocketAddress;
public class LogEventBroadCaster {
private final EventLoopGroup group;
private final Bootstrap bootstrap;
private final File file;
public LogEventBroadCaster(InetSocketAddress socketAddress, File file) {
group = new NioEventLoopGroup();
bootstrap = new Bootstrap();
bootstrap.group(group).channel(NioDatagramChannel.class).option(ChannelOption.SO_BROADCAST, true).handler(new LogEventEncoder(socketAddress));
this.file = file;
}
public void run() throws InterruptedException, IOException {
Channel channel = bootstrap.bind(0).sync().channel();
long pointer = 0;
while (true) {
long length = file.length();
if (length < pointer) {
pointer = length;
} else if (length > pointer) {
RandomAccessFile accessFile = new RandomAccessFile(file, "r");
accessFile.seek(pointer);//设置读取文件的位置
String line;
while ((line = accessFile.readLine()) != null) {
channel.writeAndFlush(new LogEvent(null, -1, file.getAbsolutePath(), line));//逐行写入日志
}
pointer = accessFile.getFilePointer();
accessFile.close();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.interrupted();
break;
}
}
}
}
public void stop() {
group.shutdownGracefully();
}
public static void main(String[] args) {
LogEventBroadCaster logEventBroadCaster = new LogEventBroadCaster(new InetSocketAddress("255.255.255.255", 8080), new File(LogEventBroadCaster.class.getClassLoader().getResource("").getPath() + "/log4j.properties"));
try {
logEventBroadCaster.run();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
logEventBroadCaster.stop();
}
}
}
<file_sep>/src/main/java/org/dq/netty/netty/chatroom/ChatServer.java
package org.dq.netty.netty.chatroom;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.CharsetUtil;
import io.netty.util.concurrent.ImmediateEventExecutor;
import org.dq.netty.netty.chatroom.frame.RouteMapping;
import org.dq.netty.netty.chatroom.frame.SpringConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import java.net.InetSocketAddress;
@Component
public class ChatServer {
private final static ChannelGroup CHANNELS = new DefaultChannelGroup(ImmediateEventExecutor.INSTANCE);
private final EventLoopGroup group = new NioEventLoopGroup();
private Channel channel;
@Autowired
private RouteMapping routeMapping;
@Autowired
private ChannelInitializer<Channel> initializer;
public ChannelFuture start(InetSocketAddress address) {
var bootStart = new ServerBootstrap();
bootStart.group(group).channel(NioServerSocketChannel.class).childHandler(initializer);
ChannelFuture future = bootStart.bind(address);
future.syncUninterruptibly();
channel = future.channel();//父channel
return future;
}
@Bean
public ChannelInitializer<Channel> createInitializer() {
return new ChatServerInitializer(CHANNELS, routeMapping);
}
public void destroy() {
if (channel != null) {
channel.close();
}
CHANNELS.close();
group.shutdownGracefully();
}
/**
* 广播消息
*
* @param msg
*/
public static void publishMsg(Object msg) {
ByteBuf buf = Unpooled.copiedBuffer(msg.toString(), CharsetUtil.UTF_8);
CHANNELS.writeAndFlush(new TextWebSocketFrame(buf));
}
public static void main(String[] args) {
//采用注解配置的方式
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
applicationContext.register(SpringConfig.class);
applicationContext.refresh();
//采用xml配置的方式
//ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");//spring托管
ChatServer chatServer = applicationContext.getBean(ChatServer.class);
ChannelFuture future = chatServer.start(new InetSocketAddress(8080));
//增加关闭钩子,在jvm关闭的时候调用
Runtime.getRuntime().addShutdownHook(new Thread(() -> chatServer.destroy()));
future.channel().closeFuture().syncUninterruptibly();
}
}
<file_sep>/src/main/java/org/dq/netty/netty/chatroom/TextWebSocketFrameHandler.java
package org.dq.netty.netty.chatroom;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.util.CharsetUtil;
import org.dq.netty.netty.chatroom.frame.RouteMapping;
public class TextWebSocketFrameHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
private final ChannelGroup channels;
private RouteMapping routeMapping;
public TextWebSocketFrameHandler(ChannelGroup channels,RouteMapping routeMapping) {
this.channels = channels;
this.routeMapping = routeMapping;
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
String str = msg.text();//修改请求过来的数据
routeMapping.makeRoute(str);//路由到对应的处理方法中
// ByteBuf buf = Unpooled.copiedBuffer(str, CharsetUtil.UTF_8);
// ChatServer.publishMsg(new TextWebSocketFrame(buf));//广播消息
// channels.writeAndFlush(new TextWebSocketFrame(buf));//增加引用计数,并将接收到的消息,写入到所有连接的客户端
}
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if (evt instanceof WebSocketServerProtocolHandler.HandshakeComplete) {// 握手成功
ctx.pipeline().remove(HttpRequestHandler.class);
channels.writeAndFlush(new TextWebSocketFrame("Client " + ctx.channel() + " joined"));
channels.add(ctx.channel());
} else {
super.userEventTriggered(ctx, evt);
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
super.exceptionCaught(ctx, cause);
}
}
<file_sep>/src/main/java/org/dq/netty/netty/chatroom/ChatServerInitializer.java
package org.dq.netty.netty.chatroom;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.group.ChannelGroup;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import org.dq.netty.netty.chatroom.frame.RouteMapping;
public class ChatServerInitializer extends ChannelInitializer<Channel> {
private final ChannelGroup channels;
private RouteMapping routeMapping;
public ChatServerInitializer(ChannelGroup channels, RouteMapping routeMapping) {
this.channels = channels;
this.routeMapping = routeMapping;
}
@Override
protected void initChannel(Channel ch) throws Exception {
var pipeline = ch.pipeline();
pipeline.addLast(new HttpServerCodec());//将字节解码为 HttpRequest、HttpContent 和 LastHttpContent。并将 HttpRequest、 HttpContent 和 LastHttpContent 编码为字节
pipeline.addLast(new ChunkedWriteHandler());//写入一个文件的内容
pipeline.addLast(new HttpObjectAggregator(64 * 1024));//将一个 HttpMessage 和跟随它的多个 HttpContent 聚合为单个 FullHttpRequest 或者 FullHttpResponse(取决于它是被用来处理请求还是响应)。安装了这个之后,ChannelPipeline 中的下一个 ChannelHandler 将只会收到完整的 HTTP 请求或响应
pipeline.addLast(new HttpRequestHandler("/ws"));//处理 FullHttpRequest(那些不发送到/ws URI 的请求)
pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));//按照 WebSocket 规范的要求,处理 WebSocket 升级握手、PingWebSocketFrame 、 PongWebSocketFrame 和CloseWebSocketFrame
pipeline.addLast(new TextWebSocketFrameHandler(channels, routeMapping));//处理 TextWebSocketFrame 和握手完成事件
}
}
<file_sep>/src/test/java/org/dq/netty/AbsIntegerEncoderTest.java
package org.dq.netty;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.embedded.EmbeddedChannel;
import org.junit.Test;
import static org.junit.Assert.*;
public class AbsIntegerEncoderTest {
@Test
public void testEncoded() {
ByteBuf byteBuf = Unpooled.buffer();
for (var i = 0; i < 10; i++) {
byteBuf.writeInt(i);
}
EmbeddedChannel embeddedChannel = new EmbeddedChannel(new AbsIntegerEncoder());
assertTrue(embeddedChannel.writeOutbound(byteBuf.retain()));
assertTrue(embeddedChannel.finish());
for (var i = 0; i < 10; i++) {
assertEquals(i,(Object) embeddedChannel.readOutbound());
}
}
}
<file_sep>/README.md
# _netty 实战关键笔记_


## 文档<https://netty.io/4.1/api/index.html>
## 1. **_资源管理_**
- 章节 6.1
- 内存泄漏检测参数配置
> java -Dio.netty.leakDetectionLevel=ADVANCED 可以检测是否存在 ByteBuf 内存泄漏
- 泄漏检测级别
| 级别 | 描述 |
| :------: | :---------------------------------------------------------------------------------------------------------: |
| DISABLED | 禁用泄漏检测。只有在详尽的测试之后才应设置为这个值 |
| SIMPLE | 使用 1%的默认采样率检测并报告任何发现的泄露。这是默认级别,适合绝大部分的情况 |
| ADVANCED | 使用默认的采样率,报告所发现的任何的泄露以及对应的消息被访问的位置 |
| PARANOID | 类似于 ADVANCED,但是其将会对每次(对消息的)访问都进行采样。这对性能将会有很大的影响,应该只在调试阶段使用 |
## 2. **_pipeline_**
- 章节 6.2
- pipeline 的执行过程
> 在 ChannelPipeline 传播事件时,它会测试 ChannelPipeline 中的下一个 ChannelHandler 的类型是否和事件的运动方向相匹配。如果不匹配, ChannelPipeline 将跳过该
> ChannelHandler 并前进到下一个,直到它找到和该事件所期望的方向相匹配的为止。
- ChannelHandler 的用于修改 ChannelPipeline 的方法
| 名称 | 描述 |
| :---------------------------------------------: | :--------------------------------------------------------------------: |
| AddFirst<br/>addBefore<br/>addAfter<br/>addLast | 将一个 ChannelHandler 添加到 ChannelPipeline 中 |
| remove | 将一个 ChannelHandler 从 Channe****lPipeline 中移除 |
| replace | 将 ChannelPipeline 中的一个 ChannelHandler 替换为另一个 ChannelHandler |
- 总结
1. ChannelPipeline 保存了与 Channel 相关联的 ChannelHandler
2. ChannelPipeline 可以根据需要,通过添加或者删除 ChannelHandler 来动态地修改
3. ChannelPipeline 有着丰富的 API 用以被调用,以响应入站和出站事件
## 3. **_ChannelHandlerContext_**
- 章节6.3
- ChannelHandlerContext 代表了 ChannelHandler 和 ChannelPipeline 之间的关联,每当有 ChannelHandler 添加到 ChannelPipeline 中时,都会创建 ChannelHandlerContext。 ChannelHandlerContext 的主要功能是管理它所关联的 ChannelHandler 和在同一个 ChannelPipeline 中的其他 ChannelHandler 之间的交互
## 4. **_EventLoop_**
- 尽可能地重用 EventLoop,以减少线程创建所带来的开销
## 5. **_编码器解码器_**
- 146页
>引用计数对于编码器和解码器来说,其过程也是相当的简单:一旦消息被编码或者解码,它就会被 ReferenceCountUtil.release(message)调用自动释放。如果你需要保留引用以便稍后使用,那么你可以调用 ReferenceCountUtil.retain(message)方法。这将会增加该引用计数,从而防止该消息被释放。
- 如果使用 ByteToMessageDecoder 不会引入太多的复杂性,那么请使用它;否则,请使用 ReplayingDecoder
## 6. **_channel_**
- 长连接的时候,在pipeline中的只要是连接没有断,处理长连接的数据的channel都是一个实例
<file_sep>/src/test/java/org/dq/netty/FixedLengthFrameDecoderTest.java
package org.dq.netty;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.embedded.EmbeddedChannel;
import org.junit.Test;
import static org.junit.Assert.*;
public class FixedLengthFrameDecoderTest {
@Test
public void testFramesDecoded() {
var byteBuf = Unpooled.buffer();
for (var i = 0; i < 9; i++) {
byteBuf.writeByte(i);
}
var input = byteBuf.duplicate();
var embeddedChannel = new EmbeddedChannel(new FixedLengthFrameDecoder(3));//可以用来测试ChannelHandler
// assertTrue(embeddedChannel.writeInbound(input.retain()));//该断言通过
assertTrue(embeddedChannel.writeInbound(input.readBytes(2)));//该顺序下,断言不通过,因为readInbound获取不到内容(只有多于3个字节的时候,才会产生输出)
assertTrue(embeddedChannel.writeInbound(input.readBytes(7)));
assertTrue(embeddedChannel.finish());
var read = (ByteBuf) embeddedChannel.readInbound();
assertEquals(byteBuf.readBytes(3), read);
read.release();
read = embeddedChannel.readInbound();
assertEquals(byteBuf.readBytes(3), read);
read.release();
read = embeddedChannel.readInbound();
assertEquals(byteBuf.readBytes(3), read);
read.release();
assertTrue(embeddedChannel.readInbound() == null);
byteBuf.release();
}
}
<file_sep>/src/main/java/org/dq/netty/netty/chatroom/frame/SpringConfig.java
package org.dq.netty.netty.chatroom.frame;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
/**
* 开启注解扫描
*/
@Configuration
@ComponentScan("org.dq.netty.netty.chatroom")
public class SpringConfig {
}
<file_sep>/src/main/java/org/dq/netty/netty/udp/out/LogEventEncoder.java
package org.dq.netty.netty.udp.out;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.socket.DatagramPacket;
import io.netty.handler.codec.MessageToMessageEncoder;
import io.netty.util.CharsetUtil;
import java.net.InetSocketAddress;
import java.util.List;
public class LogEventEncoder extends MessageToMessageEncoder<LogEvent> {
private final InetSocketAddress socketAddress;
public LogEventEncoder(InetSocketAddress socketAddress) {
this.socketAddress = socketAddress;
}
@Override
protected void encode(ChannelHandlerContext ctx, LogEvent logEvent, List<Object> out) throws Exception {
byte[] logFile = logEvent.getLogFile().getBytes(CharsetUtil.UTF_8);
byte[] msg = logEvent.getMsg().getBytes(CharsetUtil.UTF_8);
ByteBuf buf = ctx.alloc().buffer(logFile.length + msg.length + 1);//获取byteBufHolder,通过ByteBuf池分配ByteBuf的空间
buf.writeBytes(logFile);
buf.writeByte(LogEvent.SEPARATOR);
buf.writeBytes(msg);
out.add(new DatagramPacket(buf, socketAddress));
}
}
<file_sep>/src/main/java/org/dq/netty/aio/TimeServer.java
package org.dq.netty.aio;
/**
* 事件驱动aio实现
*/
public class TimeServer {
public static void main(String[] args) {
int port = 8080;
if (args != null && args.length > 0) {
try {
port = Integer.valueOf(args[0]);
} catch (NumberFormatException e) {
}
}
AsyncTimeServerHandler timeServer = new AsyncTimeServerHandler(port);
new Thread(timeServer, "org.dq.netty.aio.TimeServer-001").start();
}
}
| 56d361a91629d12bb7cb70c13ac21d56e81fdf0f | [
"Markdown",
"Java"
] | 10 | Java | CHDQ/netty | ee7793d48bf224e059636cc9729510255eec7be9 | 040cbeb006723fc71675e2e285ee48e6fbb16dd3 |
refs/heads/master | <file_sep>import express from 'express'
const router = express.Router()
import * as Errors from '../helpers/errors'
import { validateTask } from '../middleware/validateTask'
import Logger from '../helpers/logger'
import {
taskComplete,
taskCreate,
taskDelete,
taskEdit,
taskGetMany,
taskGetOne,
} from '../controllers/taskController'
// get all
router.get('/users/:uid/tasks', async (req, res) => {
taskGetMany({ user: req.params.uid })
.then(tasks => res.send(tasks))
.catch(err => Errors.internalError(res, err.message))
})
router.get('/idinv/:idinv/tasks', async (req, res) => {
taskGetMany({ idinv: req.params.idinv })
.then(tasks => res.send(tasks))
.catch(err => Errors.internalError(res, err.message))
})
router.get('/patients/:pid/tasks', async (req, res) => {
taskGetMany({ patient: req.params.pid })
.then(tasks => res.send(tasks))
.catch(err => Errors.internalError(res, err.message))
})
// get by id
router.get('/users/:uid/tasks/:tid', async (req, res) => {
taskGetOne({ user: req.params.uid, _id: req.params.tid })
.then(tasks => {
if (!tasks) return Errors.notFound(res)
res.send(tasks)
})
.catch(err => {
Logger.error(err.message)
Errors.incorrectInput(res, err.reason.message)
})
})
router.get('/idinv/:idinv/tasks/:tid', async (req, res) => {
taskGetOne({ idinv: req.params.idinv, _id: req.params.tid })
.then(tasks => {
if (!tasks) return Errors.notFound(res)
res.send(tasks)
})
.catch(err => {
Logger.error(err.message)
Errors.incorrectInput(res, err.reason.message)
})
})
router.get('/patients/:pid/tasks/:tid', async (req, res) => {
taskGetOne({ patient: req.params.pid, _id: req.params.tid })
.then(tasks => {
if (!tasks) return Errors.notFound(res)
res.send(tasks)
})
.catch(err => {
Logger.error(err.message)
Errors.incorrectInput(res, err.reason.message)
})
})
// post
router.post('/users/:uid/tasks', validateTask, async (req, res) => {
taskCreate({ ...req.body, user: req.params.uid })
.then(task => res.send(task))
.catch(err => {
Logger.error(err.message)
if (err.code === 11000) return res.status(208).send()
Errors.incorrectInput(res)
})
})
router.post('/idinv/:idinv/tasks', validateTask, async (req, res) => {
taskCreate({ ...req.body, idinv: req.params.idinv })
.then(task => res.send(task))
.catch(err => {
Logger.error(err.message)
if (err.code === 11000) return res.status(208).send()
Errors.incorrectInput(res)
})
})
router.post('/patients/:pid/tasks', validateTask, async (req, res) => {
taskCreate({ ...req.body, patient: req.params.pid })
.then(task => res.send(task))
.catch(err => {
Logger.error(err.message)
if (err.code === 11000) return res.status(208).send()
Errors.incorrectInput(res)
})
})
router.post('/users/:uid/tasks/:tid/complete', async (req, res) => {
taskComplete(req.params.tid)
.then(task => res.status(201).send(task))
.catch(err => {
Logger.error(err.message)
Errors.incorrectInput(res)
})
})
// put
router.put('/users/:uid/tasks/:tid', validateTask, async (req, res) => {
taskEdit(req.params.tid, { ...req.body })
.then(task => res.status(201).send(task))
.catch(err => {
Logger.error(err.message)
Errors.incorrectInput(res)
})
})
router.put('/idinv/:idinv/tasks/:tid', validateTask, async (req, res) => {
taskEdit(req.params.tid, { ...req.body })
.then(task => res.status(201).send(task))
.catch(err => {
Logger.error(err.message)
Errors.incorrectInput(res)
})
})
router.put('/patients/:pid/tasks/:tid', validateTask, async (req, res) => {
taskEdit(req.params.tid, { ...req.body })
.then(task => res.status(201).send(task))
.catch(err => {
Logger.error(err.message)
Errors.incorrectInput(res)
})
})
// delete
router.delete('/users/:uid/tasks/:tid', async (req, res) => {
taskDelete(req.params.tid)
.then(() => res.status(204).send())
.catch(err => {
Errors.internalError(res, err)
})
})
router.delete('/idinv/:idinv/tasks/:tid', async (req, res) => {
taskDelete(req.params.tid)
.then(() => res.status(204).send())
.catch(err => {
Errors.internalError(res, err)
})
})
router.delete('/patients/:pid/tasks/:tid', async (req, res) => {
taskDelete(req.params.tid)
.then(() => res.status(204).send())
.catch(err => {
Errors.internalError(res, err)
})
})
export { router as tasksRouter }
<file_sep>import { Schema, model, Document } from 'mongoose'
const idinvSchema = new Schema({
_id: { type: String },
mon_type: { type: String, required: true },
mon_state: { type: String, required: true },
mon_number: { type: String, required: true },
mon_install: { type: String, required: true },
})
export interface IIdinv extends Document {
_id: string
mon_type: number
mon_state: number
mon_number: number
mon_install: number
}
const Idinv = model<IIdinv>('Idinv', idinvSchema)
export { Idinv }
<file_sep>import { timestamp } from '../helpers/timestamp'
import { Schema, model, Document, ObjectId } from 'mongoose'
const userSchema = new Schema(
{
username: { type: String, required: true },
sub: { type: String, required: true },
idinv: { type: String, required: false, ref: 'Idinv' },
patient: { type: String, ref: 'Patient' },
created_at: { type: Number },
updated_at: { type: Number },
},
{
timestamps: {
currentTime: () => timestamp(),
createdAt: 'created_at',
updatedAt: 'updated_at',
},
},
)
export interface IUser extends Document {
username: string
sub: string
idinv: string
patient: string
created_at: number
updated_at: number
}
const User = model<IUser>('User', userSchema)
export { User }
<file_sep>import { Task, ITask } from '../models/task'
interface ITaskFilter {
_id?: string
idinv?: string
user?: string
patient?: string
}
export const taskGetMany = async (filter: ITaskFilter): Promise<[ITask]> => {
return new Promise((resolve, reject) => {
Task.find(filter, (err: Error, task: [ITask]) => {
if (err) reject(err.message)
resolve(task)
})
})
}
export const taskGetOne = async (filter: ITaskFilter): Promise<ITask> => {
return new Promise((resolve, reject) => {
Task.findOne(filter, (err: Error, task: ITask) => {
if (err) reject(err.message)
resolve(task)
})
})
}
export const taskCreate = async (task: ITask): Promise<ITask> => {
return new Promise((resolve, reject) => {
const record = new Task({ ...task })
record.save((err, record: ITask) => {
if (err) reject(err)
resolve(record)
})
})
}
export const taskEdit = async (id: string, task: ITask): Promise<ITask> => {
return new Promise((resolve, reject) => {
Task.findByIdAndUpdate(id, { ...task }, { new: true }, (err: Error, task: ITask | null) => {
if (err || !task) return reject(err || { code: 404 })
resolve(task)
})
})
}
export const taskComplete = async (id: string): Promise<ITask> => {
return new Promise((resolve, reject) => {
Task.findByIdAndUpdate(id, { completed: true }, (err: Error, task: ITask | null) => {
if (err || !task) return reject(err || { code: 404 })
resolve(task)
})
})
}
export const taskDelete = async (id: string): Promise<void> => {
return new Promise((resolve, reject) => {
Task.findOneAndDelete({ _id: id }, null, (err, task) => {
if (err) return reject(err)
resolve()
})
})
}
<file_sep>import mongoose from 'mongoose'
export default (value: string): boolean => {
return mongoose.Types.ObjectId.isValid(value)
}
<file_sep>import { Authorize, Request } from './functions'
import { Types } from 'mongoose'
import { timestamp } from '../src/helpers/timestamp'
let token = ''
let _id = ''
let idinv = ''
let patient = ''
let task_id = ''
let test_task: any
describe('tasks by user', () => {
test('authorize', async () => {
const res = await Authorize()
token = res.access_token
})
test('login', async () => {
const user = await Request(token, 'login', 'POST')
expect(user).toHaveProperty('_id')
expect(user).toHaveProperty('idinv')
expect(user).toHaveProperty('patient')
_id = user._id
idinv = user.idinv
patient = user.patient
})
test('get all activities', async () => {
const activities = await Request(token, `idinv/${idinv}/tasks`, 'GET')
expect(Array.isArray(activities)).toBe(true)
if (activities.length > 0) {
expect(activities[0]).toHaveProperty('_id')
}
})
test('create tasks by user', async () => {
task_id = new Types.ObjectId().toString()
test_task = {
_id: task_id,
activity_type: 'Stairs',
time: timestamp() - 300,
patient: patient,
idinv: idinv,
user: _id,
comment: 'tasks created by test',
}
const task = await Request(token, `idinv/${idinv}/tasks/`, 'POST', test_task)
expect(task).toHaveProperty('_id', task_id)
})
test('get created tasks', async () => {
const task = await Request(token, `idinv/${idinv}/tasks/${task_id}`, 'GET')
expect(task).toHaveProperty('_id', task_id)
expect(task).toHaveProperty('comment', test_task.comment)
})
test('edit created tasks', async () => {
test_task.comment = 'edited test tasks'
test_task.activity_type = 'Walking'
const task = await Request(token, `idinv/${idinv}/tasks/${task_id}`, 'PUT', test_task)
expect(task).toHaveProperty('_id', task_id)
expect(task).toHaveProperty('comment', test_task.comment)
})
test('delete created tasks', async () => {
const task = await Request(token, `idinv/${idinv}/tasks/${task_id}`, 'DELETE')
expect(task).toBeTruthy()
})
})
<file_sep>import express from 'express'
const router = express.Router()
import { checkAuth } from '../middleware/checkAuth'
import { userEdit, userGetAll, userGetById, userLogin } from '../controllers/userController'
router.get('/users/', checkAuth, userGetAll)
router.get('/users/:id', checkAuth, userGetById)
router.put('/users/:id', checkAuth, userEdit)
router.post('/login', checkAuth, userLogin)
export { router as usersRouter }
<file_sep>import express from 'express'
const router = express.Router()
import * as Errors from '../helpers/errors'
import { saveFiles } from '../middleware/saveFiles'
import { validateActivity, validateActivityUpdate } from '../middleware/validateActivity'
import verifyObjectId from '../helpers/verifyObjectId'
import {
activityGetOne,
activityGetMany,
activityCreate,
activityEdit,
activityDelete,
activityHistoryGetMany,
activityHistoryGetOne,
activityUpdatesGetMany,
activityUpdatesCreate,
activityUpdatesEdit,
activityUpdatesDelete,
} from '../controllers/activityController'
// get by user
router.get('/users/:uid/activity', async (req, res) => {
if (!verifyObjectId(req.params.uid)) return Errors.incorrectInput(res)
activityGetMany({ user: req.params.uid })
.then(activity => res.send(activity))
.catch(err => Errors.internalError(res, err))
})
router.get('/users/:uid/activity/:aid/history', async (req, res) => {
if (!verifyObjectId(req.params.uid)) return Errors.incorrectInput(res)
activityHistoryGetMany({ user: req.params.uid, original: req.params.aid })
.then(activity => res.send(activity))
.catch(err => Errors.internalError(res, err))
})
router.get('/users/:uid/activity/:aid/updates', async (req, res) => {
if (!verifyObjectId(req.params.uid)) return Errors.incorrectInput(res)
activityUpdatesGetMany({ user: req.params.uid, original: req.params.aid })
.then(activity => res.send(activity))
.catch(err => Errors.internalError(res, err))
})
router.get('/users/:uid/activity/:aid', async (req, res) => {
activityGetOne({ user: req.params.uid, _id: req.params.aid })
.then(activity => res.send(activity))
.catch(err => Errors.internalError(res))
})
// get by patient
router.get('/patients/:pid/activity/:aid/history', async (req, res) => {
activityHistoryGetMany({ patient: req.params.pid, original: req.params.aid })
.then(activity => res.send(activity))
.catch(err => Errors.internalError(res, err))
})
router.get('/patients/:pid/activity/:aid/updates', async (req, res) => {
activityUpdatesGetMany({ patient: req.params.pid, original: req.params.aid })
.then(activity => res.send(activity))
.catch(err => Errors.internalError(res, err))
})
router.get('/patients/:pid/activity', async (req, res) => {
activityGetMany({ patient: req.params.pid })
.then(activity => res.send(activity))
.catch(err => Errors.internalError(res, err))
})
router.get('/patients/:pid/activity/:aid', async (req, res) => {
if (!verifyObjectId(req.params.aid)) return Errors.incorrectInput(res)
activityGetOne({ patient: req.params.pid, _id: req.params.aid })
.then(activity => res.send(activity))
.catch(err => Errors.internalError(res, err))
})
// get by idinv
router.get('/idinv/:idinv/activity', async (req, res) => {
activityGetMany({ idinv: req.params.idinv })
.then(activity => {
res.send(activity)
})
.catch(err => Errors.internalError(res))
})
router.get('/idinv/:idinv/activity/:aid/history', async (req, res) => {
activityHistoryGetOne({ idinv: req.params.idinv, original: req.params.aid })
.then(activity => res.send(activity))
.catch(err => Errors.internalError(res, err))
})
router.get('/idinv/:idinv/activity/:aid/updates', async (req, res) => {
activityUpdatesGetMany({ idinv: req.params.idinv, original: req.params.aid })
.then(activity => res.send(activity))
.catch(err => Errors.internalError(res, err))
})
router.get('/idinv/:idinv/activity/:aid', async (req, res) => {
activityGetOne({ idinv: req.params.idinv, _id: req.params.aid })
.then(activity => res.send(activity))
.catch(err => Errors.internalError(err))
})
// post
router.post('/users/:uid/activity', saveFiles, validateActivity, (req, res) => {
activityCreate({ ...req.body, user: req.params.uid })
.then(activity => res.send(activity))
.catch(err => {
if (err.code === 11000) return res.status(208).send()
Errors.internalError(res, err.message)
})
})
router.post('/idinv/:idinv/activity', saveFiles, validateActivity, (req, res) => {
activityCreate({ ...req.body, idinv: req.params.idinv })
.then(activity => res.send(activity))
.catch(err => {
if (err.code === 11000) return res.status(208).send()
Errors.internalError(res, err.message)
})
})
router.post('/patients/:pid/activity', saveFiles, validateActivity, (req, res) => {
activityCreate({ ...req.body, patient: req.params.pid })
.then(activity => res.send(activity))
.catch(err => {
if (err.code === 11000) return res.status(208).send()
Errors.internalError(res, err.message)
})
})
router.post('/users/:uid/activity/:aid/updates', validateActivityUpdate, (req, res) => {
activityUpdatesCreate(
req.body._id,
{ ...req.body, original: req.params.aid },
req.body.updates_by,
)
.then(activity => res.send(activity))
.catch(err => {
if (err.code === 11000) return res.status(208).send()
Errors.internalError(res, err.message)
})
})
router.post('/idinv/:idinv/activity/:aid/updates', validateActivityUpdate, (req, res) => {
activityUpdatesCreate(
req.body._id,
{ ...req.body, original: req.params.aid },
req.body.updates_by,
)
.then(activity => res.send(activity))
.catch(err => {
if (err.code === 11000) return res.status(208).send()
Errors.internalError(res, err.message)
})
})
router.post('/patients/:pid/activity/:aid/updates', validateActivityUpdate, (req, res) => {
activityUpdatesCreate(
req.body._id,
{ ...req.body, original: req.params.aid },
req.body.updates_by,
)
.then(activity => res.send(activity))
.catch(err => {
if (err.code === 11000) return res.status(208).send()
Errors.internalError(res, err.message)
})
})
// put
router.put('/users/:uid/activity/:aid/updates/:auid', validateActivityUpdate, (req, res) => {
activityUpdatesEdit(req.params.auid, {
...req.body,
original: req.params.aid,
user: req.params.uid,
})
.then(activity => res.send(activity))
.catch(err => {
if (err.code === 404) return Errors.notFound(res)
Errors.internalError(res, err.message)
})
})
router.put(
'/idinv/:idinv/activity/:aid/updates/:auid',
validateActivityUpdate,
async (req, res) => {
activityUpdatesEdit(req.params.auid, {
...req.body,
original: req.params.aid,
idinv: req.params.idinv,
})
.then(activity => res.send(activity))
.catch(err => {
Errors.internalError(res, err.message)
})
},
)
router.put(
'/patients/:pid/activity/:aid/updates/:auid',
validateActivityUpdate,
async (req, res) => {
activityUpdatesEdit(req.params.auid, {
...req.body,
original: req.params.aid,
patient: req.params.pid,
})
.then(activity => res.send(activity))
.catch(err => {
Errors.internalError(res, err.message)
})
},
)
router.put('/users/:uid/activity/:aid', saveFiles, validateActivity, (req, res) => {
activityEdit(req.params.aid, { ...req.body, user: req.params.uid })
.then(activity => res.send(activity))
.catch(err => {
if (err.code === 404) return Errors.notFound(res)
Errors.internalError(res, err.message)
})
})
router.put('/idinv/:idinv/activity/:aid', saveFiles, validateActivity, async (req, res) => {
activityEdit(req.params.aid, { ...req.body, idinv: req.params.idinv })
.then(activity => res.send(activity))
.catch(err => {
Errors.internalError(res, err.message)
})
})
router.put('/patients/:pid/activity/:aid', saveFiles, validateActivity, async (req, res) => {
activityEdit(req.params.aid, { ...req.body, patient: req.params.pid })
.then(activity => res.send(activity))
.catch(err => {
Errors.internalError(res, err.message)
})
})
// delete
router.delete('/users/:uid/activity/:aid/updates/:auid', async (req, res) => {
activityUpdatesDelete(req.params.auid)
.then(() => res.status(204).send())
.catch(err => Errors.internalError(res, err))
})
router.delete('/idinv/:idinv/activity/:aid/updates/:auid', async (req, res) => {
activityUpdatesDelete(req.params.auid)
.then(() => res.status(204).send())
.catch(err => Errors.internalError(res, err))
})
router.delete('/patients/:pid/activity/:aid/updates/:auid', async (req, res) => {
activityUpdatesDelete(req.params.auid)
.then(() => res.status(204).send())
.catch(err => Errors.internalError(res, err))
})
router.delete('/users/:uid/activity/:aid', async (req, res) => {
activityDelete(req.params.aid)
.then(() => res.status(204).send())
.catch(err => Errors.internalError(res, err))
})
router.delete('/idinv/:idinv/activity/:aid', async (req, res) => {
activityDelete(req.params.aid)
.then(() => res.status(204).send())
.catch(err => Errors.internalError(res, err))
})
router.delete('/patients/:pid/activity/:aid', async (req, res) => {
activityDelete(req.params.aid)
.then(() => res.status(204).send())
.catch(err => Errors.internalError(res, err))
})
export { router as activityRouter }
<file_sep>import * as Errors from '../helpers/errors'
import Logger from '../helpers/logger'
import { Request, Response, NextFunction } from 'express'
export const validateTask = (req: Request, res: Response, next: NextFunction) => {
if (req.body.activity_type && req.body.time) {
next()
} else {
Logger.info(`task validation failed: ${JSON.stringify(req.body)}`)
Errors.incompleteInput(res)
}
}
<file_sep>import { timestamp } from '../helpers/timestamp'
import { Schema, model, Document, ObjectId, Mixed } from 'mongoose'
export interface IActivityUpdate {
doctor: ObjectId
activity_type: String
time_started: Number
time_ended: Number
utc_offset: Number
idinv: ObjectId
comment: String
data: Mixed
task: ObjectId
deleted: Boolean
}
const activitySchema = new Schema(
{
activity_type: { type: String, required: true },
time_started: { type: Number, required: true },
time_ended: { type: Number },
utc_offset: { type: Number },
user: { type: Schema.Types.ObjectId, ref: 'User' },
patient: { type: String, ref: 'Patient' },
idinv: { type: String, ref: 'Idinv' },
comment: { type: String },
data: { type: Schema.Types.Mixed, default: {} },
task: { type: Schema.Types.ObjectId, ref: 'Task' },
created_at: { type: Number },
updated_at: { type: Number },
},
{
timestamps: {
currentTime: () => timestamp(),
createdAt: 'created_at',
updatedAt: 'updated_at',
},
},
)
export interface IActivity extends Document {
activity_type: string
time_started: number
time_ended: number
utc_offset: number
user: ObjectId
patient: ObjectId
idinv: ObjectId
comment: string
data: Mixed
task: ObjectId
updates: Mixed
}
const Activity = model<IActivity>('Activity', activitySchema)
export interface IActivityHistory extends IActivity {
original: ObjectId
action: 'created' | 'updated' | 'deleted'
}
const activityHistorySchema = new Schema(
{
original: { type: Schema.Types.ObjectId, required: true, ref: 'Activity' },
action: { type: String, required: true },
activity_type: { type: String },
time_started: { type: Number },
time_ended: { type: Number },
utc_offset: { type: Number },
user: { type: Schema.Types.ObjectId, ref: 'User' },
patient: { type: String, ref: 'Patient' },
idinv: { type: String, ref: 'Idinv' },
comment: { type: String },
data: { type: Schema.Types.Mixed, default: {} },
task: { type: Schema.Types.ObjectId, ref: 'Task' },
created_at: { type: Number },
},
{
timestamps: {
currentTime: () => timestamp(),
createdAt: 'created_at',
updatedAt: false,
},
},
)
const ActivityHistory = model<IActivityHistory>('ActivityHistory', activityHistorySchema)
export interface IActivityUpdates extends IActivity {
original: ObjectId
updated_by: ObjectId
}
const activityUpdatesSchema = new Schema(
{
original: { type: Schema.Types.ObjectId, required: true, ref: 'Activity' },
updated_by: { type: Schema.Types.ObjectId, required: true, ref: 'User' },
activity_type: { type: String },
time_started: { type: Number },
time_ended: { type: Number },
utc_offset: { type: Number },
user: { type: Schema.Types.ObjectId, ref: 'User' },
patient: { type: String, ref: 'Patient' },
idinv: { type: String, ref: 'Idinv' },
comment: { type: String },
data: { type: Schema.Types.Mixed, default: {} },
task: { type: Schema.Types.ObjectId, ref: 'Task' },
created_at: { type: Number },
},
{
timestamps: {
currentTime: () => timestamp(),
createdAt: 'created_at',
updatedAt: 'updated_at',
},
},
)
const ActivityUpdates = model<IActivityUpdates>('ActivityUpdates', activityUpdatesSchema)
export { Activity, ActivityHistory, ActivityUpdates }
<file_sep>module.exports = {
db_url: 'mongodb://localhost:27017/cjournal',
log_level: 'debug',
}
<file_sep>import express from 'express'
const router = express.Router()
import * as Errors from '../helpers/errors'
import { patientEdit, patientGetMany, patientGetOne } from '../controllers/patientController'
router.get('/patients/', (req, res) => {
patientGetMany({})
.then(patient => res.send(patient))
.catch(err => Errors.internalError(res, err))
})
router.get('/patients/:pid', (req, res) => {
patientGetOne({ _id: req.params.pid })
.then(patient => {
if (!patient) return Errors.notFound(res)
res.send(patient)
})
.catch(err => Errors.internalError(res, err))
})
router.put('/patients/:pid', (req, res) => {
patientEdit(req.params.pid, req.body)
.then(patient => res.status(201).send(patient))
.catch(err => Errors.internalError(res, err))
})
export { router as PatientsRouter }
<file_sep>export default {
db_url: 'mongodb://localhost:27017/cjournal',
identity: 'https://identity.incart.ru/connect/userinfo',
port: 8628,
log_level: 'error',
test_url: 'http://localhost:8628/api/',
test_username: process.env.TEST_USERNAME,
test_password: <PASSWORD>,
uploads_dir: './uploads',
accepted_mime_types: ['audio/wave', 'image/png', 'image/jpeg', 'text/plain'],
accepted_file_size: 1024 * 1024 * 3,
}
<file_sep>module.exports = {
db_url: process.env.MONGO_DB,
log_level: 'debug',
}
<file_sep>import { Schema, model, Document, ObjectId, Mixed } from 'mongoose'
import { timestamp } from '../helpers/timestamp'
const taskSchema = new Schema(
{
activity_type: { type: String, required: true },
time: { type: Number, required: true },
user: { type: Schema.Types.ObjectId, ref: 'User' },
patient: { type: String, required: false },
idinv: { type: String, required: false },
comment: { type: String, required: false },
data: { type: Schema.Types.Mixed, required: false },
activity: { type: Schema.Types.ObjectId, ref: 'Activity' },
completed: { type: Boolean, required: false, default: false },
created_at: { type: Number },
updated_at: { type: Number },
},
{
timestamps: {
currentTime: () => timestamp(),
createdAt: 'created_at',
updatedAt: 'updated_at',
},
},
)
export interface ITask extends Document {
activity_type: string
time: number
user: ObjectId
patient: string
idinv: string
comment: string
data: Mixed
activity: ObjectId
completed: boolean
}
const Task = model<ITask>('Task', taskSchema)
export { Task }
<file_sep>import { Response } from 'express'
export const unauthorized = function unauthorized(res: Response, message: string = 'unauthorized') {
res.status(401).send({ error: message })
}
export const internalError = function internalError(
res: Response,
message: string = 'internal error',
) {
res.status(409).send({ error: message })
}
export const notFound = function notFound(res: Response, message: string = 'not found') {
res.status(404).send({ error: message })
}
export const incompleteInput = function incompleteInput(
res: Response,
message: string = 'incomplete input',
) {
res.status(409).send({ error: message })
}
export const incorrectInput = function incorrectInput(
res: Response,
message: string = 'incorrect input',
) {
res.status(400).send({ error: message })
}
<file_sep>export const timestamp = (date: Date = new Date()): number => {
return Math.round(Date.now() / 1000)
}
<file_sep>import express from 'express'
import bodyParser from 'body-parser'
import mongoose from 'mongoose'
import cors from 'cors'
import { usersRouter } from './routes/users'
import { activityRouter } from './routes/activity'
import { tasksRouter } from './routes/tasks'
import { PatientsRouter } from './routes/patients'
import { IdinvRouter } from './routes/idinv'
import { winstonMiddleware } from './helpers/logger'
import config from './config'
const app = express()
const port = config.port || 8626
if (!config.db_url)
throw new Error(
'credentials for mongodb are not found. Please lookup the config file for more information',
)
mongoose.connect(
config.db_url,
{
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
useCreateIndex: true,
},
err => {
if (err) return console.log(err)
console.log('Connected to database')
},
)
mongoose.connection.setMaxListeners(0) // allow infinite listeners
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json({ limit: '5mb' }))
app.use(cors())
app.use(winstonMiddleware)
app.use('/api/', usersRouter)
app.use('/api/', activityRouter)
app.use('/api/', tasksRouter)
app.use('/api/', PatientsRouter)
app.use('/api/', IdinvRouter)
app.get('/api/', (req, res) => {
res.status(200).send({ status: 'alive!' })
})
// serve static files
app.use('/uploads/', express.static('uploads'))
app.listen(port, () => {
console.log(`Server is started on port ${port}`)
})
<file_sep>import * as Errors from '../helpers/errors'
import Logger from '../helpers/logger'
import fetch from 'node-fetch'
import { userFindOrCreate } from '../helpers/userFindOrCreate'
import { Request, Response, NextFunction } from 'express'
import { ObjectId } from 'mongoose'
import config from '../config'
export interface ReqWithUser extends Request {
user?: {
id: ObjectId
sub: string
name: string
role?: string | Array<string>
display_name?: string
}
}
export const checkAuth = (req: Request, res: Response, next: NextFunction) => {
let token: string = req.query.token as string
if (req.headers.authorization)
if (req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer')
token = req.headers.authorization.split(' ')[1]
const url: string = config.identity as string
fetch(url, {
method: 'POST',
headers: {
Authorization: 'Bearer ' + token,
},
})
.then(response => {
if (response.status === 401) throw new Error('unauthorized')
return response.json()
})
.then(identityUser => {
userFindOrCreate(identityUser.sub, identityUser.name)
.then(res => {
;(req as ReqWithUser).user = {
id: res,
...identityUser,
}
next()
})
.catch((err: any) => {
Logger.error(err.message)
})
})
.catch(err => {
Logger.error(err.message)
Errors.unauthorized(res)
})
}
<file_sep>import Logger from '../helpers/logger'
import { IUser, User } from '../models/user'
import { ObjectId, CallbackError } from 'mongoose'
export async function userFindOrCreate(sub: string, username: string): Promise<ObjectId> {
return new Promise((resolve, reject) => {
User.findOne({ sub: sub }, null, null, (err: CallbackError, user: IUser | null) => {
if (!user) {
const user = new User({ sub, username })
user.save((err: CallbackError, user: IUser) => {
if (err) {
Logger.error('Error in userFindOrUpdate: ' + err)
reject(err)
}
resolve(user._id)
})
} else {
// there's user!
resolve(user._id)
}
})
})
}
<file_sep>import { Schema, model, Document } from 'mongoose'
const patientSchema = new Schema({
_id: { type: String },
idinv: { type: String, ref: 'Idinv' },
hide_elements: { type: [String], default: [] },
course_therapy: { type: [String], default: [] },
relief_of_attack: { type: [String], default: [] },
tests: { type: [String], default: [] },
})
export interface IPatient extends Document {
_id: string
idinv?: string
hide_elements?: [string]
course_therapy?: [string]
relief_of_attack?: [string]
tests?: [string]
}
const Patient = model<IPatient>('Patient', patientSchema)
export { Patient }
<file_sep>module.exports = {
db_url: 'mongodb://mongo:27017/cjournal?retryWrites=true&w=majority',
log_level: 'error',
}
<file_sep>import Logger from './logger'
import { IPatient, Patient } from '../models/patient'
import { IUser, User } from '../models/user'
export async function patientFindOrCreate(user: string, patient: string): Promise<IPatient> {
return new Promise((resolve, reject) => {
Patient.findOne({ id: patient }).then(async (patient: IPatient | null) => {
if (!patient) {
try {
const newPatient = new Patient({ id: patient })
newPatient.save((err, patient: IPatient) => {
if (err) return reject(null)
// link user to patient
User.findOneAndUpdate(
{ id: user },
{ patient: patient._id },
(err: Error, user: IUser) => {
if (err) Logger.error(`Error on patient find or create: ${err}`)
resolve(patient)
},
)
})
} catch (error) {
Logger.error('Error in patientFindOrUpdate: ' + error)
reject(null)
}
} else {
resolve(patient)
}
})
})
}
<file_sep>import * as dotenv from 'dotenv'
dotenv.config()
import defaults from './default'
const config = require('./' + (process.env.NODE_ENV || 'production'))
type ConfigType = {
db_url: string
identity: string
port: number
log_level: string
test_url: string
test_username: string | undefined
test_password: string | undefined
uploads_dir: string
accepted_mime_types: string[]
accepted_file_size: number
}
const final: ConfigType = { ...defaults, ...config }
export default final
<file_sep>import fetch from 'node-fetch'
import config from '../src/config'
export const Authorize = (): Promise<any> => {
return new Promise((resolve, reject) => {
const details: any = {
grant_type: 'password',
client_id: 'ApiClient',
password: <PASSWORD>,
username: config.test_username,
}
let formBody: any = []
for (let property in details) {
let encodedKey = encodeURIComponent(property)
let encodedValue = encodeURIComponent(details[property])
formBody.push(encodedKey + '=' + encodedValue)
}
formBody = formBody.join('&')
fetch('https://identity.incart.ru/connect/token', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: formBody,
})
.then(res => res.json())
.then(res => resolve(res))
.catch(err => reject(err))
})
}
export const Request = (
token: string,
path: string,
method: string = 'GET',
body?: object | undefined,
): Promise<any> => {
return new Promise((resolve, reject) => {
const init = {
method: method,
headers: {
Authorization: `Bearer ${token}`,
'Content-Type': 'application/json; charset=utf-8',
},
body: JSON.stringify(body),
}
return fetch(config.test_url + path, init)
.then(res => {
const contentType = res.headers.get('content-type')
if (contentType && contentType.indexOf('application/json') !== -1) return res.json()
else return {}
})
.then(res => {
resolve(res)
})
.catch(err => reject(err))
})
}
export const getRandomNumber = (n: number): number => {
return Math.floor(Math.random() * (9 * Math.pow(10, n))) + Math.pow(10, n)
}
export const getRandomString = () => {
return Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15)
}
<file_sep>import { User } from '../models/user'
import { Patient, IPatient } from '../models/patient'
import { idinvCreate } from './idinvController'
import { IIdinv } from '../models/idinv'
import Logger from '../helpers/logger'
export const patientGetMany = async (filter: any): Promise<IPatient> => {
return new Promise((resolve, reject) => {
Patient.find(filter)
.then((patient: IPatient) => resolve(patient))
.catch((err: any) => reject(err))
})
}
export const patientGetOne = async (filter: any): Promise<IPatient> => {
return new Promise((resolve, reject) => {
Patient.findOne(filter)
.then((patient: IPatient) => resolve(patient))
.catch((err: any) => reject(err))
})
}
export const patientEdit = async (id: string, patient: IPatient): Promise<IPatient> => {
return new Promise((resolve, reject) => {
Patient.findByIdAndUpdate(
id,
{ ...patient },
{ new: true },
(err: Error, patient: IPatient | null) => {
if (err || !patient) return reject(err || null)
if (patient.idinv) {
idinvCreate(patient.idinv)
.then((idinv: IIdinv) => {
Logger.info(
`idinv '${patient.idinv}' created for patient '${patient._id}'`,
)
})
.catch(err => {
if (err.code !== 11000)
Logger.error(
`Error creating idinv '${patient.idinv}' for patient '${patient._id}: ${err}`,
)
})
User.findOneAndUpdate(
{ patient: patient._id },
{ idinv: patient.idinv },
null,
(err, user) => {
if (err)
return Logger.error(
`Error linking idinv ${patient.idinv} for user with patient id: ${patient._id}`,
)
Logger.info(
`idinv '${patient.idinv}' linked for user with patient id '${patient._id}'`,
)
},
)
}
resolve(patient)
},
)
})
}
export const patientDelete = async (id: string): Promise<any> => {
return new Promise((resolve, reject) => {
Patient.findByIdAndDelete(id, null, (err: Error, doc) => {
if (err) return reject(err)
resolve(doc)
})
})
}
export const patientCreate = async (patient: any): Promise<IPatient> => {
return new Promise((resolve, reject) => {
const newPatient = new Patient({ ...patient })
newPatient.save((err, act: IPatient) => {
if (err) reject(err)
resolve(act)
})
})
}
<file_sep>import {
Activity,
ActivityHistory,
IActivity,
IActivityHistory,
ActivityUpdates,
IActivityUpdates,
} from '../models/activity'
import Logger from '../helpers/logger'
interface IActivityFilter {
_id?: string
idinv?: string
user?: string
patient?: string
original?: string
}
type historyActions = 'created' | 'edited' | 'deleted'
export const activityGetMany = async (filter: IActivityFilter): Promise<[IActivity]> => {
return new Promise((resolve, reject) => {
Activity.find(filter, (err: Error, activity: [IActivity]) => {
if (err) reject(err.message)
resolve(activity)
})
})
}
export const activityGetOne = async (filter: IActivityFilter): Promise<IActivity> => {
return new Promise((resolve, reject) => {
Activity.findOne(filter, (err: Error, activity: IActivity) => {
if (err) reject(err.message)
resolve(activity)
})
})
}
export const activityCreate = async (activity: IActivity): Promise<IActivity> => {
return new Promise((resolve, reject) => {
const record = new Activity({ ...activity })
record.save((err, record: IActivity) => {
if (err) return reject(err)
activityHistoryCreate(activity._id, activity, 'created')
resolve(record)
})
})
}
export const activityEdit = async (id: string, activity: IActivity): Promise<IActivity> => {
return new Promise((resolve, reject) => {
Activity.findByIdAndUpdate(
id,
{ ...activity },
{ new: true },
(err: Error, act: IActivity | null) => {
if (err || !act) return reject(err || { code: 404 })
activityHistoryCreate(id, activity, 'edited')
resolve(act)
},
)
})
}
export const activityDelete = async (id: string): Promise<void> => {
return new Promise((resolve, reject) => {
Activity.findOneAndDelete({ _id: id }, null, (err, activity) => {
if (err) return reject(err)
if (activity) activityHistoryCreate(id, (activity as any)._doc, 'deleted')
resolve()
})
})
}
export const activityHistoryGetMany = async (
filter: IActivityFilter,
): Promise<[IActivityHistory]> => {
return new Promise((resolve, reject) => {
ActivityHistory.find(filter, (err: Error, activity: [IActivityHistory]) => {
if (err) reject(err.message)
resolve(activity)
})
})
}
export const activityHistoryGetOne = async (filter: IActivityFilter): Promise<IActivityHistory> => {
return new Promise((resolve, reject) => {
ActivityHistory.find(filter)
// .populate('original')
.exec((err: Error, activity: IActivityHistory) => {
if (err) reject(err.message)
resolve(activity)
})
})
}
export const activityHistoryCreate = async (
id: string,
activity: any,
action: historyActions,
): Promise<IActivityHistory> => {
return new Promise((resolve, reject) => {
if (activity._id) delete activity._id
const history = new ActivityHistory({ ...activity, original: id, action })
history.save((err, history: IActivityHistory) => {
if (err) {
reject(err)
Logger.error(`Error in activityHistoryCreate: ${err.message}`)
}
Logger.info(`Activity history record created: ${history._id}`)
resolve(history)
})
})
}
export const activityUpdatesGetMany = async (
filter: IActivityFilter,
): Promise<[IActivityUpdates]> => {
return new Promise((resolve, reject) => {
ActivityUpdates.find(filter, (err: Error, activity: [IActivityUpdates]) => {
if (err) reject(err.message)
resolve(activity)
})
})
}
export const activityUpdatesGetOne = async (filter: IActivityFilter): Promise<IActivityUpdates> => {
return new Promise((resolve, reject) => {
ActivityUpdates.find(filter)
// .populate('original')
.exec((err: Error, activity: IActivityUpdates) => {
if (err) reject(err.message)
resolve(activity)
})
})
}
export const activityUpdatesCreate = async (
id: string,
activity: any,
doctor: string,
): Promise<IActivityUpdates> => {
return new Promise((resolve, reject) => {
if (activity._id) delete activity._id
const history = new ActivityUpdates({ ...activity, original: id, update_by: doctor })
history.save((err, history: IActivityUpdates) => {
if (err) {
reject(err)
Logger.error(`Error in activityUpdatesCreate: ${err.message}`)
}
Logger.info(`Activity history record created: ${history._id}`)
resolve(history)
})
})
}
export const activityUpdatesEdit = async (
id: string,
activity: IActivity,
): Promise<IActivityUpdates> => {
return new Promise((resolve, reject) => {
ActivityUpdates.findByIdAndUpdate(
id,
{ ...activity },
{ new: true },
(err: Error, act: IActivityUpdates | null) => {
if (err || !act) return reject(err || { code: 404 })
resolve(act)
},
)
})
}
export const activityUpdatesDelete = async (id: string): Promise<void> => {
return new Promise((resolve, reject) => {
ActivityUpdates.findOneAndDelete({ _id: id }, null, (err, activity) => {
if (err) return reject(err)
resolve()
})
})
}
<file_sep>import { Authorize, Request, getRandomNumber, getRandomString } from './functions'
let token = ''
let username = ''
let patient = ''
let idinv = ''
let _id = ''
test('authorize', async () => {
const res = await Authorize()
token = res.access_token
})
test('login', async () => {
const user = await Request(token, 'login', 'POST')
expect(user.username).toBeTruthy()
_id = user._id
username = user.username
})
test('get all users', async () => {
const users = await Request(token, 'users', 'GET')
expect(users[0].username).toBe(username)
})
test('get all users unauthorized', async done => {
Request('', `users/`, 'GET').then(err => {
expect(err.error).toBe('unauthorized')
done()
})
})
test('get one user', async () => {
const users = await Request(token, `users/${_id}`, 'GET')
expect(users.username).toBe(username)
})
test('get one user unauthorized', async done => {
Request('', `users/${_id}`, 'GET').then(err => {
expect(err.error).toBe('unauthorized')
done()
})
})
test('change user', async () => {
idinv = '045_000_00089_' + getRandomNumber(5)
patient = getRandomString()
const body = {
idinv: idinv,
patient: patient,
}
const user = await Request(token, `users/${_id}`, 'PUT', body)
expect(user.idinv).toBe(idinv)
expect(user.patient).toBe(patient)
})
test('change user unauthorized', async done => {
Request('', `users/${_id}`, 'PUT').then(err => {
expect(err.error).toBe('unauthorized')
done()
})
})
test('checkout patient', async () => {
const doc = await Request(token, `patients/${patient}`, 'GET')
expect(doc).toHaveProperty('_id', patient)
expect(doc).toHaveProperty('idinv', idinv)
})
test('change patient', async () => {
const relief_of_attack = [getRandomString(), getRandomString(), getRandomString()]
const course_therapy = [getRandomString(), getRandomString(), getRandomString()]
const tests = [getRandomString(), getRandomString(), getRandomString()]
const doc = await Request(token, `patients/${patient}`, 'PUT', {
relief_of_attack,
course_therapy,
tests,
})
expect(doc).toHaveProperty('relief_of_attack')
expect(doc).toHaveProperty('course_therapy')
expect(doc).toHaveProperty('tests')
expect(doc.relief_of_attack[0]).toEqual(relief_of_attack[0])
expect(doc.course_therapy[0]).toEqual(course_therapy[0])
expect(doc.tests[0]).toEqual(tests[0])
})
<file_sep>import * as Errors from '../helpers/errors'
import { Request, Response, NextFunction } from 'express'
import Logger from '../helpers/logger'
export const validateActivity = (req: Request, res: Response, next: NextFunction) => {
if (
(req.body.user || req.body.idinv || req.body.patient) &&
req.body._id &&
req.body.activity_type &&
req.body.time_started
) {
next()
} else {
Logger.info(`activity validation error: ${JSON.stringify(req.body)}`)
Errors.incompleteInput(res)
}
}
export const validateActivityUpdate = (req: Request, res: Response, next: NextFunction) => {
if (
(req.body.user || req.body.idinv || req.body.patient) &&
req.body.updated_by &&
req.body.original &&
req.body.activity_type &&
req.body.time_started
) {
next()
} else {
Logger.info(`activity update validation error: ${JSON.stringify(req.body)}`)
Errors.incompleteInput(res)
}
}
<file_sep>import { Request, Response } from 'express'
import { User, IUser } from '../models/user'
import * as Errors from '../helpers/errors'
import Logger from '../helpers/logger'
import { ReqWithUser } from '../middleware/checkAuth'
import { idinvCreate } from './idinvController'
import { IIdinv } from '../models/idinv'
import { Patient } from '../models/patient'
import { patientCreate } from './patientController'
import verifyObjectId from '../helpers/verifyObjectId'
export const userGetAll = async (req: Request, res: Response) => {
const users = await User.find()
res.send(users)
}
export const userGetById = async (req: ReqWithUser, res: Response) => {
if (!verifyObjectId(req.params.id)) return Errors.incorrectInput(res)
const identityUser = req.user
User.findById(req.params.id)
.populate('patient')
.exec(function (err: Error, user: IUser) {
if (err) res.status(400).send({ error: err.message })
else {
if (!user) return Errors.notFound(res)
res.send(user)
}
})
}
export const userEdit = async (req: Request, res: Response) => {
User.findByIdAndUpdate(req.params.id, { idinv: req.body.idinv }, { new: true }, (err, user) => {
if (err) {
Logger.error(err.message)
Errors.incorrectInput(res)
}
if (req.body.idinv) {
idinvCreate(req.body.idinv)
.then((idinv: IIdinv) => {
Logger.info(`idinv '${req.body.idinv}' created for user '${req.params.id}'`)
})
.catch(err => {
if (err.code !== 11000)
Logger.error(
`Error creating idinv '${req.body.idinv}' for user '${req.params.id}: ${err}`,
)
})
Patient.findOneAndUpdate(
{ _id: user.patient },
{ idinv: user.idinv },
null,
(err, patient) => {
if (err || !patient) return Logger.error(`Error linking idinv to patient `, err)
Logger.info(`Idinv ${user.idinv} is linked to patient ${patient._id}`)
},
)
}
res.status(201).send(user)
})
}
export const userLogin = (req: ReqWithUser, res: Response) => {
const identityUser = req.user
User.findOne({ sub: identityUser!.sub })
.populate('patient')
.then((user: IUser | null) => {
if (!user) return Errors.notFound(res)
const doc = (user as any)._doc
res.send({ ...doc, identity: { ...identityUser } })
})
.catch((err: any) => {
Errors.incorrectInput(res, err.reason.message)
})
}
export const userCreate = (username: string, sub: string): Promise<IUser> => {
return new Promise((resolve, reject) => {
const user = new User({ sub, username })
user.save(function (error, user: IUser) {
if (error) {
Logger.error('Error in userCreate: ' + error)
reject(error)
}
// create patient
resolve(user)
})
})
}
export const userDelete = (req: Request, res: Response) => {
User.deleteOne({ _id: req.params.id })
.then((user: IUser) => {
if (!user) return Errors.notFound(res)
res.send(user)
})
.catch((err: any) => {
Errors.incorrectInput(res, err.reason.message)
})
}
<file_sep># CJournal API
## Technology stack
built using `typescript`, `node`, `express`
`mongodb` for database
`Microsoft Identity Server` for authorization is required
## Database
[Current database schema](https://app.dbdesigner.net/designer/schema/0-cjournal_new)
## Config
Requires `.env` file in root directory.
- `NODE_ENV` Options supported: _development_, _production_ and _docker_
- `MONGO_DB` mongoDB connection url
- `LOG_LEVEL` winston log level
- `TEST_USERNAME` (optional) identity username (only to runtests)
- `TEST_PASSWORD` (optional) identity password (only to runtests)
## Running
`npm install`
`npm start`
`npm run test` for testing
## Headers
#### Authorization
Using Identity Server protocol
headers: { Authorization: "Bearer {{token}} }
#### Content type
Content-Type: application/json
## Endpoints
**users:**
- `GET `/api/users/
- `GET` /api/users/:id
- `PUT` /api/users/:id
**patient**
- `GET `/api/patients/
- `GET` /api/patients/:id
- `PUT` /api/patients/:id
**idinv**
- `GET `/api/idinv/
- `GET` /api/idinv/:idinv
**activity**
- `GET `/api/users/:id/activity
- `GET `/api/patients/:id/activity
- `GET `/api/idinv/:idinv/activity
- `GET `/api/users/:id/activity/:id
- `GET `/api/patients/:id/activity/:id
- `GET `/api/idinv/:idinv/activity/:id
- `POST `/api/users/:id/activity/
- `POST `/api/patients/:id/activity
- `POST `/api/idinv/:idinv/activity
- `PUT `/api/users/:id/activity/:id
- `PUT `/api/patients/:id/activity/:id
- `PUT `/api/idinv/:idinv/activity/:id
- `DELETE `/api/users/:id/activity/:id
- `DELETE `/api/patients/:id/activity/:id
- `DELETE `/api/idinv/:idinv/activity/:id
**activity history**
- `GET `/api/users/:id/activity/history
- `GET `/api/patients/:id/activity/history
- `GET `/api/idinv/:idinv/activity/history
- `GET `/api/users/:id/activity/history/:id
- `GET `/api/patients/:id/activity/history/:id
- `GET `/api/idinv/:idinv/activity/history/:id
**task**
- `GET `/api/users/:id/tasks
- `GET `/api/patients/:id/tasks
- `GET `/api/idinv/:idinv/tasks
- `GET `/api/users/:id/tasks/:id
- `GET `/api/patients/:id/tasks/:id
- `GET `/api/idinv/:idinv/tasks/:id
- `POST `/api/users/:id/tasks/
- `POST `/api/patients/:id/tasks
- `POST `/api/idinv/:idinv/tasks
- `PUT `/api/users/:id/tasks/:id
- `PUT `/api/patients/:id/tasks/:id
- `PUT `/api/idinv/:idinv/tasks/:id
- `DELETE `/api/users/:id/tasks/:id
- `DELETE `/api/patients/:id/tasks/:id
- `DELETE `/api/idinv/:idinv/tasks/:id
## Request body
#### Activity
Required for `POST` and `PUT` requests:
- \_id
- activity_type
- time_started
- user || patient || idinv
```
{
"_id": "603bcf6633ca323f18cc0a7d",
"activity_type": "Meal",
"time_started": 1579167281,
"time_ended": 1579167641,
"idinv": "045_000_00089_00026",
"user": "<KEY>",
"comment": "Test",
"created_at": 1614532455,
}
```
#### Tasks
Required for `POST` and `PUT` requests:
- \_id
- activity_type
- time
- user || patient || idinv
```
{
"_id": "603bcf6633ca323f18cc0a5d",
"activity_type": "Walking",
"time_started": 1579167281,
"time_ended": 1579167641,
"idinv": "045_000_00089_00026",
"user": "<KEY>",
"comment": "Test",
"created_at": 1614532455,
}
```
<file_sep>import { NextFunction, Request, Response } from 'express'
import winston, { format } from 'winston'
import config from '../config'
const logConfiguration = {
transports: [
new winston.transports.Console({
level: 'error',
}),
new winston.transports.File({
level: config.log_level,
filename: './logs/combined.log',
format: format.combine(
format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss:ms' }),
format.printf(info => `${info.level}: [${info.timestamp}] ${info.message}`),
),
}),
],
}
export default winston.createLogger(logConfiguration)
export const winstonMiddleware = (req: Request, res: Response, next: NextFunction): void => {
const Logger = winston.createLogger(logConfiguration)
const { authorization, ...headersWithNoToken } = req.headers
Logger.log(
'http',
`${req.ip} ${req.method} ${req.originalUrl} ${JSON.stringify(
headersWithNoToken,
)} ${JSON.stringify(req.body)}`,
)
next()
}
<file_sep>import path from 'path'
import multer from 'multer'
import { NextFunction, Request, Response } from 'express'
import { Types } from 'mongoose'
import Logger from '../helpers/logger'
import fs from 'fs'
import config from '../config'
const storage = multer.diskStorage({
destination: (req, file, cb) => {
createUploadsDir().then(() => {
cb(null, config.uploads_dir)
})
},
filename: (req, file, cb) => {
const filename = new Types.ObjectId() + path.extname(file.originalname)
cb(null, filename)
},
})
const createUploadsDir = async (): Promise<void> => {
return new Promise(resolve => {
const dir = config.uploads_dir
if (!fs.existsSync(dir)) {
resolve(fs.mkdirSync(dir))
} else {
resolve()
}
})
}
const fileFilter = (req: Request, file: Express.Multer.File, cb: multer.FileFilterCallback) => {
if (config.accepted_mime_types.includes(file.mimetype)) return cb(null, true)
cb(null, false)
}
const upload = multer({
storage: storage,
limits: { fileSize: config.accepted_file_size },
fileFilter: fileFilter,
})
const saveFilesMiddleware = upload.fields([
{ name: 'audio', maxCount: 1 },
{ name: 'image', maxCount: 1 },
{ name: 'log', maxCount: 1 },
])
export const saveFiles = function (req: Request, res: Response, next: NextFunction) {
const saveNext: NextFunction = () => {
if (req.files) {
// todo: improve
if (!req.body.data || typeof req.body.data !== 'object') req.body.data = {}
if ((req as any).files.audio) {
req.body.data.audio = (req as any).files.audio[0].path.replace('\\', '/')
Logger.info(`File successfully saved ${req.body.data.audio}`)
}
if ((req as any).files.image) {
req.body.data.image = (req as any).files.image[0].path.replace('\\', '/')
Logger.info(`File successfully saved ${req.body.data.image}`)
}
if ((req as any).files.log) {
req.body.data.log = (req as any).files.log[0].path.replace('\\', '/')
Logger.info(`File successfully saved ${req.body.data.log}`)
}
}
next()
}
saveFilesMiddleware(req, res, saveNext)
}
<file_sep>import { Request, Response } from 'express'
import { Idinv, IIdinv } from '../models/idinv'
import * as Errors from '../helpers/errors'
import Logger from '../helpers/logger'
export const idinvGetAll = async (req: Request, res: Response) => {
const idinv = await Idinv.find()
res.send(idinv)
}
export const idinvGetById = async (req: Request, res: Response) => {
Idinv.findById(req.params.idinv)
.then((idinv: IIdinv) => {
if (!idinv) return Errors.notFound(res)
res.send(idinv)
})
.catch((err: any) => {
Logger.error('Error in idinvGetById controller: ' + err.message)
Errors.incorrectInput(res, err.reason.message)
})
}
export const idinvCreate = async (idinvString: string): Promise<IIdinv> => {
return new Promise((resolve, reject) => {
const [mon_type, mon_state, mon_number, mon_install] = idinvString.split('_')
if (!mon_type || !mon_state || !mon_number || !mon_install)
reject(new Error('incomplete idinv'))
const idinv = new Idinv({
_id: idinvString,
mon_type: mon_type,
mon_state: mon_state,
mon_number: mon_number,
mon_install: mon_install,
})
idinv.save((err, idinv: IIdinv) => {
if (err) reject(err)
resolve(idinv)
})
})
}
<file_sep>import express from 'express'
const router = express.Router()
import { idinvGetAll, idinvGetById } from '../controllers/idinvController'
import { checkAuth } from '../middleware/checkAuth'
router.get('/idinv/', checkAuth, idinvGetAll)
router.get('/idinv/:idinv', checkAuth, idinvGetById)
export { router as IdinvRouter }
<file_sep>import { Authorize, Request } from './functions'
import { Types } from 'mongoose'
import { timestamp } from '../src/helpers/timestamp'
let token = ''
let _id = ''
let idinv = ''
let patient = ''
let act_id = ''
let test_activity: any
describe('activity by idinv', () => {
test('authorize', async () => {
const res = await Authorize()
token = res.access_token
})
test('login', async () => {
const user = await Request(token, 'login', 'POST')
expect(user).toHaveProperty('_id')
expect(user).toHaveProperty('idinv')
expect(user).toHaveProperty('patient')
_id = user._id
idinv = user.idinv
patient = user.patient
})
test('idinv get all activities', async () => {
const activities = await Request(token, `idinv/${idinv}/activity`, 'GET')
expect(Array.isArray(activities)).toBe(true)
if (activities.length > 0) {
expect(activities[0]).toHaveProperty('_id')
}
})
test('idinv create activity', async () => {
act_id = new Types.ObjectId().toString()
test_activity = {
_id: act_id,
activity_type: 'Meal',
time_started: timestamp() - 300,
time_ended: timestamp(),
patient: patient,
idinv: idinv,
user: _id,
comment: 'activity created by test',
}
const act = await Request(token, `idinv/${idinv}/activity/`, 'POST', test_activity)
expect(act).toHaveProperty('_id', act_id)
})
test('idinv get created activity', async () => {
const act = await Request(token, `idinv/${idinv}/activity/${act_id}`, 'GET')
expect(act).toHaveProperty('_id', act_id)
expect(act).toHaveProperty('comment', test_activity.comment)
})
test('idinv edit created activity', async () => {
test_activity.comment = 'edited test activity'
test_activity.activity_type = 'Alcohol'
const act = await Request(token, `idinv/${idinv}/activity/${act_id}`, 'PUT', test_activity)
expect(act).toHaveProperty('_id', act_id)
expect(act).toHaveProperty('comment', test_activity.comment)
})
test('idinv delete created activity', async () => {
test_activity.comment = 'edited test activity'
test_activity.activity_type = 'Alcohol'
const act = await Request(token, `idinv/${idinv}/activity/${act_id}`, 'DELETE')
expect(act).toBeTruthy()
})
test('idinv get created activity history', async done => {
const histories = await Request(token, `idinv/${idinv}/activity/history/${act_id}`, 'GET')
expect(Array.isArray(histories)).toBe(true)
for (const h of histories) {
expect(h).toHaveProperty('original', act_id)
}
setTimeout(async () => {
expect(histories[0].action).toEqual('created')
expect(histories[1].action).toEqual('edited')
expect(histories[2].action).toEqual('deleted')
done()
}, 500)
})
})
| 7018f0a3e312308460c02fffca35a689a5e54094 | [
"Markdown",
"TypeScript"
] | 36 | TypeScript | irondsd/cjournal-api | 5bec75c1e96927612f04e56bab5d9b0372e8f9fb | f613c1cba677dde7e0c432e14e238b72128fd76b |
refs/heads/master | <repo_name>super0201/SaleFTP<file_sep>/app/src/main/java/com/team2/saleftp/MainActivity.java
package com.team2.saleftp;
import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.SearchView;
import java.util.ArrayList;
import java.util.Objects;
import adapter.ProductMainAdapter;
import adapter.RecyclerItemClickListener;
import dao.ProductDAO;
import dao.UserDAO;
import model.Product;
import model.ProductDetail;
import model.User;
import session.SessionManager;
/**
* Created By JohnNguyen - Onesoft on 12/12/2018
*/
public class MainActivity extends AppCompatActivity {
private ArrayList<Product> list = new ArrayList<>();
public static ProductDetail list2;
ProductDAO dao;
SearchView search;
ImageView imvProfile;
FloatingActionButton fab;
ProductMainAdapter mAdapter;
RecyclerView mRecyclerView;
SessionManager sessionManager;
UserDAO userDAO;
public static User USER = null;
@SuppressLint("ResourceType")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sessionManager = new SessionManager(getBaseContext());
dao = new ProductDAO(getBaseContext());
list = dao.viewAll();
fab = findViewById(R.id.fab);
search = findViewById(R.id.search);
imvProfile = findViewById(R.id.imvProfile);
//custom searchview
search.isIconfiedByDefault();
closeKeyboard();
//setOnClick profile
imvProfile.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//insert your profile code here
if (sessionManager.isLoggedIn()){
Intent i = new Intent(getBaseContext(), UserInfoActivity.class);
startActivity(i);
} else {
Intent i = new Intent(getBaseContext(), LoginActivity.class);
startActivity(i);
}
}
});
//list product adapter
mRecyclerView = findViewById(R.id.rvMain);
mRecyclerView.setLayoutManager(new GridLayoutManager(getBaseContext(), 2));
mRecyclerView.setHasFixedSize(true);
mAdapter = new ProductMainAdapter(getBaseContext(), list);
mRecyclerView.setAdapter(mAdapter);
//setOnClick event
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(getBaseContext(), CartActivity.class);
startActivity(i);
}
});
mRecyclerView.addOnItemTouchListener(new RecyclerItemClickListener(getBaseContext(),
new RecyclerItemClickListener.OnItemClickListener() {
@Override
public void onItemClick(View view, int position) {
//intent Parcelable data to DetailActivity
String id;
id = list.get(position).getId();
list2 = dao.viewDetail(id);
Intent intent = new Intent(getBaseContext(), DetailActivity.class);
intent.putParcelableArrayListExtra("data", list);
intent.putExtra("pos", position);
startActivityForResult(intent, 10001);
}
}));
}
public void closeKeyboard() {
View currentFocus = this.getCurrentFocus();
if (currentFocus != null) {
android.view.inputmethod.InputMethodManager imm = (android.view.inputmethod.InputMethodManager) this.getSystemService(android.content.Context.INPUT_METHOD_SERVICE);
assert imm != null;
Objects.requireNonNull(imm).hideSoftInputFromWindow(currentFocus.getWindowToken(), 0);
}
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
return super.onCreateOptionsMenu(menu);
}
@SuppressLint("ResourceType")
@Override
public void onBackPressed() {
new AlertDialog.Builder(this)
.setIcon(R.raw.logo)
.setTitle("FTP")
.setMessage("Bạn Muốn Thoát Ứng Dụng?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which) {
moveTaskToBack(true);
finish();
}
})
.setNegativeButton("No", null)
.show();
}
private void initial() {
SessionManager session = new SessionManager(getBaseContext());
userDAO = new UserDAO(getBaseContext());
if (session.isLoggedIn()) {
// String x = session.getSharedUsername();
LoginActivity.USER = userDAO.getUserByUsername(session.getSharedUsername());
}
}
@Override
protected void onResume() {
super.onResume();
initial();
closeKeyboard();
}
}
<file_sep>/app/src/main/java/adapter/OrderAdapter.java
package adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.team2.saleftp.R;
import java.text.DecimalFormat;
import java.util.ArrayList;
import dao.ProductDAO;
import model.Cart;
public class OrderAdapter extends BaseAdapter {
private Context context;
private LayoutInflater inflater;
ArrayList<Cart> arrCart;
ProductDAO productDAO;
public OrderAdapter(Context context, ArrayList<Cart> arrayCart) {
super();
this.context = context;
this.arrCart = arrayCart;
this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
productDAO = new ProductDAO(context);
}
@Override
public int getCount() {
return arrCart.size();
}
@Override
public Object getItem(int position) {
return arrCart.get(position);
}
@Override
public long getItemId(int position) {
return 0;
}
public static class ViewHolder {
TextView tvNameP, tvAmountP, tvPriceP;
ImageView imvIconP;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.item_order, null);
holder.imvIconP = (ImageView) convertView.findViewById(R.id.imvPOrder);
holder.tvNameP = (TextView) convertView.findViewById(R.id.tvNamePOrder);
holder.tvAmountP = (TextView) convertView.findViewById(R.id.tvAmountPOrder);
holder.tvPriceP = (TextView) convertView.findViewById(R.id.tvPricePOrder);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Cart cart = (Cart) arrCart.get(position);
holder.tvNameP.setText("Tên: " + cart.getName());
holder.tvAmountP.setText("Số lượng: " + cart.getAmount());
DecimalFormat decimalFormat = new DecimalFormat("###,###,###");
holder.tvPriceP.setText("Giá: " + decimalFormat.format(cart.getPrice()));
Glide.with(context).load(arrCart.get(position).getImage())
.into(holder.imvIconP);
return convertView;
}
@Override public void notifyDataSetChanged() {
super.notifyDataSetChanged();
}
public void changeDataset(ArrayList<Cart> items){
this.arrCart = items;
notifyDataSetChanged();
}
}
<file_sep>/app/src/main/java/adapter/ProductMainAdapter.java
package adapter;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.team2.saleftp.R;
import java.text.DecimalFormat;
import java.util.ArrayList;
import model.Product;
/**
* Created By JohnNguyen - Onesoft on 14/12/2018
*/
public class ProductMainAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
ArrayList<Product> data;
Context context;
public ProductMainAdapter(Context context, ArrayList<Product> data) {
this.context = context;
this.data = data;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
RecyclerView.ViewHolder viewHolder;
View v;
v = LayoutInflater.from(parent.getContext()).inflate(
R.layout.item_product, parent, false);
viewHolder = new ProductMainAdapter.MyItemHolder(v);
return viewHolder;
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
Product Product = data.get(position);
MyItemHolder myItemHolder = (MyItemHolder) holder;
myItemHolder.tvName.setText(Product.getName());
Integer d = Product.getPrice();
DecimalFormat decimalFormat = new DecimalFormat("###,###,###");
myItemHolder.tvPrice.setText(decimalFormat.format(d));
Glide.with(context)
.load(data.get(position).getImage())
.into(((MyItemHolder) holder).imvProduct);
}
@Override
public int getItemCount() {
return data.size();
}
public static class MyItemHolder extends RecyclerView.ViewHolder {
ImageView imvProduct;
TextView tvName, tvPrice;
private MyItemHolder(View itemView) {
super(itemView);
tvName = (TextView) itemView.findViewById(R.id.tvName);
tvPrice = (TextView) itemView.findViewById(R.id.tvPrice);
imvProduct = (ImageView) itemView.findViewById(R.id.imvProduct);
}
}
}
<file_sep>/app/src/main/java/adapter/CartAdapter.java
package adapter;
import android.content.Context;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.team2.saleftp.R;
import java.text.DecimalFormat;
import java.util.ArrayList;
import dao.ProductDAO;
import model.Cart;
public class CartAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context mContext;
Context context;
ArrayList<Cart> data;
ProductDAO productDAO;
public CartAdapter(Context context, ArrayList<Cart> data) {
this.context = context;
this.data = data;
productDAO = new ProductDAO(context);
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
RecyclerView.ViewHolder viewHolder;
View v;
v = LayoutInflater.from(parent.getContext()).inflate(
R.layout.item_cart, parent, false);
viewHolder = new CartAdapter.MyItemHolder(v);
return viewHolder;
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
Cart cart = data.get(position);
MyItemHolder myItemHolder = (MyItemHolder) holder;
myItemHolder.tvName.setText(cart.getName());
Integer i = cart.getPrice();
CharSequence x = myItemHolder.tvAmount.getText();
DecimalFormat decimalFormat = new DecimalFormat("###,###,###");
myItemHolder.tvPrice.setText(decimalFormat.format(i * Integer.parseInt(x.toString()))+ "Đ");
Glide.with(context).load(data.get(position).getImage())
.thumbnail(0.4f)
.into(((MyItemHolder) holder).imvCart);
myItemHolder.imvDel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
AlertDialog.Builder alertbox = new AlertDialog.Builder(view.getRootView().getContext());
alertbox.setMessage("Bạn Muốn Xóa Khỏi Giỏ Hàng?");
alertbox.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
productDAO.deleteCart(data.get(position).getIdproduct());
data.remove(position);
changeDataset(data);
}
});
alertbox.setNegativeButton("No", null);
alertbox.show();
}
});
productDAO.updateCart(Integer.parseInt(x.toString()), cart.getIdproduct());
}
public void changeDataset(ArrayList<Cart> items){
this.data = items;
notifyDataSetChanged();
}
@Override
public int getItemCount() {
return data.size();
}
public class MyItemHolder extends RecyclerView.ViewHolder {
ImageView imvCart, imvDel;
TextView tvName;
TextView tvPrice;
TextView tvAmount;
Button btnPlus, btnMinus;
Cart cart;
ProductDAO productDAO;
int amount = 1;
public MyItemHolder(View itemView) {
super(itemView);
tvName = itemView.findViewById(R.id.tvNameCart);
imvCart = itemView.findViewById(R.id.imvCart);
tvPrice = itemView.findViewById(R.id.tvPriceCart);
tvAmount = itemView.findViewById(R.id.tvAmount);
btnPlus = itemView.findViewById(R.id.btnPlus);
btnMinus = itemView.findViewById(R.id.btnMinus);
imvDel = itemView.findViewById(R.id.imvDel);
tvAmount.setText(""+ amount);
btnPlus.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
amount++;
tvAmount.setText(""+ amount);
notifyDataSetChanged();
}
});
btnMinus.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(amount > 0) {
amount --;
tvAmount.setText("" + amount);
notifyDataSetChanged();
}
}
});
}
}
}
// Cart c = arrCart.get(i);
// viewHolder.tvName.setText(c.getName());
//// DecimalFormat decimalFormat = new DecimalFormat("###,###,###");
//// viewHolder.tvPrice.setText(decimalFormat.format(cart.getPrice()) + "Đ");
//
// Glide.with(ct).load(c.getImage()).into(viewHolder.imvCart);
// viewHolder.btnAmount.setText(cart.getAmount() + "");
// int sl = Integer.parseInt(viewHolder.btnAmount.getText().toString());
// if(sl>10){
// viewHolder.btnPlus.setVisibility(View.INVISIBLE);
// viewHolder.btnMinus.setVisibility(View.VISIBLE);
// }else if(sl <=1){
// viewHolder.btnMinus.setVisibility(View.INVISIBLE);
// }else if(sl >= 1){
// viewHolder.btnMinus.setVisibility(View.VISIBLE);
// viewHolder.btnPlus.setVisibility(View.VISIBLE);
// }
// final Button btnplus = viewHolder.btnPlus;
// final Button btnminus = viewHolder.btnMinus;
// final Button btnamount = viewHolder.btnAmount;
// final TextView tvnewprice = viewHolder.tvPrice;
//
// btnplus.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View view) {
// int newamount = Integer.parseInt(btnamount.getText().toString()) +1;
// int nowamount = DetailActivity.arrCart.get(i).getAmount();
// double pricenow = DetailActivity.arrCart.get(i).getPrice();
//
// DetailActivity.arrCart.get(i).setAmount(newamount);
// double newprice = (pricenow * newamount) / nowamount;
//
// DetailActivity.arrCart.get(i).setPrice(newprice);
// DecimalFormat decimalFormat = new DecimalFormat("###,###,###");
//
// tvnewprice.setText(decimalFormat.format(newprice) + "Đ");
// CartActivity.Event();
//
// if(newamount > 9){
// btnplus.setVisibility(View.INVISIBLE);
// btnminus.setVisibility(View.VISIBLE);
// btnamount.setText(String.valueOf(newamount));
// }else {
// btnminus.setVisibility(View.VISIBLE);
// btnplus.setVisibility(View.VISIBLE);
// btnamount.setText(String.valueOf(newamount));
// }
// }
// });
//
// viewHolder.btnMinus.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View view) {
// int newamount = Integer.parseInt(btnamount.getText().toString()) +1;
// int nowamount = DetailActivity.arrCart.get(i).getAmount();
// double pricenow = DetailActivity.arrCart.get(i).getPrice();
//
// DetailActivity.arrCart.get(i).setAmount(newamount);
// double newprice = (pricenow * newamount) / nowamount;
// DetailActivity.arrCart.get(i).setPrice(newprice);
//
// DecimalFormat decimalFormat = new DecimalFormat("###,###,###");
// tvnewprice.setText(decimalFormat.format(newprice) + "Đ");
// CartActivity.Event();
//
// if(newamount < 2){
// btnminus.setVisibility(View.INVISIBLE);
// btnplus.setVisibility(View.VISIBLE);
// btnamount.setText(String.valueOf(newamount));
// }else {
// btnminus.setVisibility(View.VISIBLE);
// btnplus.setVisibility(View.VISIBLE);
// btnamount.setText(String.valueOf(newamount));
// }
// }
// });
<file_sep>/app/src/main/java/dao/UserDAO.java
package dao;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import database.UserDB;
import model.User;
public class UserDAO {
private static SQLiteDatabase db;
private UserDB dbHelper;
public UserDAO(Context context) {
dbHelper = new UserDB(context);
// db = dbHelper.getWritableDatabase();
// db = dbHelper.getReadableDatabase();
}
//insert
public long insertUser(String username, String pass, String name, String email, String addr, String phone){
ContentValues values = new ContentValues();
values.put("Username", username.toLowerCase());
values.put("Password", <PASSWORD>);
values.put("Email", email);
values.put("Address", addr);
values.put("Phone", phone);
values.put("Name", name);
long pos = db.insert("User",null, values);
return pos;
}
//getAll
public List<User> getAllUser() throws ParseException {
db = dbHelper.getReadableDatabase();
List<User> dsUser = new ArrayList<>();
Cursor c = db.query("User",null,null,null,null,null,null);
c.moveToFirst();
while (c.isAfterLast()==false){
User ee = new User();
ee.setUsername(c.getString(0));
ee.setPassword(c.getString(2));
ee.setName(c.getString(1));
ee.setPhone(c.getString(3));
ee.setAddr(c.getString(4));
dsUser.add(ee);
c.moveToNext();
}
c.close();
return dsUser;
}
public int updateUser(String username, String name, String email, String addr, String phone){
ContentValues values = new ContentValues();
values.put("Username",username);
values.put("Name",name);
values.put("Email", email);
values.put("Address",addr);
values.put("Phone",phone);
int result = db.update("User",values,"username=?", new String[]{username});
if (result == 0){
return -1;
}
return 1;
}
public int changePasswordUser(User nd){
db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("Username",nd.getUsername());
values.put("Password",nd.<PASSWORD>());
int result = db.update("User",values,"username=?", new String[]{nd.getUsername()});
if (result == 0){
return -1;
}
return 1;
}
//delete
public int deleteUsername(String username){
int result = db.delete("User","Username=?",new String[]{username});
if (result == 0)
return -1;
return 1;
}
//check login
public int checkLoginStat(String user, String pass){
db = dbHelper.getReadableDatabase();
try {
String check = "SELECT * FROM User WHERE Username='" + user + "' COLLATE NOCASE AND Password='" + pass + "'";
Cursor cs = db.rawQuery(check, null);
if (cs.getCount() == 0){
return -1;
}
return 1;
} finally {
db.close();
}
}
public int checkUser(String username) {
db = dbHelper.getReadableDatabase();
String sql = "SELECT * FROM " + "User" + " WHERE Username='" + username + "'";
Cursor cs = db.rawQuery(sql, null);
if (cs.getCount() <= 0) {
return -1;
}
cs.close();
return 1;
}
public User getUserByUsername(String username) {
db = dbHelper.getReadableDatabase();
User m = null;
//WHERE clause
String selection = "username = ?";
//WHERE clause arguments
String[] selectionArgs = {username};
Cursor c = db.query("User",null,selection,selectionArgs,null,null,null);
c.moveToFirst();
while (!c.isAfterLast()){
m = new User();
m.setUsername(c.getString(0));
m.setName(c.getString(1));
m.setPassword(c.getString(2));
m.setPhone((c.getString(3)));
m.setAddr(c.getString(4));
m.setEmail(c.getString(5));
break;
} c.close();
return m;
}
}
<file_sep>/app/src/main/java/database/UserDB.java
package database;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class UserDB extends SQLiteOpenHelper {
public UserDB(Context context) {
super(context, "User", null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
String sqlUser = "CREATE TABLE User(Username text primary key , Name text, Password text, Phone text, Address text, Email text)";
db.execSQL(sqlUser);
sqlUser = "Insert Into User values ('admin','Admin','12345678', '0796181953', 'Quận 7', '<EMAIL>')";
db.execSQL(sqlUser);
sqlUser = "Insert Into User values ('super0201','Guest','12345678', '089274721', 'Quận 9', '<EMAIL>')";
db.execSQL(sqlUser);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
<file_sep>/app/src/main/java/com/team2/saleftp/CartActivity.java
package com.team2.saleftp;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.text.DecimalFormat;
import java.util.ArrayList;
import adapter.CartAdapter;
import dao.ProductDAO;
import model.Cart;
import session.SessionManager;
public class CartActivity extends AppCompatActivity {
private ArrayList<Cart> cart = new ArrayList<>();
RecyclerView lvCart;
TextView tvNoti;
static TextView tvTotal;
Button btnPayment, btnContinue;
SessionManager sessionManager;
CartAdapter cartAdapter;
ProductDAO dao;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cart);
lvCart = findViewById(R.id.lvCart);
// tvNoti = findViewById(R.id.tvNoti);
// tvTotal = findViewById(R.id.tvTotal);
sessionManager = new SessionManager(getBaseContext());
dao = new ProductDAO(getBaseContext());
cart = dao.viewAllCart();
lvCart = findViewById(R.id.lvCart);
lvCart.setLayoutManager(new GridLayoutManager(getBaseContext(), 1));
lvCart.setHasFixedSize(true);
cartAdapter = new CartAdapter(getBaseContext(), cart);
lvCart.setAdapter(cartAdapter);
cartAdapter.changeDataset(cart);
if (cart.size() > 0){
cartAdapter.notifyDataSetChanged();
} else {
Toast.makeText(getBaseContext(), "Không Có Hàng Trong Giỏ", Toast.LENGTH_SHORT).show();
}
btnPayment = findViewById(R.id.btnPay);
btnContinue = findViewById(R.id.btnContinue);
btnPayment.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (sessionManager.isLoggedIn()){
Intent i = new Intent(getBaseContext(), OrderActivity.class);
startActivity(i);
} else {
Intent i = new Intent(getBaseContext(), LoginActivity.class);
startActivity(i);
}
}
});
btnContinue.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(getBaseContext(), MainActivity.class);
startActivity(intent);
}
});
}
// private void CatchOnItemListView(){
// lvCart.(new AdapterView.OnItemLongClickListener() {
// @Override
// public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
// AlertDialog.Builder builder = new AlertDialog.Builder(CartActivity.this);
// builder.setTitle("Xác nhận");
// builder.setMessage("Bạn có muốn xóa sản phẩm này ?");
// builder.setPositiveButton("Có", new DialogInterface.OnClickListener() {
// @Override
// public void onClick(DialogInterface dialogInterface, int i) {
// if(DetailActivity.arrCart.size()<=0){
// tvNoti.setVisibility(View.INVISIBLE);
// }else {
// DetailActivity.arrCart.remove(i);
// cartAdapter.notifyDataSetChanged();
// Event();
// if(DetailActivity.arrCart.size() <= 0){
// tvNoti.setVisibility(View.VISIBLE);
// }else {
// tvNoti.setVisibility(View.INVISIBLE);
// }
// }
// }
// });
// builder.setNegativeButton("Không", new DialogInterface.OnClickListener() {
// @Override
// public void onClick(DialogInterface dialogInterface, int i) {
// cartAdapter.notifyDataSetChanged();
// Event();
// }
// });
// builder.show();
// return true;
// }
// });
// }
// public void Event(){
// double total = 0;
// for (int i = 0; i < cart.size(); i++){
// int y = cart.get(i).getPrice();
// total += y;
// }
//
// DecimalFormat decimalFormat = new DecimalFormat("###,###,###");
// tvTotal.setText(decimalFormat.format(total)+ "Đ");
// }
@Override
public void onBackPressed() {
finish();
super.onBackPressed();
}
@Override
protected void onResume() {
if (cart.size() > 0){
cartAdapter.notifyDataSetChanged();
}
super.onResume();
}
// private void CheckData(){
// if(cart.size() <= 0){
// cartAdapter.notifyDataSetChanged();
//// tvNoti.setVisibility(View.VISIBLE);
// lvCart.setVisibility(View.INVISIBLE);
// }else {
// cartAdapter.notifyDataSetChanged();
//// tvNoti.setVisibility(View.INVISIBLE);
// lvCart.setVisibility(View.VISIBLE);
// }
// }
}
<file_sep>/app/src/main/java/model/ProductDetail.java
package model;
public class ProductDetail {
private String id, scr, scrRes, frCam, reCam, cpu, ram, rom, sim, mCard, battCap, os;
public ProductDetail() {
}
public ProductDetail(String id, String scr, String scrRes, String frCam, String reCam, String cpu, String ram, String rom, String sim, String mCard, String battCap, String os) {
this.id = id;
this.scr = scr;
this.scrRes = scrRes;
this.frCam = frCam;
this.reCam = reCam;
this.cpu = cpu;
this.ram = ram;
this.rom = rom;
this.sim = sim;
this.mCard = mCard;
this.battCap = battCap;
this.os = os;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getScr() {
return scr;
}
public void setScr(String scr) {
this.scr = scr;
}
public String getScrRes() {
return scrRes;
}
public void setScrRes(String scrRes) {
this.scrRes = scrRes;
}
public String getFrCam() {
return frCam;
}
public void setFrCam(String frCam) {
this.frCam = frCam;
}
public String getReCam() {
return reCam;
}
public void setReCam(String reCam) {
this.reCam = reCam;
}
public String getCpu() {
return cpu;
}
public void setCpu(String cpu) {
this.cpu = cpu;
}
public String getRam() {
return ram;
}
public void setRam(String ram) {
this.ram = ram;
}
public String getRom() {
return rom;
}
public void setRom(String rom) {
this.rom = rom;
}
public String getSim() {
return sim;
}
public void setSim(String sim) {
this.sim = sim;
}
public String getmCard() {
return mCard;
}
public void setmCard(String mCard) {
this.mCard = mCard;
}
public String getBattCap() {
return battCap;
}
public void setBattCap(String battCap) {
this.battCap = battCap;
}
public String getOs() {
return os;
}
public void setOs(String os) {
this.os = os;
}
}
<file_sep>/app/src/main/java/database/CartDB.java
package database;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* Created By JohnNguyen - Onesoft on 16/12/2018
*/
public class CartDB extends SQLiteOpenHelper {
public CartDB(Context context) {
super(context, "Cart", null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
String sqlCart = "CREATE TABLE Cart (ID text primary key," + "Name text, Price integer, Amount integer, Image text)";
db.execSQL(sqlCart);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
| 6d2d4c582f27d12cebb777732d3588c9a4edbffb | [
"Java"
] | 9 | Java | super0201/SaleFTP | 2f29089eae379e073803e2cfb441e8d4a686e8e4 | 7915c6233cd9cfe5a593498edc5e661a700f0e32 |
refs/heads/master | <repo_name>aarishramesh/spreadsheet-evaluator<file_sep>/src/com/spreadsheet/util/PostfixExprEval.java
package com.spreadsheet.util;
import java.util.Stack;
/**
* Post fix expression evaluation using stack
*
* Assumes the given post fix expression is valid
*
* Runtime complexity - O(N)
*
* Spacetime complexity - O(N) for additional stack
*
* @author polymath
*
*/
public class PostfixExprEval {
public static void main(String[] args) {
String expr = "7 --";
System.out.println(evaluate(expr));
}
public static float evaluate(String expr) {
String[] exprArr = expr.split(" ");
Stack<String> operStack = new Stack<String>();
for (String val : exprArr) {
if (isFloat(val)) {
operStack.add(val + "");
} else {
if (val.equals("++")) {
operStack.add((Float.parseFloat(operStack.pop()) + 1) + "");
} else if (val.equals("--")) {
operStack.add((Float.parseFloat(operStack.pop()) - 1) + "");
} else {
float num2 = Float.parseFloat(operStack.pop());
float num1 = Float.parseFloat(operStack.pop());
operStack.add((eval(num1, num2, val.charAt(0))) + "");
}
}
}
return Float.parseFloat(operStack.get(0));
}
private static float eval(float num1, float num2, char operator) {
if (operator == '+')
return num1 + num2;
if (operator == '-')
return num1 - num2;
if (operator == '*')
return num1 * num2;
if (operator == '/')
return num1 / num2;
return 0;
}
private static boolean isFloat(String val) {
try {
Float.parseFloat(val);
return true;
} catch (Exception ex) {
}
return false;
}
}
<file_sep>/src/com/spreadsheet/Workbook.java
package com.spreadsheet;
import java.util.ArrayList;
import java.util.List;
public class Workbook {
private List<Spreadsheet> spreadsheets = new ArrayList<Spreadsheet>();
public List<Spreadsheet> getSpreadsheets() {
return spreadsheets;
}
public void setSpreadsheets(List<Spreadsheet> spreadsheets) {
this.spreadsheets = spreadsheets;
}
}
| 6c67e6c71b55f28fbf85b76e8007bfe8a8ac79ce | [
"Java"
] | 2 | Java | aarishramesh/spreadsheet-evaluator | b0ab9cfb51f4533f5c3e277854461368e1afcfe9 | d4a31869acaa5ce8ca433c1ca70312ef63786d6e |
refs/heads/main | <file_sep>package com.ferjuarez.readerhackernews.repository
import com.ferjuarez.readerhackernews.data.get
import com.ferjuarez.readerhackernews.data.models.Article
import com.ferjuarez.readerhackernews.networking.ArticlesApiDataSource
import com.ferjuarez.readerhackernews.persistance.ArticleDao
import javax.inject.Inject
class ArticlesRepository @Inject constructor(
private val remoteDataSource: ArticlesApiDataSource,
private val localDataSource: ArticleDao
) {
fun getArticles() = get(
databaseQuery = { localDataSource.getAll() },
networkCall = { remoteDataSource.getArticles() },
saveCallResult = { localDataSource.insertAll(it.hits) }
)
suspend fun deleteArticle(article: Article) {
article.deleted = true
localDataSource.update(article)
}
}<file_sep>package com.ferjuarez.readerhackernews.ui.fragments
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.core.os.bundleOf
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.ferjuarez.readerhackernews.R
import com.ferjuarez.readerhackernews.data.models.Article
import com.ferjuarez.readerhackernews.databinding.FragmentHomeBinding
import com.ferjuarez.readerhackernews.networking.Resource
import com.ferjuarez.readerhackernews.ui.adapters.ArticleAdapter
import com.ferjuarez.readerhackernews.ui.viewmodels.HomeViewModel
import com.ferjuarez.readerhackernews.utils.SwipeToDeleteCallback
import com.ferjuarez.readerhackernews.utils.autoCleared
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class HomeFragment : Fragment(), ArticleAdapter.ArticleItemListener, SwipeRefreshLayout.OnRefreshListener {
private var binding: FragmentHomeBinding by autoCleared()
private val viewModel: HomeViewModel by viewModels()
private lateinit var adapter: ArticleAdapter
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentHomeBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setupRecyclerView()
initGetArticles()
}
private fun setupRecyclerView() {
adapter = ArticleAdapter(this)
binding.recyclerViewArticles.layoutManager = LinearLayoutManager(requireContext())
binding.recyclerViewArticles.adapter = adapter
binding.swipeRefreshLayout.setOnRefreshListener(this)
val swipeHandler = object : SwipeToDeleteCallback(requireContext()) {
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
viewModel.removeArticle(adapter.getItem(viewHolder.adapterPosition))
adapter.removeAt(viewHolder.adapterPosition)
}
}
val itemTouchHelper = ItemTouchHelper(swipeHandler)
itemTouchHelper.attachToRecyclerView(binding.recyclerViewArticles)
}
private fun initGetArticles() {
viewModel.getArticles().observe(viewLifecycleOwner, Observer {
when (it.status) {
Resource.Status.SUCCESS -> showNews(it)
Resource.Status.ERROR -> showError(it.message)
Resource.Status.LOADING -> showLoading()
}
})
}
private fun showLoading(){
binding.progressBar.visibility = View.VISIBLE
}
private fun showNews(resource: Resource<List<Article>>){
hideRefreshing()
binding.progressBar.visibility = View.GONE
if (!resource.data.isNullOrEmpty()) {
val ordered = ArrayList(resource.data)
ordered.sortByDescending{ article -> article.created_at_i}
adapter.setItems(ordered)
binding.textViewEmptyList.visibility = View.GONE
binding.recyclerViewArticles.visibility = View.VISIBLE
} else {
binding.textViewEmptyList.visibility = View.VISIBLE
binding.recyclerViewArticles.visibility = View.GONE
}
}
private fun showError(message: String?){
hideRefreshing()
Toast.makeText(requireContext(), message, Toast.LENGTH_SHORT).show()
}
override fun onArticleClicked(url: String?) {
if (!url.isNullOrEmpty()){
findNavController().navigate(
R.id.action_home_to_article,
bundleOf("url" to url)
)
} else {
Toast.makeText(requireContext(), getString(R.string.message_url_empty), Toast.LENGTH_SHORT).show()
}
}
override fun onRefresh() {
binding.swipeRefreshLayout.isRefreshing = true
initGetArticles()
}
private fun hideRefreshing(){
if (binding.swipeRefreshLayout.isRefreshing){
binding.swipeRefreshLayout.isRefreshing = false
}
}
}
<file_sep>package com.ferjuarez.readerhackernews.data.models
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName = "articles")
data class Article(
val title: String?,
val story_title: String?,
val author: String,
val created_at: String?,
val created_at_i: Long,
val url: String?,
var deleted: Boolean,
@PrimaryKey
val objectID: Int
)<file_sep>package com.ferjuarez.readerhackernews.data.models
data class ArticlesList(
val hits: List<Article>
)<file_sep>package com.ferjuarez.readerhackernews.di
import android.content.Context
import com.ferjuarez.readerhackernews.BuildConfig
import com.ferjuarez.readerhackernews.networking.ArticleService
import com.ferjuarez.readerhackernews.networking.ArticlesApiDataSource
import com.ferjuarez.readerhackernews.persistance.AppDatabase
import com.ferjuarez.readerhackernews.persistance.ArticleDao
import com.ferjuarez.readerhackernews.repository.ArticlesRepository
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.components.ApplicationComponent
import dagger.hilt.android.qualifiers.ApplicationContext
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import javax.inject.Singleton
@Module
@InstallIn(ApplicationComponent::class)
object AppModule {
@Singleton
@Provides
fun provideRetrofit() : Retrofit {
val httpClient = OkHttpClient.Builder()
if (BuildConfig.DEBUG) {
val loggingInterceptor = HttpLoggingInterceptor()
loggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
httpClient.addInterceptor(loggingInterceptor)
}
val gson = GsonBuilder()
.setLenient()
.create()
return Retrofit.Builder()
.baseUrl("https://hn.algolia.com/api/")
.addConverterFactory(GsonConverterFactory.create(gson))
.client(httpClient.build())
.build();
}
@Provides
fun provideGson(): Gson = GsonBuilder().create()
@Provides
fun provideArticleService(retrofit: Retrofit): ArticleService = retrofit.create(ArticleService::class.java)
@Singleton
@Provides
fun provideArticleRemoteDataSource(articleService: ArticleService) = ArticlesApiDataSource(articleService)
@Singleton
@Provides
fun provideDatabase(@ApplicationContext appContext: Context) = AppDatabase.getDatabase(appContext)
@Singleton
@Provides
fun provideArticleDao(db: AppDatabase) = db.articlesDao()
@Singleton
@Provides
fun provideRepository(remoteDataSource: ArticlesApiDataSource,
localDataSource: ArticleDao) =
ArticlesRepository(remoteDataSource, localDataSource)
}<file_sep>package com.ferjuarez.readerhackernews.networking
import javax.inject.Inject
class ArticlesApiDataSource @Inject constructor(private val articlesService: ArticleService): BaseDataSource() {
suspend fun getArticles() = getResult { articlesService.getAllArticles() }
}<file_sep># hacker_news_reader
A simple HackerNews Android reader
# Note
I added a tag parameters for HN api because for the tag "story" most data has completed info (anyway some urls are null)<file_sep>package com.ferjuarez.readerhackernews.ui.adapters
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.ferjuarez.readerhackernews.data.models.Article
import com.ferjuarez.readerhackernews.databinding.ArticleRowBinding
class ArticleAdapter(private val listener: ArticleItemListener) : RecyclerView.Adapter<ArticleViewHolder>() {
interface ArticleItemListener {
fun onArticleClicked(url: String?)
}
private val items = ArrayList<Article>()
fun setItems(items: ArrayList<Article>) {
this.items.clear()
this.items.addAll(items.filter { !it.deleted })
notifyDataSetChanged()
}
fun removeAt(position: Int) {
items.removeAt(position)
notifyItemRemoved(position)
}
fun getItem(position: Int): Article{
return items[position]
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ArticleViewHolder {
val binding: ArticleRowBinding = ArticleRowBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return ArticleViewHolder(binding, listener)
}
override fun getItemCount(): Int = items.size
override fun onBindViewHolder(holder: ArticleViewHolder, position: Int) = holder.bind(items[position])
}
<file_sep>package com.ferjuarez.readerhackernews.ui.viewmodels
import androidx.hilt.lifecycle.ViewModelInject
import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.ferjuarez.readerhackernews.data.models.Article
import com.ferjuarez.readerhackernews.networking.Resource
import com.ferjuarez.readerhackernews.repository.ArticlesRepository
import kotlinx.coroutines.launch
class HomeViewModel @ViewModelInject constructor(repository: ArticlesRepository) : ViewModel() {
private var repo = repository
fun getArticles(): LiveData<Resource<List<Article>>> {
return repo.getArticles()
}
fun removeArticle(item: Article) {
viewModelScope.launch {
repo.deleteArticle(item)
}
}
}
<file_sep>package com.ferjuarez.readerhackernews.ui.fragments
import android.annotation.SuppressLint
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.webkit.WebChromeClient
import android.webkit.WebView
import androidx.fragment.app.Fragment
import com.ferjuarez.readerhackernews.databinding.FragmentArticleBinding
import com.ferjuarez.readerhackernews.utils.autoCleared
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class ArticleFragment : Fragment() {
private var binding: FragmentArticleBinding by autoCleared()
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentArticleBinding.inflate(inflater, container, false)
return binding.root
}
@SuppressLint("SetJavaScriptEnabled")
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
arguments?.getString("url")?.let {
binding.webView.webChromeClient = object : WebChromeClient() {
override fun onProgressChanged(view: WebView, progress: Int) {
if (isAdded){
if (progress == 100) binding.webViewProgressBar.visibility = View.INVISIBLE
}
}
}
binding.webView.loadUrl(it)
}
}
}
<file_sep>package com.ferjuarez.readerhackernews.ui.adapters
import android.annotation.SuppressLint
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import com.ferjuarez.readerhackernews.data.models.Article
import com.ferjuarez.readerhackernews.databinding.ArticleRowBinding
import org.ocpsoft.prettytime.PrettyTime
import java.util.*
class ArticleViewHolder(private val itemBinding: ArticleRowBinding, private val listener: ArticleAdapter.ArticleItemListener) : RecyclerView.ViewHolder(itemBinding.root),
View.OnClickListener {
private lateinit var article: Article
init {
itemBinding.root.setOnClickListener(this)
}
@SuppressLint("SetTextI18n")
fun bind(article: Article) {
this.article = article
itemBinding.textViewTitle.text = article.title ?: article.story_title
val time = PrettyTime().format(Date(article.created_at_i*1000))
itemBinding.textViewCreation.text = """by ${article.author.capitalize()} - $time"""
}
override fun onClick(v: View?) {
listener.onArticleClicked(article.url)
}
}<file_sep>package com.ferjuarez.readerhackernews.networking
import com.ferjuarez.readerhackernews.data.models.ArticlesList
import retrofit2.Response
import retrofit2.http.GET
interface ArticleService {
@GET("v1/search_by_date?query=android&tags=story")
suspend fun getAllArticles() : Response<ArticlesList>
}<file_sep>package com.ferjuarez.readerhackernews.persistance
import androidx.lifecycle.LiveData
import androidx.room.*
import com.ferjuarez.readerhackernews.data.models.Article
@Dao
interface ArticleDao {
@Query("SELECT * FROM articles")
fun getAll() : LiveData<List<Article>>
@Query("SELECT * FROM articles WHERE objectID = :id")
fun getArticle(id: Int): LiveData<Article>
@Insert(onConflict = OnConflictStrategy.IGNORE)
suspend fun insertAll(articles: List<Article>)
@Insert(onConflict = OnConflictStrategy.IGNORE)
suspend fun insert(article: Article)
@Update()
suspend fun update(article: Article)
} | 6b85d1f837226a9ebe19d3db00a0f57f6e1bd3df | [
"Markdown",
"Kotlin"
] | 13 | Kotlin | ferjuarezlp/hacker_news_reader | 0fb777c3c716d16651c28d5cc6d9047a50596f7d | c6aa167c4b9fb41bffea82ec57009de540a12902 |
refs/heads/master | <repo_name>electron0/getkickcount<file_sep>/GetKickCount/GKC.cpp
#include "stdafx.h"
#include "GKC.h"
#include "stdafx.h"
#include "resource.h"
#include "GetKickCount.h"
#include "KickStats.h"
#include <time.h>
#include <Windows.h>
#include <winhttp.h>
bool PutToFile(wchar_t *path, wchar_t *format, long value)
{
FILE *f = NULL;
int iResult = _wfopen_s(&f, path, L"wt");
if (iResult == 0 && f != NULL)
{
fwprintf(f, format, value);
fclose(f);
return true;
}
else
MessageBox(NULL, L"Can't write to disc", L"error", MB_OK);
return false;
}
bool PutToFile(wchar_t *path, wchar_t *format, float value)
{
FILE *f = NULL;
int iResult = _wfopen_s(&f, path, L"wt");
if (iResult == 0 && f != NULL)
{
fwprintf(f, format, value);
fclose(f);
return true;
}
else
MessageBox(NULL, L"Can't write to disc", L"error", MB_OK);
return false;
}
GKC::GKC()
{
}
GKC::~GKC()
{
if (m_kickStats)
{
m_kickStats->Disconnect();
delete m_kickStats;
m_kickStats = NULL;
}
}
void GKC::InitGUI(HWND parent)
{
HWND hwndTemp = CreateWindowEx(WS_EX_RIGHT, L"STATIC", L"Betrag:",
WS_CHILDWINDOW | WS_VISIBLE | WS_CLIPSIBLINGS,
20, 20, 80, 20,
parent, (HMENU)IDS_COUNTNUMBER, 0, 0);
SendMessage(hwndTemp, WM_SETFONT, (WPARAM)GetStockObject(DEFAULT_GUI_FONT), TRUE);
wndPledged = CreateWindowEx(WS_EX_RIGHT | WS_EX_CLIENTEDGE, L"EDIT", L"#####",
WS_CHILDWINDOW | WS_VISIBLE | WS_CLIPSIBLINGS,
110, 20, 80, 20,
parent, (HMENU)IDS_COUNTNUMBER, 0, 0);
SendMessage(wndPledged, WM_SETFONT, (WPARAM)GetStockObject(DEFAULT_GUI_FONT), TRUE);
hwndTemp = CreateWindowEx(WS_EX_RIGHT, L"STATIC", L"Spender:",
WS_CHILDWINDOW | WS_VISIBLE | WS_CLIPSIBLINGS,
20, 50, 80, 20,
parent, (HMENU)IDS_COUNTNUMBER, 0, 0);
SendMessage(hwndTemp, WM_SETFONT, (WPARAM)GetStockObject(DEFAULT_GUI_FONT), TRUE);
wndBackers = CreateWindowEx(WS_EX_RIGHT | WS_EX_CLIENTEDGE, L"EDIT", L"#####",
WS_CHILDWINDOW | WS_VISIBLE | WS_CLIPSIBLINGS,
110, 50, 80, 20,
parent, (HMENU)IDS_COUNTNUMBER, 0, 0);
SendMessage(wndBackers, WM_SETFONT, (WPARAM)GetStockObject(DEFAULT_GUI_FONT), TRUE);
hwndTemp = CreateWindowEx(WS_EX_RIGHT, L"STATIC", L"Kommentare:",
WS_CHILDWINDOW | WS_VISIBLE | WS_CLIPSIBLINGS,
20, 80, 80, 20,
parent, (HMENU)IDS_COUNTNUMBER, 0, 0);
SendMessage(hwndTemp, WM_SETFONT, (WPARAM)GetStockObject(DEFAULT_GUI_FONT), TRUE);
wndComments = CreateWindowEx(WS_EX_RIGHT | WS_EX_CLIENTEDGE, L"EDIT", L"#####",
WS_CHILDWINDOW | WS_VISIBLE | WS_CLIPSIBLINGS,
110, 80, 80, 20,
parent, (HMENU)IDS_COUNTNUMBER, 0, 0);
SendMessage(wndComments, WM_SETFONT, (WPARAM)GetStockObject(DEFAULT_GUI_FONT), TRUE);
}
bool GKC::ConnectToKick()
{
m_kickStats = new KickStats;
if ( m_kickStats && config && config->IsSuccess() &&
m_kickStats->SetUrl(config->GetUrl()) &&
//m_kickStats->SetUrl(std::wstring(L"https://127.0.0.1/kick.php")) &&
m_kickStats->Connect()
)
return true;
else
MessageBox(NULL, L"Can't connect to kickstarter.com", L"error", MB_OK);
return false;
}
void GKC::DisconnectToKick()
{
if (m_kickStats)
{
m_kickStats->Disconnect();
delete m_kickStats;
m_kickStats = NULL;
}
}
void CALLBACK GKC::TimerTick(HWND hwnd, UINT message, UINT idTimer, DWORD dwTime)
{
if (!gkc->GetStats()->SendRequest())
return;
ProjectStats *stats = gkc->GetStats()->GetProjectStats();
if (stats)
{
#ifdef _DEBUG
srand(time(NULL));
stats->nBackers = rand();
stats->nComments = rand() * 7;
stats->fPledged = float(rand()) * 3.1415;
#endif
gkc->SetBackers(stats->nBackers);
PutToFile(L"backers.txt", L"%d", stats->nBackers);
gkc->SetComments(stats->nComments);
PutToFile(L"comments.txt", L"%d", stats->nComments);
gkc->SetPledged(stats->fPledged);
PutToFile(L"pledged.txt", L"%.2f", stats->fPledged);
delete stats;
}
}
void GKC::SetBackers(long amount)
{
TCHAR sAmount[20];
swprintf(sAmount, sizeof(sAmount), L"%d", amount);
SetWindowText(wndBackers, sAmount);
}
void GKC::SetComments(long amount)
{
TCHAR sAmount[20];
swprintf(sAmount, sizeof(sAmount), L"%d", amount);
SetWindowText(wndComments, sAmount);
}
void GKC::SetPledged(float amount)
{
TCHAR sAmount[20];
swprintf(sAmount, sizeof(sAmount), L"%.2f", amount);
SetWindowText(wndPledged, sAmount);
}
KickStats *GKC::GetStats()
{
return m_kickStats;
}<file_sep>/README.md
Ein kleines Programm, dass die Anzahl der Backer, den gespendeten Betrag und die Anzahl der Kommentare in 3 seperate txt-Dateien ablegt.
Gedacht als Textelement für die streaming Programme OBS und OBS-Studio.<file_sep>/GetKickCount/Config.cpp
#include "stdafx.h"
#include "Config.h"
#include "GetKickCount.h"
Config::Config()
{
m_bLoadSuccess = false;
m_wsUrl = std::wstring();
m_nRequestInterval = 1000;
}
Config::~Config()
{
}
void jsonNodeComplete(JSONNODE *root, void *identifier)
{
Config *cfg = (Config *)identifier;
wchar_t logstr[1024];
if (root == NULL)
return;
KickLog(L"config JSON Knoten korrekt");
// ------------ URL ------------
JSONNODE *n_url = json_get_nocase(root, "project_url");
if (n_url == NULL && json_type(n_url) != JSON_STRING)
return;
const char *url = json_as_string(n_url);
const size_t cSize = strlen(url) + 1;
wchar_t* wc = new wchar_t[cSize];
mbstowcs(wc, url, cSize);
cfg->SetUrl(wc);
swprintf(logstr, L"url: %s", wc);
KickLog(logstr);
// ------------ request interval ------------
JSONNODE *n_req = json_get_nocase(root, "requesttime");
if (n_req == NULL && json_type(n_req) != JSON_NUMBER)
return;
unsigned long nReq = json_as_int(n_req);
cfg->SetRequestInterval(nReq);
swprintf(logstr, L"request interval: %d", nReq);
KickLog(logstr);
}
void jsonNodeError(void *identifier)
{
//MessageBox(NULL, L"Can't read JSON node", L"error", MB_OK);
KickLog(L"config-Datei ist kein gueltiges JSON-Format");
return;
}
bool Config::ParseFile(const wchar_t * wsPath)
{
JSONSTREAM *stream = json_new_stream(jsonNodeComplete, jsonNodeError, this);
FILE *f = NULL;
char buffer[256];
memset(buffer, 0, sizeof(buffer));
int iResult = _wfopen_s(&f, wsPath, L"rt");
if (iResult == 0 && f != NULL)
{
while (buffer != NULL && !feof(f))
{
fgets(buffer, sizeof(buffer), f);
RemoveComments(buffer);
json_stream_push(stream, buffer);
}
fclose(f);
}
// TODO: file not found
json_delete_stream(stream);
if (m_wsUrl != std::wstring())
{
m_bLoadSuccess = true;
return true;
}
return false;
}
bool Config::IsSuccess()
{
return m_bLoadSuccess;
}
std::wstring Config::GetUrl()
{
return m_wsUrl;
}
bool Config::SetUrl(std::wstring url)
{
m_wsUrl = url;
return true;
}
unsigned long Config::GetRequestInterval()
{
return m_nRequestInterval;
}
bool Config::SetRequestInterval(unsigned long req)
{
m_nRequestInterval = req;
return true;
}
char *Config::RemoveComments(char *line)
{
char *pc = line, *mls = NULL;
int nbQuotes = 0, runs = 0;
static bool bInMultiLineComment = false;
while (*pc != NULL)
{
++runs;
if (*pc == '"') // in case: foo "bar
if (runs >= 2 && *(pc - 1) == '\\') // in case: foo \"bar
{
if (runs >= 3 && *(pc - 2) == '\\') // in case: foo \\"bar
++nbQuotes;
}
else
++nbQuotes;
if (!(nbQuotes % 2))
{
if (*pc == '/' && *(pc + 1) != NULL && *(pc + 1) == '/')
{
*pc = NULL; // end the string
return line;
}
if (*pc == '/' && *(pc + 1) != NULL && *(pc + 1) == '*')
{
mls = pc; // multi line start point
bInMultiLineComment = true;
}
if (bInMultiLineComment && *pc == '*' && *(pc + 1) != NULL && *(pc + 1) == '/')
{
if (mls)
{
memmove(mls, pc + 2, strlen(pc) + 2);
pc = mls;
}
else
{
//multi line comment from other line
memmove(line, pc + 2, strlen(pc) + 2);
pc = line;
}
mls = NULL; // multi line start point
bInMultiLineComment = false;
}
}
++pc;
}
if (bInMultiLineComment)
if (mls)
*mls = NULL; // end the string
else
*line = NULL;
return line;
}<file_sep>/GetKickCount/KickStats.cpp
#include "stdafx.h"
#include "KickStats.h"
#include "libjson.h"
#include "GetKickCount.h"
KickStats::KickStats() :
m_hSession(NULL),
m_hConnect(NULL),
m_hRequest(NULL),
m_wsHost(L""),
m_wsPath(L""),
m_sContent("")
{
}
KickStats::~KickStats()
{
}
bool KickStats::Connect()
{
// User-Agent: Firefox 44.0
m_hSession = WinHttpOpen(L"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:44.0) Gecko/20100101 Firefox/44.0",
WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,
WINHTTP_NO_PROXY_NAME,
WINHTTP_NO_PROXY_BYPASS, 0);
if (!m_hSession)
return false;
m_hConnect = WinHttpConnect(m_hSession, m_wsHost.c_str(),
INTERNET_DEFAULT_HTTPS_PORT, 0);
if (!m_hConnect)
return false;
m_hRequest = WinHttpOpenRequest(m_hConnect, L"GET", m_wsPath.c_str(),
NULL,
WINHTTP_NO_REFERER,
WINHTTP_DEFAULT_ACCEPT_TYPES,
WINHTTP_FLAG_SECURE | WINHTTP_FLAG_REFRESH);
if (m_hRequest)
return true;
return false;
}
bool KickStats::Disconnect()
{
if (m_hRequest)
WinHttpCloseHandle(m_hRequest);
if (m_hConnect)
WinHttpCloseHandle(m_hConnect);
if (m_hSession)
WinHttpCloseHandle(m_hSession);
return false;
}
bool KickStats::Connected()
{
return (m_hRequest && m_hConnect && m_hSession);
}
bool KickStats::SendRequest()
{
if (!Connected())
return false;
BOOL bResults = FALSE;
DWORD dwSize = 0;
DWORD dwDownloaded = 0;
LPSTR pszOutBuffer;
TCHAR statusCode[8];
DWORD statusCodeLen;
int nStatusCode = -1;
TCHAR contentLength[8];
DWORD contentLengthLen;
long nContentlength = -1;
int runs = 0;
m_sContent.clear();
m_sContent.resize(0);
bResults = WinHttpSendRequest(m_hRequest,
WINHTTP_NO_ADDITIONAL_HEADERS, 0,
WINHTTP_NO_REQUEST_DATA, 0,
0, 0);
int err = GetLastError();
if (bResults)
bResults = WinHttpReceiveResponse(m_hRequest, NULL);
statusCodeLen = sizeof(statusCode);
WinHttpQueryHeaders(m_hRequest, WINHTTP_QUERY_STATUS_CODE, WINHTTP_HEADER_NAME_BY_INDEX, &statusCode, &statusCodeLen, WINHTTP_NO_HEADER_INDEX);
nStatusCode = _wtol(statusCode);
contentLengthLen = sizeof(contentLength);
WinHttpQueryHeaders(m_hRequest, WINHTTP_QUERY_CONTENT_LENGTH, WINHTTP_HEADER_NAME_BY_INDEX, &contentLength, &contentLengthLen, WINHTTP_NO_HEADER_INDEX);
nContentlength = _wtol(contentLength);
// KickLog(L"==============");
if (bResults && nStatusCode == 200)
{
do
{
// Check for available data.
dwSize = 0;
dwDownloaded = 0;
++runs;
if (runs > 1)
{
wchar_t str[1024];
swprintf(str, L"run: %d", runs);
// KickLog(str);
}
if (!WinHttpQueryDataAvailable(m_hRequest, &dwSize))
MessageBox(NULL, L"WinHttpQueryDataAvailable failed", L"error", 1);
// Allocate space for the buffer.
pszOutBuffer = new char[dwSize + 1];
if (!pszOutBuffer)
{
KickLog(L"KickStats::SendRequest: Out of memory");
return false;
}
else
{
// Read the data.
ZeroMemory(pszOutBuffer, dwSize + 1);
if (!WinHttpReadData(m_hRequest, (LPVOID)pszOutBuffer, dwSize, &dwDownloaded))
{
KickLog(L"KickStats::SendRequest: WinHttpReadData failed");
delete[] pszOutBuffer;
return false;
}
else
{
//wchar_t str[1024];
//swprintf(str, L"down: %d - size: %d - length: %d", dwDownloaded, dwSize, nContentlength);
//KickLog(str);
//KickLog(pszOutBuffer);
m_sContent.append(pszOutBuffer);
}
// Free the memory allocated to the buffer.
delete[] pszOutBuffer;
}
} while (dwSize > 0);
}
// KickLog(m_sContent);
if (!bResults)
MessageBox(NULL, L"WinHttpReceiveResponse failed", L"error", MB_OK);
return true;
}
ProjectStats *KickStats::GetProjectStats()
{
JSONNODE *n = json_parse(m_sContent.c_str());
if (n == NULL)
{
KickLog(L"Invalid JSON Node");
return NULL;
}
// {"project":{"id":375955643, "state_changed_at" : 1452521021, "state" : "live", "backers_count" : 239, "pledged" : "5307.0", "comments_count" : 6}}
JSONNODE *n_pro = json_get_nocase(n, "project");
if (n_pro == NULL && json_type(n_pro) != JSON_NODE)
{
KickLog(L"Invalid JSON structure (project not found)");
return NULL;
}
JSONNODE *n_backers = json_get_nocase(n_pro, "backers_count");
long backers = -1;
if (n_backers == NULL)
{
KickLog(L"Invalid JSON structure (backers_count not found)");
return NULL;
}
if (json_type(n_backers) == JSON_NUMBER)
{
backers = json_as_int(n_backers);
}
JSONNODE *n_comments = json_get_nocase(n_pro, "comments_count");
long comments = -1;
if (n_comments == NULL)
{
KickLog(L"Invalid JSON structure (comments_count not found)");
return NULL;
}
if (json_type(n_comments) == JSON_NUMBER)
{
comments = json_as_int(n_comments);
}
JSONNODE *n_pledged = json_get_nocase(n_pro, "pledged");
double pledged = -2.0;
if (n_pledged == NULL)
{
KickLog(L"Invalid JSON structure (pledged not found)");
return NULL;
}
if (json_type(n_pledged) == JSON_STRING)
{
pledged = atof(json_as_string(n_pledged));
}
ProjectStats *stats = new ProjectStats;
stats->nBackers = backers;
stats->nComments = comments;
stats->fPledged = pledged;
return stats;
}
bool KickStats::SetUrl(std::wstring url)
{
wchar_t szHostName[MAX_PATH] = L"";
wchar_t szURLPath[MAX_PATH * 4] = L"";
URL_COMPONENTS urlComp;
memset(&urlComp, 0, sizeof(urlComp));
urlComp.dwStructSize = sizeof(urlComp);
//urlComp.nScheme = INTERNET_SCHEME_HTTPS;
urlComp.lpszHostName = szHostName;
urlComp.dwHostNameLength = MAX_PATH;
urlComp.lpszUrlPath = szURLPath;
urlComp.dwUrlPathLength = MAX_PATH * 4;
//urlComp.dwSchemeLength = 1;
if (!WinHttpCrackUrl(url.c_str(), url.size(), 0, &urlComp))
{
// DWORD err = GetLastError();
MessageBox(NULL, L"not a valid URL", L"error", MB_OK);
KickLog(L"not a valid URL");
return false;
}
m_wsHost = std::wstring(szHostName);
m_wsPath = std::wstring(szURLPath);
wchar_t logstr[1024];
swprintf(logstr, L"host: %s; url-Path: %s", m_wsHost.c_str(), m_wsPath.c_str());
KickLog(logstr);
return true;
}<file_sep>/GetKickCount/KickStats.h
#ifndef KICK_STATS_H
#define KICK_STATS_H
#include <winhttp.h>
#include <string>
struct ProjectStats
{
long nBackers;
long nComments;
float fPledged;
};
#pragma once
class KickStats
{
HINTERNET m_hSession;
HINTERNET m_hConnect;
HINTERNET m_hRequest;
std::wstring m_wsHost;
std::wstring m_wsPath;
std::string m_sContent;
public:
KickStats();
~KickStats();
bool Connect();
bool Disconnect();
bool Connected();
bool SendRequest();
ProjectStats *GetProjectStats();
bool SetUrl(std::wstring url);
};
#endif // KICK_STATS_H<file_sep>/GetKickCount/GKC.h
#ifndef GET_KICK_COUNT_H
#define GET_KICK_COUNT_H
#include "KickStats.h"
#pragma once
bool PutToFile(wchar_t *path, wchar_t *format, long value);
bool PutToFile(wchar_t *path, wchar_t *format, float value);
class GKC
{
public:
GKC();
~GKC();
void InitGUI(HWND parent);
bool ConnectToKick();
void DisconnectToKick();
static void CALLBACK TimerTick(HWND hwnd, UINT message, UINT idTimer, DWORD dwTime);
void SetBackers(long amount);
void SetComments(long amount);
void SetPledged(float amount);
KickStats *GetStats();
private:
HWND wndBackers;
HWND wndComments;
HWND wndPledged;
KickStats *m_kickStats;
};
#endif // GET_KICK_COUNT_H<file_sep>/GetKickCount/GetKickCount.cpp
// GetKickCount.cpp : Definiert den Einstiegspunkt für die Anwendung.
//
#include "stdafx.h"
#include "GetKickCount.h"
#ifndef UNICODE
#define UNICODE
#endif
#include <windows.h>
#define CONFIG_FILENAME L"config.json"
GKC* gkc;
Config* config;
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE, PWSTR pCmdLine, int nCmdShow)
{
gkc = new GKC;
config = new Config;
// Register the window class.
const wchar_t CLASS_NAME[] = L"GetKickCount";
WNDCLASS wc = {};
wc.lpfnWndProc = WindowProc;
wc.hInstance = hInstance;
wc.lpszClassName = CLASS_NAME;
RegisterClass(&wc);
// Create the window.
HWND hwnd = CreateWindowEx(
0, // Optional window styles.
CLASS_NAME, // Window class
L"GetKickCount - Holt den Spendenstand von Kickstarter", // Window text
WS_OVERLAPPED | WS_SYSMENU & ~WS_SIZEBOX, // Window style
// Size and position
CW_USEDEFAULT, CW_USEDEFAULT, 250, 150,
NULL, // Parent window
NULL, // Menu
hInstance, // Instance handle
NULL // Additional application data
);
if (hwnd == NULL)
return 1;
ShowWindow(hwnd, nCmdShow);
// Run the message loop.
MSG msg = {};
while (GetMessage(&msg, NULL, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
delete config;
delete gkc;
return 0;
}
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch (uMsg)
{
case WM_CREATE:
{
KickLog(L"***************************************");
gkc->InitGUI(hwnd);
KickLog(L"Lade config-Datei: " CONFIG_FILENAME);
if (!config->ParseFile(CONFIG_FILENAME))
{
MessageBox(hwnd, L"konnte config-Datei nicht lesen", L"Fehler", MB_OK);
KickLog(L"konnte config-Datei nicht lesen");
LRESULT res = SendMessage(hwnd, WM_CLOSE, NULL, NULL);
return 0;
}
KickLog(L"config-Datei geladen");
KickLog(L"Stelle Verbindung zum Kickstarter projekt her");
if (gkc->ConnectToKick() && config->IsSuccess())
{
KickLog(L"Verbindung hergestellt; starte Abfrage-Interval");
UINT uResult = SetTimer(hwnd, // handle to main window
IDT_HTTPREQUEST, // timer identifier
config->GetRequestInterval(), // interval (in ms)
(TIMERPROC)&GKC::TimerTick); // timer callback
GKC::TimerTick(hwnd, 0, IDT_HTTPREQUEST, 0);
}
else
{
MessageBox(hwnd, L"Konnte keine Verbindung herstellen", L"Fehler", MB_OK);
KickLog(L"Konnte keine Verbindung herstellen");
LRESULT res = SendMessage(hwnd, WM_CLOSE, NULL, NULL);
}
return 0;
}
case WM_DESTROY:
{
KillTimer(hwnd, IDT_HTTPREQUEST);
gkc->DisconnectToKick();
KickLog(L"Programm beendet und Verbindung getrennt");
PostQuitMessage(0);
return 0;
}
case WM_PAINT:
{
PAINTSTRUCT ps;
HDC hdc = BeginPaint(hwnd, &ps);
FillRect(hdc, &ps.rcPaint, (HBRUSH)(COLOR_WINDOW));
EndPaint(hwnd, &ps);
return 0;
}
}
return DefWindowProc(hwnd, uMsg, wParam, lParam);
}
bool KickLog(std::wstring msg)
{
FILE *f = NULL;
int iResult = _wfopen_s(&f, L"debug.log", L"at");
if (iResult == 0 && f != NULL)
{
std::string str(msg.begin(), msg.end());
str.append("\r\n");
fwrite(str.c_str(), str.size(), 1, f);
fclose(f);
return true;
}
else
MessageBox(NULL, L"Can't write in log file to disc", L"error", MB_OK);
return false;
}
bool KickLog(std::string msg)
{
FILE *f = NULL;
int iResult = _wfopen_s(&f, L"debug.log", L"at");
if (iResult == 0 && f != NULL)
{
msg.append("\r\n");
fwrite(msg.c_str(), msg.size(), 1, f);
fclose(f);
return true;
}
else
MessageBox(NULL, L"Can't write in log file to disc", L"error", MB_OK);
return false;
}<file_sep>/GetKickCount/GetKickCount.h
#pragma once
#include "resource.h"
#include "GKC.h"
#include "Config.h"
#include <string>
bool KickLog(std::wstring msg);
bool KickLog(std::string msg);
extern GKC* gkc;
extern Config* config;
<file_sep>/GetKickCount/Config.h
#ifndef CONFIG_H
#define CONFIG_H
#include "libjson.h"
#pragma once
class Config
{
private:
std::wstring m_wsUrl;
unsigned long m_nRequestInterval;
bool m_bLoadSuccess;
public:
Config();
~Config();
bool ParseFile(const wchar_t * wsPath);
bool IsSuccess();
std::wstring GetUrl();
bool SetUrl(std::wstring url);
unsigned long GetRequestInterval();
bool SetRequestInterval(unsigned long req);
private:
char *RemoveComments(char *line);
};
#endif // CONFIG_H | f3b4036f098c68ab6fddcebb620adae1539abbde | [
"Markdown",
"C++"
] | 9 | C++ | electron0/getkickcount | 46fd0d2476e12d7876871b2a0741b8acb18a56ea | 5113e5652d91bbdf0c0de372734d1535958fadfe |
refs/heads/master | <repo_name>marvinmosa/DelegationActivityTemplate<file_sep>/app/src/main/java/com/ki/dat/delegationactivitytemplate/delegation/NavigationDrawerActivity.java
package com.ki.dat.delegationactivitytemplate.delegation;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.Toolbar;
import android.view.View;
import com.ki.dat.delegationactivitytemplate.R;
import com.ki.dat.delegationactivitytemplate.base.BaseDelegationActivity;
import butterknife.BindView;
import butterknife.OnClick;
public class NavigationDrawerActivity extends BaseDelegationActivity<
NavigationDrawerContract.NavigationDrawerView,
NavigationDrawerPresenter,
NavigationDrawerDelegate>
implements NavigationDrawerContract.NavigationDrawerView {
@BindView(R.id.toolbar)
protected Toolbar mToolbar;
public static Intent newIntent(Context context) {
return new Intent(context, NavigationDrawerActivity.class);
}
@Override
protected NavigationDrawerDelegate instantiateDelegateInstance() {
return new NavigationDrawerDelegate();
}
@NonNull
@Override
protected NavigationDrawerPresenter getPresenterInstance() {
return new NavigationDrawerPresenter();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_navigation_drawer);
setSupportActionBar(mToolbar);
super.onCreate(savedInstanceState);
}
@Override
public NavigationDrawerActivity getActivity() {
return this;
}
@OnClick(R.id.fab)
public void onFabClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
@Override
public void onBackPressed() {
if (!mDelegate.closeDrawer()) {
super.onBackPressed();
}
}
@Override
public void onSomethingDone() {
Snackbar.make(getContentView(), "Done", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
@Override
public void openCamera() {
Snackbar.make(getContentView(), "open camera", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
}
<file_sep>/app/src/main/java/com/ki/dat/delegationactivitytemplate/base/BaseView.java
package com.ki.dat.delegationactivitytemplate.base;
import android.content.Context;
import android.support.annotation.StringRes;
import android.view.View;
/**
* Created by ihor on 05.04.17.
*/
public interface BaseView {
void showProgress();
void hideProgress();
View getContentView();
}
<file_sep>/app/src/main/java/com/ki/dat/delegationactivitytemplate/delegation/NavigationDrawerContract.java
package com.ki.dat.delegationactivitytemplate.delegation;
import com.ki.dat.delegationactivitytemplate.base.BasePresenter;
import com.ki.dat.delegationactivitytemplate.base.BaseView;
/**
* Created by ihor on 17.04.17.
*/
public class NavigationDrawerContract {
interface NavigationDrawerView extends BaseView {
void openCamera();
void onSomethingDone();
NavigationDrawerActivity getActivity();
}
interface NavigationDrawerPresenter extends BasePresenter<NavigationDrawerView> {
void doSomething();
}
}
<file_sep>/app/src/main/java/com/ki/dat/delegationactivitytemplate/delegation/NavigationDrawerPresenter.java
package com.ki.dat.delegationactivitytemplate.delegation;
import com.ki.dat.delegationactivitytemplate.base.BasePresenterImpl;
/**
* Created by ihor on 17.04.17.
*/
public class NavigationDrawerPresenter
extends BasePresenterImpl<NavigationDrawerContract.NavigationDrawerView>
implements NavigationDrawerContract.NavigationDrawerPresenter {
@Override
public void doSomething() {
mView.onSomethingDone();
}
}
<file_sep>/app/src/main/java/com/ki/dat/delegationactivitytemplate/delegation/NavigationDrawerDelegate.java
package com.ki.dat.delegationactivitytemplate.delegation;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import com.ki.dat.delegationactivitytemplate.R;
import com.ki.dat.delegationactivitytemplate.base.BaseActivityDelegate;
import butterknife.BindView;
/**
* Created by ihor on 17.04.17.
*/
public class NavigationDrawerDelegate extends BaseActivityDelegate<
NavigationDrawerContract.NavigationDrawerView,
NavigationDrawerPresenter> implements NavigationView.OnNavigationItemSelectedListener {
@BindView(R.id.drawer_layout)
protected DrawerLayout mDrawerLayout;
@BindView(R.id.toolbar)
protected Toolbar mToolBar;
@BindView(R.id.nav_view)
protected NavigationView mNavigationView;
@Override
public void onCreate(NavigationDrawerPresenter presenter) {
super.onCreate(presenter);
configureDrawer();
}
private void configureDrawer() {
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
mPresenter.getView().getActivity(),
mDrawerLayout,
mToolBar,
R.string.navigation_drawer_open,
R.string.navigation_drawer_close);
mPresenter.getView().getActivity().getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mDrawerLayout.addDrawerListener(toggle);
toggle.syncState();
mNavigationView.setNavigationItemSelectedListener(this);
}
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.nav_camera:
mPresenter.getView().openCamera();
break;
case R.id.nav_gallery:
break;
case R.id.nav_slideshow:
break;
case R.id.nav_manage:
break;
case R.id.nav_share:
break;
case R.id.nav_send:
mPresenter.doSomething();
break;
}
closeDrawer();
return true;
}
/***
*
* @return true if Drawer was opened.
*/
public boolean closeDrawer() {
if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
mDrawerLayout.closeDrawer(GravityCompat.START);
return true;
} else {
return false;
}
}
}
<file_sep>/app/src/main/java/com/ki/dat/delegationactivitytemplate/simple/SimpleActivity.java
package com.ki.dat.delegationactivitytemplate.simple;
import android.os.Bundle;
import android.support.annotation.NonNull;
import com.ki.dat.delegationactivitytemplate.R;
import com.ki.dat.delegationactivitytemplate.base.BaseActivity;
import com.ki.dat.delegationactivitytemplate.delegation.NavigationDrawerActivity;
import butterknife.OnClick;
public class SimpleActivity extends BaseActivity<SimpleContract.SimplePresenter>
implements SimpleContract.SimpleView {
@NonNull
@Override
protected SimpleContract.SimplePresenter getPresenterInstance() {
return new SimplePresenter();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_simple);
}
@OnClick(R.id.btnGo)
public void onBtnGoClick() {
mPresenter.doSomething();
}
@Override
public void onSomethingDone() {
startActivity(NavigationDrawerActivity.newIntent(this));
}
}
<file_sep>/README.md
# Clean Your Activity Using Delegation Pattern

## Read article [here](https://medium.com/@kucherenkoigor/clean-your-activity-using-delegation-pattern-fcaafd82336d)
Whenever we add Navigation Drawer to our app, we face a lot of boilerplate code
that pollutes the Activity. It’ll further detract from main logic and can lead
to over-proliferation of class. Side menu is a good design pattern for navigation,
and most large apps use it. That’s why I decided to create template project based on
MVP to solve this problem.
This project contains base classes for MVP architecture and you can use it as template.
```java
public abstract class BaseActivity<P extends BasePresenter> extends AppCompatActivity
implements BaseView {
private Unbinder mUnBinder;
private ProgressDialog mProgressDialog = null;
protected @NonNull abstract P getPresenterInstance();
protected P mPresenter;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mPresenter = getPresenterInstance();
mPresenter.attachView(this);
}
@Override
public void setContentView(@LayoutRes int layoutResID) {
super.setContentView(layoutResID);
mUnBinder = ButterKnife.bind(this);
}
@Override
protected void onDestroy() {
mPresenter.detachView();
mUnBinder.unbind();
super.onDestroy();
}
@Override
public View getContentView() {
return getWindow().getDecorView();
}
}
```
## Base Presenter:
```java
public interface BasePresenter<V extends BaseView> {
void attachView(V view);
void detachView();
}
```
## Helpful simple implementation of base Presenter:
```java
public class BasePresenterImpl<V extends BaseView> implements BasePresenter<V> {
protected V mView;
@Override
public void attachView(V view) {
mView = view;
}
@Override
public void detachView() {
mView = null;
}
public V getView() {
return mView;
}
}
```
## Base view:
```java
public interface BaseView {
void showProgress();
void hideProgress();
View getContentView();
}
```

You can check out all these classes in [base package](https://github.com/KucherenkoIhor/DelegationActivityTemplate/tree/master/app/src/main/java/com/ki/dat/delegationactivitytemplate/base) of the template.
It demonstrates a basic Model‑View‑Presenter (MVP) architecture and provides a foundation on which the sample is built.
I also recommend you visit [Android Architecture Blueprints](https://github.com/googlesamples/android-architecture) for more details.
## Delegation pattern
To reduce the amount of code in Activity, we will use the [Delegation pattern](https://en.wikipedia.org/wiki/Delegation_pattern).
The point is that an instance handles a request by delegating to a second object (the delegate).
Also, we have to keep in mind the fact that we deal with Android and adapt our Delegate class to Activity Lifecycle.

This project contains base classes which will handle main challenges:
```java
public abstract class BaseDelegationActivity<
V extends BaseView,
P extends BasePresenterImpl<V>,
D extends BaseActivityDelegate<V, P>>
extends BaseActivity<P> {
protected D mDelegate;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mDelegate = instantiateDelegateInstance();
mDelegate.onCreate(mPresenter);
}
protected abstract D instantiateDelegateInstance();
@Override
protected void onDestroy() {
mDelegate.onDestroy();
super.onDestroy();
}
}
```
And base class of delegates:
```java
public abstract class BaseActivityDelegate<
V extends BaseView,
P extends BasePresenterImpl<V>> {
private Unbinder mUnBinder = null;
protected P mPresenter;
public void onCreate(P presenter) {
mPresenter = presenter;
mUnBinder = ButterKnife.bind(this, mPresenter.getView().getContentView());
}
public void onDestroy() {
mUnBinder.unbind();
}
}
```
Inheritors of this [BaseDelegationActivity](https://github.com/KucherenkoIhor/DelegationActivityTemplate/blob/master/app/src/main/java/com/ki/dat/delegationactivitytemplate/base/BaseDelegationActivity.java) will
delegate tasks to heirs of [BaseActivityDelegate](https://github.com/KucherenkoIhor/DelegationActivityTemplate/blob/master/app/src/main/java/com/ki/dat/delegationactivitytemplate/base/BaseActivityDelegate.java). Let’s take a look at the result:
```java
public class NavigationDrawerDelegate extends BaseActivityDelegate<
NavigationDrawerContract.NavigationDrawerView,
NavigationDrawerPresenter> implements NavigationView.OnNavigationItemSelectedListener {
@BindView(R.id.drawer_layout)
protected DrawerLayout mDrawerLayout;
@BindView(R.id.toolbar)
protected Toolbar mToolBar;
@BindView(R.id.nav_view)
protected NavigationView mNavigationView;
@Override
public void onCreate(NavigationDrawerPresenter presenter) {
super.onCreate(presenter);
configureDrawer();
}
private void configureDrawer() {
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
mPresenter.getView().getActivity(),
mDrawerLayout,
mToolBar,
R.string.navigation_drawer_open,
R.string.navigation_drawer_close);
mPresenter.getView().getActivity().getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mDrawerLayout.addDrawerListener(toggle);
toggle.syncState();
mNavigationView.setNavigationItemSelectedListener(this);
}
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.nav_camera:
mPresenter.getView().openCamera();
break;
case R.id.nav_gallery:
break;
case R.id.nav_slideshow:
break;
case R.id.nav_manage:
break;
case R.id.nav_share:
break;
case R.id.nav_send:
mPresenter.doSomething();
break;
}
closeDrawer();
return true;
}
public boolean closeDrawer() {
if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
mDrawerLayout.closeDrawer(GravityCompat.START);
return true;
} else {
return false;
}
}
}
```
As we can see, all logic of Navigation Drawer is contained in [NavigationDrawerDelegate](https://github.com/KucherenkoIhor/DelegationActivityTemplate/blob/master/app/src/main/java/com/ki/dat/delegationactivitytemplate/delegation/NavigationDrawerDelegate.java).
```java
public class NavigationDrawerActivity extends BaseDelegationActivity<
NavigationDrawerContract.NavigationDrawerView,
NavigationDrawerPresenter,
NavigationDrawerDelegate>
implements NavigationDrawerContract.NavigationDrawerView {
@BindView(R.id.toolbar)
protected Toolbar mToolbar;
public static Intent newIntent(Context context) {
return new Intent(context, NavigationDrawerActivity.class);
}
@Override
protected NavigationDrawerDelegate instantiateDelegateInstance() {
return new NavigationDrawerDelegate();
}
@NonNull
@Override
protected NavigationDrawerPresenter getPresenterInstance() {
return new NavigationDrawerPresenter();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_navigation_drawer);
setSupportActionBar(mToolbar);
super.onCreate(savedInstanceState);
}
@Override
public NavigationDrawerActivity getActivity() {
return this;
}
@OnClick(R.id.fab)
public void onFabClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
@Override
public void onBackPressed() {
if (!mDelegate.closeDrawer()) {
super.onBackPressed();
}
}
@Override
public void onSomethingDone() {
Snackbar.make(getContentView(), "Done", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
@Override
public void openCamera() {
Snackbar.make(getContentView(), "open camera", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
}
```
We’ve succeeded and our Activity is cleaner.
## Conclusions
Activity is a sample of [God object anti-pattern](https://en.wikipedia.org/wiki/God_object), that’s why the problem of over-proliferation is actual.
We considered using Delegation pattern to move a part of code into a separate class and created template project.
You can check out [article](https://medium.com/@kucherenkoigor/clean-your-activity-using-delegation-pattern-fcaafd82336d) for more details.
<file_sep>/app/src/main/java/com/ki/dat/delegationactivitytemplate/base/BasePresenterImpl.java
package com.ki.dat.delegationactivitytemplate.base;
/**
* Created by ihor on 05.04.17.
*/
public class BasePresenterImpl<V extends BaseView> implements BasePresenter<V> {
protected V mView;
@Override
public void attachView(V view) {
mView = view;
}
@Override
public void detachView() {
mView = null;
}
public V getView() {
return mView;
}
}
| 99131e7bdb6353a1a023cb48a8091791dded6456 | [
"Markdown",
"Java"
] | 8 | Java | marvinmosa/DelegationActivityTemplate | 2b3486c57c0a7682ec7f61792fe8152ab9b16b37 | 1003da39f32eb44c8eb163845f3e14cbc353de4f |
refs/heads/master | <file_sep>package tech.wetech.admin.aspect;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 忽略日志切面
* @author cjbi
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
public @interface LogIgnore {
}
<file_sep>DROP TABLE IF EXISTS `sys_permission`;
CREATE TABLE `sys_permission` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '编号',
`name` varchar(100) DEFAULT NULL COMMENT '名称',
`type` tinyint(1) NOT NULL COMMENT '资源类型(1.菜单 2.按钮或文本块)',
`parent_id` bigint(20) DEFAULT NULL COMMENT '父编号',
`parent_ids` varchar(100) DEFAULT NULL COMMENT '父编号列表',
`permission` varchar(100) DEFAULT NULL COMMENT '权限字符串',
`icon` varchar(100) DEFAULT NULL COMMENT '图标',
`sort` int(11) NOT NULL DEFAULT '0' COMMENT '排序',
`status` tinyint(1) DEFAULT '1' COMMENT '是否有效',
`config` json DEFAULT NULL COMMENT '权限配置',
PRIMARY KEY (`id`),
KEY `idx_sys_permission_parent_id` (`parent_id`),
KEY `idx_sys_permission_parent_ids` (`parent_ids`)
) COMMENT='资源表';
DROP TABLE IF EXISTS `sys_role`;
CREATE TABLE `sys_role` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '编号',
`role` varchar(100) NOT NULL COMMENT '唯一标识',
`name` varchar(100) DEFAULT NULL COMMENT '角色名称',
`description` varchar(100) DEFAULT NULL COMMENT '描述',
`status` tinyint(1) DEFAULT '1' COMMENT '状态 1.正常 0.禁用',
`permission_ids` varchar(500) DEFAULT NULL COMMENT '资源编号列表',
PRIMARY KEY (`id`),
KEY `idx_sys_role_resource_ids` (`permission_ids`)
) COMMENT='角色表';
DROP TABLE IF EXISTS `sys_user`;
CREATE TABLE `sys_user` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '编号',
`username` varchar(100) DEFAULT NULL COMMENT '用户名',
`password` varchar(100) DEFAULT NULL COMMENT '密码',
`salt` varchar(100) DEFAULT NULL COMMENT '盐值',
`role_ids` varchar(100) DEFAULT NULL COMMENT '角色列表',
`locked` tinyint(1) DEFAULT '0' COMMENT '是否锁定',
PRIMARY KEY (`id`),
UNIQUE KEY `idx_sys_user_username` (`username`)
) COMMENT='用户表';
<file_sep>import { axios } from '@/utils/request'
const api = {
user: '/user',
lockUser: '/user/{id}/lock',
role: '/role',
service: '/service',
permissionNoPager: '/permission/no-pager',
permission: '/permission',
permissionTree: '/permission/tree',
orgTree: '/org/tree'
}
export default api
export function deletePermission (parameter) {
return axios({
url: api.permission + '/' + parameter,
method: 'delete'
})
}
export function updatePermission (data) {
return axios({
url: api.permission,
method: 'put',
data: data
})
}
export function createPermission (data) {
return axios({
url: api.permission,
method: 'post',
data: data
})
}
export function deleteRole (parameter) {
return axios({
method: 'DELETE',
url: api.role + '/' + parameter
})
}
export function saveRole (data) {
return axios({
url: api.role,
method: data.id ? 'put' : 'post',
data: data
})
}
export function getUserList (parameter) {
return axios({
url: api.user,
method: 'get',
params: parameter
})
}
export function deleteUser (data) {
return axios({
method: 'delete',
url: api.user,
data: data
})
}
export function lockUser (parameter) {
return axios({
url: api.lockUser.replace('{id}', parameter.id),
method: 'put',
params: { locked: parameter.locked }
})
}
export function getPermissionTree () {
return axios({
url: api.permissionTree,
method: 'get'
})
}
export function getRoleList (parameter) {
return axios({
url: api.role,
method: 'get',
params: parameter
})
}
export function createUser (parameter) {
return axios({
url: api.user,
method: 'post',
data: parameter
})
}
export function updateUser (parameter) {
return axios({
url: api.user,
method: 'put',
data: parameter
})
}
// 以下方法准备删除
export function getServiceList (parameter) {
return axios({
url: api.service,
method: 'get',
params: parameter
})
}
export function getPermissions (parameter) {
return axios({
url: api.permissionNoPager,
method: 'get',
params: parameter
})
}
export function getOrgTree (parameter) {
return axios({
url: api.orgTree,
method: 'get',
params: parameter
})
}
// id == 0 add post
// id != 0 update put
export function saveService (parameter) {
return axios({
url: api.service,
method: parameter.id === 0 ? 'post' : 'put',
data: parameter
})
}
<file_sep>package tech.wetech.admin.model.dto;
import lombok.Data;
import java.util.List;
/**
* @author cjbi
*/
@Data
public class UserPageDTO {
private Long id; //编号
private String username; //用户名
private List<Long> roleIds; //拥有的角色列表
private List<String> roleNames;//
private Integer locked;
}
<file_sep>package tech.wetech.admin.model.dto;
import lombok.Data;
import org.springframework.util.ObjectUtils;
import tech.wetech.admin.model.entity.Role;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@Data
public class RoleDTO {
private Long id;
/**
* 角色标识 程序中判断使用,如"admin"
*/
private String role;
/**
* 角色名称
*/
private String name;
/**
* 角色描述,UI界面显示使用
*/
private String description;
/**
* 状态,如果不可用将不会添加给用户。1.正常 0.禁用
*/
private Integer status;
/**
* 拥有的权限
*/
private List<Long> permissionIds;
public RoleDTO() {
}
public RoleDTO(Role role) {
this.id = role.getId();
this.role = role.getRole();
this.name = role.getName();
this.description = role.getDescription();
this.status = role.getStatus();
this.permissionIds = getPermissionIds(role.getPermissionIds());
}
private List<Long> getPermissionIds(String permissionIdStr) {
if (ObjectUtils.isEmpty(permissionIdStr)) {
return Collections.emptyList();
}
return Stream.of(permissionIdStr.split(","))
.map(Long::valueOf)
.collect(Collectors.toList());
}
}
<file_sep>package tech.wetech.admin.exception;
import tech.wetech.admin.model.ResultStatus;
public class BusinessException extends RuntimeException {
ResultStatus status;
public BusinessException(ResultStatus status) {
//不生成栈追踪信息
super(status.getMessage(), null, false, false);
this.status = status;
}
public BusinessException(ResultStatus status, String message) {
super(message);
this.status = status;
}
public ResultStatus getStatus() {
return status;
}
public void setStatus(ResultStatus status) {
this.status = status;
}
}
<file_sep>#!/bin/sh
# 运行环境
env=@spring.application.proflies@
# jar包名称
jar_name=@build.finalName@.jar
# 根据启动的jar包名称关闭旧的进程实例
pid=`ps -ef | grep ${jar_name} | grep -v grep | awk '{print $2}'`
echo "Wetech-Admin服务旧应用进程id:$pid"
if [ -n "$pid" ]
then
echo "关闭Wetech-Admin服务旧进程:$pid"
kill -9 $pid
fi
echo "启动Wetech-Admin服务..."
nohup java -jar -Dspring.profiles.active=${env} ${jar_name} >/dev/null 2>&1 &
<file_sep>package tech.wetech.admin.mapper;
import tech.wetech.admin.model.entity.Role;
import tech.wetech.mybatis.mapper.BaseMapper;
public interface RoleMapper extends BaseMapper<Role> {
}<file_sep>package tech.wetech.admin.model.query;
import lombok.Data;
/**
* @author cjbi
*/
@Data
public class UserQuery extends PageQuery {
private Long id;
private String username;
private Integer locked;
}
<file_sep>package tech.wetech.admin.exception;
import org.apache.shiro.authz.UnauthorizedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import tech.wetech.admin.model.Result;
import tech.wetech.admin.model.enumeration.CommonResultStatus;
import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
/**
* @author <EMAIL>
*/
@RestControllerAdvice
public class GlobalExceptionHandler {
private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
@ExceptionHandler({Throwable.class})
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public Result<Object> handleThrowable(HttpServletRequest request, Throwable e) {
log.error("execute method exception error.url is {}", request.getRequestURI(), e);
return Result.failure(CommonResultStatus.INTERNAL_SERVER_ERROR, e);
}
/**
* 服务异常
*
* @param request
* @param e
* @return
*/
@ExceptionHandler({BusinessException.class})
public Result handleBusinessException(HttpServletRequest request, BusinessException e) {
log.error("execute method exception error.url is {}", request.getRequestURI(), e);
return Result.failure(e.getStatus(), e.getMessage());
}
/**
* 参数校验异常
* <p>使用 @Valid 注解,方法上加@RequestBody注解修饰的方法未校验通过会抛MethodArgumentNotValidException,否则抛BindException。
* <p>使用 @Validated 注解,未校验通过会抛ConstraintViolationException
* <p>关于 @Valid和@Validated注解的区别:
* <p> 这两个注解都是实现JSR-303规范,不同的是@Validated是spring的注解支持groups以及可以用在spring mvc处理器的方法级别入参验证 ,@Valid是Javax提供的注解,可以支持多个bean嵌套验证。
*
* @param request
* @param e
* @return
*/
@ExceptionHandler({MethodArgumentNotValidException.class, BindException.class, ConstraintViolationException.class})
public Result handleJSR303Exception(HttpServletRequest request, Exception e) {
log.error("execute method exception error.url is {}", request.getRequestURI(), e);
BindingResult br = null;
Result result = Result.builder()
.success(false)
.code(CommonResultStatus.PARAM_ERROR.getCode())
.message(CommonResultStatus.PARAM_ERROR.getMessage())
.build();
if (e instanceof BindException) {
br = ((BindException) e).getBindingResult();
}
if (e instanceof MethodArgumentNotValidException) {
br = ((MethodArgumentNotValidException) e).getBindingResult();
}
if (br != null) {
result.setResult(
br.getFieldErrors().stream()
.collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage, (oldValue, newValue) -> oldValue.concat(",").concat(newValue)))
);
result.setMessage(
br.getFieldErrors().stream()
.map(f -> f.getField().concat(f.getDefaultMessage()))
.collect(Collectors.joining(","))
);
return result;
}
if (e instanceof ConstraintViolationException) {
Set<ConstraintViolation<?>> constraintViolations = ((ConstraintViolationException) e).getConstraintViolations();
result.setResult(
constraintViolations.stream().collect(Collectors.toMap(ConstraintViolation::getPropertyPath, ConstraintViolation::getMessage))
);
result.setMessage(e.getMessage());
}
return result;
}
/**
* 捕获sql语法异常,原生的Message不适合中文环境
*
* @param request
* @param e
* @return
*/
@ExceptionHandler(BadSqlGrammarException.class)
public Result handleSQLSyntaxErrorException(HttpServletRequest request, BadSqlGrammarException e) {
String message = e.getSQLException().getMessage();
Map<String, String> regexMap = new HashMap<>();
//数据表不存在
regexMap.put("Table '(\\S+)' doesn't exist", "表($1)不存在");
//唯一键
regexMap.put("Duplicate entry '(\\S+)' for key '(\\S+)'", "$1已经存在了");
for (Map.Entry<String, String> entry : regexMap.entrySet()) {
if (message.matches(entry.getKey())) {
message = message.replaceAll(entry.getKey(), entry.getValue());
break;
}
}
log.warn(">>> Handle SQLSyntaxErrorException, url is {}, message is {}", request.getRequestURI(), message);
return Result.failure(CommonResultStatus.INTERNAL_SERVER_ERROR, message);
}
@ExceptionHandler(UnauthorizedException.class)
public Result handleUnauthorizedException(HttpServletRequest request, UnauthorizedException e) {
Map<String, String> regexMap = new HashMap<>();
regexMap.put("Subject does not have permission (\\S+)", "操作失败,用户不存在权限$1,请检查权限配置");
String message = e.getMessage();
for (Map.Entry<String, String> entry : regexMap.entrySet()) {
if (message.matches(entry.getKey())) {
message = message.replaceAll(entry.getKey(), entry.getValue());
break;
}
}
log.error("execute method exception error.url is {}", request.getRequestURI(), e);
return Result.failure(CommonResultStatus.UNAUTHORIZED, message);
}
}
<file_sep>package tech.wetech.admin.utils;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/**
* 日期工具
*
* @author zhaohuihua
* @version V1.0 2015年10月23日
*/
public class DateUtil {
/** 一秒有多少毫秒 **/
public static final long RATE_SECOND = 1000;
/** 一分钟有多少毫秒 **/
public static final long RATE_MINUTE = 60 * RATE_SECOND;
/** 一小时有多少毫秒 **/
public static final long RATE_HOUR = 60 * RATE_MINUTE;
/** 一天有多少毫秒 **/
public static final long RATE_DAY = 24 * RATE_HOUR;
public static Date addYear(Date date, int year) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.YEAR, year);
return calendar.getTime();
}
public static Date addMonth(Date date, int month) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.MONTH, month);
return calendar.getTime();
}
public static Date addDay(Date date, int day) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.DAY_OF_MONTH, day);
return calendar.getTime();
}
public static Date addMinute(Date date, int minute) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.MINUTE, minute);
return calendar.getTime();
}
public static Date addSecond(Date date, int second) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.SECOND, second);
return calendar.getTime();
}
public static Date addMillisecond(Date date, int millisecond) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.MILLISECOND, millisecond);
return calendar.getTime();
}
public static Date setYear(Date date, int year) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.YEAR, year);
return calendar.getTime();
}
public static Date setMonth(Date date, int month) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.MONTH, month);
return calendar.getTime();
}
public static Date setDay(Date date, int day) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.DAY_OF_MONTH, day);
return calendar.getTime();
}
public static Date setMinute(Date date, int minute) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.MINUTE, minute);
return calendar.getTime();
}
public static Date setSecond(Date date, int second) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.SECOND, second);
return calendar.getTime();
}
public static Date setMillisecond(Date date, int millisecond) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.set(Calendar.MILLISECOND, millisecond);
return calendar.getTime();
}
/**
* 转换为标准的字符串, 如 2012-08-08 20:00:00.000
*
* @param date 待处理的日期
* @return 日期字符串
*/
public static String toNormativeString(Date date) {
if (date == null) {
return null;
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
return sdf.format(date);
}
/**
* 转换为日期字符串, 如 2012-08-08
*
* @param date 待处理的日期
* @return 日期字符串
*/
public static String toDateString(Date date) {
if (date == null) {
return null;
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
return sdf.format(date);
}
/**
* 转换为时间字符串, 如 20:00:00.000
*
* @param date 待处理的日期
* @return 时间字符串
*/
public static String toTimeString(Date date) {
if (date == null) {
return null;
}
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
return sdf.format(date);
}
/**
* 转换为日期加时间字符串, 如 2012-08-08 20:00:00
*
* @param date 待处理的日期
* @return 日期字符串
*/
public static String toDateTimeString(Date date) {
if (date == null) {
return null;
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return sdf.format(date);
}
/**
* 转换为第1时间<br>
* Calendar.YEAR=当年第1时间, Calendar.MONTH=当月第1时间, Calendar.DAY_OF_MONTH=当日第1时间, ...<br>
* 如 toFirstTime(2016-08-08 20:30:40.500, Calendar.YEAR) --- 2016-01-01 00:00:00.000<br>
* 如 toFirstTime(2016-08-08 20:30:40.500, Calendar.MONTH) --- 2016-08-01 00:00:00.000<br>
* 如 toFirstTime(2016-08-08 20:30:40.500, Calendar.DAY_OF_MONTH) --- 2016-08-08 00:00:00.000<br>
* 如 toFirstTime(2016-08-08 20:30:40.500, Calendar.HOUR_OF_DAY) --- 2016-08-08 20:00:00.000<br>
* 如 toFirstTime(2016-08-08 20:30:40.500, Calendar.MINUTE) --- 2016-08-08 20:30:00.000<br>
* 如 toFirstTime(2016-08-08 20:30:40.500, Calendar.SECOND) --- 2016-08-08 20:30:40.000<br>
*
* @param date 待处理的日期
* @param field 类型
* @return 第1时间
*/
public static Date toFirstTime(Date date, int field) {
if (date == null) {
return null;
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
switch (field) {
case Calendar.YEAR:
calendar.set(Calendar.MONTH, Calendar.JANUARY);
case Calendar.MONTH:
calendar.set(Calendar.DAY_OF_MONTH, 1);
case Calendar.DAY_OF_MONTH:
calendar.set(Calendar.HOUR_OF_DAY, 0);
case Calendar.HOUR_OF_DAY:
calendar.set(Calendar.MINUTE, 0);
case Calendar.MINUTE:
calendar.set(Calendar.SECOND, 0);
case Calendar.SECOND:
calendar.set(Calendar.MILLISECOND, 0);
}
return calendar.getTime();
}
/**
* 转换为最后时间<br>
* Calendar.YEAR=当年最后时间, Calendar.MONTH=当月最后时间, Calendar.DAY_OF_MONTH=当日最后时间, ...<br>
* 如 toLastTime(2016-08-08 20:30:40.500, Calendar.YEAR) --- 2016-12-31 23:59:59.999<br>
* 如 toLastTime(2016-08-08 20:30:40.500, Calendar.MONTH) --- 2016-08-31 23:59:59.999<br>
* 如 toLastTime(2016-08-08 20:30:40.500, Calendar.DAY_OF_MONTH) --- 2016-08-08 23:59:59.999<br>
* 如 toLastTime(2016-08-08 20:30:40.500, Calendar.HOUR_OF_DAY) --- 2016-08-08 20:59:59.999<br>
* 如 toLastTime(2016-08-08 20:30:40.500, Calendar.MINUTE) --- 2016-08-08 20:30:59.999<br>
* 如 toLastTime(2016-08-08 20:30:40.500, Calendar.SECOND) --- 2016-08-08 20:30:40.999<br>
*
* @param date 待处理的日期
* @param field 类型
* @return 最后时间
*/
public static Date toLastTime(Date date, int field) {
if (date == null) {
return null;
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
switch (field) {
case Calendar.YEAR:
calendar.set(Calendar.MONTH, Calendar.DECEMBER);
case Calendar.MONTH:
// 下月1日的前一天
calendar.add(Calendar.MONTH, 1);
calendar.set(Calendar.DAY_OF_MONTH, 1);
calendar.add(Calendar.DAY_OF_MONTH, -1);
case Calendar.DAY_OF_MONTH:
calendar.set(Calendar.HOUR_OF_DAY, 23);
case Calendar.HOUR_OF_DAY:
calendar.set(Calendar.MINUTE, 59);
case Calendar.MINUTE:
calendar.set(Calendar.SECOND, 59);
case Calendar.SECOND:
calendar.set(Calendar.MILLISECOND, 999);
}
return calendar.getTime();
}
/**
* 转换为结束时间, 即设置时分秒为00:00:00
*
* @param date 待处理的日期
* @return 结束时间
*/
public static Date toStartTime(Date date) {
if (date == null) {
return null;
}
return toFirstTime(date, Calendar.DAY_OF_MONTH);
}
/**
* 转换为结束时间, 即设置时分秒为23:59:59
*
* @param date 待处理的日期
* @return 结束时间
*/
public static Date toEndTime(Date date) {
if (date == null) {
return null;
}
return toLastTime(date, Calendar.DAY_OF_MONTH);
}
/**
* 获取当天的毫秒数
*
* @param date
* @return
*/
public static long getMillisOfDay(Date date) {
Date start = toStartTime(date);
return date.getTime() - start.getTime();
}
}
<file_sep>package tech.wetech.admin.model.dto;
/**
* @author cjbi
*/
public class TreeDTO {
private Long id;
private Long pId;
private String name;
private boolean parent;
private Object obj;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Object getObj() {
return obj;
}
public void setObj(Object obj) {
this.obj = obj;
}
public TreeDTO() {
}
public Long getPId() {
return pId;
}
public void setPId(Long pId) {
this.pId = pId;
}
public boolean getIsParent() {
return parent;
}
public void setParent(boolean parent) {
this.parent = parent;
}
public TreeDTO(Long id, Long pId, String name, boolean parent, Object obj) {
super();
this.id = id;
this.pId = pId;
this.name = name;
this.parent = parent;
this.obj = obj;
}
}
<file_sep>package tech.wetech.admin.model;
import java.util.HashMap;
import java.util.Map;
/**
* @author cjbi
*/
public class SystemContextHolder {
private static final ThreadLocal<Map<String, Object>> store = ThreadLocal.withInitial(() -> new HashMap<>(16));
public static void putThreadCache(String key, Object value) {
store.get().put(key, value);
}
public static <T> T getThreadCache(String key) {
return (T) store.get().get(key);
}
}
<file_sep>package tech.wetech.admin.mapper;
import tech.wetech.admin.model.entity.User;
import tech.wetech.mybatis.mapper.BaseMapper;
public interface UserMapper extends BaseMapper<User> {
/**
* 获取单个用户
* @param username
* @return
*/
default User selectByUsername(String username) {
return this.createCriteria().andEqualTo(User::getUsername, username).selectOne();
}
}
<file_sep>package tech.wetech.admin.model.vo;
import lombok.Data;
import javax.validation.constraints.NotEmpty;
@Data
public class UserBatchDeleteVO {
@NotEmpty
private Long[] ids;
}
<file_sep>#!/bin/sh
# jar包名称
jar_name=@build.finalName@.jar
# 根据启动的jar包名称关闭旧的进程实例
pid=`ps -ef | grep ${jar_name} | grep -v grep | awk '{print $2}'`
echo "Wetech-Admin服务旧应用进程id:$pid"
if [ -n "$pid" ]
then
echo "关闭Wetech-Admin服务旧进程:$pid"
kill -9 $pid
fi<file_sep>package tech.wetech.admin.model;
/**
* @author cjbi
*/
public interface ResultStatus {
/**
* 错误码
*/
int getCode();
/**
* 错误信息
*/
String getMessage();
}
<file_sep>package tech.wetech.admin.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tech.wetech.admin.mapper.RoleMapper;
import tech.wetech.admin.model.dto.RoleDTO;
import tech.wetech.admin.model.entity.Role;
import tech.wetech.admin.service.PermissionService;
import tech.wetech.admin.service.RoleService;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@Service
public class RoleServiceImpl implements RoleService {
@Autowired
private RoleMapper roleMapper;
@Autowired
private PermissionService permissionService;
@Override
public Set<String> queryRoles(Long... roleIds) {
Set<String> roles = new HashSet<>();
List<Role> roleList = roleMapper.createCriteria().andIn(Role::getId, Arrays.asList(roleIds)).selectList();
for (Role role : roleList) {
roles.add(role.getRole());
}
return roles;
}
@Override
public Map<String, String> queryRoleNames(Long... roleIds) {
Map<String, String> roleMap = new HashMap<>();
List<Role> roleList = roleMapper.createCriteria().andIn(Role::getId, Arrays.asList(roleIds)).selectList();
for (Role role : roleList) {
roleMap.put(role.getRole(), role.getName());
}
return roleMap;
}
@Override
public Set<String> queryPermissions(Long... roleIds) {
return permissionService.queryPermissionTree(
roleMapper.createCriteria().andIn(Role::getId, Arrays.asList(roleIds)).selectList().stream().flatMap(r ->
Stream.of(r.getPermissionIds().split(","))
).map(Long::valueOf).collect(Collectors.toSet()).toArray(new Long[]{})
);
}
@Override
public List<RoleDTO> queryAllRole() {
return roleMapper.selectAll().stream()
.map(RoleDTO::new)
.collect(Collectors.toList());
}
@Override
public void create(Role role) {
roleMapper.insertSelective(role);
}
@Override
public void updateNotNull(Role role) {
roleMapper.updateByPrimaryKeySelective(role);
}
@Override
public void deleteById(Long id) {
roleMapper.deleteByPrimaryKey(id);
}
}
<file_sep>package tech.wetech.admin.controller;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import tech.wetech.admin.model.Result;
import tech.wetech.admin.model.dto.RoleDTO;
import tech.wetech.admin.model.entity.Role;
import tech.wetech.admin.service.RoleService;
import java.util.List;
/**
* @author cjbi
*/
@RestController
@RequestMapping("role")
public class RoleController {
@Autowired
private RoleService roleService;
@GetMapping
@RequiresPermissions("role:view")
public Result<List<RoleDTO>> queryRoleList() {
return Result.success(roleService.queryAllRole());
}
@RequiresPermissions("role:create")
@PostMapping
public Result create(@RequestBody Role role) {
roleService.create(role);
return Result.success();
}
@RequiresPermissions("role:update")
@PutMapping
public Result update(@RequestBody Role role) {
roleService.updateNotNull(role);
return Result.success();
}
@RequiresPermissions("role:delete")
@DeleteMapping("{id}")
public Result deleteByIds(@PathVariable("id") Long id) {
roleService.deleteById(id);
return Result.success();
}
}
| 01076e972905b2a1e63f3e1669e4026508a162cc | [
"JavaScript",
"Java",
"Shell",
"SQL"
] | 19 | Java | feixiangsnail/wetech-admin | 9ae38b7e72d34202b8f8ce7780951f7913c7af9a | 27ec6f8da3343fc16a9abdc8e317eaf6ea1bc984 |
refs/heads/master | <file_sep>var helpers = require('../lib/helpers');
var config = require('../lib/config');
exports.construct = function () {
// This method adds support for a `--coffee` flag
this.option('tmp');
this.option('component');
};
exports.questions = function () {
var prompts = [];
if (!this.name) {
prompts = prompts.concat([
{
type: 'input',
name: 'bpName',
message: 'Define a blueprint name:',
validate: function (answer) {
var done = this.async();
if (!answer) {
done("Please add a blueprint name!");
return;
}
done(true);
}
}
])
}
if (!this.options.component && !this.options.block) {
prompts = prompts.concat([
{
name: 'bpType',
type: 'list',
message: 'What type is your blueprint?',
choices: [
{
name: 'block',
value: 'b-',
checked: false
},
{
name: 'component',
value: 'c-',
checked: true
},
{
name: 'something else',
value: 'global',
checked: false
}
]
}
]);
}
prompts = prompts.concat([
{
type: 'confirm',
name: 'bpWithWrapWith',
message: 'Do you want use this blueprint as wrap-writh template?',
default: false
},
{
type: 'confirm',
name: 'bpWithJs',
message: 'Do you want to add JavaScript to this blueprint?',
default: true
}
]);
return prompts;
};
exports.save = function (props) {
this.name = this.name ? this.name : props.bpName;
this.filename = helpers.hyphenate(this.name);
this.bpName = helpers.toCamelCase(this.name);
this.bpWrapWith = props.bpWithWrapWith;
this.bpJsName = helpers.capitalizeFirstLetter(this.bpName);
this.bpWithJs = props.bpWithJs || false;
if (this.options.component || this.options.block) {
if (this.options.component) {
this.bpType = 'c-';
} else if (this.options.block) {
this.bpType = 'b-';
} else {
this.bpType = '';
}
} else {
this.bpType = props.bpType === 'global' ? '' : props.bpType;
}
};
exports.setup = function () {
this.dataFile = 'data/bp.json.ejs';
this.tplFile = 'partials/bp.hbs.ejs';
this.styleFile = 'scss/bp.scss.ejs';
this.usageFile = 'usage/README.md.ejs';
this.jsFile = 'js/bp.js.ejs';
};
exports.scaffold = function () {
var path = this.options.tmp ? 'tmp/' : '';
this.template(this.dataFile, path + this.filename + '/data/' + this.filename + '-bp.json');
this.template(this.tplFile, path + this.filename + '/partials/' + this.bpType + this.filename + '.hbs');
this.template(this.styleFile, path + this.filename + '/scss/_' + this.bpType + this.filename + '.scss');
this.template(this.usageFile, path + this.filename + '/usage/README.md');
if (this.bpWithJs) {
this.template(this.jsFile, path + this.filename + '/js/' + this.filename + '.js');
}
};<file_sep>'use strict';
var chalk = require('chalk');
var config = require('./config');
/**
* Helper utilities
*/
var helpers = module.exports;
helpers.welcome = '' +
chalk.cyan('\n.##.....##.########....###....##.....##..######.') +
chalk.cyan('\n.##.....##.##.........##.##...###...###.##....##') +
chalk.cyan('\n.##.....##.##........##...##..####.####.##......') +
chalk.cyan('\n.##.....##.######...##.....##.##.###.##..######.') +
chalk.cyan('\n..##...##..##.......#########.##.....##.......##') +
chalk.cyan('\n...##.##...##.......##.....##.##.....##.##....##') +
chalk.cyan('\n....###....########.##.....##.##.....##..######.') +
chalk.cyan('\n................................................') +
chalk.cyan('\n...............http://veams.org.................') +
chalk.yellow('\n\n Welcome ladies and gentlemen!') +
chalk.yellow('\nWant to make your life easy???') +
chalk.red('\n\nBe sure you have installed') +
chalk.red('\n* bower: http://bower.io/') +
chalk.red('\n* grunt: http://gruntjs.com\n\n');
helpers.cleanupPath = function (path) {
if (path !== '') {
return path.replace(/\/?$/, '/');
}
};
helpers.definePaths = function () {
this.generatorHelperPath = '../../' + config.paths.appPath + config.paths.helperPath;
this.generatorGruntPath = '../../' + config.paths.appPath + config.paths.gruntPath;
this.generatorGulpPath = '../../' + config.paths.appPath + config.paths.gulpPath;
this.generatorSrcPath = '../../' + config.paths.appPath + config.paths.srcPath;
this.helperPath = this.helperPath || config.paths.helperPath;
this.gruntPath = this.gruntPath || config.paths.gruntPath;
this.gulpPath = this.gulpPath || config.paths.gulpPath;
this.srcPath = this.srcPath || config.paths.srcPath;
this.helperPath = helpers.cleanupPath(this.helperPath);
this.gruntPath = helpers.cleanupPath(this.gruntPath);
this.gulpPath = helpers.cleanupPath(this.gulpPath);
this.srcPath = helpers.cleanupPath(this.srcPath);
};
helpers.toCamelCase = function (str) {
// Lower cases the string
return str.toLowerCase()
// Replaces any - or _ characters with a space
.replace(/[-_]+/g, ' ')
// Removes any non alphanumeric characters
.replace(/[^\w\s]/g, '')
// Uppercases the first character in each group immediately following a space
// (delimited by spaces)
.replace(/ (.)/g, function ($1) {
return $1.toUpperCase();
})
// Removes spaces
.replace(/ /g, '');
};
helpers.hyphenate = function (str) {
return str.replace(/\s/g, "-").toLowerCase();
};
helpers.capitalizeFirstLetter = function(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}; | 444860633d973e57aad8e357a362c2b82f350a0b | [
"JavaScript"
] | 2 | JavaScript | HenriPodolski/generator-veams | ebbae5d12acf5e0856e08e63c8439ba8db2010d8 | f3da0c61dbe45f424993d5bd47267e65a77a1ae3 |
refs/heads/master | <file_sep>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { ReactiveFormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { FontAwesomeModule } from '@fortawesome/angular-fontawesome';
import { LoginComponent } from './login/login.component';
import { ForgotComponent } from './forgot/forgot.component';
import { ErrorComponent } from './error/error.component';
import { PageNotFoundComponent } from './page-not-found/page-not-found.component';
import { ProductsComponent } from './products/products.component';
import { HomeComponent } from './home/home.component';
import { RegisterComponent } from './register/register.component';
import { ContactusComponent } from './contactus/contactus.component';
import { AboutusComponent } from './aboutus/aboutus.component';
import { ResetpasswordComponent } from './resetpassword/resetpassword.component';
@NgModule({
declarations: [
AppComponent,
LoginComponent,
ForgotComponent,
ErrorComponent,
PageNotFoundComponent,
ProductsComponent,
HomeComponent,
RegisterComponent,
ContactusComponent,
AboutusComponent,
ResetpasswordComponent
],
imports: [
BrowserModule,
AppRoutingModule,
FontAwesomeModule,
ReactiveFormsModule,
HttpClientModule,
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
<file_sep>import { Component, OnInit } from '@angular/core';
import { faShoppingCart } from '@fortawesome/free-solid-svg-icons';
import{ Router } from '@angular/router';
@Component({
selector: 'app-products',
templateUrl: './products.component.html',
styleUrls: ['./products.component.css']
})
export class ProductsComponent implements OnInit {
public faShoppingCart = faShoppingCart;
constructor(private router: Router) {}
ngOnInit(): void {
if(!sessionStorage.getItem('sid')){
this.router.navigate(['login']);
}
}
processLogout(){
sessionStorage.removeItem('sid');
this.router.navigate(['/login']);
}
}
<file_sep>import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { ForgotComponent } from './forgot/forgot.component';
import { ErrorComponent } from './error/error.component';
import { PageNotFoundComponent } from './page-not-found/page-not-found.component';
import { ProductsComponent } from './products/products.component';
import { LoginComponent } from './login/login.component';
import { HomeComponent } from './home/home.component';
import { RegisterComponent } from './register/register.component';
import { AboutusComponent } from './aboutus/aboutus.component';
import { ContactusComponent } from './contactus/contactus.component';
import { ResetpasswordComponent } from './resetpassword/resetpassword.component';
const routes: Routes = [
{ path:'forgot',component: ForgotComponent},
{path:'product',component: ProductsComponent},
{path:'error',component: ErrorComponent},
{path:'login',component: LoginComponent},
{path: 'home',component: HomeComponent, children:[
{ path:'aboutus',component:AboutusComponent},
{ path:'contactus',component:ContactusComponent}
]},
{path:'reset',component:ResetpasswordComponent},
{path: 'register',component: RegisterComponent},
{path:'',redirectTo:'login',pathMatch: 'full'},
{path:'**',component:PageNotFoundComponent},
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
| a22fce965f22b33ec103eddec53b98f8d0a87271 | [
"TypeScript"
] | 3 | TypeScript | KaushikSawant/project | f468290a03a10f2ad0891dfa1f362c6c25500b60 | 7094ca57d5acc2224cfe9379ba4e6d5326a70eb4 |
refs/heads/master | <file_sep>var gulp = require('gulp');
var browserSync = require('browser-sync').create();
const jsPath = './app/javascript/**/*.js';
gulp.task('javascript', function(){
browserSync.reload({
// stream: true
});
});
gulp.task('watch-it', ['self-sync', 'javascript'], function(){
gulp.watch(jsPath, ['javascript'])
});
gulp.task('self-sync', function() {
browserSync.init({
server: {
baseDir: 'app'
},
});
});
<file_sep># Activity one.
The first task is to make the following responsive:
[Codepen](http://codepen.io/chriscoyier/pen/lDJmf)
The exercise should be completed purely in HTML/CSS. Feel free to use vanilla CSS, or the pre-processor of your choice (LESS, SASS etc).
This application was developed on OS X El Capitan Version 10.11.6.
## Technologies used:
* HTML, CSS
## Possible Improvements
* For consistency - would either add fourth secondary image or resize third image to cover entire width at smaller screen size.
<file_sep># Activity three.
## Brief
Choose your preferred JS framework and create an app which allows users to search and playing YouTube videos via the YouTube API. Anything goes here, so feel free to code as little/as much as you want in whatever JS based technology you're comfortable with.
We'll be looking specifically at your approach to a full project in JS that makes use of a Restful API. We're likely to be more interested in the tools you choose and and how well you use them over the beauty of the finished product (though a slick interface won't be overlooked).
This application was developed on OS X El Capitan Version 10.11.6.
## Technologies used:
* HTML, CSS, JS, Handlebars, Underscore.js, jQuery, Gulp.
# Thoughts
* I originally thought about using React with Node.js or Backbone but decided not to overcomplicate things. I just needed a simple update to the view upon the user searching for videos and figured handlebars would be adequate for the app.
## Possible Improvements
* Could list out results as links to appropriate videos.
* Work on page responsiveness.
<file_sep># Activity two.
## Brief
Implement a banner carousel for a web page. This is a commonly used piece of functionality and we are keen to see how you would approach it. We don't expect you to write an entire plugin from scratch, but we'd like to see how you approach putting something together that addresses the following key areas:
* Animated slide transitions.
* Responsive layouts.
* User interaction/controls.
* Consideration of accessibility.
We'll be looking at a combination of the HTML, CSS, and JavaScript you use. Feel free to use placeholder images for the banners, alternatively we'd love you to show us how we could have implemented some of our own banner designs better.
This application was developed on OS X El Capitan Version 10.11.6.
## Technologies used:
* HTML, CSS, JS
# Thoughts
* I enjoy experimenting with css animations and thought it would be interesting to give the slide some perspective.
## Possible Improvements
* Images are slightly different heights.
* Image bottom cut off on resize.
* Accessibility could be improved. At the moment users are able to:
* Pause slide movement.
* Play through slides.
* Move forward or backwards through slides with arrows.
* Color contrast ratio 9.79:1.
* Given more time I would implement the slide nav dots. At the moment they are purely cosmetic.
| e97527740491b2594e7c44af57ab378a642e0912 | [
"JavaScript",
"Markdown"
] | 4 | JavaScript | Lupeman/misc | ba446dde4c616dbf30156127044c9fc3b63960b1 | 44133247a4833cfa2700051b54ff99baaca7abc4 |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Neudesic.Model.Events
{
public class Admin
{
public List<Events> EventList { get; set; } = new List<Events>();
public void AddEvent(int eventId, string eventName, string eventPlace, int eventFee)
{
EventList.Add(new Events() { Id = eventId, Name = eventName, Place = eventPlace, Fee = eventFee });
}
public List<Events> SeeEvents()
{
return EventList;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Neudesic.Model.Events
{
public class User : Admin
{
public new List<Events> SeeEvents()
{
//foreach (var events in EventList)
//{
// Console.WriteLine(events.Id + "." + events.Name + " " + events.Place + " " + events.Fee);
//}
return EventList;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Neudesic.Model.Events;
namespace Neudesic.Home
{
class Home
{
public static List<Events> EventList { get; private set; }
static void Main(string[] args)
{
Admin admin = new Admin();
User user = new User();
Console.WriteLine("-------------------Enter your role-------------------");
Console.WriteLine("1.Admin");
Console.WriteLine("2.User");
int input = Convert.ToInt32(Console.ReadLine());
if (input == 1)
{
int check;
do
{
Console.WriteLine("-------------------Enter your choice-------------------");
Console.WriteLine("1.Create event");
Console.WriteLine("2.See events");
Console.WriteLine("3.Exit");
int choice = Convert.ToInt32(Console.ReadLine());
switch (choice)
{
case 1:
Console.WriteLine("Enter EventId");
int eventId = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter Event name");
string eventName = Console.ReadLine();
Console.WriteLine("Enter Event place");
string eventPlace = Console.ReadLine();
Console.WriteLine("Enter Event Fee");
int eventFee = Convert.ToInt32(Console.ReadLine());
admin.AddEvent(eventId, eventName, eventPlace, eventFee);
Console.WriteLine("Successfully Created event");
break;
case 2:
EventList = admin.SeeEvents();
foreach (var events in EventList)
{
Console.WriteLine(events.Id + "." + events.Name + " " + events.Place + " " + events.Fee);
}
break;
case 3:
break;
default:
Console.WriteLine("Invalid choice");
break;
}
check = choice;
} while (check != 3);
}
else
{
int option;
do
{
Console.WriteLine("-------------------Enter your choice-------------------");
Console.WriteLine("1.See events");
Console.WriteLine("2.Exit");
int select = Convert.ToInt32(Console.ReadLine());
switch (select)
{
case 1:
user.SeeEvents();
break;
case 2:
break;
default:
Console.WriteLine("Invalid choice");
break;
}
option = select;
} while (option != 2);
}
}
}
}
| b897c8d5168e981b4da5da2ec34bc60221a64c5b | [
"C#"
] | 3 | C# | RamyaVempalla/Event | 338c742b88f04822f087b29d4d2224fe7e0a67a7 | 1951bd381163f46d2f0a78d73e01db93834ef967 |
refs/heads/main | <repo_name>KmH210/firebase-lab-1<file_sep>/frontend/src/service/ShoutOutApiService.ts
import axios from "axios";
import ShoutOuts from "../model/shoutOuts";
const baseUrl = process.env.REACT_APP_API_URL || "";
if (!baseUrl) {
console.error("REACT_APP_API_URL environment variable not set.");
}
export function readAllShoutOuts():Promise<ShoutOuts[]> {
return axios.get(baseUrl).then(res => res.data);
}
export function readShoutOutsByPerson (to: string):Promise<ShoutOuts[]> {
return axios.get(baseUrl, {
params: {to: to}
}).then(res => res.data);
}
export function createShoutOut(shoutOut: ShoutOuts):Promise<ShoutOuts> {
return axios.post(baseUrl, shoutOut).then(res => res.data);
}
export function deleteShoutOut(shoutOutId: string):Promise<void> {
return axios.delete(`${baseUrl}/${encodeURIComponent(shoutOutId)}`);
}<file_sep>/frontend/src/firebaseConfig.ts
import firebase from "firebase/app";
import "firebase/auth";
import "firebase/storage";
// Your web app's Firebase configuration
const firebaseConfig = {
apiKey: "<KEY>",
authDomain: "shout-outs-lab-89003.firebaseapp.com",
projectId: "shout-outs-lab-89003",
storageBucket: "shout-outs-lab-89003.appspot.com",
messagingSenderId: "79254251767",
appId: "1:79254251767:web:d9f2326e8084c272c20bf2"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
//export app again once it has been configured
export const authProvider = new firebase.auth.GoogleAuthProvider();
export function signInWithGoogle(): void {
firebase.auth().signInWithPopup(authProvider);
}
export function signOut(): void {
firebase.auth().signOut();
}
export default firebase;<file_sep>/functions/src/model/shoutOuts.ts
import { ObjectId } from 'mongodb';
export default interface ShoutOuts {
_id?: ObjectId;
to: string;
from: string;
message: string;
}
// db.shoutouts.insertMany([
// {to: "Beyonce", from: "The beyhive", message: "We love you!"},
// {to: "Michael", from: "Dwight", message: "You're the best boss!"},
// {to: "staples", from: "<NAME>", message: "Thank you paper clips for being like staples for people who can't commit"},
// ]); | 45f9469c08ded0f16255f646d899e875c2b43643 | [
"TypeScript"
] | 3 | TypeScript | KmH210/firebase-lab-1 | 4922fd530a16c7644b5832b41dedd8cc9a4340e5 | 60959456a100670aff0865c3c7f04f395136eee4 |
refs/heads/master | <file_sep>#include "std_lib_facilities.h"
int main(){
cout << "prompt\n";
int lval = 0;
int rval;
int res;
cin >> lval;
if(!cin) error("E1");
for(char op; cin>>op;){
if(op != 'x'){
cin>>rval;
if(!cin) error("E2");
switch(op){
case '+':
lval += rval;
res = lval;
cout << res << "\n";
break;
case '-':
lval -= rval;
res = lval;
cout << res << "\n";
break;
case '*':
lval *= rval;
res = lval;
cout << res << "\n";
break;
case '/':
lval /= rval;
res = lval;
cout << res << "\n";
break;
default:
cout << "Invalid Expression.\n";
return 1;
}
}else{
cout << "Calculator Terminated.\n";
return 0;
}
}
return 0;
}
<file_sep>#include "std_lib_facilities.h"
#include <locale>
int main(){
std::locale loc;
vector<string> v;
cout << "Input words separated by line break.\n";
for(string curIn; cin>>curIn;){
//conver all input to lowercase and push to vector.
for(std::string::size_type i=0; i<curIn.size(); i++)
curIn[i]=std::tolower(curIn[i],loc);
v.push_back(curIn);
}
cout << "\n******************\n";
sort(v);
string prev=v[0];
int curRep=0;
for(string s:v){
if(s==prev){
//Increment counter.
curRep += 1;
}else{
//Print stats and reset counters.
cout << prev << ": " << curRep << "\n";
curRep = 1;
prev = s;
}
}
cout << prev << ": " << curRep << "\n";
return 0;
}
<file_sep>#include "std_lib_facilities.h"
#include "Token.h"
//DEBUG FUNCTIONS
void PrintToken(Token t, string s){
cout << s << t.type << "|" << t.value << endl;
return;
}
void Println(string s){
cout << s << endl;
return;
}
//TOKEN STREAM FUNCTIONS
void TokenStream::putback(Token t){
buffer.push_back(t);
}
void TokenStream::clearbuffer(){
buffer.clear();
}
Token TokenStream::get(){
if(buffer.size() > 0){
Token t = buffer.back();
buffer.pop_back();
// PrintToken(buffer, "Out from buffer |> ");
return t;
}else{
Token eToken = Token{'e', 0};
Token outToken('e');
char ch;
cin >> ch;
switch(ch){
case ';': case 'q': case '(': case '+': case '-': case '^':
case '/': case '*': case ')': case '%': case '=': case 'h':
outToken = Token(ch);
// PrintToken(outToken, "OutToken |> ");
return outToken;
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
cin.putback(ch);
double val;
cin >> val;
outToken = Token('#', val);
// PrintToken(outToken, "OutToken |> ");
return outToken;
default:
if(isalpha(ch)){
string vName;
vName += ch;
while(cin.get(ch) && (isalpha(ch) || isdigit(ch))){
vName += ch;
}
cin.putback(ch);
// cout << "VAR NAME | " << vName << endl;
return Token{cName, vName};
}else if(ch == '['){
}
}
return eToken;
}
}
<file_sep>
#include "std_lib_facilities.h"
#include "date.h"
int main(){
Date today{1999, 5, 22};
cout << "Today: "
<< today.getYear() << "/"
<< today.getMonth() << "/"
<< today.getDay() << "\n";
Date emm{Month{January}};
emm.EMonthTest();
}
<file_sep>#include "std_lib_facilities.h"
int main(){
double res;
for(int i=1; i<=100; i++){
res = i * i;
cout << i << "^2=" << res << "\n";
}
return 0;
}
<file_sep>#include <iostream>
#include <string>
using namespace std;
//Not really useful.
enum Month{
jan=1,feb,mar,apr,may,jun,jul,aug,sep,oct,nov,dec
};
class Date {
public:
//CONSTRUCTORS
Date(int yy, int mm, int dd, bool overrideValidity = false);
//GETTERS AND SETTERS
void AddDay(int n);
int getYear();
int getMonth();
int getDay();
void setYear(int n);
void setMonth(int n);
void setDay(int n);
void addYear(int n);
void addMonth(int n);
void addDay(int n);
void printFull();
//UTILITY FUNCTIONS
string toString() const;
bool isValid();
void ForceValid();
//OPERATOR OVERLOADS
bool operator == (const Date &other);
bool operator != (const Date &other);
friend ostream& operator << (ostream &out, const Date &d);
friend istream& operator >> (istream &in, Date &d);
private:
int yy;
int mm;
int dd;
};
<file_sep>#include "std_lib_facilities.h"
class Token{
public:
char type;
double value;
};
Token get_token(){
Token eToken = Token{'e', 0};
char ch;
cin >> ch;
switch(ch){
case ';': case 'q': case '(': case '+': case '-':
case '/': case '*': case ')': case '%':
return Token{ch, 0};
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
cin.putback(ch);
double val;
cin >> val;
return Token{'#', val};
}
return eToken;
}
Vector<Token> tokens;
int main(){
cout << "Input Tokens. Use q to print and exit.\n";
for(Token t=get_token(); t.type != 'q'; t=get_token()){
tokens.push_back(t);
}
cout << "TYPE | VALUE\n";
for(Token t : tokens){
cout << t.type << "|" << t.value << "\n";
}
}
<file_sep>#include "std_lib_facilities.h"
int main(){
cout << "prompt\n";
int lval = 0;
int rval;
char op;
int res;
cin >> lval >> op >> rval;
if(op == '+'){
res = lval + rval;
cout << res << "\n";
}else if(op == '-'){
res = lval - rval;
cout << res << "\n";
}else{
cout << "\nInvalid Expression.\n";
return 1;
}
return 0;
}
<file_sep>
#include "std_lib_facilities.h"
#include "date.h"
void PrintHelp();
int main(){
Date tempDate;
Date today{2000, 5, 22, false};
bool equalit = today == tempDate;
cout << "Enter Initial Date(YYYY/MM/DD): ";
cin >> today;
cout << "The Date Set is: " << today;
cout << "this is set and printed with stream operator overloads '<<' and '>>'.\n";
cout << "\nInteract with Date class here.\n"
<< "type 'h' for help.\n";
char cmd;
while(cin){
cout << "|> ";
cin >> cmd;
switch(cmd){
case 'h':
PrintHelp();
break;
case 'q':
return 0;
case 'p':
cout << "The date is: " << today;
cout << "Use f for full date print" << endl;
break;
case 's':
cout << "Enter date to set(YYYY/MM/DD): ";
cin >> today;
cout << "The Date Set is: " << today;
break;
case 'd':
cout << "Number of days to add: ";
int nd;
cin >> nd;
today.addDay(nd);
cout << "The new date is: " << today;
break;
case 'm':
cout << "Number of months to add: ";
int nm;
cin >> nm;
today.addMonth(nm);
cout << "The new date is: " << today;
break;
case 'y':
cout << "Number of years to add: ";
int ny;
cin >> ny;
today.addYear(ny);
cout << "The new date is: " << today;
break;
case 'f':
cout << "The full date is: " << endl;
today.printFull();
break;
case 'e':
cout << "Current date is: " << today;
cout << "Enter date to compare(YYYY/MM/DD): ";
cin >> tempDate;
equalit = tempDate==today;
cout << "EQUALITY TEST: " << equalit << endl;
break;
default:
cout << "Invalid Entry. Type 'h' for help.\n";
break;
}
}
}
void PrintHelp(){
cout << endl
<< "Below are commands for interacting with Date.\n"
<< "h : help\n" << "p : print date\n" << "s : set date\n"
<< "d : add days\n" << "m : add months\n" << "y : add years\n"
<< "e : test equality\n"
<< "q : quit\n\n";
return;
}
<file_sep>#include "std_lib_facilities.h"
double statement(TokenStream& tokenStream);
double expression(TokenStream& tokenStream);
double term(TokenStream& tokenStream);
double expo(TokenStream& tokenStream);
double primary(TokenStream& tokenStream);
<file_sep>#include "std_lib_facilities.h"
//This class has memory management issues as a demonstration.
class vect{
int sz;
double* elem;
public:
vect(int s):sz{s}, elem{new double [s]} {}
~vect() {delete[] elem;}
double get(int i) {return elem[i];}
void set(int i, double d){
elem[i]=d;
}
};
int main(){
vect v(3);
v.set(2, 2.2);
vect v2 = v;
v.set(1, 9.9);
v2.set(0, 8.8);
cout << v.get(0) << ' ' << v2.get(1);
}
<file_sep>#include "std_lib_facilities.h"
int main(){
double sDbl = 6666666666;
int sInt = 242;
char sChar = 'x';
cout << "Now Converting Double to:\n";
cout << "INITIAL DOUBLE VALUE: " << sDbl << "\n";
int tInt = sDbl;
cout << "int |> " << tInt << "\n";
double bDbl = tInt;
cout << "Converted back |> " << bDbl << "\n";
char tC = sDbl;
cout << "char |> " << tC << "\n";
bDbl = tC;
cout << "Converted back |> " << bDbl << "\n";
cout << "******************\n"
<< "Also beware conversion of decimal numbers, which char and int do not support."
<< "\n******************\n";
bool tB = sDbl;
cout << "bool |> " << tB << "\n";
bDbl = tB;
cout << "Converted back |> " << bDbl << "\n";
cout << "\nNow Converting Int to:\n";
cout << "INITIAL INT VALUE: " << sInt << "\n";
char tCc = sInt;
cout << "char |> " << tCc << "\n";
int bInt = tCc;
cout << "Converted back |> " << bInt << "\n";
bool tBb = sInt;
cout << "bool |> " << tBb << "\n";
bInt = tBb;
cout << "Converted back |> " << bInt << "\n";
cout << "\nNow Converting Char to:\n";
cout << "INITIAl CHAR VALUE: " << sChar << "\n";
bool tBbb = sChar;
cout << "bool |> " << tBbb << "\n";
char bChar = tBbb;
cout << "Converted back |> " << bChar << "\n";
cout << "\nDONE\n";
}
<file_sep>#include "std_lib_facilities.h"
#include "parser.h"
class Token{
public:
char type;
double value;
};
class TokenStream{
public:
Token get();
void putback(Token t);
private:
Token buffer;
bool full{false};
};
//TOKEN STREAM FUNCTIONS
void TokenStream::putback(Token t){
buffer = t;
full = true;
}
Token TokenStream::get(){
if(full){
full = false;
return buffer;
}else{
Token eToken = Token{'e', 0};
char ch;
cin >> ch;
switch(ch){
case ';': case 'q': case '(': case '+': case '-':
case '/': case '*': case ')': case '%': case 'h':
return Token{ch, 0};
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
cin.putback(ch);
double val;
cin >> val;
return Token{'#', val};
}
return eToken;
}
}
Vector<Token> tokens;
TokenStream tokenStream;
//DEBUG FUNCTIONS
void PrintToken(Token t, string s){
cout << s << t.type << "|" << t.value << endl;
return;
}
//PARSER DEFINITIONS
double expression(){
double left = term();
Token t = tokenStream.get();
// PrintToken(t, "EXPRESSION SCOPE TOKEN |> ");
while(true){
switch(t.type){
case '+':
left += term();
break;
case '-':
left -= term();
break;
default:
tokenStream.putback(t);
return left;
}
t = tokenStream.get();
}
}
double term(){
return primary();
}
double primary(){
Token t = tokenStream.get();
// PrintToken(t, "PRIMARY SCOPE TOKEN |> ");
return t.value;
}
int main(){
try{
double val = 0.0;
while(cin){
Token t = tokenStream.get();
// PrintToken(t, "MAIN SCOPE TOKEN |> ");
if(t.type == 'q') break;
if(t.type == ';')
cout << '=' << val << '\n';
else
tokenStream.putback(t);
val = expression();
// cout << "VAL RETURNED: " << val << endl;
}
}catch(std::error_code){
return 1;
}
/*STREAM AND TOKEN TESTING
for(Token t=tokenStream.get(); t.type != 'q'; t=tokenStream.get()){
tokens.push_back(t);
}
for(Token t : tokens){
cout << t.type << "|" << t.value << "\n";
}
*/
}
<file_sep>#include "std_lib_facilities.h"
#include "date.h"
int mDays[13] = {0, 31,28,31,30,31,30,31,31,30,31,30,31};
int mDaysLeap[13] = {0, 31,29,31,30,31,30,31,31,30,31,30,31};
string mLookup[13] =
{"invalid", "January", "February", "March", "April",
"May", "June", "July", "August", "September",
"October", "November", "December"};
//CONSTRUCTOR
Date::Date(int y, int m, int d, bool oV):yy{y}, mm{m}, dd{d}{
if(!oV){
if(!isValid()){
ForceValid();
cout << "Invalid Construction. Validy has been enforced.\n";
}
}
}
Date::Date(){
yy = 1999;
mm = 1;
dd = 1;
}
//GETTERS AND SETTERS
void Date::addDay(int n){
dd += n;
ForceValid();
return;
}
void Date::addMonth(int n){
mm += n;
ForceValid();
return;
}
void Date::addYear(int n){
yy += n;
ForceValid();
return;
}
void Date::setYear(int n){
yy = n;
}
void Date::setMonth(int n){
Date tDate{yy, n, dd, false};
if(!tDate.isValid()){
cout << "Invalid date, date remains unchanged." << endl;
return;
}
mm = n;
return;
}
void Date::setDay(int n){
Date tDate{yy, mm, n, false};
if(!tDate.isValid()){
cout << "Invalid date, date remains unchanged." << endl;
return;
}
dd = n;
return;
}
int Date::getYear(){
return yy;}
int Date::getMonth(){
return mm;}
int Date::getDay(){
return dd;}
void Date::printFull(){
cout << mLookup[mm] << " " << dd
<< ", " << yy << endl;
return;
}
//UTILITY FUNCTIONS
string Date::toString() const{
string outS = std::to_string(yy);
outS += "/" + std::to_string(mm);
outS += "/" + std::to_string(dd);
return outS;
}
bool Date::isValid() const{
if(mm > 12){
return false;
}
if(dd > mDays[mm]){
if(isLeap()){
if(dd > mDaysLeap[mm])
return false;
}else{
return false;
}
}
return true;
}
bool Date::isLeap() const{
if(yy%4 == 0) return true;
return false;
}
void Date::ForceValid(){
while(!isValid()){
if(isLeap()){
if(dd > mDaysLeap[mm]){
dd -= mDaysLeap[mm];
mm += 1;
}
}else{
if(dd > mDays[mm]){
dd -= mDays[mm];
mm += 1;
}
}
if(mm > 12){
yy += 1;
mm -= 12;
}
}
}
//OPERATOR OVERLOADS
bool Date::operator == (const Date &other){
if(this->dd == other.dd && this->mm == other.mm && this->yy == other.yy){
return true;
}
return false;
}
bool Date::operator != (const Date &other){
return !(*this == other);
}
std::ostream& operator << (std::ostream &out, const Date &d){
out << d.toString() << endl;
return out;
}
std::istream& operator >> (std::istream &in, Date &d){
int inY; int inM; int inD;
char sep1; char sep2;
in >> inY >> sep1 >> inM >> sep2 >> inD;
Date tDate{inY, inM, inD, true};
if(!tDate.isValid()){
cout << "Invalid date, date remains unchanges.\nUse format YYYY/MM/DD.\n";
return in;
}
d.setYear(inY);
d.setMonth(inM);
d.setDay(inD);
return in;
}
<file_sep>
double expression();
double term();
double primary();
<file_sep>#include "std_lib_facilities.h"
#include "Token.h"
#include "parser.h"
#include "vars.h"
//PARSER DEFINITIONS
double statement(TokenStream& tokenStream){
Token t = tokenStream.get();
if(t.type == cName){
string vName = t.name;
// cout << "statement() got var with name " << vName << endl;
Token next = tokenStream.get();
if(next.type == '='){
double eRight = expression(tokenStream);
set_value(vName, eRight);
return eRight;
}else if(next.type == ';'){
tokenStream.putback(next);
return get_value(vName);
}
}
tokenStream.putback(t);
return expression(tokenStream);
}
double expression(TokenStream& tokenStream){
// cout << "Calling expression()" << endl;
double left = term(tokenStream);
Token t = tokenStream.get();
// cout << "Initial left |> " << left << endl;
while(true){
// cout << "EXPRESSION LOOP" << endl;
switch(t.type){
case '+':
// cout << "Found +" << endl;
left += term(tokenStream);
break;
case '-':
// cout << "Found -" << endl;
left -= term(tokenStream);
break;
default:
// cout << "Returning left" << endl;
tokenStream.putback(t);
// cout << "RETURNING FROM EXPRESSION |> " << left << endl;
return left;
}
t = tokenStream.get();
}
}
double term(TokenStream& tokenStream){
// cout << "Calling term()" << endl;
double left = expo(tokenStream);
Token t = tokenStream.get();
while(true){
// cout << "TERM LOOP" << endl;
switch(t.type){
case '*':
{
left *= expo(tokenStream);
t = tokenStream.get();
break;
}
case '/':
{
double divisor = expo(tokenStream);
if(divisor == 0)
error("Division by zero.");
left /= divisor;
t = tokenStream.get();
break;
}
case '%':
{
double next = expo(tokenStream);
if(next == 0)
error("Division by zero.");
left = fmod(left, next);
t = tokenStream.get();
break;
}
default:
{
tokenStream.putback(t);
return left;
}
}
}
}
double expo(TokenStream& tokenStream){
// cout << "Calling expo()" << endl;
double left = primary(tokenStream);
Token t = tokenStream.get();
while(true){
// cout << "EXPO LOOP" << endl;
switch(t.type){
case '^':
{
left = pow(left, primary(tokenStream));
t = tokenStream.get();
break;
}
default:
{
tokenStream.putback(t);
return left;
}
}
}
}
double primary(TokenStream& tokenStream){
// cout << "Calling primary()" << endl;
Token t = tokenStream.get();
switch(t.type){
case '(':
{
double next = expression(tokenStream);
t = tokenStream.get();
if(t.type != ')')
error("Closing bracket ')' expected but not found.");
return next;
}
case '#':
{
return t.value;
}
case '-':
{
return -primary(tokenStream);
}
case '+':
{
return primary(tokenStream);
}
default:
{
error("Primary acquisition failure.");
}
}
return t.value;
}
<file_sep>#include <iostream>
int main(){
int i = 1;
int *p;
while(true){
try{
p = new int[10000 * i];
i+=1;
}catch(const std::exception& e){
std::cout << "Iteration: " << i << std::endl;
std::cout << "Error: " << e.what() << std::endl;
return 0;
}
}
return 0;
}
<file_sep>#include "std_lib_facilities.h"
#include "vars.h"
int main(){
set_value("a", 3);
set_value("b", 4);
set_value("c", 5);
double d;
d = get_value("a");
cout << "a = " << d << endl;
d = get_value("b");
cout << "b = " << d << endl;
d = get_value("c");
cout << "c = " << d << endl;
}
<file_sep>#include <string>
#include <array>
#include <iostream>
#include <fstream>
#include "std_lib_facilities.h"
using namespace std;
struct InFormat {
int hour;
double low;
double high;
};
int main(){
string iFName;
cout << "Enter name of (existing) input file: ";
cin >> iFName;
ifstream ist {iFName};
if(!ist){
cout << "Could not open specified input file.";
return 1;
}
cout << endl;
string oFName;
cout << "Enter name of (existing) output file: ";
cin >> oFName;
ofstream ost {oFName};
if(!ost){
cout << "Could not open specified output file.";
return 1;
}
cout << endl;
vector<InFormat> fIn;
int curHr;
double curLow;
double curHigh;
char sep1;
char sep2;
while (ist >> curHr >> sep1 >> curLow >> sep2 >> curHigh){
fIn.push_back(InFormat{curHr, curLow, curHigh});
}
for (InFormat i : fIn){
ost << '(' << i.hour << "\t"
<< i.low << "\t" << i.high
<< ')' << endl;
}
return 0;
}
<file_sep>
enum Month{
January = 1, February, March, April, May, June,
July, August, Septembber, October, November, December,
};
class Date {
public:
Date(int yy, int mm, int dd);
Date(Month eMonth);
void AddDay(int n);
int getYear();
int getMonth();
int getDay();
Month eMonth;
void EMonthTest();
private:
int yy;
int mm;
int dd;
};
<file_sep>
double expression(TokenStream& tokenStream);
double term(TokenStream& tokenStream);
double primary(TokenStream& tokenStream);<file_sep>Testing
Pythonanywhere
Git
COmmit
<file_sep>#include <iostream>
char c = 'a';
int i = 4092;
double d = 3.14;
char* pC = &c;
int* pI = &i;
double* pD = &d;
int main(){
std::cout << "pI = " << pI << " with value " << *pI << std::endl;
std::cout << "pC = " << pC << " with value " << *pC << std::endl;
std::cout << "pD = " << pD << " with value " << *pD << std::endl;
std::cout << "size of pI = " << sizeof(pI) << ", size of (i) = " << sizeof(i) << std::endl;
std::cout << "size of pC = " << sizeof(pC) << ", size of (c) = " << sizeof(c) << std::endl;
std::cout << "size of pD = " << sizeof(pD) << ", size of (d) = " << sizeof(d) << std::endl;
}
<file_sep>
def stackRec(i):
print i;
try:
stackRec(i+1);
except:
print("Max recursion depth reached.");
return;
stackRec(0);
<file_sep>#include "std_lib_facilities.h"
#include "token.h"
#include "parser.h"
//PARSER DEFINITIONS
double expression(TokenStream& tokenStream){
// cout << "Calling expression()" << endl;
double left = term(tokenStream);
Token t = tokenStream.get();
// cout << "Initial left |> " << left << endl;
// cout << "Operator |> " << t.type << endl;
// PrintToken(t, "EXPRESSION SCOPE TOKEN |> ");
while(true){
switch(t.type){
case '+':
// cout << "Found +" << endl;
left += term(tokenStream);
break;
case '-':
// cout << "Found -" << endl;
left -= term(tokenStream);
break;
default:
// cout << "Returning left" << endl;
tokenStream.putback(t);
// cout << "RETURNING FROM EXPRESSION |> " << left << endl;
return left;
}
t = tokenStream.get();
}
}
double term(TokenStream& tokenStream){
// cout << "Calling term()" << endl;
double left = primary(tokenStream);
Token t = tokenStream.get();
while(true){
switch(t.type){
case '*':
{
left *= primary(tokenStream);
t = tokenStream.get();
break;
}
case '/':
{
double divisor = primary(tokenStream);
if(divisor == 0)
error("Division by zero.");
left /= divisor;
t = tokenStream.get();
break;
}
case '%':
{
double next = primary(tokenStream);
if(next == 0)
error("Division by zero.");
left = fmod(left, next);
t = tokenStream.get();
break;
}
default:
{
tokenStream.putback(t);
return left;
}
}
}
}
double primary(TokenStream& tokenStream){
// cout << "Calling primary()" << endl;
Token t = tokenStream.get();
switch(t.type){
case '(':
{
double next = expression(tokenStream);
t = tokenStream.get();
if(t.type != ')')
error("Closing bracket ')' expected but not found.");
return next;
}
case '#':
{
return t.value;
}
case '-':
{
return -primary(tokenStream);
}
case '+':
{
return primary(tokenStream);
}
default:
{
error("Primary acquisition failure.");
}
}
return t.value;
}<file_sep>#include "std_lib_facilities.h"
//This class has memory management issues as a demonstration.
class vect{
int sz;
double* elem;
public:
//Constructors
vect(int s):sz{s}, elem{new double [s]} {}
vect(const vect &arg):sz{arg.sz}, elem{new double[arg.sz]}{
copy(arg.elem, arg.elem + arg.sz, elem);
}
//Operator Overloads
vect& operator=(const vect& other){
double * p = new double[other.sz];
copy(other.elem, other.elem + other.sz, p);
delete[] elem;
elem = p;
sz = other.sz;
return *this;
}
double& operator[](int n) const {
return elem[n];
}
//Getters and setters
double& get(int i) {return elem[i];}
void set(int i, double d){
elem[i]=d;
}
~vect() {delete[] elem;}
};
int main(){
vect v(3);
v[2] = 2.2;
vect v2 = v;
v[1] = 9.9;
v2[0] = 8.8;
std::cout << v[0] << ' ' << v2[1] << endl;
std::cout << v[1] << ' ' << v2[0] << endl;
}
<file_sep>#include "std_lib_facilities.h"
int main(){
cout << "Please Enter Name:\n";
string first_name;
int age;
cin >> first_name;
cout << "Please Enter Age:\n";
cin >> age;
cout << "Hello " << first_name << "\n";
cout << "Age: " << age << "\n";
}
<file_sep>#include "std_lib_facilities.h"
const char cInvalid = 'e';
const char cNum = '#';
const char cName = 'a';
const char cPrint = ';';
const char cQuit = 'q';
class Token{
public:
char type;
double value;
string name;
//CONSTRUCTORS
Token(char ch){
type = ch;
value = 2053;
}
Token(char ch, double val){
type = ch;
value = val;
}
Token(char ch, string n){
type = ch;
name = n;
}
};
class TokenStream{
public:
Token get();
void putback(Token t);
void clearbuffer();
private:
vector<Token> buffer;
};
<file_sep>#include "std_lib_facilities.h"
#include "Token.h"
#include "vars.h"
#include "parser.h"
const string prompt = "> ";
int main(){
TokenStream ts;
try{
double val = 0.0;
while(cin){
cout << prompt;
Token t = ts.get();
// cout << "Main got Token |> " << t.type << "|" << t.value << endl;
if(t.type == 'q') break;
if(t.type == ';')
cout << '=' << val << '\n';
else{
ts.putback(t);
val = statement(ts);
}
// cout << "VAL RETURNED: " << val << endl;
}
}catch(int e){
return 1;
}
/* STREAM AND TOKEN TESTING
for(Token t=tokenStream.get(); t.type != 'q'; t=tokenStream.get()){
tokens.push_back(t);
}
for(Token t : tokens){
cout << t.type << "|" << t.value << "\n";
}
*/
return 0;
}
<file_sep>#include "std_lib_facilities.h"
int main(){
vector<double> v;
double curIn;
while(cin >> curIn){
v.push_back(curIn);
}
cout << "Data in Vector:\n{ ";
for(double x:v){
cout << x << " ";
}
cout << "}\n";
}
<file_sep>#include "std_lib_facilities.h"
int main(){
cout << "Input temparatures separated by line break to find average.\n";
vector<double> uInputs;
for(double temp; cin>>temp;)
uInputs.push_back(temp);
double total=0.0;
for(double temp:uInputs)
total += temp;
double mean = total / uInputs.size();
cout << "The mean of the inputs is: " << mean << "\n";
sort(uInputs);
cout << "The median of the inputs is: " << uInputs[uInputs.size()/2] << "\n";
return 0;
}
<file_sep>#include "std_lib_facilities.h"
#include "Token.h"
#include "vars.h"
#include "parser.h"
const string prompt = "> ";
void PrintHelp();
int main(){
TokenStream ts;
try{
double val = 0.0;
cout << "Calculator for Object Oriented Programming." << endl;
cout << "Input Below. Type 'h' into prompt for help." << endl;
while(cin){
cout << prompt;
Token t = ts.get();
// cout << "Main got Token |> " << t.type << "|" << t.value << endl;
if(t.type == 'q') break;
if(t.type == 'h'){
PrintHelp();
}else if(t.type == ';'){
cout << '=' << val << '\n';
ts.clearbuffer();
}else{
ts.putback(t);
val = statement(ts);
}
// cout << "VAL RETURNED: " << val << endl;
}
}catch(int e){
return 1;
}
return 0;
}
void PrintHelp(){
cout << "Available Operations: "
<< "+ - * / % ^" << endl
<< "\nAvailable Functions: "
<< "sin, cos, tan" << endl
<< "asin, acos, atan" << endl
<< "log, log2, log10" << endl
<< "e(^), sqrt" << endl
<< "\nFor Assigning Variable, use '=' (x=3)." << endl
<< "\nFor Print, use ';' (3+7;)." << endl
<< endl;
return;
}
<file_sep>#include "std_lib_facilities.h"
#include "date.h"
Date::Date(int y, int m, int d):yy{y}, mm{m}, dd{d}{
}
Date::Date(Month em):eMonth{em}{
}
void Date::EMonthTest(){
int oInt = eMonth;
cout << eMonth << "|" << oInt << endl;
}
void Date::AddDay(int n){
cout << "Adding day:" << n << endl;
return;
}
int Date::getYear(){
return yy;
}
int Date::getMonth(){
return mm;
}
int Date::getDay(){
return dd;
}
| 81a6c027458c7860cd5019131ba350315656fc8a | [
"C",
"Python",
"C++"
] | 33 | C++ | Ashment/CS2124 | 4b6fd05df7340d122bb82b285005fcbe2455e8da | 01e8c04ba1294290d6bfda275f8dd3d0e0604499 |
refs/heads/master | <repo_name>gallottaj/chair-app<file_sep>/config/routes.rb
Rails.application.routes.draw do
# STEP 1: A ROUTE triggers a controller action
# verb "/urls" => "namespace/controllers#action"
namespace :api do
get '/chairs' => 'chairs#index'
get '/chair/:id' => 'chairs#show'
post '/chair' => 'chairs#create'
patch '/chair/:id' => 'chairs#update'
delete '/chair/:id' => 'chairs#delete'
end
end
<file_sep>/app/controllers/api/chairs_controller.rb
class Api::ChairsController < ApplicationController
def index
@chairs = Chair.all
render 'index.json.jbuilder'
end
def show
@chair = Chair.find_by(id: params[:id])
render "show.json.jbuilder"
end
def create
@chair = Chair.new({style: params[:style], color: params[:color]})
@chair.save
render "show.json.jbuilder"
end
def update
@chair = Chair.find_by(id: params[:id])
@chair = @chair.update({style: params[:style], color: params[:color]})
render "show.json.jbuilder"
end
def delete
@chair = Chair.find_by(id: params[:id])
@chair.destroy
render "delete.json.jbuilder"
end
end
| f86e62f4145f6a136ea58b19c4c6429efbfbbe91 | [
"Ruby"
] | 2 | Ruby | gallottaj/chair-app | f013f2f40281765b5db88c144436abb9c4743e26 | 9acf6365631d26d542b10c5368cb6dc97e32a8a0 |
refs/heads/master | <file_sep>public class Main {
public static void main(String[] args) {
int num = -121;
Pallindrom pallindrom = new Pallindrom ();
boolean answer = pallindrom.isPalindrome (num);
System.out.println (answer);
}
}
| 745a97490358d9916d6acfcf44f24b4581b9307b | [
"Java"
] | 1 | Java | wanghanting/Leetcode | 2c218e0474eed291bf834e54f45e77105c5f9af6 | f086744440e01663aa78a806420e6b66568e7dde |
refs/heads/main | <repo_name>cquan808/simple-python-app<file_sep>/README.md
# simple-python-app
A simple python application to convert your weight to kg or lbs
<file_sep>/testMain.py
import unittest
import unitConverter
class TestMain(unittest.TestCase):
"""
Test the add function from the calc library
"""
def test_kg_to_lbs(self):
"""
Test that kg is converted to lbs
"""
result = unitConverter.kg_to_lbs(90)
self.assertEqual(result, 200.0)
def test_lbs_to_kg(self):
"""
Test that lbs is converted to kg
"""
result = unitConverter.lbs_to_kg(145)
self.assertEqual(result, 65.25)
if __name__ == '__main__':
unittest.main()<file_sep>/main.py
# This is a simple application to convert your weight from lbs to kg or
# from kg to lbs
import unitConverter
class PrintResults():
def print_results(name, weight, unit_result):
# only for python version 3+
# print(f"Hello {name}, your weight is {weight} in {unit_result}.")
print("Hello " + name + ", your weight is " + weight + " in " + unit_result + ".")
'''
name = input("What is your name: ")
try:
weight = int(input("What is your weight: "))
except ValueError:
print("Invalid value")
unit = (input("(K)g or (l)bs: ")).upper()
'''
name = "Chris"
weight = int(143)
unit = "l"
unit_result = ""
if unit.upper() == "K":
unit_result = "lbs"
weight = unitConverter.kg_to_lbs(weight)
# print(f"Hello {name}, your weight is {weight} in {unit_result}")
PrintResults.print_results(name, weight, unit_result)
elif unit.upper() == "L":
unit_result = "kg"
weight = unitConverter.lbs_to_kg(weight)
# print(f"Hello {name}, your weight is {weight} in {unit_result}")
PrintResults.print_results(name, weight, unit_result)
else:
print("Unit must be 'k' for kg or 'l' for lbs, please try again") | 2e9b6235d0d119c8ac84a50aa3ab920bd7233cd1 | [
"Markdown",
"Python"
] | 3 | Markdown | cquan808/simple-python-app | 512fe8fc6e4388c8735aed60650b6695b0384fbc | 583dbb1c1facf5060c145ef70e0bd17106a36734 |
refs/heads/master | <file_sep>package com.example.chris.sipho;
import java.io.Serializable;
/**
* Created by salv8 on 19/10/2017.
*/
public class Comentario implements Serializable {
private long usuario;
private String coment, valoracion, fecha, nomusr, img;
public Comentario(long usuario, String coment, String valoracion, String fecha, String nomusr, String img) {
this.usuario = usuario;
this.coment = coment;
this.valoracion = valoracion;
this.fecha = fecha;
this.nomusr = nomusr;
this.img = img;
}
public long getUsuario() {
return usuario;
}
public void setUsuario(long usuario) {
this.usuario = usuario;
}
public String getComent() {
return coment;
}
public void setComent(String coment) {
this.coment = coment;
}
public String getValoracion() {
return valoracion;
}
public void setValoracion(String valoracion) {
this.valoracion = valoracion;
}
public String getFecha() {
return fecha;
}
public void setFecha(String fecha) {
this.fecha = fecha;
}
public String getNomusr() {
return nomusr;
}
public void setNomusr(String nomusr) {
this.nomusr = nomusr;
}
public String getImg() {
return img;
}
public void setImg(String img) {
this.img = img;
}
}
<file_sep>package com.example.chris.sipho;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.signature.StringSignature;
import java.util.List;
import static com.facebook.FacebookSdk.getApplicationContext;
/**
* Created by salv8 on 03/12/2017.
*/
public class AdaptadorUsr extends BaseAdapter {
Context contexto;
List<Usuario> ListaUsuarios;
ImageView imagenUsuario;
public AdaptadorUsr(Context contexto, List<Usuario> listaUsuarios) {
this.contexto = contexto;
ListaUsuarios = listaUsuarios;
}
@Override
public int getCount() {
return ListaUsuarios.size();
}
@Override
public Object getItem(int position) {
return ListaUsuarios.get(position);
}
@Override
public long getItemId(int position) {
long i= Long.valueOf(ListaUsuarios.get(position).getId());
return i;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View vista = convertView;
LayoutInflater inflate = LayoutInflater.from(contexto);
vista = inflate.inflate(R.layout.usr_adapter , null);
imagenUsuario = (ImageView) vista.findViewById(R.id.imageViewUsrAdapter);
TextView nombreCompleto= (TextView) vista.findViewById(R.id.textViewNombreUsrAdapter);
TextView nombreCorto = (TextView) vista.findViewById(R.id.textViewUsrAdapter);
nombreCompleto.setText("@"+ListaUsuarios.get(position).getNombreCompleto());
nombreCorto.setText(ListaUsuarios.get(position).getNombreUsuario());
Glide.with(getApplicationContext())
.load(ListaUsuarios.get(position).getImagen())
.signature((new StringSignature(String.valueOf(System.currentTimeMillis()/ (15 * 1000)))))
.into(imagenUsuario);
return vista;
}
}
<file_sep>package com.example.chris.sipho;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.facebook.AccessToken;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.Profile;
import com.facebook.ProfileTracker;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import org.json.JSONArray;
import org.json.JSONException;
import static android.provider.ContactsContract.CommonDataKinds.Website.URL;
public class LoginActivity extends AppCompatActivity {
private CallbackManager callbackManager;
private LoginButton loginButton;
private int resp;
Metodos met = new Metodos();
private ProfileTracker profileTracker;
JSONArray ja;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
callbackManager = CallbackManager.Factory.create();
final String bd = met.getBdUrl();
loginButton = (LoginButton) findViewById(R.id.loginButton);
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
profileTracker = new ProfileTracker() {
@Override
protected void onCurrentProfileChanged(Profile oldProfile, Profile currentProfile) {
if (currentProfile != null) {
//met.guardarDatosFacebook(currentProfile);
final Profile profile = Profile.getCurrentProfile();
String id = profile.getId();
String url= bd+"consulta.php?id="+id;
buscarExistencia(url);
}
}
};
if (AccessToken.getCurrentAccessToken() == null) {
Toast.makeText(LoginActivity.this, "Error facebook", Toast.LENGTH_SHORT).show();
} else {
final Profile profile = Profile.getCurrentProfile();
if (profile != null) {
met.guardarDatosFacebook(profile);
String url= bd+"consulta.php?id="+met.getId();
buscarExistencia(url);
} else {
Profile.fetchProfileForCurrentAccessToken();
}
}
}
@Override
public void onCancel() {
Toast.makeText(LoginActivity.this, "Cancelado", Toast.LENGTH_SHORT).show();
}
@Override
public void onError(FacebookException error) {
Toast.makeText(LoginActivity.this, "Error", Toast.LENGTH_LONG).show();
}
});
}
private void goMainScreen() {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
private void goCrearScreen() {
Intent intent = new Intent(this, CrearActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
public void buscarExistencia(String URL){
Log.i("url",""+URL);
RequestQueue queue = Volley.newRequestQueue(this);
StringRequest stringRequest = new StringRequest(Request.Method.GET, URL, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
ja = new JSONArray(response);
String contra = ja.getString(0);
if(contra.equals("")){
}else{
resp=0;
}
} catch (JSONException e) {
e.printStackTrace();
resp = 1;
Toast.makeText(getApplicationContext(),"El usuario no existe en la base de datos",Toast.LENGTH_SHORT).show();
}
if(resp == 1){
goCrearScreen();
}else {
goMainScreen();
Toast.makeText(LoginActivity.this, "Bienvenido de vuelta", Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(LoginActivity.this, "Ops Error", Toast.LENGTH_SHORT).show();
}
});
queue.add(stringRequest);
}
}
<file_sep>package com.example.chris.sipho;
import java.io.Serializable;
/**
* Created by salv8 on 03/12/2017.
*/
public class Usuario implements Serializable {
private String id,nombreCompleto,nombreUsuario,imagen;
public Usuario(String id, String nombreCompleto, String nombreUsuario, String imagen) {
this.id = id;
this.nombreCompleto = nombreCompleto;
this.nombreUsuario = nombreUsuario;
this.imagen = imagen;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getNombreCompleto() {
return nombreCompleto;
}
public void setNombreCompleto(String nombreCompleto) {
this.nombreCompleto = nombreCompleto;
}
public String getNombreUsuario() {
return nombreUsuario;
}
public void setNombreUsuario(String nombreUsuario) {
this.nombreUsuario = nombreUsuario;
}
public String getImagen() {
return imagen;
}
public void setImagen(String imagen) {
this.imagen = imagen;
}
}
<file_sep>package com.example.chris.sipho;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import java.util.ArrayList;
public class VerInformacion extends AppCompatActivity {
String id,tipo,URL;
TextView textoSuperior;
ListView listaUsuarios;
ArrayList<Usuario> Lista1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ver_informacion);
Intent intent = getIntent();
id=intent.getStringExtra("idUsuario");
tipo= intent.getStringExtra("tipo");
textoSuperior = (TextView) findViewById(R.id.textViewInfoSeguidos);
listaUsuarios = (ListView) findViewById(R.id.lstInfo);
Lista1 = new ArrayList<Usuario>();
switch (tipo){
case "seguidor":
URL="https://salv8.000webhostapp.com/seguidores.php?id="+id;
textoSuperior.setText("Seguidores");
break;
case "seguidos":
URL="https://salv8.000webhostapp.com/seguidos.php?id="+id;
textoSuperior.setText("Seguidos");
break;
}
buscarUsuarios(URL);
}
private void buscarUsuarios(String url) {
Log.i("url",""+URL);
RequestQueue queue = Volley.newRequestQueue(this);
StringRequest stringRequest = new StringRequest(Request.Method.GET, URL, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
response = response.replace("][",",");
if(response.length()>0){
try {
JSONArray mja = new JSONArray(response);
Log.i("sizejson",""+mja.length());
prepararList(mja);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),"Error "+e,Toast.LENGTH_LONG).show();
}catch (NullPointerException s){
s.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(VerInformacion.this, "Ops Error 1"+error, Toast.LENGTH_SHORT).show();
}
});
queue.add(stringRequest);
}
private void prepararList(JSONArray mja){
Lista1.clear();
ArrayList<String> lista = new ArrayList<>();
for (int i=0;i<mja.length();i+=8){
try {
lista.add(mja.getString(i)+",æè"+mja.getString(i+1)+",æè"+mja.getString(i+2)+",æè"+mja.getString(i+3)+",æè"+mja.getString(i+4)+",æè"+mja.getString(i+5)+",æè"+mja.getString(i+6)+",æè"+mja.getString(i+7));
}catch (JSONException e){
}
}
for (int m=0;m<lista.size();m++) {
String[] slista = lista.get(m).split(",æè");
Lista1.add(new Usuario(slista[0],slista[1],slista[2],slista[3]));
}
AdaptadorUsr miadaptador = new AdaptadorUsr(getApplicationContext(),Lista1);
listaUsuarios.setAdapter(miadaptador);
}
}
<file_sep>package com.example.chris.sipho;
import android.content.Intent;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.bumptech.glide.Glide;
import com.bumptech.glide.signature.StringSignature;
import com.facebook.Profile;
import com.facebook.ProfileTracker;
import org.json.JSONArray;
import org.json.JSONException;
import de.hdodenhof.circleimageview.CircleImageView;
import static android.icu.lang.UCharacter.GraphemeClusterBreak.T;
import static com.example.chris.sipho.R.id.idTextView;
import static com.example.chris.sipho.R.id.nameTextView;
import static com.example.chris.sipho.R.id.photoImageView;
public class CrearActivity extends AppCompatActivity {
private Button btnCrear;
private ImageView imageViewCrear;
private EditText editTextCrear;
private TextView textViewCrear;
private ProfileTracker profileTracker;
Profile profile = Profile.getCurrentProfile();
Metodos met = new Metodos();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_crear);
met.guardarDatosFacebook(profile);
btnCrear = (Button) findViewById(R.id.buttonCrear);
imageViewCrear = (CircleImageView) findViewById(R.id.imageViewCrear);
editTextCrear = (EditText) findViewById(R.id.editTextCrear);
textViewCrear = (TextView) findViewById(R.id.textViewCrear);
//Toast.makeText(CrearActivity.this, "1", Toast.LENGTH_SHORT).show();
final String id = profile.getId();
displayProfileInfo();
btnCrear.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String nombre = editTextCrear.getText().toString();
if(nombre.isEmpty()){
editTextCrear.setError("¡Ingresa tu nombre de usuario!");
}else{
if(nombre.length() < 3){
editTextCrear.setError("Minimo 3 caracteres");
}else {
String existe= met.getBdUrl()+"completarVerOferta.php?nombre="+nombre;
buscarExistencia(existe);
}
}
}
});
}
public void buscarExistencia(String URL){
Log.i("url",""+URL);
RequestQueue queue = Volley.newRequestQueue(this);
StringRequest stringRequest = new StringRequest(Request.Method.GET, URL, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONArray ja;
ja = new JSONArray(response);
Toast.makeText(CrearActivity.this, "Usuario ya existe", Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
String insertar = met.getBdUrl()+"registro.php?id="+profile.getId()+"&nombre="+editTextCrear.getText().toString()+"&completo="+met.getName()+"&img="+met.getPhotoUrl();
insertar = insertar.replaceAll(" ","%20");
insertarDatos(insertar);
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(CrearActivity.this, "Ops Error", Toast.LENGTH_SHORT).show();
}
});
queue.add(stringRequest);
}
public void insertarDatos(String URL){
Log.i("url",""+URL);
RequestQueue queue = Volley.newRequestQueue(this);
StringRequest stringRequest = new StringRequest(Request.Method.GET, URL, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Toast.makeText(CrearActivity.this, "Correcto!", Toast.LENGTH_SHORT).show();
goMainScreen();
}
}, new Response.ErrorListener(){
@Override
public void onErrorResponse(VolleyError error) {
}
});
queue.add(stringRequest);
}
private void displayProfileInfo() {
String id = met.getId();
String name = met.getName();
String photoUrl = met.getPhotoUrl();
textViewCrear.setText(name);
Glide.with(getApplicationContext())
.load(photoUrl)
.signature((new StringSignature(String.valueOf(System.currentTimeMillis()/ (15 * 1000)))))
.into(imageViewCrear);
}
private void goMainScreen() {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
<file_sep>package com.example.chris.sipho;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.signature.StringSignature;
import java.util.List;
import de.hdodenhof.circleimageview.CircleImageView;
import static com.facebook.FacebookSdk.getApplicationContext;
/**
* Created by salv8 on 19/10/2017.
*/
public class AdaptadorComentarios extends BaseAdapter {
Context contexto;
List<Comentario> ListaComentario;
public AdaptadorComentarios(Context contexto, List<Comentario> listaComentario) {
this.contexto = contexto;
ListaComentario = listaComentario;
}
@Override
public int getCount() {
return ListaComentario.size();
}
@Override
public Object getItem(int position) {
return ListaComentario.get(position);
}
@Override
public long getItemId(int position) {
return ListaComentario.get(position).getUsuario();
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View vista = convertView;
LayoutInflater inflate = LayoutInflater.from(contexto);
vista = inflate.inflate(R.layout.comentarios_list_view , null);
CircleImageView imgusr = (CircleImageView) vista.findViewById(R.id.imageViewUsuarioComent);
TextView nomusr = (TextView) vista.findViewById(R.id.textUsrNmeComent);
TextView fecha = (TextView) vista.findViewById(R.id.textFechaComent);
TextView coment = (TextView) vista.findViewById(R.id.textComentComent);
ImageView reco = (ImageView) vista.findViewById(R.id.imageViewComent);
nomusr.setText("@"+ListaComentario.get(position).getNomusr());
fecha.setText(ListaComentario.get(position).getFecha());
coment.setText(ListaComentario.get(position).getComent());
Glide.with(getApplicationContext())
.load(ListaComentario.get(position).getImg())
.signature((new StringSignature(String.valueOf(System.currentTimeMillis()/ (15 * 1000)))))
.into(imgusr);
if(ListaComentario.get(position).getValoracion().equals("Si")){
reco.setImageResource(R.drawable.icon_thumbs_up);
}else{
reco.setImageResource(R.drawable.icon_thumbs_down);
}
return vista;
}
}
<file_sep>package com.example.chris.sipho;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Created by salv8 on 21/11/2017.
*/
public class DialogoGustos extends DialogFragment {
ArrayList mSelectedItems;
List cargar = new ArrayList();
boolean[] selec= new boolean[9];
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
mSelectedItems = new ArrayList(); // Where we track the selected items
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
TinyDB tinydb = new TinyDB(getActivity());
cargar=tinydb.getListInt("SIPHO_GUSTOS");
if(cargar.size()!=0){
for (int i=0;i<cargar.size();i++){
String b = cargar.get(i).toString();
int a = Integer.valueOf(b);
selec[a]=true;
mSelectedItems.add(a);
}
}else{
Arrays.fill(selec,true);
for(int v=0;v<9;v++){
mSelectedItems.add(v);
}
}
// Set the dialog title
builder.setTitle(R.string.gusto)
// Specify the list array, the items to be selected by default (null for none),
// and the listener through which to receive callbacks when items are selected
.setMultiChoiceItems(R.array.opcionesCategoria, selec,
new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog, int which,
boolean isChecked) {
if (isChecked) {
// If the user checked the item, add it to the selected items
mSelectedItems.add(which);
} else if (mSelectedItems.contains(which)) {
// Else, if the item is already in the array, remove it
mSelectedItems.remove(Integer.valueOf(which));
}
}
})
// Set the action buttons
.setPositiveButton(R.string.aceptar, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
TinyDB tinydb2 = new TinyDB(getActivity());
tinydb2.putListInt("SIPHO_GUSTOS",mSelectedItems);
Intent intent = new Intent(getActivity(), MainActivity.class);
startActivity(intent);
}
})
.setNegativeButton(R.string.cancelar, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
dismiss();
}
});
return builder.create();
}
}
| dfd8d8aa27fa169929675ae265418b4f6eb85bcb | [
"Java"
] | 8 | Java | ChrisAbarza/Sipho | a4d7c2d94fd8595292e644a35f3c970d2d1629c7 | 2cb692bd59ae824a8b9f5cf28897eb2ca6c3c012 |
refs/heads/master | <file_sep>package com.telusko;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
public class CreateDoc extends HttpServlet {
static final String SAVE_DIR = "G://JavaProject/FileUploadDemo/";
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String fileName = request.getHeader("fileName");
System.out.println("CreateDoc: " + fileName);
OutputStream output = new FileOutputStream(SAVE_DIR + fileName);
output.flush();
output.close();
Process process = Runtime.getRuntime().exec("cmd /c "
+ SAVE_DIR + fileName);
response.getWriter().print("File was create");
}
}
| 0351d3bba62754c5feb7ed72eea45cba55dbe0c9 | [
"Java"
] | 1 | Java | YauhenBel/FileUploadDemo | 31b2f5aefaa0f3c9fb5ec34d8bf5be2ec0c05f7d | ac396044a1f755477cebca83e7eb2f45cf3eb94b |
refs/heads/main | <file_sep>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define MAX 100
#define TRUE 1
#define FALSE 0
typedef int element;
typedef struct {
element data[MAX];
int top;
}Stacktype;
// 스택 초기화 함수
void init_stack(Stacktype* s)
{
s->top = -1;
}
//공백 상태 검출 함수
int is_empty(Stacktype* s)
{
return (s->top == -1);
}
//포화 상태 검출 함수
int is_full(Stacktype * s)
{
return (s->top == (MAX - 1));
}
//삽입함수
void push(Stacktype * s, element item)
{
if (is_full(s)) {
fprintf(stderr, "스택 포화 에러\n");
return;
}
else s->data[++(s->top)] = item;
}
//삭제 함수
element pop(Stacktype * s)
{
if (is_empty(s)) {
fprintf(stderr, "스택 공백 에러\n");
exit(1);
}
else return s->data[(s->top)--];
}
//피크 함수
element peek(Stacktype * s)
{
if (is_empty(s)) {
fprintf(stderr, "스택 공백 에러\n");
exit(1);
}
else return s->data[s->top];
}
int check(char palindrome[]) {
Stacktype sent;
int i = 0;
char ch_in, ch_out;
int length = 0;
init_stack(&sent);
length = strlen(palindrome);
for (i = 0; i < length; i++) {
ch_in = palindrome[i];
if (ch_in == ' ' || ch_in == ',') continue;
ch_in = tolower(ch_in);
push(&sent,ch_in);
}
for (i = 0; i < length; i++) {
ch_in = palindrome[i];
if (ch_in == ' ' || ch_in == ',') continue;
ch_in = tolower(ch_in);
ch_out = pop(&sent);
if (ch_in != ch_out) return FALSE;
}
return TRUE;
}
int main() {
char sentence[MAX];
int end = 0;
printf("원하는 영어단어를 입력하세요.\n");
scanf_s("%s",&sentence,MAX);
end = check(sentence);
if (end != TRUE) {
printf("회문이아닙니다.\n");
}
else {
printf("회문입니다.\n");
}
}<file_sep># palindrome_c
find palindrome using c
| 8d0bf06d15af5537bc83359d2bf5e83e6eac5eb3 | [
"Markdown",
"C"
] | 2 | C | HRDI0/palindrome_c | 69bc2fa6897c4ef72c3b2c02854d37bd1cf85c08 | 9b62abcbe056c51f913110fe2acf2add7580bb71 |
refs/heads/master | <repo_name>vishalgaichor954/ProductManagementAngular<file_sep>/src/app/shared/enum/todo-action-types-enum.ts
export enum TodoActionTypes{
Add = 'Add',
Remove = 'Remove',
Login = 'Login',
Logout = 'Logout',
GetUser = 'GetUser',
SetIsLoginFlag = 'SetIsLoginFlag',
GetIsLoginFlag = 'GetIsLoginFlag'
}<file_sep>/src/app/services/DataService.ts
import { Injectable } from '@angular/core';
import { HttpHeaders, HttpClient } from '@angular/common/http';
import { catchError, map } from 'rxjs/operators';
// import { Observable } from 'rxjs';
import { Observable } from 'rxjs';
import { AppError } from '../Common/AppError';
export class DataService {
// private url = "";// = "https://csacsacjsonplaceholder.typicode.com/posts";
constructor(private url: string, private http: HttpClient) {
}
login(resource: any) {
const body = new URLSearchParams();
body.set('grant_type', resource.grant_type);
body.set('username', resource.username);
body.set('password', <PASSWORD>);
const options: any = {
headers: new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
};
// const headers = { 'Content-Type': resource.ContentType };
// const headers = new Headers({'Content-Type': resource.ContentType});
// const body = { grant_type: resource.grant_type, username: resource.username, password: <PASSWORD> };
return this.http.post(this.url, body.toString(), options).pipe(
map(response => response),
// catchError(this.handleError)
);
}
private handleError(error: Response)
{
return Observable.throw(new AppError(error));
}
}<file_sep>/src/app/Common/AppError.ts
export class AppError{
constructor(public originalerror: Response){
// debugger;
alert('AppError');
alert(JSON.stringify(originalerror));
}
}<file_sep>/src/app/app.component.ts
import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { Store } from '@ngrx/store';
import { SetLoginAction, SetLoginFlagAction } from '../app/actions/todo.actions';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'ProductManagement';
constructor(private router: Router, private store: Store<{ loginuser: any }>){
// debugger;
const user = localStorage.getItem('user');
if (user === undefined || user === '' || user === null)
{
this.store.dispatch(new SetLoginFlagAction(false));
this.router.navigate(['/login']);
}
else if(user && JSON.parse(user).access_token)
{
this.store.dispatch(new SetLoginAction(user))
this.store.dispatch(new SetLoginFlagAction(true));
this.router.navigate(['/']);
}
}
}
<file_sep>/src/app/app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule, ErrorHandler } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { LoginComponent } from './login/login.component';
import { NavbarComponent } from './navbar/navbar.component';
import { HttpClientModule } from '@angular/common/http';
import { RouterModule } from '@angular/router';
import { PageNotFoundComponent } from './page-not-found/page-not-found.component';
import { HomeComponent } from './home/home.component';
import { AuthService } from './services/AuthService';
import { AppErrorHandler } from './Common/AppErrorHandler';
import { StoreModule} from '@ngrx/store';
import { TodoReducer } from '../app/reducers/todo.reducers';
import { IsLoginFlagReducer, LoginReducer } from './reducers/login.reducers';
@NgModule({
declarations: [
AppComponent,
LoginComponent,
NavbarComponent,
PageNotFoundComponent
],
imports: [
// NgbModule,
BrowserModule,
FormsModule,
ReactiveFormsModule,
HttpClientModule,
AppRoutingModule,
RouterModule.forRoot(
[
{ path: '', component: HomeComponent },
// { path: 'home', component: HomeComponent },
{ path: 'login', component: LoginComponent },
{ path: '**', component: PageNotFoundComponent },
]
),
StoreModule.forRoot(
{
todos: TodoReducer,
loginuser: LoginReducer,
isLoginFlag: IsLoginFlagReducer
}
)
// ,
// AppBootstrapModule
],
providers: [
AuthService,
{ provide: ErrorHandler, useClass: AppErrorHandler}
],
bootstrap: [AppComponent]
})
export class AppModule { }
<file_sep>/src/app/login/login.component.ts
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { AuthService } from '../services/AuthService';
import { Store } from '@ngrx/store';
import { SetLoginAction, SetLoginFlagAction } from '../actions/todo.actions';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
invalidLogin: boolean = false;
constructor(private router: Router,
private authservice: AuthService,
private store: Store<{ loginuser: any }>) {
}
signIn(Uservalues: any){
// debugger;
// this.invalidLogin = true;
const TempContentType = 'application/x-www-form-urlencoded';
const TempgrantType = 'password';
if(Uservalues.username !== '' && Uservalues.password !== '')
{
const credentials = {
username: Uservalues.username,
password: <PASSWORD>,
ContentType: TempContentType,
grant_type: TempgrantType
};
this.authservice.login(credentials)
.subscribe((response: any) => {
debugger;
localStorage.setItem('user', JSON.stringify(response));
if(response && response.access_token)
{
this.store.dispatch(new SetLoginAction(JSON.stringify(response)))
this.store.dispatch(new SetLoginFlagAction(true));
this.invalidLogin = false;
this.router.navigate(['/']);
}
else
{
this.store.dispatch(new SetLoginFlagAction(false));
this.invalidLogin = true;
}
},
(error: any) => {
if (error.statusText === 'Unknown Error')
{
alert('Service is temporarily down, please try after some time.');
this.invalidLogin = true;
}
else
{
this.invalidLogin = true;
}
console.log(JSON.stringify(error));
});
}
else
{
this.invalidLogin = true;
}
}
ngOnInit(): void {
}
}
<file_sep>/src/app/navbar/navbar.component.ts
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { select, Store } from '@ngrx/store';
import { SetLoginFlagAction, UserLogoutAction } from '../actions/todo.actions';
@Component({
selector: 'app-navbar',
templateUrl: './navbar.component.html',
styleUrls: ['./navbar.component.css']
})
export class NavbarComponent implements OnInit {
isloggedUser: boolean = false;
loginUsername:string ="";
constructor(private router: Router, private store: Store<{ isLoginFlag: any, loginuser: any }>) { }
ngOnInit(): void {
// debugger;
this.store.pipe(select('isLoginFlag')).subscribe(values => {
console.log(values);
this.isloggedUser = values;
});
this.store.pipe(select('loginuser')).subscribe((values : any) => {
// debugger
if(values)
{
this.loginUsername = JSON.parse(values).username;
}
});
}
LogOutUser(){
// debugger;
localStorage.clear();
this.store.dispatch(new UserLogoutAction(""));
this.store.dispatch(new SetLoginFlagAction(false));
alert("User signout successfully.");
this.router.navigate(['/login']);
}
}
<file_sep>/src/app/reducers/login.reducers.ts
import { TodoActionTypes} from '../shared/enum/todo-action-types-enum';
export const initialState: any= "";
export function LoginReducer(state:any = initialState, action:any){
// debugger;
switch(action.type){
case TodoActionTypes.Login:
state = action.payload;///[...state, action.payload]
return state;
case TodoActionTypes.Logout:
state = "";///[...state, action.payload]
return state;
default:
return state;
}
}
export function IsLoginFlagReducer(state:any = false, action:any){
// debugger;
switch(action.type){
case TodoActionTypes.SetIsLoginFlag:
state = action.payload;///[...state, action.payload]
return state;
default:
return state;
}
}<file_sep>/src/app/reducers/todo.reducers.ts
import { TodoActionTypes} from '../shared/enum/todo-action-types-enum';
import { ActionParents } from '../actions/todo.actions';
import { Todo } from '../models/todo';
export const initialState: Todo[] = [
{ title: 'Todo1'},
{ title: 'Todo2'},
{ title : 'Todo3'}
];
export function TodoReducer(state: any = initialState, action: any){
switch (action.type){
case TodoActionTypes.Add:
return [...state, action.payload];
default:
return state;
}
}<file_sep>/src/app/services/AuthService.ts
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { DataService } from './DataService';
@Injectable({
providedIn: 'root'
})
export class AuthService extends DataService {
constructor(http: HttpClient) {
super('http://localhost:44360/login', http);
}
// login(credentials: any) {
// return this.dataservice.login('http://localhost:44360/login', credentials);
// }
}<file_sep>/src/app/Common/AppErrorHandler.ts
import { ErrorHandler } from '@angular/core';
export class AppErrorHandler extends ErrorHandler{
handleError(error: any){
if(error.statusText === 'Unknown Error')
{
alert('Service is temporarily down, please try after some time.');
console.log(JSON.stringify(error));
}
}
}<file_sep>/src/app/actions/todo.actions.ts
import { Action } from '@ngrx/store';
import { TodoActionTypes} from '../shared/enum/todo-action-types-enum';
export class ActionParents implements Action {
type: any;
payload: any;
}
export class TodoAdd implements ActionParents{
type: any = TodoActionTypes.Add;
constructor(public payload: any){}
}
export class SetLoginAction implements ActionParents{
// debugger;
type: any = TodoActionTypes.Login;
constructor(public payload: any){}
}
export class UserLogoutAction implements ActionParents{
// debugger;
type: any = TodoActionTypes.Logout;
constructor(public payload: any){}
}
// export class GetLoginAction implements ActionParents{
// type: any = TodoActionTypes.GetUser;
// constructor(public payload: any){}
// }
export class SetLoginFlagAction implements ActionParents{
// debugger;
type: any = TodoActionTypes.SetIsLoginFlag;
constructor(public payload: any){}
}
// export class GetLoginFlagAction implements ActionParents{
// type: any = TodoActionTypes.GetIsLoginFlag;
// constructor(public payload: any){}
// } | 4b3da9aaa357a2e2d8f7963835414c5e58ee336f | [
"TypeScript"
] | 12 | TypeScript | vishalgaichor954/ProductManagementAngular | b816cdafc333c6b419585a18bfa7e80b8374d748 | db1f0a2cea8f72675fe6d379217c816460b15479 |
refs/heads/master | <file_sep>import React from "react";
function ErrorPage() {
return (
<div style={{ padding: "10%" }}>
<h1 style={{ textAlign: "center", color: "green" }}>
Oops.! It feels lonely here..!
</h1>
<h3 style={{ textAlign: "center", color: "grey" }}>
This route is not defined
</h3>
</div>
);
}
export default ErrorPage;
<file_sep>import React, { Component, useState, useEffect } from "react";
import axios from "axios";
import { Header, Icon, Divider } from "semantic-ui-react";
import FilterArea from "../Components/FilterArea";
import DisplayArea from "../Components/DisplayArea";
// import ButtonGrp from "../Components/ButtonGroup";
import "../Assets/style.css";
function HomePage() {
const [data, setData] = React.useState([]);
const [launch, setLaunch] = React.useState("");
const [land, setLand] = React.useState(null);
const [year, setYear] = React.useState("");
const [s, setS] = React.useState("");
const loading = data.length === 0;
const FetchData = async () => {
var config = {
method: "get",
url: `https://api.spacexdata.com/v3/launches?limit=100`,
headers: {
// Cookie: "__cfduid=d3a4f794862e712b2abd9daeac009c6c91614260982",
},
};
var temp = [];
await axios(config)
.then(function (response) {
setData([]);
temp = [];
if (launch === "Succes")
temp = response.data.filter((a) => {
if (a.launch_success) {
return a;
}
});
else if (launch === "Fai")
temp = response.data.filter((a) => a.launch_success === false);
else temp = response.data;
if (land)
temp = temp.filter((a) => {
if (a.rocket.first_stage.cores[0].land_success) {
return a;
}
});
else temp = temp.slice();
if (year)
temp = temp.filter((a) => {
if (a.launch_year == year) return a;
});
else temp = temp.slice();
console.log("NEW Data", temp);
setData(temp.slice());
console.log("DATA REC:", data);
})
.catch(function (error) {
console.log(error);
});
};
React.useEffect(() => {
FetchData();
}, [launch, land, year]);
// var f = [
// { val: launch, str: `&launch_succcess=${launch}` },
// // { val: land, str: `&land_success=${land}` },
// // { val: year, str: `&launch_year=${year}` },
// ];
// var temp_s = "";
// f.forEach((item) => {
// if (item.val) {
// temp_s = temp_s + item.str;
// }
// });
// setS(temp_s);
return (
<div className="demo-big-content">
<Header
inverted
as="h1"
className="head"
style={{ padding: "2%", margin: "1%", borderRadius: 10 }}
>
<Icon name="space shuttle" /> Explor SpaceX Programs
</Header>
<FilterArea setLaunch={setLaunch} setLand={setLand} setYear={setYear} />
<Divider style={{ margin: "2%" }} />
{loading ? (
<h2 style={{ textAlign: "center", marginTop: "5%" }}>Loading...</h2>
) : (
<DisplayArea data={data} />
)}
</div>
);
}
export default HomePage;
<file_sep>import React, { Component } from "react";
import { Table } from "semantic-ui-react";
export default class DisplayArea extends Component {
constructor(props) {
super(props);
this.state = {
column: null,
data: this.props.data,
direction: null,
};
}
render() {
return (
<div style={{ margin: "2%" }}>
<Table sortable celled>
<Table.Header>
<Table.Row>
<Table.HeaderCell
sorted={
this.state.column === "flight_num"
? this.state.direction
: null
}
// onClick={() => dispatch({ type: "CHANGE_SORT", this.state.column: "name" })}
>
Flight No.
</Table.HeaderCell>
<Table.HeaderCell
sorted={
this.state.column === "mission_name"
? this.state.direction
: null
}
// onClick={() => dispatch({ type: "CHANGE_SORT", this.state.column: "age" })}
>
Mission Name
</Table.HeaderCell>
<Table.HeaderCell
sorted={
this.state.column === "launch_year"
? this.state.direction
: null
}
// onClick={() =>dispatch({ type: "CHANGE_SORT", this.state.column: "gender" })}
>
Launch Year
</Table.HeaderCell>
<Table.HeaderCell
sorted={
this.state.column === "launch_status"
? this.state.direction
: null
}
// onClick={() =>dispatch({ type: "CHANGE_SORT", this.state.column: "gender" })}
>
Launch Status
</Table.HeaderCell>
<Table.HeaderCell
sorted={
this.state.column === "launch_status"
? this.state.direction
: null
}
// onClick={() =>dispatch({ type: "CHANGE_SORT", this.state.column: "gender" })}
>
Landing Status
</Table.HeaderCell>
<Table.HeaderCell
sorted={
this.state.column === "details" ? this.state.direction : null
}
// onClick={() =>dispatch({ type: "CHANGE_SORT", this.state.column: "gender" })}
>
Details
</Table.HeaderCell>
</Table.Row>
</Table.Header>
<Table.Body>
{this.state.data.map((item, index) => (
<Table.Row key={item.flight_number}>
<Table.Cell>{item.flight_number}</Table.Cell>
<Table.Cell>{item.mission_name}</Table.Cell>
<Table.Cell>{item.launch_year}</Table.Cell>
<Table.Cell>
{item.launch_success ? "Success" : "Fail"}
</Table.Cell>
<Table.Cell>
{item.rocket.first_stage.cores[0].land_success === null
? "N/A"
: "Success"}
</Table.Cell>
<Table.Cell>
{item.details ? item.details : "No Details Available"}
</Table.Cell>
</Table.Row>
))}
</Table.Body>
</Table>
</div>
);
}
}
<file_sep># SpaceX-Programs
## Snapshots of the Web-App
### Main Page

### Filter Applied

### Simultaneous Filters

## Technology Stack
### Framework - ReactJS
### UI Library - Semantic UI
### API Module - Axios
### Live Demo : https://fast-eyrie-05031.herokuapp.com/
<file_sep>import React from "react";
import { Form, Checkbox, Table } from "semantic-ui-react";
function FilterArea(props) {
const [launchyear, setLaunchYear] = React.useState("");
const [launchstatus, setLaunchStatus] = React.useState("");
const [landingstatus, setLandingStatus] = React.useState("");
const [togglelaunch, toggleLaunch] = React.useState(false);
const [toggleland, toggleLand] = React.useState(false);
const [toggleyear, toggleYear] = React.useState(false);
const filters = [
{
id: "00",
placeholder: "Launch Year",
name: "launchyear",
value: launchyear,
toggle: async () => {
await toggleYear(!toggleyear);
if (toggleyear) props.setYear(launchyear);
else {
props.setYear("");
setLaunchYear("");
}
},
change: async (x) => {
await setLaunchYear(x);
if (toggleyear) await props.setYear(launchyear);
else await props.setYear("");
},
},
{
id: "01",
placeholder: "Launch Status",
name: "launchstatus",
value: launchstatus,
toggle: async () => {
await toggleLaunch(!togglelaunch);
if (togglelaunch) props.setLaunch(launchstatus);
else {
props.setLaunch("");
setLaunchStatus("");
}
},
change: (x) => {
setLaunchStatus(x);
if (togglelaunch) props.setLaunch(launchstatus);
else props.setYear("");
},
},
{
id: "10",
placeholder: "Landing Status",
name: "landingstatus",
value: landingstatus,
toggle: async () => {
await toggleLand(!toggleland);
if (toggleland) props.setLand(landingstatus);
else {
props.setLand("");
setLandingStatus("");
}
},
change: (x) => {
setLandingStatus(x);
if (toggleland) props.setLand(landingstatus);
else props.setYear("");
},
},
];
return (
<div style={{ marginLeft: "2%", marginRight: "80%" }}>
{/* <h3>Filters</h3> */}
<Form>
<Table celled columns={3}>
<Table.Header>
<Table.Row>
<Table.HeaderCell colSpan="3">Apply Filters</Table.HeaderCell>
{/* <Table.HeaderCell />
<Table.HeaderCell /> */}
</Table.Row>
</Table.Header>
<Table.Body>
<Table.Row>
{filters.map((item, index) => (
<Table.Cell key={item.id}>
<Table.Cell>
<Checkbox slider onChange={item.toggle} />
</Table.Cell>
<Table.Cell>
<Form.Input
placeholder={item.placeholder}
name={item.name}
value={item.value}
onChange={(e) => item.change(e.target.value)}
/>
{/* <h6>{item.value}</h6> */}
</Table.Cell>
</Table.Cell>
))}
</Table.Row>
</Table.Body>
</Table>
{/* <Form.Button content="Filter Data" /> */}
</Form>
</div>
);
}
export default FilterArea;
| d259ce84c655a4feb958a61741f96433cf5ad2a3 | [
"JavaScript",
"Markdown"
] | 5 | JavaScript | jayeshuk/SpaceX-Programs | aace6b1f27a3f884d659f3db309846d8ad3b5d4e | 09fdd50ab5a2b3e7a033e7f82b17268bf4548fe4 |
refs/heads/master | <file_sep># print("Hello World")
# n = input("What's your name? ")
# print("Hi")
# print(n)
r = int(input("nhap vao ban kinh: "))
p = 3.14
s = r*r*p
print(s) | ceb4d8bc6a2d1829962cc8f0128003e495ef148d | [
"Python"
] | 1 | Python | thewantedx/NguyenQuangHuy-Python-C4T | 19ecd16480b2a19a28a6ad029c132341de084c13 | 2624ccd9ef44b02d0268423e6430cdc176b2a394 |
refs/heads/master | <file_sep>/* ageOut.js */
function calculateAgeOut(month, day, year) {
var maxAge = 21
var bonusYear = (month >= 6)
return (year + maxAge) + (bonusYear)
}
function haveIAgedOut(month, day, year) {
var currentTime = new Date()
var currentYear = currentTime().getFullYear()
var currentMonth = currentTime.getMonth() + 1 // Because normally 0-11.
var finalsAreOver = (currentMonth > 8) // Not quite, but ok for now.
return (currentYear > calculateAgeOut(month, day, year) ||
(currentYear === calculateAgeOut(month, day, year) &&
finalsAreOver))
}<file_sep>import time
'''
I was born mach 20th 1995
Today is May 15th-ish 2014
2014 - 1995 = 19. (Assumes birthday is january 1st, sorta)
birthDayAfterJune1st = (birthMonth > 6) or (birthMonth == 6 and birthDay > 1)
If your birthday is after june 1st, on june 1st, you'll be a year younger that
expected.
'''
def calculateAgeOut(month, day, year):
maxAge = 21
bonusYear = (month >= 6)
return (year + maxAge) + (bonusYear)
def haveIAgedOut(month, day, year):
currentYear = int(time.strftime('%Y'))
currentMonth = int(time.strftime('%m'))
finalsAreOver = (currentMonth > 8) # This is not completely correct.
return (currentYear > calculateAgeOut(month, day, year) or
(currentYear == calculateAgeOut(month, day, year) and
finalsAreOver))
<file_sep>whenDoIAgeOut
=============
Small web app that calculates age out years for DCI and WGI. Built with Bootstrap, hosted at whenDoIAgeOut.herokuapp.com
| 0ba2750d53c24c2bf515d7ef6319a85843b65dc6 | [
"JavaScript",
"Python",
"Markdown"
] | 3 | JavaScript | evanbergeron/whenDoIAgeOut | e2f20f042c51277b9da18df845df6f2fe50f7ea8 | 8787f3971b4075cc6211ae93a5c589a12135531d |
refs/heads/master | <repo_name>bryce-fitzsimons/slack-gamebot<file_sep>/index.js
var http = require('http');
var request = require('request');
var extend = require('extend');
var WebSocket = require('ws');
var Game = require('./game');
// Fillable via custom bot token and name:
var bot_token = "<PASSWORD>'<PASSWORD>TOKEN";
var bot_name = "gamebot";
// Hold an array of all active PvP games.
// Key: user_id, Value: game instance
// Each game instance will have 2 keys (2 players) pointing to the same game
var games = [];
function SlackBot(token, name) {
this.token = token;
this.name = name;
// Message send counter
this.message_no = 1;
// Keep track of direct message channels
this.dm_channels = [];
// Once created, start connection
this.connect();
}
// Connection authentication must be done by HTTP API.
SlackBot.prototype.connect = function() {
var params = {name: this.name, token: this.token};
var data = {
url: 'https://slack.com/api/rtm.start',
form: params
};
console.log(data);
request.post(data, (function postResponse(error, response, body){
if(error){
console.log("POST ERROR: "+error);
}else{
var response_data = JSON.parse(body);
if ( response_data.hasOwnProperty('error') )
console.log("ERROR: "+response_data.error);
else
this.login(response_data);
}
}).bind(this));
}
// Once authenticated, continue the login process.
SlackBot.prototype.login = function(data) {
this.wsUrl = data.url;
this.self = data.self;
this.team = data.team;
this.channels = data.channels;
this.users = data.users;
this.ims = data.ims;
this.groups = data.groups;
// Get the ID of the #general channel
this.general_channel_id = this.channels.filter( function(obj){
return obj.name == "general";
})[0].id;
(this.wsConnect.bind(this))();
}
// Establish WebSocket connection. Listen to incoming events.
SlackBot.prototype.wsConnect = function() {
this.ws = new WebSocket(this.wsUrl);
// WS: OPEN
this.ws.on('open', function(data) {
console.log('WS open');
}.bind(this));
// WS: CLOSE
this.ws.on('close', function(data) {
console.log('WS close');
}.bind(this));
// WS: MESSAGE
this.ws.on('message', function(data) {
var message_obj = JSON.parse(data);
// Received Slack event of type "message"
if( message_obj.type == "message" ){
var sender_obj = this.users.filter( function(obj){
return obj.id == message_obj.user;
})[0];
// First, make sure to populate DM channels:
this.dm_channels[sender_obj.id] = message_obj.channel;
var message_text = message_obj.text;
var message_parts = message_text.split(' ');
// Command matching - case insensitive:
// ====================================
/***********************
==== Command: PLAY ====
***********************/
if(message_parts[0].match(/play/i)){
// Matches: "play username" | "Play @username"
var player_id_1 = sender_obj.id;
var player_id_2 = message_parts[1];
// If you used "@name", slack will return "<@UID>". Process accordingly:
if( player_id_2.slice(0,2) == "<@" && player_id_2.slice(-1) == ">" ){
player_id_2 = player_id_2.slice(2,-1);
}else
player_id_2 = this.getUserIdByName(message_parts[1]);
// Both player IDs are valid:
if( player_id_1 !== false && player_id_2 !== false){
var in_game = false;
// Make sure both players aren't already in a game
if( games.hasOwnProperty(player_id_1) ){
this.send("You're already in a game!", message_obj.channel);
in_game = true;
}
if( games.hasOwnProperty(player_id_2) ){
this.send(message_parts[1]+" is already in a game!", message_obj.channel);
in_game = true;
}
// Both players are not already in a game:
if ( !in_game ){
// Let the game begin!
// Create a new game, push it to the global games list
var game = new Game(player_id_1, player_id_2);
// We want 2 keys (user_id) per game, for easy retrieval
games[player_id_1] = game;
games[player_id_2] = game;
// (JS functions are passed by reference, so no duplicates are made)
var msg = game.renderBoard();
msg += "Make your move. `choose a # between 1-7 to select a column`";
this.send(msg, message_obj.channel);
var player_2_channel = this.getChannelByUserId(player_id_2);
if( !player_2_channel ){
var msg = "Please tell @"+this.getUserNameById(player_id_2)+" to say \"hi\" to me, otherwise they won't be able to receive messages from me.";
this.send(msg, message_obj.channel);
}
else
{
var msg = "@"+this.getUserNameById(player_id_1)+" has begun a game of Connect Four with you. Their move first...";
this.send(msg, player_2_channel);
}
}
}
else
{
this.send("Invalid players", message_obj.channel);
}
}
/***********************
==== Command: MOVE ====
***********************/
else if ( message_parts.length == 1 && /^[1-7]$/.test(message_parts[0]) ) {
if ( !games.hasOwnProperty(sender_obj.id) ){
this.send("You're not in a game!", message_obj.channel);
}
else
{
var game = games[sender_obj.id];
// Is it our turn?
if( !game.myTurn(sender_obj.id) ){
this.send("Wait your turn!", message_obj.channel);
}
else
{
var rival_id = game.getRivalId(sender_obj.id);
var rival_name = this.getUserNameById(rival_id);
var rival_channel = this.getChannelByUserId(rival_id);
var result = game.addPiece(sender_obj.id, message_parts[0]);
// Successful placement
if ( result == 1 ){
var msg = game.renderBoard();
this.send(msg+"Thanks!", message_obj.channel);
if( rival_channel ){
this.send("@"+this.getUserNameById(sender_obj.id)+" has moved.\n"+msg+"Your move...", rival_channel);
}
else
{
var msg = "Please tell @"+this.getUserNameById(rival_id)+" to say \"hi\" to me, otherwise they won't be able to receive messages from me.";
this.send(msg, message_obj.channel);
}
}
// Winning move
else if ( result == 2 ){
var msg = game.renderBoard();
this.send(msg+"YOU WIN!!!", message_obj.channel);
if( rival_channel ){
this.send("@"+this.getUserNameById(sender_obj.id)+" has moved.\n"+msg+"YOU LOSE.", rival_channel);
}
else
{
var msg = "Please tell @"+this.getUserNameById(rival_id)+" to say \"hi\" to me, otherwise they won't be able to receive messages from me.";
this.send(msg, message_obj.channel);
}
// Post the game status to #general (if the bot has been added there already)
// BOTS CAN NOT JOIN CHANNELS BY THEMSELVES. They need to be added manually.
var msg = "@"+this.getUserNameById(sender_obj.id)+" has beaten @"+this.getUserNameById(rival_id)+" in a game of Connect Four";
this.send(msg, this.general_channel_id);
// end game
if( games.hasOwnProperty(sender_obj.id) ){
var game = games[sender_obj.id]
delete games[sender_obj.id];
delete games[rival_id]; // delete both pointers to same game
delete game; // make sure it's gone
}
}
// Invalid move
else
{
this.send("Invalid move. Try again.", message_obj.channel);
}
}
}
}
/***********************
==== Command: QUIT ====
***********************/
else if(message_parts[0].match(/quit/i)){
if( games.hasOwnProperty(sender_obj.id) ){
var game = games[sender_obj.id];
var player_id_2 = game.player_id_2;
delete games[sender_obj.id];
delete games[player_id_2];
delete game;
this.send("Quitter...", message_obj.channel);
}
else
{
this.send("You're not in a game yet.", message_obj.channel);
}
}
}
}.bind(this));
};
/*******************
Helper functions:
*******************/
// Get a User name by id
SlackBot.prototype.getUserIdByName = function(name){
var user = this.users.filter( function(obj){
// Find matching name, ignore the leading '@' symbol.
return obj.name == ( name.replace(/^@/, '') );
})[0];
if( user )
return user.id;
else
return false;
}
// Get a User id by name
SlackBot.prototype.getUserNameById = function(id){
var user = this.users.filter( function(obj){
return obj.id == id;
})[0];
if( user )
return user.name;
else
return false;
}
// Get a Direct Message channel id by User id
// Only works if the channel already exists; bots cannot initialize a DM
SlackBot.prototype.getChannelByUserId = function(id){
if ( this.dm_channels.hasOwnProperty(id) )
return this.dm_channels[id];
else
return false;
}
// Send a message via RTM API
SlackBot.prototype.send = function(message, channel){
var json_message = {
"id": this.message_no++,
"type": "message",
"channel": channel,
"text": message
};
this.ws.send( JSON.stringify(json_message) );
}
/******************
APP ENTRY POINT:
******************/
var bot = new SlackBot(bot_token, bot_name);
<file_sep>/game.js
'use strict';
var Game = function(player_id_1, player_id_2) {
this.player_id_1 = player_id_1;
this.player_id_2 = player_id_2;
this.turn = 1;
this.board = [];
for( var row=0; row<6; row++ ){
this.board.push( [0,0,0,0,0,0,0] );
}
}
Game.prototype.renderBoard = function() {
var str = "";
for( var row=0; row<6; row++ ){
for( var col=0; col<7; col++ ){
switch( this.board[row][col] ){
case 0:
str += ":white_large_square:";
break;
case 1:
str += ":red_circle:";
break;
case 2:
str += ":black_circle:";
break;
}
}
str += "\n";
}
return str;
}
Game.prototype.addPiece = function(player_id, col){
var valid_move = 0;
var player_no;
if ( player_id == this.player_id_1 )
player_no = 1;
else if ( player_id == this.player_id_2 )
player_no = 2;
// Drop it like it's hot:
for( var row=6; row>=1; row-- ){
if( this.board[row-1][col-1] == 0 ){
this.board[row-1][col-1] = player_no;
valid_move = this.checkForWin(player_no, row, col);
break;
}
}
// Advance the turn:
if( valid_move > 0 ){
this.turn++;
if( this.turn > 2 )
this.turn = 1;
}
return valid_move;
}
Game.prototype.checkForWin = function(player_no, row, col){
var result = 1;
var count = 0;
// check horizontal
for(var c=0; c<7; c++) {
if ( this.board[row-1][c]==player_no )
count++;
else
count=0;
if ( count>=4 )
return 2;
}
count = 0;
// check vertical
for(var r=0; r<6; r++) {
if ( this.board[r][col-1]==player_no )
count++;
else
count=0;
if ( count>=4 )
return 2;
}
count = 0;
// check diagonal down (\) ...pretty cool algorithm I think
r = 0;
c = -(row-1)+(col-1);
for(var i=0; i<6; i++){
if ( (r+i)>=0 && (r+i)<6 && (c+i)>=0 && (c+i)<7 ){
if ( this.board[r+i][c+i]==player_no )
count++;
else
count=0;
if ( count>=4 )
return 2;
}
}
count = 0;
// check diagonal up (/)
r = 0;
c = (row-1)+(col-1);
for(var i=0; i<6; i++){
if ( (r+i)>=0 && (r+i)<6 && (c-i)>=0 && (c-i)<7 ){
if ( this.board[r+i][c-i]==player_no )
count++;
else
count=0;
if ( count>=4 )
return 2;
}
}
return result;
}
Game.prototype.myTurn = function(player_id){
if( this.turn == 1 && this.player_id_1 == player_id )
return true;
else if ( this.turn == 2 && this.player_id_2 == player_id )
return true;
else
return false;
}
Game.prototype.getRivalId = function(player_id){
if( this.player_id_1 == player_id )
return this.player_id_2;
else if( this.player_id_2 == player_id )
return this.player_id_1;
else
return false;
}
module.exports = Game;
<file_sep>/readme.md
# **GameBot** (Slack)
### A _Connect Four_ bot for **Slack** using the _RTM API_
By: <NAME><br>
bryce1<at>gmail<.>com
___
## Synopsis
GameBot is a Slack Bot that allows users to challenge each other to a game of Connect Four. A player challenge an opponent by DM'ing GameBot with "play @Opponent".
GameBot is written in Node.js. It uses the Slack RTM API, which uses an active WebSocket connection. Thus, the GameBot Node app must be left running in order for it to function. If the Node app is closed, all ongoing games will be reset.
GameBot contains a custom, lightweight Slack RTM API wrapper. It does not use any third party Slack tools or API wrappers.
## Installation
1. Create a Slack bot account within your team.<br>
➾ Go to https://YOUR\_DOMAIN.slack.com/apps/manage/custom-integrations<br>
➾ Click “Bots”<br>
➾ Click “Add Configuration”<br>
➾ Fill in the <b>bot name</b> and details as you like.<br>
➾ Obtain a <b>bot token</b><br>
<br>
2. Extract the project to a directory where you can run it with Node.js. The app should work fine locally or remotely, as long as Node is available.
<br><br>
3. Edit <u>index.js</u>. On lines 9-10, enter in your own <b>bot token</b> and <b>bot name</b>.
```javascript
// Fillable via custom bot token and name:
var bot_token = "xoxb-YOUR_BOT'S_GENERATED_TOKEN";
var bot_name = "gamebot";
```
4. Using the command line / terminal, run the <u>index.js</u> file with Node.
```
$ node index.js
```
5. If you would like GameBot to be able to notify your Slack team's _#general_ channel of Connect Four winners, you must manually add the _@gamebot_ user to the channel. Slackbots are not able to join channels automatically.
## Usage
### Starting a game
Challenge a Slack teammate to a game of Connect Four by DM'ing the _@gamebot_ user with the _play_ command. The "@" symbol is optional:
```
play @username
```
**Important:** A Slackbot cannot begin a new DM with your opponent. Therefore, your opponent must first DM _@gamebot_ by sending a message such as "hi".
If you would like your entire Slack team to see your game, play-by-play, then you can also enter the _play @username_ command in the _#general_ channel (instead of DM). Just make sure that _@gamebot_ has been added to that channel first.
### Making a move
If it's your turn, drop a Connect 4 piece by entering the column number, 1 ~ 7.
### Quitting
Just type _quit_ to stop playing.
| 27b1d2774088eb3c6858d38315cc16fdd8fa7835 | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | bryce-fitzsimons/slack-gamebot | c7b8cfe6c5e036a28bbc025a150652ede2e174cf | 2684697d9064796b29ce74caa3e2c04336e2e130 |
refs/heads/master | <file_sep>var testMaintenance = {
_modified: false,
init : function(){
//test description rich editor initialization
$('#txtDescription').wysiwyg();
$('#txtDescription').on('keyup', function(){testMaintenance.setModified(true)});
//storage
require([
"dojo/store/Memory"
], function (MemoryStore) {
testMaintenance._storeTestList = new MemoryStore({
idProperty : '_id'
});
testMaintenance._loadTestNames();
});
},
setModified : function(modified){
testMaintenance._modified = modified;
var b = $('#btnUpdate');
b.disable(!modified);
if (modified){
b.addClass('btn-info');
}else{
b.removeClass('btn-info');
}
},
updateTestDetails : function(){
if ($('#txtTestId').val()){
testMaintenance.ajax({
url : '/rest/updateTestDetails',
dataType : 'json',
cache : 'false',
type : 'POST',
data : {
testId : $('#txtTestId').val(),
testName : $('#txtTestName').val().trim(),
testDescription : $("#txtDescription").cleanHtml()
}
})
.done(function(res){
if (res.valid){
testMaintenance.setModified(false);
testMaintenance._loadTestNames();
}else{
utils.showError('Error while updating the test details in the database'
+ (res.message? ': ' + res.message: '')
);
}
})
.fail(function(err){
//endpoint is not accessible
utils.showError('Error while calling dashboard backend (updateTestDetails)'
+ (err.message? ': ' + err.message: '')
);
});
}
},
deleteTestRuns : function(){
var ids = [];
for (var testId in testMaintenance._grid.selection){
ids.push(testId);
}
if (ids.length){
utils.showConfirmation('Are you sure you want to permanently delete the selected Test Run(s)?', function(){
utils.showLoading(true, 'Removing the data from the database...');
var index = 0;
var del = function(){
testMaintenance.ajax({
url : '/rest/removeTest',
dataType : 'json',
cache : 'false',
type : 'GET',
data : {
testId : ids[index]
}
})
.done(function(res){
if (res.valid){
index++;
if (index < ids.length){
del();
}else{
utils.showLoading(false);
testMaintenance._loadTestNames();
}
}else{
utils.showLoading(false);
utils.showError('Error while removing the test data from the database'
+ (res.message? ': ' + res.message: '')
);
}
})
.fail(function(err){
utils.showLoading(false);
//endpoint is not accessible
utils.showError('Error while calling dashboard backend (removeTest)'
+ (err.message? ': ' + err.message: '')
);
});
};
del();
});
}
},
_loadTestNames : function(){
testMaintenance.ajax({
url : '/rest/getTestNames',
dataType : 'json',
cache : 'false'
})
.done(function(res){
if (res.valid){
testMaintenance._populateTestListGrid(res.data)
}else{
utils.showError('Cannot read list of the available tests' + (res.message? ': ' + res.message : ''));
}
});
},
_populateTestListGrid : function(data){
require([
"dojo/_base/declare",
"dgrid/OnDemandGrid",
"dgrid/Keyboard",
"dgrid/Selection",
"dojo/dom",
"dojo/domReady!"
], function (declare,OnDemandGrid, Keyboard, Selection, dom) {
//setting the data
testMaintenance._storeTestList.setData(data);
if (!testMaintenance._grid){
// Create an instance of OnDemandGrid with Selection and Keyboard plugins referencing the store
var CustomGrid = declare([OnDemandGrid, Keyboard, Selection]);
var grid = new CustomGrid({
store : testMaintenance._storeTestList,
columns : [
{field: "_id"},
{field: 'testName', label : 'Test Name'}
],
selectionMode : "extended",
cellNavigation : false
});
dom.byId("gridTestListContainer").appendChild(grid.domNode);
grid.startup();
grid.styleColumn(0, 'display:none');
grid.on("dgrid-error", function(event) {
utils.showError('Error while querying list of tests: ' + event.error.message);
grid.destroy();
});
grid.on("dgrid-refresh-complete", function() {
if (testMaintenance._storeTestList.data.length){
grid.select(
$('#txtTestId').val()?
$('#txtTestId').val() :
testMaintenance._storeTestList.data[0]._id
);
}
});
grid.on('dgrid-select', function(e){
testMaintenance._displayDetails(e.rows[0].data._id);
});
testMaintenance._grid = grid;
}else{
testMaintenance._grid.refresh();
}
});
},
_displayDetails : function(_id){
testMaintenance.ajax({
url : '/rest/getTestDetails',
dataType : 'json',
cache : 'false',
data : {
testId : _id
}
})
.done(function(res){
testMaintenance.setModified(false);
if (res.valid){
$('#txtTestId').val(_id);
$('#txtTestName').val(res.data[0].testName);
$('#txtDescription').html(res.data[0].testDescription);
}else{
utils.showError('Cannot get test details' + (res.message? ': ' + res.message : ''));
}
});
},
//unified ajax wrapper
ajax : function(params){
return $.ajax(params)
.done(function(){ })
.fail(function(err){utils.showError('Backend communication error' + (err.message? ': ' + err.message : '')); });
}
};<file_sep>var testRunner = {
COOKIE_NA : 'naroute_urls',
COOKIE_FS : 'featureservice_urls',
routeUrlPreset : [
{name: 'AGOL QA', url : "http://routeqa.arcgis.com/arcgis/rest/services/World/Route/NAServer/Route_World"},
{name: 'AGOL Development', url : "http://routedev.arcgis.com/arcgis/rest/services/World/Route/NAServer/Route_World"}
],
fsUrlPreset : [
{name : '1K AGO Pairs on DevExt', url : "http://servicesdev1.arcgis.com/5uh3wwYLNzBuU0Eu/arcgis/rest/services/AGO_1k/FeatureServer/0"},
{name : '10K AGO Pairs on DevExt', url : "http://servicesdev1.arcgis.com/5uh3wwYLNzBuU0Eu/ArcGIS/rest/services/AGO_9493Success/FeatureServer/0"}
],
processInProgress : false,
init : function(){
//Route Service endpoint controls initialization
var $c = $("#txtRouteUrl");
$c[0].aCredentials = $("#aCredentialsNA");
testRunner.invalidateNAUrl($c[0]);
testRunner.populateNAUrlPresetsAndHistory();
//Feature Service endpoint controls initialization
$c = $("#txtFSUrl");
$c[0].aCredentials = $("#aCredentialsFS");
testRunner.invalidateUrl($c[0]);
testRunner.populateFSUrlPresetsAndHistory();
//# of clients spinner initialization
$('#spnClientsCount').spinedit({
minimum: 1,
maximum: 64,
step: 1,
value: 4,
numberOfDecimals: 0
});
//test description rich editor initialization
$('#txtDescription').wysiwyg();
},
initAvgResponseTimeChart : function(callback){
$('#dvChart').highcharts({
title: {
text: 'Average Solve Response Time',
x: -20 //center
},
subtitle: {
text: 'Network Analyst Server Route REST Endpoint',
x: -20
},
xAxis: {
type : 'datetime'
},
yAxis: {
title: {
text: 'Response Time (ms)'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
valueSuffix: 'ms'
},
legend: {
enabled: false
},
series: [{
name: 'Route Solve Time',
data: []
}],
chart:{
events: {
load : function(){
callback();
}
}
}
});
},
populateNAUrlPresetsAndHistory : function(){
testRunner.populateUrlPresetsAndHistory(
$("#txtRouteUrl"),
$("#ulRouteUrlHistory"),
testRunner.routeUrlPreset,
testRunner.COOKIE_NA,
function(container){
testRunner.invalidateNAUrl(container);
}
);
},
populateFSUrlPresetsAndHistory : function(){
testRunner.populateUrlPresetsAndHistory(
$("#txtFSUrl"),
$("#ulFSUrlHistory"),
testRunner.fsUrlPreset,
testRunner.COOKIE_FS,
function(container){
testRunner.invalidateUrl(container);
}
);
},
populateUrlPresetsAndHistory : function($url, $history, presets, cookieName, invalidateUrl){
$history.empty();
var onPresetUrlClick = function(url){
$url.val(url);
invalidateUrl($url[0]);
};
var addUrls = function(urls){
urls.forEach(function(url){
$history.append($('<li>')
.append($('<a>')
.click(function(){onPresetUrlClick(url.url);})
.append($('<attr title="' + url.name + '"></attr>')
.append(url.url)
)
)
);
});
};
//preconfigured AGOL Route Services
addUrls(presets);
$history.append($("<li class='divider'>"));
//History from the Cookies
addUrls( testRunner.getHistoricalUrlsFromCookie(cookieName) );
},
invalidateUrl : function(container){
var $c = $(container);
$(":button", $c.parent())
.removeClass("btn-info")
.addClass("btn-danger");
$c[0].aCredentials.toggle(container.value.trim() > '');
$c[0].valid = false;
$c[0].jsonSD = null;
var url = $c.val().trim();
if (~url.indexOf('?')){url = url.substr(0, url.indexOf('?'));}
$c.val(url);
},
invalidateNAUrl : function(container){
testRunner.invalidateUrl(container);
$('#aAdvancedParams').hide();
$('#dvCollapsableJsonEditorContainer').collapse('hide');
},
validateNARouteUrl : function(callback){
var $c = $("#txtRouteUrl");
if (!callback){
testRunner.invalidateNAUrl($c[0]);
}
var url = $c.val().trim();
if (url === '' || $c[0].valid){
if (callback){callback();}
return;
}
//sending REST request to NAServer
testRunner.ajax({
url : '/rest/validateNARouteUrl',
dataType : 'json',
cache : false,
data : {
url : url
}
})
.done(function(res){
if (res.error){
if (res.error.code === 499 || res.error.code === 498 || res.error.code === 400){
testRunner.promptAndApplyCredentials($c, testRunner.validateNARouteUrl, 'Route Service');
} else {
//unexpected error
utils.showError(res.error.message);
}
} else if (res.valid){
//good response, service is accessible
$c[0].valid = true;
$c[0].jsonSD = res;
//populating the Json Parameters editor
$('#aAdvancedParams').show();
$('#edJsonRouteParams').jsonEditor(res.params, {
change: function(params) {
$c[0].jsonSD.params = params;
}
});
//making the buttons on the right of blue color
$(":button", $c.parent())
.removeClass("btn-danger")
.addClass("btn-info");
//saving url in history for future use
testRunner.setHistoricalUrlsCookie(testRunner.COOKIE_NA, url, res.name, testRunner.routeUrlPreset);
testRunner.populateNAUrlPresetsAndHistory();
} else{
//wrong url or service type
utils.showError('Invalid URL or service type other than "esriNAServerRouteLayer"');
}
//callback, if any
if (callback){callback();}
})
.fail(function(err){
//endpoint is not accessible
utils.showError('Invalid URL\n' + err.message);
console.log(err);
//callback, if any
if (callback){callback();}
});
},
validateFSUrl : function(callback){
var $c = $("#txtFSUrl");
if (!callback){
testRunner.invalidateUrl($c[0]);
}
var url = $c.val().trim();
if (url === '' || $c[0].valid){
if (callback){callback();}
return;
}
//sending REST request to the Feature Service
testRunner.ajax({
url : '/rest/validateFSUrl',
dataType : 'json',
cache : false,
data : {
url : url
}
})
.done(function(res){
if (res.error){
if (res.error.code === 499 || res.error.code === 498 || res.error.code === 400){
testRunner.promptAndApplyCredentials($c, testRunner.validateFSUrl, 'Feature Service');
} else {
//unexpected error
utils.showError(res.error.message);
}
} else if (res.valid){
//making sure there are X1, Y1, X2, Y2 fields in the service definition
var x1 = false, y1 = false, x2 = false, y2 = false, id = false;
res.fields.forEach(function(f){
x1 = x1 || f.name === 'X1';
y1 = y1 || f.name === 'Y1';
x2 = x2 || f.name === 'X2';
y2 = y2 || f.name === 'Y2';
id = id || f.name === 'ID';
});
if (x1 && y1 && x2 && y2 && id){
if (res.maxRecordCount > 0 && res.capabilities.toLowerCase().indexOf('query') > -1){
//good response, service is accessible, and has all four required fields
$c[0].valid = true;
$c[0].jsonSD = res;
//making the buttons on the right of blue color
$(":button", $c.parent())
.removeClass("btn-danger")
.addClass("btn-info");
//saving url in history for future use
testRunner.setHistoricalUrlsCookie(testRunner.COOKIE_FS, url, res.name, testRunner.fsUrlPreset);
testRunner.populateFSUrlPresetsAndHistory();
}else{
utils.showError('Feature Service does not support "Query" operation.');
}
}else{
utils.showError('Feature Service must have "X1", "Y1", "X2", "Y2" numeric fields storing coordinates in WGS84, and "ID" field with unique values.');
}
} else{
//wrong url or service type
utils.showError('Invalid URL or service type other than "Feature Service"');
}
//callback, if any
if (callback){callback();}
})
.fail(function(err){
//endpoint is not accessible
utils.showError('Invalid URL\n' + err.message);
console.log(err);
//callback, if any
if (callback){callback();}
});
},
getHistoricalUrlsFromCookie : function(cookieName){
try{
return JSON.parse($.cookie(cookieName));
}catch(err){
return [];
}
},
setHistoricalUrlsCookie : function(cookieName, url, name, presets){
var hurls = [];
try{
hurls = JSON.parse($.cookie(cookieName));
}catch(err){}
var urls = hurls.concat(presets);
var index = -1;
for (var i = 0; i < urls.length; i++){
if (urls[i].url === url){
index = i;
break;
}
}
if (index === -1){
hurls.push({url : url, name : name});
}
$.cookie(cookieName, JSON.stringify(hurls), { expires: 365, path: '/' });
},
promptAndApplyCredentials : function($inputControl, fnValidator, title){
var $c = $inputControl;
var url = $c.val().trim();
if (url === ''){return;}
//service requires a token
//showing the sign-in dialog
var $d = $('#dlgSignin');
$d.modal({remote : '/dialogs/signin.html'})
.one('shown.bs.modal', function(){
//once shown:
// set the title
$('.modal-dialog .modal-title')[0].innerHTML = title;
// set the username and password text box values
$('#txtUsername').val($c[0].username === undefined? '' : $c[0].username);
$('#txtPassword').val($c[0].password === undefined? '' : $c[0].password);
$('#frmSignin').one('submit', function(evt){
//once new credentials are provided, let's pass them down to the proxy
evt.preventDefault();
$c[0].username = $('#txtUsername').val().trim();
$c[0].password = $('#<PASSWORD>').val().trim();
$d.modal('hide')
.one('hidden.bs.modal', function(){
testRunner.ajax({
url : '/rest/applyCredentials',
dataType : 'json',
cache : 'false',
data : {
url : url,
username : $c[0].username,
password : <PASSWORD>
}
})
.done(function(res){
//response from the proxy received:
fnValidator();
if (!res.success){
utils.showError(
'Error occurred while trying to set service endpoint credentials'
+ (res.message? ': ' + res.message: '')
);
}
})
.fail(function(err){
//proxy returned a communication error
utils.showError(
'Error occurred while trying to set service endpoint credentials'
+ (err.message? ': ' + err.message: '')
);
});
});
});
});
},
cacheFeatureServiceData : function(callback){
//calling cacheFeatureServiceData method of the REST endpoint to cache the features from input
//Feature Service in NodejS app memory for future use in load test
var $fs = $("#txtFSUrl");
testRunner.startMultistageProcess(function(){testRunner.cancelCaching();});
testRunner.ajax({
url : '/rest/cacheFeatureServiceData',
dataType : 'json',
cache : 'false',
data : {
url : $fs.val(),
maxRecordCount : $fs[0].jsonSD.maxRecordCount
}
})
.done(function(res){
if (res.valid && res.cachingInProgress){
//caching is in progress: let's poll every second to check fo status
var checkCachingProgress = function(){
testRunner.ajax({
url : '/rest/checkCachingStatus',
dataType : 'json',
cache : 'false'
})
.done(function(res){
if (res.valid){
if (res.cachingInProgress){
utils.updateProgressBar(Math.floor(res.cachedFeatureCount / res.featureCount * 100), res.cachedFeatureCount + ' rows cached...');
setTimeout(checkCachingProgress, 1000);
}else{
if (res.featureCount){
testRunner.stopMultistageProcess(100, 'Done. ' + res.featureCount + ' rows cached.');
if (callback){
testRunner.disableUserInputs(true);
setTimeout(function(){
callback(true);
}, 2000);
}
}else{
testRunner.stopMultistageProcess(0, 'Canceled.');
}
}
}else{
testRunner.stopMultistageProcess(0, 'Error while caching input features (checkCachingStatus)'
+ (err.message? ': ' + err.message: '')
);
if (callback){callback(false);}
}
})
.fail(function(err){
//endpoint is not accessible
testRunner.stopMultistageProcess(0, 'Error while calling dashboard backend (checkCachingStatus)'
+ (err.message? ': ' + err.message: '')
);
if (callback){callback(false);}
});
};
checkCachingProgress();
}else{
testRunner.stopMultistageProcess(0, 'Error while caching input features (cacheFeatureServiceData)'
+ (err.message? ': ' + err.message: '')
);
if (callback){callback(false);}
}
})
.fail(function(err){
//endpoint is not accessible
testRunner.stopMultistageProcess(0, 'Error while calling dashboard backend (checkCachingStatus)'
+ (err.message? ': ' + err.message: '')
);
if (callback){callback(false);}
});
},
runNewTest : function(){
/*
0. verify there is no other load test running
0.1 no load test in progress
0.2 no caching in progress
in proceedWithLaunch()
1. validate route url
2. validate fs url
3. validate test name
4. cache input features
5. save details of new run in the db
6. run the actual test
*/
/* 0.1 */
//verifying there is no other load test running
testRunner.ajax({
url : '/rest/checkLoadTestStatus',
dataType : 'json',
cache : 'false'
})
.done(function(res){
if (res.testInProgress){
utils.showConfirmation(
'There is another load test running (' + (res.featureIndex / res.featureCount * 100).toFixed(2) + '% completed).' +
' Are you absolutely sure you want to stop it? Seriously?',
function(){
testRunner.cancelLoadTest(function(){
//running the new test after user stopped the previously running one.
testRunner.proceedWithLaunch();
});
});
}else{
/* 0.2 */
//making sure there is no other caching process in progress
testRunner.ajax({
url : '/rest/checkCachingStatus',
dataType : 'json',
cache : 'false'
})
.done(function(res){
if (res.cachingInProgress){
utils.showConfirmation(
'There is another load test running (Caching features now).' +
' Are you absolutely sure you want to stop it? Seriously?',
function(){
testRunner.cancelCaching(function(){
testRunner.cancelLoadTest(function(){
//running the new test after user stopped the previously running one.
testRunner.proceedWithLaunch();
});
});
});
}else{
//running the test after we checked that there is no other test running
testRunner.proceedWithLaunch();
}
})
.fail(function(err){
//endpoint is not accessible
testRunner.stopMultistageProcess(0, 'Error while calling dashboard backend (checkCachingStatus(0))'
+ (err.message? ': ' + err.message: '')
);
});
}
})
.fail(function(err){
//endpoint is not accessible
testRunner.stopMultistageProcess(0, 'Error while calling dashboard backend (checkLoadTestStatus(0))'
+ (err.message? ': ' + err.message: '')
);
});
},
cancelCaching : function(callback){
//function which cancels the caching process
testRunner.ajax({
url : '/rest/cancelCaching',
dataType : 'json',
cache : 'false'
})
.done(function(res){
testRunner.stopMultistageProcess(0, 'Canceled.');
if (callback){callback();}
})
.fail(function(err){
//endpoint is not accessible
testRunner.stopMultistageProcess(0, 'Error while calling dashboard backend (cancelCaching)'
+ (err.message? ': ' + err.message: '')
);
});
},
cancelLoadTest : function(callback){
//function which cancels the execution of the load test
testRunner.ajax({
url : '/rest/cancelLoadTest',
dataType : 'json',
cache : 'false'
})
.done(function(res){
testRunner.stopMultistageProcess(0, 'Canceled.');
if (callback){callback();}
})
.fail(function(err){
//endpoint is not accessible
testRunner.stopMultistageProcess(0, 'Error while calling dashboard backend (cancelLoadTest)'
+ (err.message? ': ' + err.message: '')
);
});
},
proceedWithLaunch : function(){
/*
in runNewTest()
0. verify there is no other load test running
0.1 no load test in progress
0.2 no caching in progress
in proceedWithLaunch()
1. validate route url
2. validate fs url
3. validate test name
4. cache input features
5. save details of new run in the db
6. run the actual test
*/
/* 1 */
//route service validation
testRunner.startMultistageProcess();
testRunner.validateNARouteUrl(function(){
var $rs = $("#txtRouteUrl");
if ($rs[0].valid){
/* 2 */
//feature service validation
testRunner.validateFSUrl(function(){
var $fs = $("#txtFSUrl");
if ($fs[0].valid){
/* 3 */
//validating new test name
var $tn = $("#txtTestName");
var testName = $tn.val().trim();
if (testName !== ''){
//check if there is another testRun with the same name in the DB
testRunner.ajax({
url : '/rest/checkTestNameAvailable',
dataType : 'json',
cache : 'false',
data : {
testName : testName
}
})
.done(function(res){
if (res.valid){
if (res.available){
//average response time chart initialization
testRunner.initAvgResponseTimeChart(function(){
/* 4 */
//caching features
testRunner.cacheFeatureServiceData(function(cachingSucceeded){
if (cachingSucceeded){
testRunner.startMultistageProcess(function(){testRunner.cancelLoadTest();});
/* 5 */
//saving the new test details in the database
//using POST here as this is the way this method is available
//POST is needed to support images submissions as base64 strings
testRunner.ajax({
url : '/rest/saveTestDetails',
dataType : 'json',
cache : 'false',
type : 'POST',
data : {
testName : testName,
testDescription : $("#txtDescription").cleanHtml(),
clientsCount : parseInt( $("#spnClientsCount").val() ),
routeUrl : $rs.val(),
fsUrl : $fs.val(),
routeParams : $rs[0].jsonSD.params
}
})
.done(function(res){
if (res.valid){
/* 6 */
//sending the command to the web-tier to launch the load test
testRunner.ajax({
url : '/rest/launchLoadTest',
dataType : 'json',
cache : 'false',
data : {
testId : res._id
}
})
.done(function(res){
if (res.valid){
//periodically polling for progress, status, metrics
var checkLoadTestStatus = function(){
testRunner.ajax({
url : '/rest/checkLoadTestStatus',
dataType : 'json',
cache : 'false'
})
.done(function(res){
if (res.testInProgress){
utils.updateProgressBar(Math.floor(res.featureIndex / res.featureCount * 100), res.featureIndex + ' routes solved...');
//updating the average response time chart
try{
var d = new Date();
var ms = d.getTime() - d.getTimezoneOffset() * 60 * 1000;
$('#dvChart').highcharts().series[0].addPoint([ms, res.avgResponseTime]);
}catch(err){
console.log(err);
}
testRunner.showMessages(res.messages);
setTimeout(checkLoadTestStatus, 1000);
}else{
testRunner.stopMultistageProcess(100, 'Done. ' + res.featureCount + ' routes solved.');
}
})
.fail(function(err){
//endpoint is not accessible
testRunner.stopMultistageProcess(0, 'Error while calling dashboard backend (checkLoadTestStatus)'
+ (err.message? ': ' + err.message: '')
);
});
};
checkLoadTestStatus();
}else{
testRunner.stopMultistageProcess(0, 'Error while trying to launch the load test (launchLoadTest)'
+ (err.message? ': ' + err.message: '')
);
}
})
.fail(function(err){
//endpoint is not accessible
testRunner.stopMultistageProcess(0, 'Error while calling dashboard backend (launchLoadTest)'
+ (err.message? ': ' + err.message: '')
);
});
}else{
testRunner.stopMultistageProcess(0, 'Error while saving test details in the database (saveTestDetails)'
+ (err.message? ': ' + err.message: '')
);
}
})
.fail(function(err){
//endpoint is not accessible
testRunner.stopMultistageProcess(0, 'Error while calling dashboard backend (saveTestDetails)'
+ (err.message? ': ' + err.message: '')
);
});
}
});
});
}else{
utils.showError(
'Another test with the same name already exists in the database. Please choose a different name.',
function(){$tn.focus();}
);
testRunner.stopMultistageProcess();
}
}else{
//error while querying the DB
//good message comes for the _db tier
testRunner.stopMultistageProcess(0, err.message);
}
})
.fail(function(err){
//endpoint is not accessible
testRunner.stopMultistageProcess(0, 'Error while calling dashboard backend (checkTestNameAvailable)'
+ (err.message? ': ' + err.message: '')
);
});
}else{
utils.showError('Please provide a test name.', function(){$tn.focus();});
testRunner.stopMultistageProcess();
}
} else{
utils.showError('Please validate Feature Service endpoint first.', function(){$fs.focus();});
testRunner.stopMultistageProcess();
}
});
} else{
utils.showError('Please validate Route Service endpoint first.', function(){$rs.focus();});
testRunner.stopMultistageProcess();
}
});
},
showMessages : function(messages){
var $mt = $('<table>');
for (var i = messages.length - 1; i >= 0; i--){
var m = messages[i];
$mt.append( $('<tr' + (!m.valid? ' style="color:red;"' : '') +'>')
.append( $('<td>' + (new Date(m.date)).toLocaleTimeString() + '</td>') )
.append( $('<td>' + m.message + '</td>') )
);
}
var $dm = $('#dvMessages');
$dm.empty();
$dm.append($mt);
},
startMultistageProcess : function(fnCancel){
testRunner.processInProgress = true;
testRunner.disableUserInputs(true);
var $sb = $('#btnStop');
$sb.unbind('click');
$sb.click(fnCancel);
},
stopMultistageProcess : function(pct, msg){
testRunner.processInProgress = false;
testRunner.disableUserInputs(false);
if (msg){
utils.updateProgressBar(pct, msg);
}else{
utils.updateProgressBar(0, '');
}
},
disableUserInputs : function(disable){
$('.userInputs input, .userInputs button').attr('disabled', disable? 'disabled' : null);
$('#aCredentialsFS').toggle(!disable);
$('#aCredentialsNA').toggle(!disable);
$('#txtDescription').disable(disable);
testRunner.disableRunButton(disable);
testRunner.disableStopButton(!disable || !testRunner.processInProgress);
},
disableRunButton : function(disable){
utils.disableButton($('#btnRun'), disable);
},
disableStopButton : function(disable){
utils.disableButton($('#btnStop'), disable);
},
//unified ajax wrapper
ajax : function(params){
testRunner.disableUserInputs(true);
return $.ajax(params)
.done(function(){ testRunner.disableUserInputs(testRunner.processInProgress); })
.fail(function(err){ testRunner.stopMultistageProcess(0, 'Backend communication error' + (err.message? ': ' + err.message : '')); });
}
};
<file_sep>var title = 'naDashBoard';
var version = '1.0.1';
var menu = [
{label : 'New Test', href : '/'},
{label : 'Compare Results', href : 'testComparator'},
{label : 'Maintenance', href : 'testMaintenance'}
];
function renderMenu(activeItem){
var res = '';
for (var i = 0; i < menu.length; i++){
res += '<li' + (menu[i].label === activeItem? ' class="active"' : '') + '><a href="' + menu[i].href + '">' + menu[i].label + '</a></li>\n';
}
return res;
}
exports.testRunner = function(req, res){
res.render('testRunner', { title: title, version: version, menu : renderMenu('New Test') });
};
exports.testComparator = function(req, res){
res.render('testComparator', { title: title, version: version, menu : renderMenu('Compare Results') });
};
exports.testMaintenance = function(req, res){
res.render('testMaintenance', { title: title, version: version, menu : renderMenu('Maintenance') });
};<file_sep>var http = require('http');
var https = require('https');
var Url = require('url');
var queryString = require('querystring');
var zlib = require('zlib');
/*
Associative array of credentials and tokens per every endpoint.
Used for tokens and credentials lookup.
authPool[<url>]:{
username : <>,
password : <>,
token : <>
}
*/
var authPool = {};
var referer = 'http://5797Ubuntu64:3000';
//for debugging through Fiddler running on a remote Windows machine
var USE_PROXY = false;
var proxy_config = {
hostname : 'dmitry3',
port: 8888
};
/**
*
* main method which is used to perform outgoing calls to REST services
*
* @param url
* @param callback
* @param errback
* @param [ignoreAuthErrors]
*/
exports.doJsonRequest = function(url, callback, errback, ignoreAuthErrors){
var ru = Url.parse(url, true, true);
//http ot https
var transport = http;
if (!USE_PROXY){
transport = ru.protocol === 'http:'? http : https;
}
//making sure f=json is present
ru.query.f = 'json';
//attaching token, if token is available
var ac = lookupAuthContainer(url);
if (ac && ac.token){ru.query.token = ac.token;}
var postData = queryString.stringify(ru.query);
var options = {
hostname : ru.hostname,
port : ru.port,
path : ru.pathname,
method :'POST',
headers: {
'Content-Length' : postData.length,
'Host' : ru.host,
'Cache-Control': 'no-cache',
'Accept-Encoding' : 'gzip, deflate',
'Accept-Charset' : 'utf-8',
'Content-Type' : 'application/x-www-form-urlencoded',
'Referer' : referer
}
};
if (USE_PROXY){
options.hostname = proxy_config.hostname;
options.port = proxy_config.port;
options.path = ru.protocol + '//' + ru.host + ru.pathname;
}
//sending request
var req = transport.request(
options,
function(res){
var buff = "";
var output;
if( res.headers['content-encoding'] == 'gzip' ){
output = zlib.createGunzip();
res.pipe(output);
} else if(res.headers['content-encoding'] == 'deflate') {
output = zlib.createInflate();
res.pipe(output);
} else{
output = res;
}
output.on('data', function (chunk) {
buff += chunk.toString('utf-8');
});
output.on('end', function () {
if (buff === ''){buff = '{}';}
try{
jsn = JSON.parse(buff);
if (jsn.error){
if (jsn.error.code === 498){
//token expired
if (!ignoreAuthErrors){
requestNewToken(url, function(token){
ac.token = token;
exports.doJsonRequest(url, callback, errback, true);
}, function(err){
if (errback){errback(err);}
});
}else{
if (errback){errback(new Error('Failed to renew the service token.'));}
}
}else{
//any other error, including the 499 (token required) just got returned down to client
//
//token required - let's ask user for credentials
//once user app is provided with the credentials, it will
//call applyResourceCredentials() to get a token
//and the repeat the request
if (callback){ callback(jsn);}
}
}else{
//success
if (callback){ callback(jsn);}
}
}catch(err){
if (errback){errback(new Error("Can't parse the response:\n" + err.message));}
}
});
}
).on('error', function(err){
if (errback){errback(err);}
});
req.write(postData);
req.end();
};
/**
* storing credentials for the url and obtaining a new token
*
* @param url
* @param username
* @param password
* @param callback
* @param errback
*/
exports.applyResourceCredentials = function(url, username, password, callback, errback){
//this function accepts and stores user credentials which are sent by client
//once it receives back 499 (Token Required) response.
var ac = {
username : username,
password : <PASSWORD>
};
authPool[url] = ac;
requestNewToken(url, function(token){
ac.token = token;
if (callback){callback( {success : true} );}
}, function(err){
if (errback){errback(err);}
});
}
// INTERNALS
function requestNewToken(url, callback, errback){
//obtaining new token
var infoUrl = url.substr(0, url.toLowerCase().indexOf('/rest/') + 6);
if (infoUrl === ''){
if (errback){ errback(new Error("Can't find the Info endpoint for the " + url)); }
return;
}
infoUrl += 'info';
var ac = lookupAuthContainer(url);
if (!ac || ac && (!ac.username || !ac.password)){
if (errback){ errback(new Error("Don't have credentials to request new token for the endpoint " + url)); }
return;
}
//let's ask the /info endpoint for the Url of the authentication service
exports.doJsonRequest(infoUrl, function(res){
if (res.authInfo && res.authInfo.tokenServicesUrl){
//token service url is received: let's proceed with asking for the new token
exports.doJsonRequest(
res.authInfo.tokenServicesUrl + '?username=' + ac.username + '&password=' + <PASSWORD> + '&client=referer&referer=' + referer,
function(res){
//token response received
if (res.token){
if (callback) { callback(res.token); }
}else{
if (errback){ errback(new Error("Token request did not succeed for the " + url)); }
}
}, function(err){
if (errback){errback(err);}
}, true
);
}else{
if (errback){ errback(new Error("TokenServicesUrl is not defined for the " + url)); }
}
}, function(err){
if (errback){errback(err);}
}, true);
}
function lookupAuthContainer(url){
for (var stored_url in authPool){
if (url.indexOf(stored_url) === 0){
return authPool[stored_url];
}
}
return null;
} | 4a975c04ca033d0b041c25ab3d0efb9405770eba | [
"JavaScript"
] | 4 | JavaScript | RouteTaskEx/dashboard | 19fdb37a914b78b3c08726dce8350f29f3e78bc0 | c9eea7c0e90115cec0e1f2db2839a4d91de17b3b |
refs/heads/master | <file_sep>//
// RoomsTableViewDataSource.swift
// Koleda
//
// Created by <NAME> on 7/15/19.
// Copyright © 2019 koleda. All rights reserved.
//
import Foundation
import UIKit
class RoomsTableViewDataSource: NSObject, UITableViewDataSource {
var rooms: [Room] = []
var viewModel: HomeViewModelProtocol?
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func numberOfSections(in tableView: UITableView) -> Int {
return self.rooms.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: HomeCell.get_identifier, for: indexPath) as? HomeCell else {
log.error("Invalid cell type call")
return UITableViewCell()
}
let room = self.rooms[indexPath.section]
cell.loadData(room: RoomViewModel(room: room))
return cell
}
}
<file_sep>//
// LegalMenuCell.swift
// Koleda
//
// Created by <NAME> on 11/8/20.
// Copyright © 2020 koleda. All rights reserved.
//
import UIKit
class LegalMenuCell: UITableViewCell {
@IBOutlet weak var titleLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
}
func setText(title: String) {
titleLabel.text = title
}
}
<file_sep>//
// InviteFriendsDetailViewController.swift
// Koleda
//
// Created by <NAME> on 6/23/20.
// Copyright © 2020 koleda. All rights reserved.
//
import UIKit
import RxSwift
import SVProgressHUD
class InviteFriendsDetailViewController: BaseViewController, BaseControllerProtocol {
@IBOutlet weak var messageLabel: UILabel!
@IBOutlet weak var emailTextField: AndroidStyleTextField!
@IBOutlet weak var emailsTableView: UITableView!
@IBOutlet weak var inviteButton: UIButton!
@IBOutlet weak var backButton: UIButton!
@IBOutlet weak var continueButton: UIButton!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var descriptionLabel: UILabel!
var viewModel: InviteFriendsDetailViewControllerProtocol!
private let disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
configurationUI()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationBarTransparency()
navigationController?.setNavigationBarHidden(true, animated: animated)
}
private func configurationUI() {
emailsTableView.dataSource = self
emailsTableView.delegate = self
Style.Button.primary.apply(to: continueButton)
viewModel.emailText.asObservable().bind(to: emailTextField.rx.text).disposed(by: disposeBag)
emailTextField.rx.text.orEmpty.bind(to: viewModel.emailText).disposed(by: disposeBag)
inviteButton.rx.tap.bind { [weak self] in
SVProgressHUD.show()
self?.inviteButton.isEnabled = false
self?.viewModel.invitedAFriend(completion: { success, error in
SVProgressHUD.dismiss()
self?.inviteButton.isEnabled = true
if success {
self?.emailTextField.text = ""
} else if let error = error {
self?.app_showAlertMessage(title: "ERROR_TITLE".app_localized, message: error.localizedDescription)
}
})
}.disposed(by: disposeBag)
continueButton.isHidden = UserDefaultsManager.loggedIn.enabled
continueButton.rx.tap.bind { [weak self] in
self?.viewModel.showInviteFriendsFinished()
}.disposed(by: disposeBag)
backButton.rx.tap.bind { [weak self] in
self?.closeCurrentScreen()
}.disposed(by: disposeBag)
viewModel.fiendsEmailList.asObservable().subscribe(onNext: { [weak self] _ in
self?.emailsTableView.reloadData()
}).disposed(by: disposeBag)
viewModel.emailErrorMessage.asObservable().subscribe(onNext: { [weak self] message in
self?.emailTextField.errorText = message
if message.isEmpty {
self?.emailTextField.showError(false)
} else {
self?.emailTextField.showError(true)
}
}).disposed(by: disposeBag)
viewModel.showErrorMessage.asObservable().subscribe(onNext: { [weak self] errorMessage in
self?.app_showAlertMessage(title: "KOLEDA_TEXT", message: errorMessage)
}).disposed(by: disposeBag)
titleLabel.text = "SHARE_THE_WARMTH_TEXT".app_localized
descriptionLabel.text = "INVITE_FRIENDS_AND_FAMILY_MESS".app_localized
inviteButton.setTitle("INVITE_TEXT".app_localized, for: .normal)
emailTextField.titleText = "EMAIL_TITLE".app_localized
}
}
extension InviteFriendsDetailViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.viewModel.fiendsEmailList.value.count
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let emails = self.viewModel.fiendsEmailList.value
guard let cell = tableView.dequeueReusableCell(withIdentifier: FriendTableViewCell.get_identifier, for: indexPath) as? FriendTableViewCell else {
log.error("Invalid cell type call")
return UITableViewCell()
}
cell.loadData(email: emails[indexPath.row])
cell.removeButtonHandler = { [weak self] email in
SVProgressHUD.show()
self?.viewModel.removeFriendBy(email: email, completion: {
SVProgressHUD.dismiss()
})
}
return cell
}
}
<file_sep>//
// ProgressBarView.swift
// Koleda
//
// Created by <NAME> on 7/23/20.
// Copyright © 2020 koleda. All rights reserved.
//
import UIKit
import RxSwift
class ProgressBarView: UIView {
@IBOutlet weak var backImageView: UIImageView!
@IBOutlet weak var stepLabel: UILabel!
@IBOutlet weak var backButton: UIButton!
@IBOutlet weak var progressView: UIProgressView!
private let disposeBag = DisposeBag()
override func awakeFromNib() {
super.awakeFromNib()
kld_loadContentFromNib()
}
func setupNav(viewController: BaseViewController) {
backButton.rx.tap.bind {
viewController.closeCurrentScreen()
}.disposed(by: disposeBag)
if UserDefaultsManager.loggedIn.enabled || UserDataManager.shared.stepProgressBar.totalStep == 0 {
stepLabel.isHidden = true
progressView.isHidden = true
} else {
stepLabel.isHidden = false
progressView.isHidden = false
loadStep(viewController: viewController)
}
}
func loadStep(viewController: BaseViewController) {
let stepProgressBar = UserDataManager.shared.stepProgressBar
let currentStep = stepProgressBar.currentStep + 1
UserDataManager.shared.stepProgressBar.currentStep = currentStep
let stepString = "STEP_TEXT".app_localized
self.stepLabel.text = String(format: "%@ %d", stepString, currentStep)
let value = Float(currentStep)/Float(stepProgressBar.totalStep)
self.progressView.setProgress(value, animated: true)
}
}
<file_sep>//
// SignUpViewModel.swift
// Koleda
//
// Created by <NAME> on 6/4/19.
// Copyright © 2019 koleda. All rights reserved.
//
import Foundation
import RxSwift
import RxCocoa
import CopilotAPIAccess
protocol SignUpViewModelProtocol: BaseViewModelProtocol {
var fullName: Variable<String> { get }
var email: Variable<String> { get }
var password: Variable<String> { get }
var showPassword: PublishSubject<Bool> { get }
var fullNameErrorMessage: Variable<String> { get }
var emailErrorMessage: Variable<String> { get }
var passwordErrorMessage: Variable<String> { get }
var showErrorMessage: PublishSubject<String> { get }
func showPassword(isShow: Bool)
func next(completion: @escaping (WSError?) -> Void)
func loginAfterSignedUp(completion: @escaping (String) -> Void)
func goTermAndConditions()
func validateAll() -> Bool
}
class SignUpViewModel: BaseViewModel, SignUpViewModelProtocol {
let router: BaseRouterProtocol
let fullName = Variable<String>("")
let email = Variable<String>("")
let password = Variable<String>("")
let passwordConfirm = Variable<String>("")
let showPassword = PublishSubject<Bool>()
let showPasswordConfirm = PublishSubject<Bool>()
let fullNameErrorMessage = Variable<String>("")
let emailErrorMessage = Variable<String>("")
let passwordErrorMessage = Variable<String>("")
let passwordConfirmErrorMessage = Variable<String>("")
let showErrorMessage = PublishSubject<String>()
private let signUpManager: SignUpManager
private let loginAppManager: LoginAppManager
private let userManager: UserManager
init(router: BaseRouterProtocol, managerProvider: ManagerProvider = .sharedInstance) {
self.router = router
self.loginAppManager = managerProvider.loginAppManager
self.signUpManager = managerProvider.signUpManager
self.userManager = managerProvider.userManager
super.init(managerProvider: managerProvider)
}
func showPassword(isShow: Bool) {
self.showPassword.onNext(isShow)
}
func next(completion: @escaping (WSError?) -> Void) {
let emailValue = email.value.extraWhitespacesRemoved
let passwordValue = password.value.extraWhitespacesRemoved
self.signUpManager.signUp(name: fullName.value.extraWhitespacesRemoved,
email: emailValue,
password: <PASSWORD>Value,
success: { [weak self] in
Copilot.instance.report.log(event: SignupAnalyticsEvent())
completion(nil)
},
failure: { error in
completion(error as? WSError)
})
}
func loginAfterSignedUp(completion: @escaping (String) -> Void) {
let emailValue = email.value.extraWhitespacesRemoved
let passwordValue = password.value.extraWhitespacesRemoved
loginAppManager.login(email: emailValue, password: <PASSWORD>, success: { [weak self] in
self?.getCurrentUser { [weak self] in
guard let userId = UserDataManager.shared.currentUser?.id else {
return
}
Copilot.instance
.manage
.yourOwn
.sessionStarted(withUserId: userId,
isCopilotAnalysisConsentApproved: true)
Copilot.instance.report.log(event: LoginAnalyticsEvent())
completion("")
}
}, failure: { error in
completion("LOGIN_FAILED_TRY_AGAIN_MESS".app_localized)
})
}
func goTermAndConditions() {
router.enqueueRoute(with: SignUpRouter.RouteType.termAndConditions)
}
}
extension SignUpViewModel {
private func getCurrentUser(completion: @escaping () -> Void) {
userManager.getCurrentUser(success: {
completion()
}, failure: { error in
completion()
})
}
func validateAll() -> Bool {
var failCount = 0
failCount += validateFullName() ? 0 : 1
failCount += validateEmail() ? 0 : 1
failCount += validatePassword() ? 0 : 1
return failCount == 0
}
private func validateFullName() -> Bool {
let normalizedFullName = fullName.value.extraWhitespacesRemoved
if normalizedFullName.isEmpty {
fullNameErrorMessage.value = "NAME_IS_NOT_EMPTY_MESS".app_localized
return false
}
if DataValidator.isValid(fullName: normalizedFullName) && normalizedFullName.count >= 2 && normalizedFullName.count <= 50 {
fullNameErrorMessage.value = ""
return true
} else {
fullNameErrorMessage.value = "NAME_IS_INVALID_MESS".app_localized
return false
}
}
private func validateEmail() -> Bool {
if email.value.extraWhitespacesRemoved.isEmpty {
emailErrorMessage.value = "EMAIL_IS_NOT_EMPTY_MESS".app_localized
return false
}
if DataValidator.isEmailValid(email: email.value.extraWhitespacesRemoved) {
emailErrorMessage.value = ""
return true
} else {
emailErrorMessage.value = "EMAIL_IS_INVALID_MESS".app_localized
return false
}
}
private func validatePassword() -> Bool {
if password.value.extraWhitespacesRemoved.isEmpty {
passwordErrorMessage.value = "PASS_IS_NOT_EMPTY_MESS".app_localized
return false
}
if DataValidator.isEmailPassword(pass: password.value.extraWhitespacesRemoved)
{
passwordErrorMessage.value = ""
return true
} else {
passwordErrorMessage.value = "INVALID_PASSWORD_MESSAGE".app_localized
return false
}
}
}
<file_sep>//
// InstructionViewController.swift
// Koleda
//
// Created by <NAME> on 9/6/19.
// Copyright © 2019 koleda. All rights reserved.
//
import UIKit
class InstructionViewController: BaseViewController, BaseControllerProtocol {
@IBOutlet weak var sliderCollectionView: UICollectionView!
@IBOutlet weak var pageView: UIPageControl!
@IBOutlet weak var nextButton: UIButton!
@IBOutlet weak var skipButton: UIButton!
let router = InstructionForSensorRouter()
var viewModel:InstructionViewModel!
var counter = 0
var roomId: String = ""
var roomName: String = ""
var isFromRoomConfiguration: Bool = false
typealias ViewModelType = InstructionViewModel
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.setNavigationBarHidden(true, animated: false)
statusBarStyle(with: .lightContent)
viewModel = InstructionViewModel.init(router: self.router,typeInstructions: [.instructionForSensor1, .instructionForSensor2, .instructionForSensor3, .instructionForSensor4, .instructionForSensor5, .instructionForSensor6])
router.baseViewController = self
initView()
}
func initView() {
pageView.numberOfPages = viewModel.typeInstructions.value.count
pageView.currentPage = 0
}
@objc func changeImage() {
if counter < viewModel.typeInstructions.value.count - 1 {
let index = IndexPath.init(item: counter + 1, section: 0)
self.sliderCollectionView.scrollToItem(at: index, at: .centeredHorizontally, animated: true)
pageView.currentPage = counter + 1
} else {
viewModel.nextToSensorManagement(roomId: roomId, roomName: roomName, isFromRoomConfiguration: isFromRoomConfiguration)
}
}
@IBAction func nextAction(_ sender: Any) {
counter = pageView.currentPage
changeImage()
}
@IBAction func skipAction(_ sender: Any) {
viewModel.nextToSensorManagement(roomId: roomId, roomName: roomName, isFromRoomConfiguration: isFromRoomConfiguration)
}
@IBAction func backAction(_ sender: Any) {
if isFromRoomConfiguration {
back()
} else {
viewModel.backToRoot()
}
}
}
extension InstructionViewController: UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return viewModel.typeInstructions.value.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
if let instruction = cell.viewWithTag(1001) as? InstructionView {
let type = viewModel.typeInstructions.value[indexPath.row]
instruction.updateUI(type: type)
}
return cell
}
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
counter = indexPath.row
pageView.currentPage = counter
}
}
extension InstructionViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let size = sliderCollectionView.frame.size
return CGSize(width: size.width, height: size.height)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 0.0
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 0.0
}
}
<file_sep>//
// InviteFriendsViewModel.swift
// Koleda
//
// Created by <NAME> on 6/23/20.
// Copyright © 2020 koleda. All rights reserved.
//
import Foundation
import RxSwift
protocol InviteFriendViewModelProtocol: BaseViewModelProtocol {
func showHomeScreen()
func inviteFriends()
}
class InviteFriendsViewModel: BaseViewModel, InviteFriendViewModelProtocol {
let router: BaseRouterProtocol
init(router: BaseRouterProtocol, managerProvider: ManagerProvider = .sharedInstance) {
self.router = router
super.init(managerProvider: managerProvider)
}
func showHomeScreen() {
UserDefaultsManager.loggedIn.enabled = true
router.enqueueRoute(with: InviteFriendsRouter.RouteType.home)
}
func inviteFriends() {
router.enqueueRoute(with: InviteFriendsRouter.RouteType.inviteFriendsDetail)
}
}
<file_sep>//
// Locale+Extensions.swift
// Koleda
//
// Created by <NAME> on 7/2/19.
// Copyright © 2019 koleda. All rights reserved.
//
import Foundation
extension Locale {
// Provide valid ISO region code to obtain valid Locale
static func fromCountryIsoCode(_ code: String) -> Locale {
return Locale(identifier: Locale.identifier(fromComponents: [NSLocale.Key.countryCode.rawValue: code]))
}
static func currencyCode(forCountryIsoCode code: String) -> String? {
guard let result = Locale.fromCountryIsoCode(code).currencyCode else {
return nil
}
return result
}
}
extension Locale {
static var app_currentOrDefault: Locale {
let defaultLocaleIdentifier = "en_US"
let result: Locale
if let prefferedLanguage = Locale.preferredLanguages.first,
let languageCode = Locale.components(fromIdentifier: prefferedLanguage)[NSLocale.Key.languageCode.rawValue],
Bundle.main.localizations.contains(languageCode) {
result = Locale.current
} else {
result = Locale(identifier: defaultLocaleIdentifier)
}
return result
}
static var app_usPosixLocale: Locale {
let usPosixLocaleIdentifier = "en_US_POSIX"
return Locale(identifier: usPosixLocaleIdentifier)
}
static var bp_defaultLocale: Locale {
let defaultLocaleIdentifier = "en_US_POSIX"
return Locale(identifier: defaultLocaleIdentifier)
}
}
<file_sep>//
// SelectedRoomRouter.swift
// Koleda
//
// Created by <NAME> on 8/26/19.
// Copyright © 2019 koleda. All rights reserved.
//
import UIKit
class SelectedRoomRouter: BaseRouterProtocol {
enum RouteType {
case configuration(Room)
case manualBoost(Room)
}
weak var baseViewController: UIViewController?
func enqueueRoute(with context: Any?, animated: Bool, completion: ((Bool) -> Void)?) {
guard let routeType = context as? RouteType else {
assertionFailure("The route type missmatches")
return
}
guard let baseViewController = baseViewController else {
assertionFailure("baseViewController is not set")
return
}
switch routeType {
case .configuration(let selectedRoom):
let router = ConfigurationRoomRouter()
let viewModel = ConfigurationRoomViewModel.init(router: router, seletedRoom: selectedRoom)
guard let viewController = StoryboardScene.Home.instantiateConfigurationRoomViewController() as? ConfigurationRoomViewController else {
return
}
viewController.viewModel = viewModel
router.baseViewController = viewController
baseViewController.navigationController?.pushViewController(viewController, animated: true)
case .manualBoost(let selectedRoom):
let router = ManualBoostRouter()
let viewModel = ManualBoostViewModel.init(router: router, seletedRoom: selectedRoom)
guard let viewController = StoryboardScene.Home.instantiateManualBoostViewController() as? ManualBoostViewController else {
return
}
viewController.viewModel = viewModel
router.baseViewController = viewController
viewController.modalPresentationStyle = .overCurrentContext
baseViewController.present(viewController, animated: true, completion: nil)
}
}
func present(on baseVC: UIViewController, animated: Bool, context: Any?, completion: ((Bool) -> Void)?) {
}
func dismiss(animated: Bool, context: Any?, completion: ((Bool) -> Void)?) {
}
}
<file_sep>//
// InviteFriendsDetailRouter.swift
// Koleda
//
// Created by <NAME> on 6/23/20.
// Copyright © 2020 koleda. All rights reserved.
//
import Foundation
class InviteFriendsDetailRouter: BaseRouterProtocol {
weak var baseViewController: UIViewController?
enum RouteType {
case invited
}
func enqueueRoute(with context: Any?, animated: Bool, completion: ((Bool) -> Void)?) {
guard let baseViewController = baseViewController else {
assertionFailure("he route type missmatches")
return
}
guard let routeType = context as? RouteType else {
assertionFailure("baseViewController is not set")
return
}
switch routeType {
case .invited:
let router = InviteFriendsFinishedRouter()
let viewModel = InviteFriendsFinishedViewModel.init(router: router)
guard let viewController = StoryboardScene.Setup.instantiateInviteFriendsFinishedViewController() as? InviteFriendsFinishedViewController else {
assertionFailure("Setup storyboard configured not properly")
return
}
viewController.viewModel = viewModel
router.baseViewController = viewController
baseViewController.navigationController?.pushViewController(viewController, animated: true)
default:
break
}
}
func dismiss(animated: Bool, context: Any?, completion: ((Bool) -> Void)?) {
}
func present(on baseVC: UIViewController, animated: Bool, context: Any?, completion: ((Bool) -> Void)?) {
}
}
<file_sep>//
// ScheduleViewController.swift
// Koleda
//
// Created by <NAME> on 10/24/19.
// Copyright © 2019 koleda. All rights reserved.
//
import UIKit
class ScheduleViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var topLineImageView: UIImageView!
@IBOutlet weak var bottomLineImageView: UIImageView!
private var rooms: [Room] = []
private var rows: [ScheduleRow] = []
private var targetTemperature: Double = 0
override func viewDidLoad() {
super.viewDidLoad()
tableView.reloadData()
}
override func viewDidLayoutSubviews() {
tableView.frame = self.view.frame
topLineImageView.frame = CGRect(x: topLineImageView.frame.origin.x, y: tableView.frame.origin.y, width: topLineImageView.frame.width, height: topLineImageView.frame.height)
bottomLineImageView.frame = CGRect(x: bottomLineImageView.frame.origin.x, y: tableView.frame.origin.y + tableView.frame.height - 2, width: bottomLineImageView.frame.width, height: bottomLineImageView.frame.height)
}
func reloadData(content: ScheduleBlock?) {
guard let content = content else {
return
}
targetTemperature = content.targetTemperature
updateView(color: content.color)
rooms = content.rooms
self.rows = content.scheduleRows
tableView.reloadData()
}
func updateView(color: UIColor) {
topLineImageView.tintColor = color
bottomLineImageView.tintColor = color
tableView.layer.cornerRadius = 10
tableView.layer.shadowColor = color.cgColor
tableView.layer.shadowOffset = CGSize(width: 3, height: 3)
tableView.layer.shadowOpacity = 0.7
tableView.layer.shadowRadius = 10
// self.tableView.backgroundColor = UIColor.white
}
}
extension ScheduleViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return rows.count
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let row = rows[indexPath.row]
if row.type == .Header {
return 47
} else {
return 45
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let row = rows[indexPath.row]
switch row.type {
case .Header:
guard let cell = tableView.dequeueReusableCell(withIdentifier: ScheduleHeaderCell.get_identifier, for: indexPath) as? ScheduleHeaderCell else {
log.error("Invalid cell type call")
return UITableViewCell()
}
cell.setup(scheduleRow: row)
return cell
case .Footer:
guard let cell = tableView.dequeueReusableCell(withIdentifier: ScheduleFooterCell.get_identifier, for: indexPath) as? ScheduleFooterCell else {
log.error("Invalid cell type call")
return UITableViewCell()
}
cell.setup(scheduleRow: row)
return cell
default:
guard let cell = tableView.dequeueReusableCell(withIdentifier: ScheduleTableViewCell.get_identifier, for: indexPath) as? ScheduleTableViewCell else {
log.error("Invalid cell type call")
return UITableViewCell()
}
cell.setup(scheduleRow: row, targetTemperature: targetTemperature)
return cell
}
}
// func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// if rows.count == 1 && indexPath.row == 0 || indexPath.row == rows.count - 1 {
// showPopover(indexPath: indexPath)
// }
// }
//
// private func showPopover(indexPath: IndexPath) {
// guard rooms.count > 0, let cell = tableView.cellForRow(at: indexPath) else {
// return
// }
// guard let detailRoomsPopoverView = StoryboardScene.SmartSchedule.instantiateDetailRoomsPopoverView() as? DetailRoomsPopoverView else { return }
// detailRoomsPopoverView.view.backgroundColor = self.tableView.backgroundColor
// detailRoomsPopoverView.targetTemperature = targetTemperature
// detailRoomsPopoverView.rooms = rooms
// detailRoomsPopoverView.modalPresentationStyle = .popover
// let heighOfPopoverView = rooms.count*45 + 5
// detailRoomsPopoverView.preferredContentSize = CGSize(width: tableView.frame.size.width, height: CGFloat(heighOfPopoverView))
// let presentationController = detailRoomsPopoverView.popoverPresentationController
// presentationController?.delegate = self
// presentationController?.permittedArrowDirections = .up
// presentationController?.sourceView = cell
// presentationController?.sourceRect = cell.bounds
// present(detailRoomsPopoverView, animated: true, completion: nil)
// }
}
//extension ScheduleViewController: UIPopoverPresentationControllerDelegate {
// func adaptivePresentationStyle(for controller: UIPresentationController,
// traitCollection: UITraitCollection) -> UIModalPresentationStyle {
// return .none
// }
//}
<file_sep>//
// HeatersManagementRouter.swift
// Koleda
//
// Created by <NAME> on 9/4/19.
// Copyright © 2019 koleda. All rights reserved.
//
import Foundation
import UIKit
class HeatersManagementRouter: BaseRouterProtocol {
weak var baseViewController: UIViewController?
enum RouteType {
case backHome
case done
case addHeaterFlow(String, String)
}
func enqueueRoute(with context: Any?, animated: Bool, completion: ((Bool) -> Void)?) {
guard let routeType = context as? RouteType else {
assertionFailure("The route type missmatches")
return
}
guard let baseViewController = baseViewController else {
assertionFailure("baseViewController is not set")
return
}
switch routeType {
case .backHome:
baseViewController.navigationController?.popToRootViewController(animated: false)
case .done:
baseViewController.navigationController?.popViewController(animated: true)
case .addHeaterFlow(let roomId, let roomName):
baseViewController.gotoBlock(withStoryboar: "Heater", aClass: InstructionForHeaterViewController.self, sendData: { (vc) in
vc?.roomId = roomId
vc?.roomName = roomName
vc?.isFromRoomConfiguration = true
})
}
}
func present(on baseVC: UIViewController, animated: Bool, context: Any?, completion: ((Bool) -> Void)?) {
}
func dismiss(animated: Bool, context: Any?, completion: ((Bool) -> Void)?) {
}
func prepare(for segue: UIStoryboardSegue) {
}
}
<file_sep>//
// UIScrollView+Extensions.swift
// Koleda
//
// Created by <NAME> on 6/11/19.
// Copyright © 2019 koleda. All rights reserved.
//
import UIKit
extension UIScrollView {
func app_scrollToBottom(animated: Bool = true) {
if contentSize.height > bounds.size.height {
let bottomOffset = CGPoint(x:0, y: contentSize.height - bounds.size.height)
setContentOffset(bottomOffset, animated: animated)
}
}
func app_scrollToTop(animated: Bool = true) {
let desiredOffset = CGPoint(x: 0, y: -contentInset.top)
setContentOffset(desiredOffset, animated: animated)
}
}
<file_sep>
//
// ModifyModesViewModel.swift
// Koleda
//
// Created by <NAME> on 2/3/20.
// Copyright © 2020 koleda. All rights reserved.
//
import Foundation
import RxSwift
protocol ModifyModesViewModelProtocol: BaseViewModelProtocol {
var smartModes: Variable<[ModeItem]> { get }
func didSelectMode(atIndex: Int)
func loadModes()
}
class ModifyModesViewModel: BaseViewModel, ModifyModesViewModelProtocol {
let router: BaseRouterProtocol
private let settingManager: SettingManager
let smartModes = Variable<[ModeItem]>([])
init(router: BaseRouterProtocol, managerProvider: ManagerProvider = .sharedInstance) {
self.router = router
settingManager = managerProvider.settingManager
super.init(managerProvider: managerProvider)
loadModes()
}
func loadModes() {
smartModes.value = UserDataManager.shared.settingModesWithoutDefaultMode()
}
func didSelectMode(atIndex: Int) {
let selectedMode = smartModes.value[atIndex]
showDetailMode(selectedMode: selectedMode)
}
private func showDetailMode(selectedMode: ModeItem) {
router.enqueueRoute(with: ModifyModesRouter.RouteType.detailMode(selectedMode))
}
}
<file_sep>//
// WSResult.swift
// Koleda
//
// Created by <NAME> on 7/2/19.
// Copyright © 2019 koleda. All rights reserved.
//
import Foundation
public enum WSResult<T> {
case success(T)
case failure(Error)
public init(value: T) {
self = .success(value)
}
public init(error: Error) {
self = .failure(error)
}
}
extension WSResult where T == Void {
static var success: WSResult {
return .success(())
}
}
<file_sep>//
// ForgotPasswordViewModel.swift
// Koleda
//
// Created by <NAME> on 6/20/19.
// Copyright © 2019 koleda. All rights reserved.
//
import Foundation
import RxSwift
import CopilotAPIAccess
protocol ForgotPassWordViewModelProtocol: BaseViewModelProtocol {
var email: Variable<String> { get }
var emailErrorMessage: PublishSubject<String> { get }
func getNewPassword(completion: @escaping (Bool, String) -> Void)
}
class ForgotPasswordViewModel: BaseViewModel, ForgotPassWordViewModelProtocol {
var router: BaseRouterProtocol
let email = Variable<String>("")
let emailErrorMessage = PublishSubject<String>()
private let signUpManager: SignUpManager
init(router: BaseRouterProtocol, managerProvider: ManagerProvider = .sharedInstance) {
self.router = router
self.signUpManager = managerProvider.signUpManager
super.init(managerProvider: managerProvider)
}
func getNewPassword(completion: @escaping (Bool, String) -> Void) {
guard validateEmail() else {
completion(false, "")
return
}
let emailReset = email.value.extraWhitespacesRemoved
signUpManager.resetPassword(email: emailReset,
success: {
completion(true, "")
Copilot.instance.report.log(event: ForgotPasswordAnalyticsEvent(email: emailReset, screenName: self.screenName))
},
failure: { error in
var errorMessage: String = error.localizedDescription
if let wsError = error as? WSError, wsError == WSError.userNotFound {
errorMessage = String(format: "%@ %@", wsError.localizedDescription.app_localized, emailReset)
}
completion(false, errorMessage)
})
}
}
extension ForgotPasswordViewModel {
private func validateEmail() -> Bool {
if email.value.extraWhitespacesRemoved.isEmpty {
emailErrorMessage.onNext("EMAIL_IS_NOT_EMPTY_MESS".app_localized)
return false
}
if DataValidator.isEmailValid(email: email.value.extraWhitespacesRemoved) {
emailErrorMessage.onNext("")
return true
} else {
emailErrorMessage.onNext("EMAIL_IS_INVALID_MESS".app_localized)
return false
}
}
}
<file_sep>//
// ManualBoostViewController.swift
// Koleda
//
// Created by <NAME> on 8/28/19.
// Copyright © 2019 koleda. All rights reserved.
//
import UIKit
import RxSwift
import SVProgressHUD
class ManualBoostViewController: BaseViewController, BaseControllerProtocol {
private let disposeBag = DisposeBag()
@IBOutlet weak var currentTempratureLabel: UILabel!
@IBOutlet weak var editingTempratureLabel: UILabel!
@IBOutlet weak var editingTempraturesmallLabel: UILabel!
@IBOutlet weak var statusLabel: UILabel!
@IBOutlet weak var endTimeLabel: UILabel!
@IBOutlet weak var countDownTimeLabel: UILabel!
@IBOutlet weak var increaseButton: UIButton!
@IBOutlet weak var decresseButton: UIButton!
@IBOutlet weak var cancelButton: UIButton!
@IBOutlet weak var setButton: UIButton!
@IBOutlet weak var timeSlider: UISlider!
@IBOutlet weak var adjustView: UIView!
var viewModel: ManualBoostViewModelProtocol!
override func viewDidLoad() {
super.viewDidLoad()
configurationUI()
}
deinit {
NotificationCenter.default.removeObserver(self)
}
@objc private func needUpdateSelectedRoom() {
viewModel.needUpdateSelectedRoom()
}
@IBAction func close(_ sender: Any) {
self.dismiss(animated: true) {
}
}
@objc func changeVlaue(_ sender: UISlider) {
viewModel.updateSettingTime(seconds: Int(sender.value))
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationBarTransparency()
navigationController?.setNavigationBarHidden(false, animated: animated)
addCloseFunctionality()
viewModel.setup()
}
private func configurationUI() {
NotificationCenter.default.addObserver(self, selector: #selector(needUpdateSelectedRoom),
name: .KLDNeedUpdateSelectedRoom, object: nil)
Style.Button.primary.apply(to: setButton)
Style.Button.halfWithWhiteSmall.apply(to: cancelButton)
Style.View.shadowBlackRemote.apply(to: adjustView)
timeSlider.maximumValue = Float(Constants.MAX_END_TIME_POINT + 1)
timeSlider.minimumValue = 0
timeSlider.addTarget(self, action: #selector(changeVlaue(_:)), for: .valueChanged)
viewModel.statusString.asObservable().bind { [weak self] status in
self?.statusLabel.text = status
}.disposed(by: disposeBag)
increaseButton.rx.tap.bind { [weak self] _ in
self?.viewModel.adjustTemprature(increased: true)
}.disposed(by: disposeBag)
decresseButton.rx.tap.bind { [weak self] _ in
self?.viewModel.adjustTemprature(increased: false)
}.disposed(by: disposeBag)
cancelButton.rx.tap.bind { [weak self] _ in
self?.viewModel.resetSettingTime(completion: { success, errorMessage in
guard success else {
if errorMessage != "" {
self?.app_showInfoAlert(errorMessage)
}
return
}
self?.app_showInfoAlert("Reset Manual Boost Successfully!")
NotificationCenter.default.post(name: .KLDDidChangeRooms, object: nil)
})
}.disposed(by: disposeBag)
setButton.rx.tap.bind { [weak self] _ in
SVProgressHUD.show()
self?.viewModel.manualBoostUpdate(completion: { [weak self] isSuccess in
SVProgressHUD.dismiss()
if isSuccess {
NotificationCenter.default.post(name: .KLDDidChangeRooms, object: nil)
self?.app_showInfoAlert("Manual Boost updated Successfully!", title: "Koleda", completion: {
self?.dismiss(animated: true, completion: nil)
})
} else {
self?.app_showInfoAlert("Manual Boost can't update now")
}
})
}.disposed(by: disposeBag)
viewModel.currentTemperature.asObservable().bind(to: currentTempratureLabel.rx.text).disposed(by: disposeBag)
viewModel.editingTemprature.asObservable().bind { [weak self] value in
self?.editingTempratureLabel.text = "\(value)°"
}.disposed(by: disposeBag)
viewModel.editingTempratureSmall.asObservable().bind { [weak self] value in
self?.editingTempraturesmallLabel.text = value > 0 ? "\(value)" : ""
}.disposed(by: disposeBag)
viewModel.countDownTime.asObservable().bind { [weak self] value in
self?.countDownTimeLabel.text = value
}.disposed(by: disposeBag)
viewModel.endTime.asObservable().bind(to: endTimeLabel.rx.text).disposed(by: disposeBag)
viewModel.sliderValue.asObservable().bind { [weak self] value in
self?.timeSlider.setValue(value, animated: true)
self?.setButton.isEnabled = value > 0
}.disposed(by: disposeBag)
viewModel.manualBoostTimeout.asObservable().subscribe(onNext: { [weak self] in
SVProgressHUD.show(withStatus: "Manual Boost Timeout")
self?.viewModel.refreshRoom(completion: { success in
SVProgressHUD.dismiss()
})
}).disposed(by: disposeBag)
}
}
<file_sep>//
// AddHeaterViewController.swift
// Koleda
//
// Created by <NAME> on 9/4/19.
// Copyright © 2019 koleda. All rights reserved.
//
import UIKit
import RxSwift
import SVProgressHUD
class AddHeaterViewController: BaseViewController, BaseControllerProtocol {
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var tryAgainButton: UIButton!
@IBOutlet weak var searchingHeaterView: UIView!
@IBOutlet weak var searchingForHeaterLabel: UILabel!
@IBOutlet weak var moreThanOneHeaterView: UIView!
@IBOutlet weak var moreThanOneHeaterLabel: UILabel!
@IBOutlet weak var followTheInstructionsToConnectLabel: UILabel!
@IBOutlet weak var tryAgain2Button: UIButton!
@IBOutlet weak var tryAgain2Label: UILabel!
@IBOutlet weak var couldNotFindHeaterView: UIView!
@IBOutlet weak var couldNotFindHeaterLabel: UILabel!
@IBOutlet weak var connectToDeviceHotspotButton: UIButton!
@IBOutlet weak var reportSearchHeaterView: UIView!
@IBOutlet weak var haveFoundTitleView: UIView!
@IBOutlet weak var weHaveFoundOneHeaterLabel: UILabel!
@IBOutlet weak var tapToConnectLabel: UILabel!
@IBOutlet weak var lineView: UIView!
@IBOutlet weak var aHeaterView: UIView!
@IBOutlet weak var addHeaterButton: UIButton!
@IBOutlet weak var deviceModelLabel: UILabel!
@IBOutlet weak var addingHeaterTitleView: UIView!
@IBOutlet weak var addingHeaterLabel: UILabel!
@IBOutlet weak var pleaseWatiForAddingLabel: UILabel!
@IBOutlet weak var addSuccessfullyView: UIView!
@IBOutlet weak var heaterAddedSuccessLabel: UILabel!
@IBOutlet weak var addedDeviceModelLabel: UILabel!
@IBOutlet weak var addedRoomNameLabel: UILabel!
@IBOutlet weak var doYouWantAddOtherLabel: UILabel!
@IBOutlet weak var yesButton: UIButton!
@IBOutlet weak var noButton: UIButton!
@IBOutlet weak var cancelButton: UIButton!
var viewModel: AddHeaterViewModelProtocol!
var isFromRoomConfiguration: Bool = false
private let disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
configurationUI()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationBarTransparency()
navigationController?.setNavigationBarHidden(true, animated: animated)
startToDectectDevice()
}
deinit {
NotificationCenter.default.removeObserver(self)
}
@objc private func scanShellyDevices() {
startToDectectDevice()
}
private func configurationUI() {
cancelButton.isHidden = true
canBackToPreviousScreen = false
NotificationCenter.default.addObserver(self, selector: #selector(scanShellyDevices), name: .KLDDidChangeWifi, object: nil)
SVProgressHUD.setDefaultStyle(.dark)
cancelButton.rx.tap.bind { [weak self] in
self?.back()
}.disposed(by: disposeBag)
viewModel.cancelButtonHidden.asObservable().bind(to: cancelButton.rx.isHidden).disposed(by: disposeBag)
viewModel.stepAddHeaters.asObservable().subscribe(onNext: { [weak self] status in
self?.searchingHeaterView.isHidden = true
self?.moreThanOneHeaterView.isHidden = true
self?.couldNotFindHeaterView.isHidden = true
self?.reportSearchHeaterView.isHidden = true
self?.haveFoundTitleView.isHidden = true
self?.lineView.isHidden = true
self?.aHeaterView.isHidden = true
self?.addingHeaterTitleView.isHidden = true
self?.addSuccessfullyView.isHidden = true
switch status {
case .search:
self?.searchingHeaterView.isHidden = false
self?.viewModel.cancelButtonHidden.onNext(true)
case .moreThanOneDevice: //more than one heater 1
self?.moreThanOneHeaterView.isHidden = false
self?.viewModel.cancelButtonHidden.onNext(true)
case .noDevice: //no heater 2
self?.couldNotFindHeaterView.isHidden = false
self?.viewModel.cancelButtonHidden.onNext(true)
case .oneDevice: //found a heater 3
self?.reportSearchHeaterView.isHidden = false
self?.haveFoundTitleView.isHidden = false
self?.lineView.isHidden = false
self?.aHeaterView.isHidden = false
self?.deviceModelLabel.text = self?.viewModel.detectedHeaters[0].deviceModel
self?.addHeaterButton.isEnabled = true
self?.viewModel.cancelButtonHidden.onNext(true)
case .addDevice: //adding a heater 4
self?.reportSearchHeaterView.isHidden = false
self?.addingHeaterTitleView.isHidden = false
self?.lineView.isHidden = false
self?.aHeaterView.isHidden = false
self?.deviceModelLabel.text = self?.viewModel.detectedHeaters[0].deviceModel
self?.addHeaterButton.isEnabled = false
self?.viewModel.cancelButtonHidden.onNext(false)
case .addDeviceSuccess: //adding a heater successfully 5
self?.reportSearchHeaterView.isHidden = false
self?.addSuccessfullyView.isHidden = false
self?.deviceModelLabel.text = self?.viewModel.detectedHeaters[0].deviceModel
self?.addHeaterButton.isEnabled = false
self?.addedDeviceModelLabel.text = self?.viewModel.detectedHeaters[0].deviceModel
self?.viewModel.cancelButtonHidden.onNext(true)
if let userName = UserDataManager.shared.currentUser?.name, let roomName = self?.viewModel.roomName {
// self?.addedRoomNameLabel.text = "\(userName)’s \(roomName)"
} else {
// self?.addedRoomNameLabel.text = self?.viewModel.roomName
}
case .joinDeviceHotSpot:
self?.viewModel.cancelButtonHidden.onNext(true)
guard let ssid = UserDefaultsManager.wifiSsid.value, let pass = UserDefaultsManager.wifiPass.value else {
self?.viewModel.stepAddHeaters.onNext(.noDevice)
self?.app_showInfoAlert("UPDATE_WIFI_SETTINGS_INFO_MESS".app_localized, title: "KOLEDA_TEXT".app_localized, completion: {
self?.viewModel.showWifiDetail()
})
return
}
SVProgressHUD.show()
self?.viewModel.connectHeaterLocalWifi(ssid: ssid, pass: pass, completion: { [weak self] success in
SVProgressHUD.dismiss()
self?.viewModel.stepAddHeaters.onNext(.noDevice)
if success {
self?.app_showInfoAlert("HEATER_CONNECTED_TO_YOUR_LOCAL_WIFI_MESS".app_localized, title: "SUCCESSFULL_TEXT".app_localized, completion: {
SVProgressHUD.show()
self?.viewModel.waitingHeatersJoinNetwork(completion: {
SVProgressHUD.dismiss()
self?.startToDectectDevice()
})
})
} else {
self?.viewModel.stepAddHeaters.onNext(.noDevice)
self?.app_showInfoAlert("WIFI_SSID_OR_PASS_IS_INCORRECT_MESS".app_localized, title: "ERROR_TITLE".app_localized, completion: {
self?.viewModel.showWifiDetail()
})
}
})
}
}).disposed(by: disposeBag)
addHeaterButton.rx.tap.bind { [weak self] in
self?.viewModel.stepAddHeaters.onNext(.addDevice)
self?.viewModel.addAHeaterToARoom { (error, deviceModel, roomName) in
guard let error = error else {
NotificationCenter.default.post(name: .KLDDidChangeRooms, object: nil)
self?.viewModel.stepAddHeaters.onNext(.addDeviceSuccess)
return
}
if error == WSError.deviceExisted {
self?.app_showAlertMessage(title: "ERROR_TITLE".app_localized, message: String(format: "%@ %@", "THIS_HEATER_TEXT".app_localized, error.localizedDescription))
} else {
self?.app_showAlertMessage(title: "ERROR_TITLE".app_localized, message: "CAN_NOT_ADD_HEATER_MESS".app_localized)
}
}
}.disposed(by: disposeBag)
tryAgain2Button.rx.tap.bind { [weak self] in
self?.startToDectectDevice()
}.disposed(by: disposeBag)
tryAgainButton.rx.tap.bind { [weak self] in self?.startToDectectDevice()
}.disposed(by: disposeBag)
connectToDeviceHotspotButton.rx.tap.bind { [weak self] in
self?.goWifiSetting()
}.disposed(by: disposeBag)
viewModel.reSearchingHeater.asObservable().subscribe(onNext: { [weak self] success in
self?.viewModel.stepAddHeaters.onNext(.noDevice)
self?.startToDectectDevice()
}).disposed(by: disposeBag)
NotificationCenter.default.addObserver(self, selector: #selector(scanShellyDevices),
name: .KLDNeedToReSearchDevices, object: nil)
titleLabel.text = "ADD_A_HEATER_TEXT".app_localized
searchingForHeaterLabel.text = "SEARCHING_FOR_HEATER_TEXT".app_localized
couldNotFindHeaterLabel.text = "COULD_NOT_FIND_HEATER_MESS".app_localized
connectToDeviceHotspotButton.setTitle("CONNECT_TO_HEATER_HOTSPOT_TEXT".app_localized, for: .normal)
tryAgainButton.setTitle("RETRY_TEXT".app_localized, for: .normal)
weHaveFoundOneHeaterLabel.text = "WE_HAVE_FOUND_ONE_HEATER_TEXT".app_localized
tapToConnectLabel.text = "TAP_TO_CONNECT".app_localized
addHeaterButton.setTitle("ADD_TEXT".app_localized, for: .normal)
moreThanOneHeaterLabel.text = "THERE_IS_MORE_THAN_ONE_HEATER_MESS".app_localized
followTheInstructionsToConnectLabel.text = "FOLLOW_THE_INSTRUCTION_TO_CONNECT".app_localized
tryAgain2Label.text = "TRY_AGAIN_TEXT".app_localized
addingHeaterLabel.text = "ADDING_HEATER_TEXT".app_localized
pleaseWatiForAddingLabel.text = "PLEASE_WAIT_TEXT".app_localized
heaterAddedSuccessLabel.text = "HEATER_ADDED_SUCCES_MESS".app_localized
doYouWantAddOtherLabel.text = "ADD_OTHER_HEATER_CONFIRM_MESS".app_localized
yesButton.setTitle("YES_TEXT".app_localized, for: .normal)
noButton.setTitle("NO_TEXT".app_localized, for: .normal)
}
private func goWifiSetting() {
let OkAction = UIAlertAction(title: "OK".app_localized, style: .default) { action in
guard let url = URL(string: UIApplication.openSettingsURLString) else {
return
}
if UIApplication.shared.canOpenURL(url) {
UIApplication.shared.open(url, options: [:])
}
}
let cancelAction = UIAlertAction(title: "CANCEL".app_localized, style: .cancel) { action in
}
app_showAlertMessage(title: "KOLEDA_TEXT".app_localized,
message: "INSTRUCTION_FOR_SELECT_YOUR_HEATER_HOTSPOT_MESS".app_localized, actions: [cancelAction, OkAction])
}
private func startToDectectDevice() {
self.view.endEditing(true)
self.viewModel.stepAddHeaters.onNext(.search)
let ssid = viewModel.getCurrentWiFiName()
print(ssid)
guard FGRoute.getGatewayIP() != nil else {
if ssid != "" && DataValidator.isShellyHeaterDevice(hostName: ssid) {
SVProgressHUD.show()
viewModel.fetchInfoOfHeaderAPMode(completion: { [weak self] success in
SVProgressHUD.dismiss()
if success {
self?.viewModel.stepAddHeaters.onNext(.joinDeviceHotSpot)
} else {
self?.viewModel.stepAddHeaters.onNext(.noDevice)
}
})
} else {
viewModel.stepAddHeaters.onNext(.noDevice)
NotificationCenter.default.post(name: .KLDNotConnectedToInternet, object: nil)
}
return
}
closeButton?.isEnabled = false
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
self.viewModel.findHeatersOnLocalNetwork {
if self.viewModel.detectedHeaters.count == 0 {
self.viewModel.stepAddHeaters.onNext(.noDevice)
} else if self.viewModel.detectedHeaters.count > 1 {
self.viewModel.stepAddHeaters.onNext(.moreThanOneDevice)
} else if self.viewModel.detectedHeaters.count == 1 {
self.viewModel.stepAddHeaters.onNext(.oneDevice)
}
}
}
}
@IBAction func backAction(_ sender: Any) {
if isFromRoomConfiguration {
backToViewControler(viewController: HeatersManagementViewController.self)
} else {
backToRoot(animated: true)
}
}
@IBAction func yesAction(_ sender: Any) {
startToDectectDevice()
}
@IBAction func noAction(_ sender: Any) {
if addSuccessfullyView.isHidden == false {
if isFromRoomConfiguration {
backToViewControler(viewController: HeatersManagementViewController.self)
} else {
backToRoot(animated: true)
}
} else {
back()
}
}
}
extension AddHeaterViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
self.view.endEditing(true)
return true
}
}
<file_sep>//
// LegalViewModel.swift
// Koleda
//
// Created by <NAME> on 11/8/20.
// Copyright © 2020 koleda. All rights reserved.
//
import Foundation
import RxSwift
protocol LegalViewModelProtocol: BaseViewModelProtocol {
var legalItems: Variable<[String]> { get }
func viewWillAppear()
func selectedItem(index: Int)
}
class LegalViewModel: BaseViewModel, LegalViewModelProtocol {
let legalItems = Variable<[String]>([])
let router: BaseRouterProtocol
private let settingManager: SettingManager
init(router: BaseRouterProtocol, managerProvider: ManagerProvider = .sharedInstance ) {
self.router = router
self.settingManager = managerProvider.settingManager
super.init(managerProvider: managerProvider)
}
func viewWillAppear() {
var menuList: [String] = []
menuList.append("PRIVACY_POLICY_TEXT".app_localized)
menuList.append("TERMS_AND_CONDITIONS_TEXT".app_localized)
legalItems.value = menuList
}
func selectedItem(index: Int) {
switch index {
case 0:
router.enqueueRoute(with: LegalRouter.RouteType.privacyPolicy)
case 1:
router.enqueueRoute(with: LegalRouter.RouteType.termAndCondition)
default:
break
}
}
}
<file_sep>//
// SyncViewModel.swift
// Koleda
//
// Created by <NAME> on 6/24/19.
// Copyright © 2019 koleda. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
protocol SyncViewModelProtocol: BaseViewModelProtocol {
var profileImage: Driver<UIImage?> { get }
func showTermAndConditionScreen()
}
class SyncViewModel: SyncViewModelProtocol {
var router: BaseRouterProtocol
var profileImage: Driver<UIImage?> { return profileImageSubject.asDriver(onErrorJustReturn: nil) }
private var profileImageSubject = BehaviorSubject<UIImage?>(value: UIImage(named: "defaultProfileImage"))
init(with router: BaseRouterProtocol) {
self.router = router
}
func showTermAndConditionScreen() {
router.enqueueRoute(with: SyncRouter.RouteType.termAndCondition)
}
}
<file_sep>//
// ScheduleOfDay.swift
// Koleda
//
// Created by <NAME> on 10/25/19.
// Copyright © 2019 koleda. All rights reserved.
//
import Foundation
struct ScheduleOfDay: Codable {
let id: String?
let userId: String
let dayOfWeek: String
let details: [ScheduleOfTime]
func convertToDictionary() -> Dictionary<String, Any> {
var detailSchedules: [Dictionary<String, Any>] = []
for detail in self.details {
let scheduleDic: Dictionary<String, Any> = ["from": detail.from, "to": detail.to.correctLocalTimeStringFormatForService, "mode": detail.mode, "roomIds": detail.roomIds]
detailSchedules.append(scheduleDic)
}
return [
"dayOfWeek": self.dayOfWeek,
"details": detailSchedules
]
}
enum CodingKeys: String, CodingKey {
case id = "id"
case userId = "userId"
case dayOfWeek = "dayOfWeek"
case details = "details"
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.id = try container.decodeIfPresent(String.self, forKey: .id)
self.userId = try container.decode(String.self, forKey: .userId)
self.dayOfWeek = try container.decode(String.self, forKey: .dayOfWeek)
self.details = try container.decode([ScheduleOfTime].self, forKey: .details)
}
}
struct ScheduleOfTime: Codable {
let from: String
let to: String
let mode: String
let roomIds: [String]
init(from: String, to: String, mode: String, roomIds: [String]) {
self.from = from
self.to = to
self.mode = mode
self.roomIds = roomIds
}
}
extension ScheduleOfTime {
var rooms: [Room] {
var matchRooms: [Room] = []
for roomId in roomIds {
if let room = UserDataManager.shared.roomWith(roomId: roomId) {
matchRooms.append(room)
}
}
return matchRooms
}
}
extension ScheduleOfDay {
init(dayOfWeek: String, details: [ScheduleOfTime]) {
self.dayOfWeek = dayOfWeek
self.details = details
id = ""
userId = ""
}
}
<file_sep>//
// OnboardingViewController.swift
// Koleda
//
// Created by <NAME> on 5/23/19.
// Copyright © 2019 koleda. All rights reserved.
//
import UIKit
import RxSwift
import FBSDKCoreKit
import FBSDKLoginKit
import GoogleSignIn
import SVProgressHUD
import AuthenticationServices
class OnboardingViewController: BaseViewController, BaseControllerProtocol {
var viewModel: OnboardingViewModelProtocol!
@IBOutlet weak var googleLoginButton: UIButton!
@IBOutlet weak var facebookLoginButton: UIButton!
private let disposeBag = DisposeBag()
@IBOutlet weak var joinHomeButton: UIButton!
@IBOutlet weak var appleLoginButton: UIButton!
@IBOutlet weak var appleLoginView: UIView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var subTitleLabel: UILabel!
@IBOutlet weak var signUpLabel: UILabel!
@IBOutlet weak var facebookLabel: UILabel!
@IBOutlet weak var googleLabel: UILabel!
@IBOutlet weak var appleButton: UIButton!
@IBOutlet weak var alreadyHaveAnAccountLabel: UILabel!
@IBOutlet weak var loginLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
navigationBarTransparency()
statusBarStyle(with: .lightContent)
configurationUI()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(true, animated: animated)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
viewModel.prepare(for: segue)
}
@IBAction func signUp(_ sender: Any) {
viewModel.startSignUpFlow()
}
private func joinHome() {
viewModel.joinHome()
}
@IBAction func signIn(_ sender: Any) {
viewModel.startSignInFlow()
}
}
extension OnboardingViewController: ASAuthorizationControllerDelegate {
@available(iOS 13.0, *)
func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {
if let appleIDCredential = authorization.credential as? ASAuthorizationAppleIDCredential {
guard let authorizationCode = appleIDCredential.authorizationCode, let authCodeString = String(bytes: authorizationCode, encoding: .utf8) else {
appleLoginButton.isEnabled = true
app_showAlertMessage(title: "LOGIN_APPLE_FAILED_TEXT".app_localized, message: "WE_CAN_NOT_LOGIN_APPLE_MESS".app_localized)
return
}
SVProgressHUD.show()
viewModel.loginWithSocial(type: .apple, accessToken: authCodeString) { [weak self] (isSuccess, error) in
self?.appleLoginButton.isEnabled = true
SVProgressHUD.dismiss()
guard !isSuccess else {
return
}
if error == WSError.hiddenAppleEmail {
self?.app_showAlertMessage(title: "LOGIN_APPLE_FAILED_TEXT".app_localized, message: error?.errorDescription)
} else {
self?.app_showAlertMessage(title: "LOGIN_APPLE_FAILED_TEXT".app_localized, message: "LOGIN_FAILED_TRY_AGAIN_MESS".app_localized)
}
}
}
}
@available(iOS 13.0, *)
func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: Error) {
appleLoginButton.isEnabled = true
app_showAlertMessage(title: "LOGIN_APPLE_FAILED_TEXT".app_localized, message: "WE_CAN_NOT_LOGIN_APPLE_MESS".app_localized)
}
}
extension OnboardingViewController: GIDSignInDelegate {
func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!,
withError error: Error!) {
if let error = error {
googleLoginButton.isEnabled = true
log.error("\(error.localizedDescription)")
app_showAlertMessage(title: "LOGIN_GOOGLE_FAILED_TEXT".app_localized, message: "WE_CAN_NOT_LOGIN_GOOGLE_MESS".app_localized)
} else {
guard let accessToken = user.authentication.accessToken else {
googleLoginButton.isEnabled = true
app_showAlertMessage(title: "LOGIN_GOOGLE_FAILED_TEXT".app_localized, message: "WE_CAN_NOT_LOGIN_GOOGLE_MESS".app_localized)
return
}
SVProgressHUD.show()
viewModel.loginWithSocial(type: .google, accessToken: accessToken) { [weak self] (isSuccess, error) in
self?.googleLoginButton.isEnabled = true
SVProgressHUD.dismiss()
if !isSuccess {
self?.app_showAlertMessage(title: "LOGIN_GOOGLE_FAILED_TEXT".app_localized, message: "LOGIN_FAILED_TRY_AGAIN_MESS".app_localized)
}
}
}
}
func sign(_ signIn: GIDSignIn!, didDisconnectWith user: GIDGoogleUser!, withError error: Error!) {
}
func sign(_ signIn: GIDSignIn!, present viewController: UIViewController!) {
self.present(viewController, animated: true, completion: nil)
}
func sign(_ signIn: GIDSignIn!, dismiss viewController: UIViewController!) {
self.dismiss(animated: true, completion: nil)
}
}
extension OnboardingViewController {
private func configurationUI() {
googleLoginButton.rx.tap.bind { [weak self] _ in
self?.googleLoginButton.isEnabled = false
self?.loginUsingGoogle()
}.disposed(by: disposeBag)
facebookLoginButton.rx.tap.bind { [weak self] _ in
self?.facebookLoginButton.isEnabled = false
self?.loginUsingFacebook()
}.disposed(by: disposeBag)
joinHomeButton.rx.tap.bind { [weak self] _ in
self?.joinHome()
}.disposed(by: disposeBag)
setUpSignInAppleButton()
titleLabel.text = "WELCOME".app_localized
subTitleLabel.text = "SUB_TITLE".app_localized
signUpLabel.text = "SIGN_UP".app_localized
facebookLabel.text = "CONTINUE_WITH_FACEBOOK".app_localized
googleLabel.text = "CONTINUE_WITH_GOOGLE".app_localized
appleButton.setTitle("CONTINUE_WITH_APPLE".app_localized, for: .normal)
joinHomeButton.setTitle("JOIN_HOME".app_localized, for: .normal)
alreadyHaveAnAccountLabel.text = "ALREADY_HAVE_A_ACCOUNT".app_localized
loginLabel.text = "LOGIN".app_localized
}
private func setUpSignInAppleButton() {
if #available(iOS 13.0, *) {
self.appleLoginView.isHidden = false
appleLoginButton.rx.tap.bind { [weak self] _ in
self?.confirmSharingAppleEmail()
}.disposed(by: disposeBag)
} else {
// Fallback on earlier versions
self.appleLoginView.isHidden = true
}
}
private func loginUsingGoogle() {
GIDSignIn.sharedInstance()?.delegate = self
GIDSignIn.sharedInstance()?.presentingViewController = self
GIDSignIn.sharedInstance()?.signIn()
}
private func loginUsingFacebook() {
let loginFBManager = LoginManager()
loginFBManager.logOut()
loginFBManager.logIn(permissions: [Permission.publicProfile, Permission.email], viewController: self) { [weak self] loginResult in
switch loginResult {
case .failed(let error):
log.error(error.localizedDescription)
self?.facebookLoginButton.isEnabled = true
self?.app_showAlertMessage(title: "LOGIN_FACEBOOK_FAILED_TEXT".app_localized, message: "WE_CAN_NOT_LOGIN_FACEBOOK_MESS".app_localized)
case .cancelled:
self?.facebookLoginButton.isEnabled = true
self?.app_showAlertMessage(title: "LOGIN_FACEBOOK_FAILED_TEXT".app_localized, message: "WE_CAN_NOT_LOGIN_FACEBOOK_MESS".app_localized)
case .success(_, _, let fbAccessToken):
SVProgressHUD.show()
self?.viewModel.loginWithSocial(type: .facebook, accessToken: fbAccessToken.tokenString, completion: { (isSuccess, error) in
self?.facebookLoginButton.isEnabled = true
SVProgressHUD.dismiss()
guard let error = error, !isSuccess else {
return
}
if error == WSError.emailNotExisted {
self?.app_showAlertMessage(title: "LOGIN_FACEBOOK_FAILED_TEXT".app_localized, message: error.errorDescription)
} else {
self?.app_showAlertMessage(title: "LOGIN_FACEBOOK_FAILED_TEXT".app_localized, message: "LOGIN_FAILED_TRY_AGAIN_MESS".app_localized)
}
})
}
}
}
private func loginWithApple() {
if #available(iOS 13.0, *) {
let appleIDProvider = ASAuthorizationAppleIDProvider()
let request = appleIDProvider.createRequest()
request.requestedScopes = [.fullName, .email]
let authorizationController = ASAuthorizationController(authorizationRequests: [request])
authorizationController.delegate = self
authorizationController.performRequests()
}
}
private func confirmSharingAppleEmail() {
let OkAction = UIAlertAction(title: "OK".app_localized, style: .default) { [weak self] action in
self?.appleLoginButton.isEnabled = false
self?.loginWithApple()
}
let cancelAction = UIAlertAction(title: "CANCEL".app_localized, style: .cancel) { action in
}
app_showAlertMessage(title: "KOLEDA_TEXT".app_localized,
message: "PLEASE_SELECT_SHARE_EMAIL_CONTINUE_WITH_APPLE_SIGN_IN".app_localized, actions: [cancelAction, OkAction])
}
}
<file_sep>//
// EnergyTariffViewModel.swift
// Koleda
//
// Created by <NAME> on 7/31/19.
// Copyright © 2019 koleda. All rights reserved.
//
import Foundation
import RxSwift
protocol EnergyTariffViewModelProtocol: BaseViewModelProtocol {
var startOfDay: Variable<String> { get }
var endOfDay: Variable<String> { get }
var tariffOfDay: Variable<String> { get }
var startOfNight: Variable<String> { get }
var endOfNight: Variable<String> { get }
var tariffOfNight: Variable<String> { get }
var errorMessage: Variable<String> { get }
var updateFinished: PublishSubject<Bool> { get }
var currency: Variable<String> { get }
func updatetTariffOfDay(amount: String)
func updatetTariffOfNight(amount: String)
func showNextScreen()
func next(completion: @escaping () -> Void)
}
class EnergyTariffViewModel: BaseViewModel, EnergyTariffViewModelProtocol {
let router: BaseRouterProtocol
let startOfDay = Variable<String>("")
let endOfDay = Variable<String>("")
let tariffOfDay = Variable<String>("0.00")
let startOfNight = Variable<String>("")
let endOfNight = Variable<String>("")
let tariffOfNight = Variable<String>("0.00")
let currency = Variable<String>("")
let errorMessage = Variable<String>("")
let updateFinished = PublishSubject<Bool>()
private let settingManager: SettingManager
init(router: BaseRouterProtocol, managerProvider: ManagerProvider = .sharedInstance ) {
self.router = router
settingManager = managerProvider.settingManager
super.init(managerProvider: managerProvider)
getTariffInfo()
}
func showNextScreen() {
if UserDefaultsManager.loggedIn.enabled {
router.enqueueRoute(with: EnergyTariffRouter.RouteType.backHome)
} else {
router.enqueueRoute(with: EnergyTariffRouter.RouteType.temperatureUnit)
}
}
func next(completion: @escaping () -> Void) {
if validateAll() {
let tariffDay = (tariffOfDay.value as NSString).doubleValue
let tariffNight = (tariffOfNight.value as NSString).doubleValue
guard tariffDay > 0 && tariffNight > 0 else {
completion()
return
}
let tariff = Tariff(dayTimeStart: startOfDay.value,
dayTimeEnd: endOfDay.value,
dayTariff: tariffDay,
nightTimeStart: startOfNight.value,
nightTimeEnd: endOfNight.value,
nightTariff: tariffNight,
currency: currency.value)
settingManager.updateTariff(tariff: tariff, success: { [weak self] in
UserDataManager.shared.tariff = tariff
self?.updateFinished.onNext(true)
completion()
},
failure: { error in
self.updateFinished.onNext(false)
completion()
})
} else {
completion()
showNextScreen()
}
}
private func getTariffInfo() {
settingManager.getTariff(success: { [weak self] in
self?.setupTariffInfo()
}) { _ in
}
}
private func setupTariffInfo() {
guard let tariff = UserDataManager.shared.tariff else {
return
}
startOfDay.value = tariff.dayTimeStart
endOfDay.value = tariff.dayTimeEnd
tariffOfDay.value = tariff.dayTariff != 0 ? "\(tariff.dayTariff)" : "0.00"
startOfNight.value = tariff.nightTimeStart
endOfNight.value = tariff.nightTimeEnd
tariffOfNight.value = tariff.nightTariff != 0 ? "\(tariff.nightTariff)": "0.00"
currency.value = tariff.currency
}
func updatetTariffOfDay(amount: String) {
tariffOfDay.value = amount
}
func updatetTariffOfNight(amount: String) {
tariffOfNight.value = amount
}
func validateAll() -> Bool {
guard startOfDay.value.extraWhitespacesRemoved != "" else {
errorMessage.value = "START_DAYTIME_IS_NOT_EMPTY_MESS".app_localized
return false
}
guard endOfDay.value.extraWhitespacesRemoved != "" else {
errorMessage.value = "END_DAYTIME_IS_NOT_EMPTY_MESS".app_localized
return false
}
guard tariffOfDay.value.kld_doubleValue ?? 0.0 > 0.0 else {
errorMessage.value = "TARIFF_NUMBER_IS_NOT_EMPTY".app_localized
return false
}
guard startOfNight.value.extraWhitespacesRemoved != "" else {
errorMessage.value = "START_NIGHTTIME_IS_NOT_EMPTY_MESS".app_localized
return false
}
guard endOfNight.value.extraWhitespacesRemoved != "" else {
errorMessage.value = "END_NIGHTTIME_IS_NOT_EMPTY_MESS".app_localized
return false
}
guard tariffOfNight.value.kld_doubleValue ?? 0.0 > 0.0 else {
errorMessage.value = "TARIFF_NUMBER_NIGHT_IS_NOT_EMPTY".app_localized
return false
}
guard currency.value.extraWhitespacesRemoved != "" else {
errorMessage.value = "CURRENCY_IS_NOT_EMPTY".app_localized
return false
}
errorMessage.value = ""
return tariffInfoChanged()
}
private func tariffInfoChanged() -> Bool {
if let tariff = UserDataManager.shared.tariff {
let updated = (tariff.dayTimeStart != startOfDay.value.extraWhitespacesRemoved) ||
(tariff.dayTimeEnd != endOfDay.value.extraWhitespacesRemoved) ||
(tariff.nightTimeStart != startOfNight.value.extraWhitespacesRemoved) ||
(tariff.nightTimeEnd != endOfNight.value.extraWhitespacesRemoved) ||
("\(tariff.dayTariff)" != tariffOfDay.value.extraWhitespacesRemoved) ||
("\(tariff.nightTariff)" != tariffOfNight.value.extraWhitespacesRemoved) ||
tariff.currency != currency.value
return updated
} else {
return true
}
}
}
<file_sep>//
// ModifyModesViewController.swift
// Koleda
//
// Created by <NAME> on 2/3/20.
// Copyright © 2020 koleda. All rights reserved.
//
import UIKit
import RxSwift
class ModifyModesViewController: BaseViewController, BaseControllerProtocol {
var viewModel: ModifyModesViewModelProtocol!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var descriptionLabel: UILabel!
@IBOutlet weak var customTemperatureLabel: UILabel!
@IBOutlet weak var modesCollectionView: UICollectionView!
private let disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
initView()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationBarTransparency()
navigationController?.setNavigationBarHidden(true, animated: animated)
setTitleScreen(with: "")
}
@objc private func needReLoadModes() {
viewModel.loadModes()
}
private func initView() {
viewModel.smartModes.asObservable().subscribe(onNext: { [weak self] smartModes in
guard let modesCollectionViewDataSource = self?.modesCollectionView.dataSource as? ModesCollectionViewDataSource else { return }
modesCollectionViewDataSource.smartModes = smartModes
modesCollectionViewDataSource.fromModifyModesScreen = true
self?.modesCollectionView.reloadData()
}).disposed(by: disposeBag)
NotificationCenter.default.addObserver(self, selector: #selector(needReLoadModes), name: .KLDNeedReLoadModes, object: nil)
titleLabel.text = "MODIFY_TEMPERATURE_MODE_TEXT".app_localized
descriptionLabel.text = "HERE_YOU_CAN_MODIFY_TEMPERATURE_MODES_APPLY_TO_ROOM".app_localized
customTemperatureLabel.text = "CUSTOM_TEMPERATURES_TEXT".app_localized
}
@IBAction func backAction(_ sender: Any) {
back()
}
}
extension ModifyModesViewController : UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath) -> CGSize {
let numberOfCells = viewModel.smartModes.value.count
let widthOfCell: CGFloat = self.modesCollectionView.frame.width / CGFloat(numberOfCells)
return CGSize(width: (widthOfCell > 88) ? widthOfCell : 88, height: self.modesCollectionView.frame.height)
}
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
insetForSectionAt section: Int) -> UIEdgeInsets {
return .zero
}
}
extension ModifyModesViewController: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
viewModel?.didSelectMode(atIndex: indexPath.section)
}
}
<file_sep>//
// JoinHomeViewController.swift
// Koleda
//
// Created by <NAME> on 6/24/20.
// Copyright © 2020 koleda. All rights reserved.
//
import UIKit
import RxSwift
import SVProgressHUD
class JoinHomeViewController: BaseViewController, BaseControllerProtocol, KeyboardAvoidable {
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var nameTextField: AndroidStyle2TextField!
@IBOutlet weak var emailTextField: AndroidStyle2TextField!
@IBOutlet weak var passwordTextField: AndroidStyle2TextField!
@IBOutlet weak var homeIDTextField: AndroidStyle2TextField!
@IBOutlet weak var confirmFullNameImageView: UIImageView!
@IBOutlet weak var confirmEmailImageView: UIImageView!
@IBOutlet weak var confirmHomeIdImageView: UIImageView!
@IBOutlet weak var joinHomeLabel: UILabel!
@IBOutlet weak var nextLabel: UILabel!
var viewModel: JoinHomeViewModelProtocol!
var keyboardHelper: KeyboardHepler?
private let disposeBag = DisposeBag()
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(true, animated: animated)
statusBarStyle(with: .lightContent)
self.edgesForExtendedLayout = UIRectEdge.top
self.automaticallyAdjustsScrollViewInsets = false
}
override func viewDidLoad() {
super.viewDidLoad()
initView()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
removeKeyboardObservers()
}
func initView() {
keyboardHelper = KeyboardHepler(scrollView)
viewModel.fullName.asObservable().bind(to: nameTextField.rx.text).disposed(by: disposeBag)
nameTextField.rx.text.orEmpty.bind(to: viewModel.fullName).disposed(by: disposeBag)
viewModel.email.asObservable().bind(to: emailTextField.rx.text).disposed(by: disposeBag)
emailTextField.rx.text.orEmpty.bind(to: viewModel.email).disposed(by: disposeBag)
viewModel.password.asObservable().bind(to: passwordTextField.rx.text).disposed(by: disposeBag)
passwordTextField.rx.text.orEmpty.bind(to: viewModel.password).disposed(by: disposeBag)
viewModel.homeID.asObservable().bind(to: homeIDTextField.rx.text).disposed(by: disposeBag)
homeIDTextField.rx.text.orEmpty.bind(to: viewModel.homeID).disposed(by: disposeBag)
viewModel.showPassword.asObservable().subscribe(onNext: { [weak self] value in
self?.passwordTextField.isSecureTextEntry = !value
}).disposed(by: disposeBag)
viewModel.fullName.asObservable().subscribe(onNext: { [weak self] value in
self?.confirmFullNameImageView.isHidden = isEmpty(value)
}).disposed(by: disposeBag)
viewModel.email.asObservable().subscribe(onNext: { [weak self] value in
self?.confirmEmailImageView.isHidden = isEmpty(value)
}).disposed(by: disposeBag)
viewModel.password.asObservable().subscribe(onNext: { [weak self] value in
if !isEmpty(value) && value.count < Constants.passwordMinLength {
self?.passwordTextField.errorText = "Too short!".app_localized
self?.passwordTextField.showError(true)
} else {
self?.passwordTextField.errorText = ""
self?.passwordTextField.showError(false)
}
}).disposed(by: disposeBag)
viewModel.homeID.asObservable().subscribe(onNext: { [weak self] value in
self?.confirmHomeIdImageView.isHidden = isEmpty(value)
}).disposed(by: disposeBag)
viewModel.fullNameErrorMessage.asObservable().subscribe(onNext: { [weak self] message in
self?.nameTextField.errorText = message
if message.isEmpty {
self?.nameTextField.showError(false)
} else {
self?.nameTextField.showError(true)
}
}).disposed(by: disposeBag)
viewModel.emailErrorMessage.asObservable().subscribe(onNext: { [weak self] message in
self?.emailTextField.errorText = message
if message.isEmpty {
self?.emailTextField.showError(false)
} else {
self?.emailTextField.showError(true)
}
}).disposed(by: disposeBag)
viewModel.passwordErrorMessage.asObservable().subscribe(onNext: { [weak self] message in
self?.passwordTextField.errorText = message
if message.isEmpty {
self?.passwordTextField.showError(false)
} else {
self?.passwordTextField.showError(true)
}
}).disposed(by: disposeBag)
viewModel.homeIDErrorMessage.asObservable().subscribe(onNext: { [weak self] message in
self?.homeIDTextField.errorText = message
if message.isEmpty {
self?.homeIDTextField.showError(false)
} else {
self?.homeIDTextField.showError(true)
}
}).disposed(by: disposeBag)
viewModel.showErrorMessage.asObservable().subscribe(onNext: { [weak self] message in
if !message.isEmpty {
self?.app_showAlertMessage(title: "Error".app_localized, message: message)
}
}).disposed(by: disposeBag)
joinHomeLabel.text = "JOIN_HOME_TEXT".app_localized
nameTextField.titleText = "NAME_TEXT".app_localized
emailTextField.titleText = "EMAIL_TEXT".app_localized
passwordTextField.titleText = "CREATE_PASSWORD_TEXT".app_localized
homeIDTextField.titleText = "HOME ID".app_localized
nameTextField.placeholder = "ENTER_YOUR_NAME_TEXT".app_localized
emailTextField.placeholder = "ENTER_EMAIL_HERE_TEXT".app_localized
passwordTextField.placeholder = "ENTER_PASSWORD_TEXT".app_localized
homeIDTextField.placeholder = "ENTER_HOME_ID_TEXT".app_localized
nextLabel.text = "NEXT_TEXT".app_localized
}
@IBAction func showOrHidePass(_ sender: Any) {
viewModel?.showPassword(isShow: passwordTextField.isSecureTextEntry)
}
@IBAction func backAction(_ sender: Any) {
back()
}
@IBAction func next(_ sender: Any) {
if viewModel.validateAll() {
view.endEditing(true)
SVProgressHUD.show()
viewModel.next { [weak self] error in
SVProgressHUD.dismiss()
guard let error = error else {
self?.app_showInfoAlert("JOIN_HOME_SUCCESS_MESS".app_localized, title: "KOLEDA_TEXT".app_localized, completion: {
self?.loginApp()
})
return
}
self?.app_showAlertMessage(title: "ERROR_TITLE".app_localized, message: error.localizedDescription)
}
}
}
private func loginApp() {
SVProgressHUD.show()
viewModel.loginAfterJoinHome(completion: { [weak self] errorMessage in
SVProgressHUD.dismiss()
if errorMessage != "" {
self?.app_showInfoAlert(errorMessage, title: "ERROR_TITLE".app_localized, completion: {
self?.back()
})
}
})
}
}
extension JoinHomeViewController: UITextFieldDelegate {
func textField(_ textField: UITextField,
shouldChangeCharactersIn range: NSRange,
replacementString string: String) -> Bool
{
if textField == nameTextField {
let currentText = textField.text as NSString?
if let resultingText = currentText?.replacingCharacters(in: range, with: string) {
return resultingText.count <= Constants.nameMaxLength
}
} else if textField == passwordTextField {
let currentText = textField.text as NSString?
if let resultingText = currentText?.replacingCharacters(in: range, with: string) {
return resultingText.count <= Constants.passwordMaxLength
}
}
return true
}
}
<file_sep>//
// CreateHomeViewController.swift
// Koleda
//
// Created by <NAME> on 6/16/20.
// Copyright © 2020 koleda. All rights reserved.
//
import UIKit
import RxSwift
import SVProgressHUD
import SwiftRichString
class CreateHomeViewController: BaseViewController, BaseControllerProtocol {
@IBOutlet weak var progressBarView: ProgressBarView!
@IBOutlet weak var welcomeView: UIView!
@IBOutlet weak var welcomeMessageLabel: UILabel!
@IBOutlet weak var descriptionLabel: UILabel!
@IBOutlet weak var letsStartButton: UIButton!
@IBOutlet weak var homeTitleLabel: UILabel!
@IBOutlet weak var homeNameTextField: AndroidStyleTextField!
@IBOutlet weak var saveButton: UIButton!
var viewModel: CreateHomeViewModelProtocol!
private let disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
configurationUI()
}
private func configurationUI() {
progressBarView.setupNav(viewController: self)
statusBarStyle(with: .lightContent)
Style.Button.primary.apply(to: saveButton)
Style.Button.primary.apply(to: letsStartButton)
letsStartButton.rx.tap.bind { [weak self] in
self?.welcomeView.isHidden = true
self?.statusBarStyle(with: .default)
}.disposed(by: disposeBag)
saveButton.rx.tap.bind { [weak self] in
self?.saveButton.isEnabled = false
SVProgressHUD.show()
self?.viewModel.saveAction {
SVProgressHUD.dismiss()
self?.saveButton.isEnabled = true
}
}.disposed(by: disposeBag)
homeNameTextField.rx.text.orEmpty.bind(to: viewModel.homeName).disposed(by: disposeBag)
viewModel.homeNameErrorMessage.asObservable().subscribe(onNext: { [weak self] message in
self?.homeNameTextField.errorText = message
if message.isEmpty {
self?.homeNameTextField.showError(false)
} else {
self?.homeNameTextField.showError(true)
}
}).disposed(by: disposeBag)
viewModel.welcomeMessage.asObservable().bind { [weak self] title in
let normal = SwiftRichString.Style{
$0.font = UIFont.app_FuturaPTMedium(ofSize: 30)
$0.color = UIColor.black
}
let bold = SwiftRichString.Style {
$0.font = UIFont.app_FuturaPTMedium(ofSize: 30)
$0.color = UIColor.orange
}
let group = StyleGroup(base: normal, ["h1": bold])
self?.welcomeMessageLabel?.attributedText = title.set(style: group)
}.disposed(by: disposeBag)
welcomeMessageLabel.text = "WELCOME_HOME_MESS".app_localized
descriptionLabel.text = "SETUP_YOUR_FIRST_HOME_WITH_SOLUS".app_localized
letsStartButton.setTitle("LETS_START_TEXT".app_localized, for: .normal)
let normal = SwiftRichString.Style{
$0.font = UIFont.app_FuturaPTMedium(ofSize: 22)
$0.color = UIColor.black
}
let bold = SwiftRichString.Style {
$0.font = UIFont.app_FuturaPTMedium(ofSize: 22)
$0.color = UIColor.orange
}
let groupHomeTitle = StyleGroup(base: normal, ["h1": bold])
let string = "NAME_YOUR_HOME".app_localized
homeTitleLabel.attributedText = string.set(style: groupHomeTitle)
homeNameTextField.titleText = "NAME_TEXT".app_localized
saveButton.setTitle("NEXT_TEXT".app_localized, for: .normal)
}
}
<file_sep>//
// HomeCell.swift
// Koleda
//
// Created by <NAME> on 7/15/19.
// Copyright © 2019 koleda. All rights reserved.
//
import UIKit
import SwiftRichString
class HomeCell: UITableViewCell {
@IBOutlet weak var viewContent: UIView!
@IBOutlet weak var subContentView: UIView!
@IBOutlet weak var roomNameLabel: UILabel!
@IBOutlet weak var tempLabel: UILabel!
@IBOutlet weak var infoMessageLabel: UILabel!
@IBOutlet weak var roomTypeImageView: UIImageView!
@IBOutlet weak var batteryView: UIView!
@IBOutlet weak var backgroundImageView: UIImageView!
@IBOutlet weak var oCLabel: UILabel!
@IBOutlet weak var turnedOnView: UIView!
@IBOutlet weak var turnedOffView: UIView!
@IBOutlet weak var statusTitleLabel: UILabel!
@IBOutlet weak var statusImageView: UIImageView!
private var roomViewModel: RoomViewModel?
let normal = SwiftRichString.Style{
$0.font = UIFont.app_SFProDisplayMedium(ofSize: 12)
$0.color = UIColor.hex7e7d80
}
let smallBold = SwiftRichString.Style {
$0.font = UIFont.app_FuturaPTDemi(ofSize: 16)
$0.color = UIColor.hex1F1B15
}
let bold = SwiftRichString.Style {
$0.font = UIFont.app_FuturaPTDemi(ofSize: 20)
$0.color = UIColor.hex1F1B15
}
override func awakeFromNib() {
super.awakeFromNib()
}
func loadData(room: RoomViewModel) {
// Style.View.shadowStyle1.apply(to: subContentView)
self.roomViewModel = room
let turnOn = room.onOffSwitchStatus
roomNameLabel.text = room.roomName
tempLabel.text = room.temprature
roomTypeImageView.image = room.roomHomeImage
roomTypeImageView.tintColor = UIColor.white
batteryView.isHidden = !room.isLowBattery
roomNameLabel.textColor = turnOn ? UIColor.black : UIColor.white
let group = StyleGroup(base: self.normal, ["h1": self.bold])
if isEmpty(room.sensor) {
infoMessageLabel.text = room.infoMessage
infoMessageLabel.textColor = turnOn ? UIColor.black : UIColor.hex88FFFFFF
} else {
infoMessageLabel.attributedText = room.infoMessage.set(style: group)
}
oCLabel.textColor = turnOn ? UIColor.hex1F1B15 : UIColor.hex44FFFFFF
tempLabel.textColor = turnOn ? UIColor.hex1F1B15 : UIColor.white
let currentTemp = room.currentTemp ?? 0
let setTemp = Double.valueOf(clusterValue: room.settingTemprature)
let statusText = currentTemp < setTemp ? "HEATING_UP_TEXT".app_localized : (currentTemp > setTemp) ? "COOLING_DOWN_TEXT".app_localized : ""
let statusImage: String = currentTemp < setTemp ? "ic-heating-up" : (currentTemp > setTemp) ? "ic-cooling-down" : ""
var backgroundImage: String = "bg-dark-gradient"
if turnOn {
backgroundImage = currentTemp < setTemp ? "bg-warm-gradient" : (currentTemp > setTemp) ? "bg-subtle-gradient" : ""
}
statusTitleLabel.text = statusText
statusImageView.isHidden = currentTemp == setTemp
statusImageView.image = UIImage(named: statusImage)
backgroundImageView.isHidden = backgroundImage == ""
roomTypeImageView.tintColor = backgroundImage == "" ? UIColor.gray : UIColor.white
backgroundImageView.image = UIImage(named: backgroundImage)
guard !isEmpty(room.sensor) else {
turnedOffView.isHidden = false
turnedOnView.isHidden = true
return
}
turnedOffView.isHidden = turnOn
turnedOnView.isHidden = !turnOn
}
}
<file_sep>//
// RoomDetailViewController.swift
// Koleda
//
// Created by <NAME> on 7/9/19.
// Copyright © 2019 koleda. All rights reserved.
//
import UIKit
import RxSwift
import SVProgressHUD
class RoomDetailViewController: BaseViewController, BaseControllerProtocol, KeyboardAvoidable {
@IBOutlet weak var roomNameTextField: AndroidStyle3TextField!
@IBOutlet weak var screenTitleLabel: UILabel!
@IBOutlet weak var deleteButton: UIButton!
@IBOutlet weak var nextButton: UIButton!
@IBOutlet weak var widthCollectionConstraint: NSLayoutConstraint!
@IBOutlet weak var roomTypeCollectionView: UICollectionView!
@IBOutlet weak var confirmRoomNameImageView: UIImageView!
@IBOutlet weak var nextButtonConstraint: NSLayoutConstraint!
var viewModel: RoomDetailViewModelProtocol!
private let disposeBag = DisposeBag()
private let itemsPerRow: CGFloat = 3
private var selectedIndexPath: IndexPath?
var keyboardHelper: KeyboardHepler?
override func viewDidLoad() {
super.viewDidLoad()
configurationUI()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationBarTransparency()
navigationController?.setNavigationBarHidden(true, animated: animated)
viewModel.viewWillAppear()
addKeyboardObservers(forConstraints: [nextButtonConstraint])
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
removeKeyboardObservers()
}
}
extension RoomDetailViewController {
private func configurationUI() {
keyboardHelper = KeyboardHepler(self)
if UIDevice.screenType == .iPhones_5_5s_5c_SE {
widthCollectionConstraint.constant = 242
} else {
widthCollectionConstraint.constant = 344
}
viewModel.screenTitle.asObservable().bind(to: screenTitleLabel.rx.text).disposed(by: disposeBag)
viewModel.roomTypes.asObservable().subscribe(onNext: { [weak self] roomTypes in
guard roomTypes.count > 0, let roomTypeDataSource = self?.roomTypeCollectionView.dataSource as? RoomTypeDataSource else { return }
roomTypeDataSource.roomTypes = roomTypes
self?.roomTypeCollectionView.reloadData()
}).disposed(by: disposeBag)
nextButton.rx.tap.bind { [weak self] in
SVProgressHUD.show()
self?.nextButton.isEnabled = false
self?.viewModel.next(roomType: self?.viewModel.roomType(at: self?.selectedIndexPath), completion: {
SVProgressHUD.dismiss()
self?.nextButton.isEnabled = true
})
}.disposed(by: disposeBag)
deleteButton.rx.tap.bind { [weak self] in
self?.showDeletePopUp()
}.disposed(by: disposeBag)
viewModel.roomName.asObservable().bind(to: roomNameTextField.rx.text).disposed(by: disposeBag)
roomNameTextField.rx.text.orEmpty.bind(to: viewModel.roomName).disposed(by: disposeBag)
viewModel.roomName.asObservable().subscribe(onNext: { [weak self] value in
self?.confirmRoomNameImageView.isHidden = isEmpty(value)
}).disposed(by: disposeBag)
viewModel.selectedCategory.asObservable().subscribe(onNext: { [weak self] categoryString in
guard let indexpath = self?.viewModel.indexPathOfCategory(with: categoryString) else { return }
self?.selectedIndexPath = indexpath
self?.roomTypeCollectionView.selectItem(at: indexpath, animated: true, scrollPosition: .bottom)
}).disposed(by: disposeBag)
viewModel.roomNameErrorMessage.asObservable().subscribe(onNext: { [weak self] message in
self?.roomNameTextField.errorText = message
if message.isEmpty {
self?.roomNameTextField.showError(false)
} else {
self?.roomNameTextField.showError(true)
}
}).disposed(by: disposeBag)
viewModel.nextButtonTitle.asObservable().bind { [weak self] title in
self?.nextButton.setTitle(String(format: "%@ ", title), for: .normal)
}
viewModel.showPopUpSelectRoomType.asObservable().subscribe(onNext: { [weak self] show in
self?.showPopUpRequireSelectRoomType()
}).disposed(by: disposeBag)
viewModel.showPopUpSuccess.asObservable().subscribe(onNext: { [weak self] show in
self?.app_showInfoAlert("ADD_ROOM_SUCCESS_MESS".app_localized)
}).disposed(by: disposeBag)
viewModel.hideDeleteButton.asObservable().subscribe(onNext: { [weak self] show in
self?.deleteButton.isHidden = show
}).disposed(by: disposeBag)
roomNameTextField.titleText = "ROOM_NAME_TEXT".app_localized
}
private func showDeletePopUp() {
if let vc = getViewControler(withStoryboar: "Room", aClass: AlertConfirmViewController.self) {
vc.onClickLetfButton = {
self.showConfirmPopUp()
}
if let image:UIImage = viewModel.currentRoomType?.homeImage, let roomName: String = viewModel.roomName.value {
vc.typeAlert = .deleteRoom(icon: image, roomName: roomName)
}
showPopup(vc)
}
}
private func showConfirmPopUp() {
if let vc = getViewControler(withStoryboar: "Room", aClass: AlertConfirmViewController.self) {
vc.onClickRightButton = {
self.viewModel.deleteRoom()
}
vc.typeAlert = .confirmDeleteRoom
showPopup(vc)
}
}
private func showPopUpRequireSelectRoomType() {
app_showAlertMessage(title: "ERROR_TITLE".app_localized, message: "PLEASE_SELECT_ROOM_TYPE".app_localized)
}
@IBAction func backAction(_ sender: Any) {
back()
}
}
// MARK: - Collection View Flow Layout Delegate
extension RoomDetailViewController : UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
insetForSectionAt section: Int) -> UIEdgeInsets {
return .zero
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
if UIDevice.screenType == .iPhones_5_5s_5c_SE {
return CGSize(width: 80, height: 80)
} else {
return CGSize(width: 114, height: 114)
}
}
}
extension RoomDetailViewController : UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
selectedIndexPath = indexPath
}
}
<file_sep>//
// HeaterManagementCollectionViewCell.swift
// Koleda
//
// Created by <NAME> on 9/5/19.
// Copyright © 2019 koleda. All rights reserved.
//
import UIKit
import RxSwift
class HeaterManagementCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var heaterImageView: UIImageView!
@IBOutlet weak var heaterNameLabel: UILabel!
@IBOutlet weak var statusLabel: UILabel!
@IBOutlet weak var removeButton: UIButton!
var removeHandler: ((Heater) -> Void)? = nil
private let disposeBag = DisposeBag()
func setup(with heater: Heater) {
heaterNameLabel.text = heater.name
if heater.enabled {
statusLabel.text = "ACTIVE_TEXT".app_localized
statusLabel.textColor = UIColor.green
} else {
statusLabel.text = "INACTIVE_TEXT".app_localized
statusLabel.textColor = UIColor.red
}
removeButton.rx.tap.bind {
self.removeHandler?(heater)
}.disposed(by: disposeBag)
removeButton.setTitle("REMOVE_TEXT".app_localized, for: .normal)
}
}
<file_sep>//
// AddHeaterRouter.swift
// Koleda
//
// Created by <NAME> on 9/4/19.
// Copyright © 2019 koleda. All rights reserved.
//
import Foundation
import UIKit
class AddHeaterRouter: BaseRouterProtocol {
weak var baseViewController: UIViewController?
enum RouteType {
case backHome
case wifiDetail
}
func enqueueRoute(with context: Any?, animated: Bool, completion: ((Bool) -> Void)?) {
guard let routeType = context as? RouteType else {
assertionFailure("The route type missmatches")
return
}
guard let baseViewController = baseViewController else {
assertionFailure("baseViewController is not set")
return
}
switch routeType {
case .backHome:
baseViewController.navigationController?.popToRootViewController(animated: false)
case .wifiDetail:
let router = WifiDetailRouter()
let viewModel = WifiDetailViewModel.init(router: router)
guard let wifiDetailVC = StoryboardScene.Setup.instantiateWifiDetailViewController() as? WifiDetailViewController else {
assertionFailure("Setup storyboard configured not properly")
return
}
wifiDetailVC.viewModel = viewModel
router.baseViewController = wifiDetailVC
baseViewController.navigationController?.pushViewController(wifiDetailVC, animated: true)
}
}
func present(on baseVC: UIViewController, animated: Bool, context: Any?, completion: ((Bool) -> Void)?) {
}
func dismiss(animated: Bool, context: Any?, completion: ((Bool) -> Void)?) {
}
func prepare(for segue: UIStoryboardSegue) {
}
}
<file_sep>//
// WifiDetailViewController.swift
// Koleda
//
// Created by <NAME> on 12/4/19.
// Copyright © 2019 koleda. All rights reserved.
//
import UIKit
import RxSwift
class WifiDetailViewController: BaseViewController, BaseControllerProtocol {
@IBOutlet weak var progressBarView: ProgressBarView!
@IBOutlet weak var wifiSSIDTextField: AndroidStyleTextField!
@IBOutlet weak var passwordTextField: AndroidStyleTextField!
@IBOutlet weak var saveButton: UIButton!
@IBOutlet weak var titleLabel: UILabel!
var viewModel: WifiDetailViewModelProtocol!
private let disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
configurationUI()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationBarTransparency()
navigationController?.setNavigationBarHidden(true, animated: animated)
setTitleScreen(with: "")
viewModel.setup()
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .default
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
}
@IBAction func showOrHidePass(_ sender: Any) {
passwordTextField.isSecureTextEntry = !passwordTextField.isSecureTextEntry
}
private func configurationUI() {
progressBarView.setupNav(viewController: self)
Style.Button.primary.apply(to: saveButton)
viewModel.ssidText.asObservable().bind(to: wifiSSIDTextField.rx.text).disposed(by: disposeBag)
wifiSSIDTextField.rx.text.orEmpty.bind(to: viewModel.ssidText).disposed(by: disposeBag)
viewModel.wifiPassText.asObservable().bind(to: passwordTextField.rx.text).disposed(by: disposeBag)
passwordTextField.rx.text.orEmpty.bind(to: viewModel.wifiPassText).disposed(by: disposeBag)
viewModel.ssidErrorMessage.asObservable().subscribe(onNext: { [weak self] message in
self?.wifiSSIDTextField.errorText = message
if message.isEmpty {
self?.wifiSSIDTextField.showError(false)
} else {
self?.wifiSSIDTextField.showError(true)
}
}).disposed(by: disposeBag)
saveButton.rx.tap.bind { [weak self] _ in
self?.saveButton.isEnabled = false
self?.viewModel.saveWifiInfo(completion: {
self?.saveButton.isEnabled = true
})
}.disposed(by: disposeBag)
viewModel.disableCloseButton.asObservable().subscribe(onNext: { [weak self] disable in
self?.progressBarView.backButton.isEnabled = !disable
}).disposed(by: disposeBag)
titleLabel.text = "INPUT_YOUR_HOME_WIFI_MESS".app_localized
wifiSSIDTextField.titleText = "WIFI SSID".app_localized
passwordTextField.titleText = "PASSWORD_TITLE".app_localized
saveButton.setTitle("SAVE_TEXT".app_localized, for: .normal)
}
}
<file_sep>//
// ManagerProvider.swift
// Koleda
//
// Created by <NAME> on 7/2/19.
// Copyright © 2019 koleda. All rights reserved.
//
import Foundation
import Alamofire
class ManagerProvider {
static let sharedInstance: ManagerProvider = {
let geoLocationManager = GeoLocationManager()
let loginAppManager = LoginAppManager()
return ManagerProvider(loginAppManager: loginAppManager, geoLocationManager: geoLocationManager)
}()
init(loginAppManager: LoginAppManager, geoLocationManager: GeoLocationManager) {
self.loginAppManager = loginAppManager
self.geoLocationManager = geoLocationManager
}
// Available Managers
private (set) lazy var popupWindowManager = PopupWindowManager()
var signUpManager: SignUpManager {
return SignUpManagerImpl(sessionManager: loginAppManager.sessionManager)
}
var userManager: UserManager {
return UserManagerImpl(sessionManager: loginAppManager.sessionManager)
}
var homeManager: HomeManager {
return HomeManagerImpl(sessionManager: loginAppManager.sessionManager)
}
var roomManager: RoomManager {
return RoomManagerImpl(sessionManager: loginAppManager.sessionManager)
}
var shellyDeviceManager: ShellyDeviceManagerImpl {
return ShellyDeviceManagerImpl(sessionManager: loginAppManager.sessionManager)
}
var settingManager: SettingManager {
return SettingManagerImpl(sessionManager: loginAppManager.sessionManager)
}
var websocketManager: WebsocketManager {
return WebsocketManager.shared
}
var schedulesManager: SchedulesManager {
return SchedulesManagerImpl(sessionManager: loginAppManager.sessionManager)
}
let geoLocationManager: GeoLocationManager
let loginAppManager: LoginAppManager
}
<file_sep>//
// HomeManager.swift
// Koleda
//
// Created by <NAME> on 6/19/20.
// Copyright © 2020 koleda. All rights reserved.
//
import Foundation
import Alamofire
import Sync
import SwiftyJSON
protocol HomeManager {
func createHome(name: String, success: @escaping () -> Void, failure: @escaping (_ error: Error) -> Void)
}
class HomeManagerImpl: HomeManager {
private let sessionManager: Session
private func baseURL() -> URL {
return UrlConfigurator.urlByAdding()
}
init(sessionManager: Session) {
self.sessionManager = sessionManager
}
func createHome(name: String, success: @escaping () -> Void, failure: @escaping (_ error: Error) -> Void) {
let params = ["name": name]
let endPointURL = baseURL().appendingPathComponent("me/homes")
guard let request = URLRequest.postRequestWithJsonBody(url: endPointURL, parameters: params) else {
failure(RequestError.error(NSLocalizedString("Failed to send request, please try again later", comment: "")))
return
}
sessionManager.request(request).validate().responseJSON { [weak self] response in
switch response.result {
case .success(let data):
guard let json = JSON(data).dictionaryObject else {
failure(WSError.failedAddHome)
return
}
let home = Home.init(json: json)
UserDataManager.shared.currentUser?.homes = [home]
log.info("Successfully create home")
success()
case .failure(let error):
log.error("Failed to add home - \(error)")
if let error = error as? URLError, error.code == URLError.notConnectedToInternet {
NotificationCenter.default.post(name: .KLDNotConnectedToInternet, object: error)
} else if let error = error as? AFError, error.responseCode == 400 {
failure(error)
} else if let error = error as? AFError, error.responseCode == 401 {
failure(error)
} else {
failure(error)
}
}
}
}
}
<file_sep>//
// HeatersCollectionViewDataSource.swift
// Koleda
//
// Created by <NAME> on 8/27/19.
// Copyright © 2019 koleda. All rights reserved.
//
import UIKit
import Foundation
class HeatersCollectionViewDataSource: NSObject, UICollectionViewDataSource {
var heaters: [Heater]?
func numberOfSections(in collectionView: UICollectionView) -> Int {
return heaters?.count ?? 0
}
func collectionView(_ collectionView: UICollectionView,
numberOfItemsInSection section: Int) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView
.dequeueReusableCell(withReuseIdentifier: "HeaterCollectionViewCell",
for: indexPath) as? HeaterCollectionViewCell, let heaters = heaters else {
fatalError()
}
let heater = heaters[indexPath.section]
cell.setup(with: heater)
return cell
}
}
<file_sep>//
// GuideRouter.swift
// Koleda
//
// Created by <NAME> on 6/25/19.
// Copyright © 2019 koleda. All rights reserved.
//
import UIKit
class GuideRouter: BaseRouterProtocol {
weak var baseViewController: UIViewController?
enum RouteType {
case addSensor(String)
case addHeater(String)
}
func enqueueRoute(with context: Any?, animated: Bool, completion: ((Bool) -> Void)?) {
guard let routeType = context as? RouteType else {
assertionFailure("The route type missmatches")
return
}
guard let baseViewController = baseViewController else {
assertionFailure("baseViewController is not set")
return
}
switch routeType {
case .addSensor(let roomId):
let router = SensorManagementRouter()
guard let viewController = StoryboardScene.Sensor.instantiateSensorManagementViewController() as? SensorManagementViewController else { return }
let viewModel = SensorManagementViewModel.init(router: router, roomId: roomId, roomName: "")
viewController.viewModel = viewModel
router.baseViewController = viewController
baseViewController.navigationController?.pushViewController(viewController, animated: true)
case .addHeater(let roomId):
let router = AddHeaterRouter()
guard let viewController = StoryboardScene.Heater.instantiateAddHeaterViewController() as? AddHeaterViewController else { return }
let viewModel = AddHeaterViewModel.init(router: router, roomId: roomId, roomName: "")
viewController.viewModel = viewModel
router.baseViewController = viewController
baseViewController.navigationController?.pushViewController(viewController, animated: true)
}
}
func present(on baseVC: UIViewController, animated: Bool, context: Any?, completion: ((Bool) -> Void)?) {
}
func dismiss(animated: Bool, context: Any?, completion: ((Bool) -> Void)?) {
}
}
<file_sep>//
// LoginViewModel.swift
// Koleda
//
// Created by <NAME> on 6/11/19.
// Copyright © 2019 koleda. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
import FBSDKCoreKit
import FBSDKLoginKit
import GoogleSignIn
import CopilotAPIAccess
protocol LoginViewModelProtocol: BaseViewModelProtocol {
var email: Variable<String> { get }
var password: Variable<String> { get }
var emailErrorMessage: Variable<String> { get }
var passwordErrorMessage: Variable<String> { get }
var showPassword: Variable<Bool> { get }
func viewWillAppear()
func login(completion: @escaping (Bool) -> Void)
func showPassword(isShow: Bool)
func prepare(for segue: UIStoryboardSegue)
func backOnboardingScreen()
func forgotPassword()
func loginWithSocial(type: SocialType, accessToken: String, completion: @escaping (Bool, WSError?) -> Void)
}
class LoginViewModel: BaseViewModel, LoginViewModelProtocol {
var email = Variable<String>("")
let password = Variable<String>("")
let emailErrorMessage = Variable<String>("")
let passwordErrorMessage = Variable<String>("")
let showPassword = Variable<Bool>(false)
let router: BaseRouterProtocol
private var _isShowPass = BehaviorSubject(value: false)
private let loginAppManager: LoginAppManager
private let userManager: UserManager
private var disposeBag = DisposeBag()
init(router: BaseRouterProtocol, managerProvider: ManagerProvider = .sharedInstance) {
self.router = router
loginAppManager = managerProvider.loginAppManager
userManager = managerProvider.userManager
super.init(managerProvider: managerProvider)
}
func viewWillAppear() {
guard let lastestEmaillogined = UserDefaultsManager.termAndConditionAcceptedUser.value?.extraWhitespacesRemoved else {
return
}
email.value = lastestEmaillogined
}
func forgotPassword() {
router.enqueueRoute(with: LoginRouter.RouteType.forgotPassword)
}
func showPassword(isShow: Bool) {
showPassword.value = isShow
}
func login(completion: @escaping (Bool) -> Void) {
guard validateAll() else {
completion(true)
return
}
loginAppManager.login(email: email.value.extraWhitespacesRemoved,
password: password.value.extraWhitespacesRemoved,
success: { [weak self] in
log.info("User signed in successfully")
self?.processAfterLoginSuccessfull()
Copilot.instance.report.log(event: LoginAnalyticsEvent())
completion(true)
},
failure: { error in
completion(false)
})
}
func prepare(for segue: UIStoryboardSegue) {
router.prepare(for: segue)
}
func backOnboardingScreen() {
router.enqueueRoute(with: LoginRouter.RouteType.onboaring)
}
func loginWithSocial(type: SocialType, accessToken: String, completion: @escaping (Bool, WSError?) -> Void) {
loginAppManager.loginWithSocial(type: type, accessToken: accessToken,
success: { [weak self] in
log.info("User signed in successfully")
guard let `self` = self else {
return
}
Copilot.instance.report.log(event: LoginSocialAnalyticsEvent(provider: type.rawValue, token: accessToken, zoneId: TimeZone.current.identifier, screenName: self.screenName))
self.processAfterLoginSuccessfull()
completion(true, nil)
}, failure: { error in
completion(false, error as? WSError)
})
}
}
extension LoginViewModel {
private func processAfterLoginSuccessfull() {
var showTermAndCondition: Bool = true
getCurrentUser { [weak self] in
guard let userId = UserDataManager.shared.currentUser?.id else {
return
}
Copilot.instance
.manage
.yourOwn
.sessionStarted(withUserId: userId,
isCopilotAnalysisConsentApproved: true)
if let termAndConditionAcceptedUser = UserDefaultsManager.termAndConditionAcceptedUser.value?.extraWhitespacesRemoved, termAndConditionAcceptedUser == UserDataManager.shared.currentUser?.email {
showTermAndCondition = false
}
// If User hasn't created a home yet
guard let user = UserDataManager.shared.currentUser, user.homes.count > 0 else {
self?.router.enqueueRoute(with: LoginRouter.RouteType.termAndConditions)
return
}
if showTermAndCondition {
self?.router.enqueueRoute(with: LoginRouter.RouteType.termAndConditions)
} else {
UserDefaultsManager.loggedIn.enabled = true
self?.router.enqueueRoute(with: LoginRouter.RouteType.home)
}
}
}
private func getCurrentUser(completion: @escaping () -> Void) {
userManager.getCurrentUser(success: {
completion()
}, failure: { error in
completion()
})
}
private func validateAll() -> Bool {
var failCount = 0
failCount += validateEmail() ? 0 : 1
failCount += validatePassword() ? 0 : 1
return failCount == 0
}
private func validateEmail() -> Bool {
if email.value.extraWhitespacesRemoved.isEmpty {
emailErrorMessage.value = "EMAIL_IS_NOT_EMPTY_MESS".app_localized
return false
}
if DataValidator.isEmailValid(email: email.value.extraWhitespacesRemoved) {
emailErrorMessage.value = ""
return true
} else {
emailErrorMessage.value = "EMAIL_INVALID_MESSAGE".app_localized
return false
}
}
private func validatePassword() -> Bool {
if password.value.extraWhitespacesRemoved.isEmpty {
passwordErrorMessage.value = "PASS_IS_NOT_<PASSWORD>_<PASSWORD>".app_localized
return false
}
if DataValidator.isEmailPassword(pass: password.value.extraWhitespacesRemoved)
{
passwordErrorMessage.value = ""
return true
} else {
passwordErrorMessage.value = "INVALID_PASSWORD_MESSAGE".app_localized
return false
}
}
}
<file_sep>//
// MenuSettingsViewModel.swift
// Koleda
//
// Created by <NAME> on 9/9/19.
// Copyright © 2019 koleda. All rights reserved.
//
import Foundation
import RxSwift
import RxCocoa
import SVProgressHUD
import CopilotAPIAccess
enum ConsumeType: Int {
case Month = 0
case Week = 1
case Day = 2
case Unknow
init(from int: Int) {
guard let value = ConsumeType(rawValue: int) else {
self = .Unknow
return
}
self = value
}
}
protocol MenuSettingsViewModelProtocol: BaseViewModelProtocol {
func logOut()
var profileImage: Driver<UIImage?> { get }
var settingItems: Variable<[SettingMenuItem]> { get }
var userName: Variable<String> { get }
var email: Variable<String> { get}
var energyConsumed: Variable<String> { get}
var timeTitle: Variable<String> { get}
var currentTempUnit: Variable<TemperatureUnit> { get }
var needUpdateAfterTempUnitChanged: PublishSubject<Bool> { get }
var leaveHomeSubject: PublishSubject<Void> { get }
func viewWillAppear()
func selectedItem(at index: Int)
func leaveHome(completion: @escaping (Bool) -> Void)
func showConfigurationScreen(selectedRoom: Room)
func showEneryConsume(of type: ConsumeType)
func updateTempUnit(completion: @escaping () -> Void)
}
class MenuSettingsViewModel: BaseViewModel, MenuSettingsViewModelProtocol {
var profileImage: Driver<UIImage?> { return profileImageSubject.asDriver(onErrorJustReturn: nil) }
let settingItems = Variable<[SettingMenuItem]>([])
let userName = Variable<String>("")
let email = Variable<String>("")
let energyConsumed = Variable<String>("$0.0")
let timeTitle = Variable<String>("SPENT_TO_FAR_THIS_MONTH_TEXT".app_localized)
let currentTempUnit = Variable<TemperatureUnit>(.C)
let needUpdateAfterTempUnitChanged = PublishSubject<Bool>()
let leaveHomeSubject = PublishSubject<Void>()
private var profileImageSubject = BehaviorSubject<UIImage?>(value: UIImage(named: "defaultProfileImage"))
let router: BaseRouterProtocol
private let userManager: UserManager
private let settingManager: SettingManager
private var currentConsumeType: ConsumeType = .Month
private var userType: UserType = .Undefine
func viewWillAppear() {
var menuList = SettingMenuItem.initSettingMenuItems()
userType = UserType.init(fromString: UserDataManager.shared.currentUser?.userType ?? "")
if userType == .Guest {
menuList.append(SettingMenuItem(title: "LEAVE_SHARING_HOME_TEXT".app_localized, icon: UIImage(named: "ic-menu-multiple-user-access")))
} else {
menuList.append(SettingMenuItem(title: "SHARING_HOME_MANAGEMENT_TEXT".app_localized, icon: UIImage(named: "ic-menu-multiple-user-access")))
}
menuList.append(SettingMenuItem(title: "LEGAL_TEXT".app_localized, icon: UIImage(named: "ic-menu-legal")))
settingItems.value = menuList
currentTempUnit.value = UserDataManager.shared.temperatureUnit
guard let name = UserDataManager.shared.currentUser?.name else {
return
}
userName.value = name
guard let emailOfUser = UserDataManager.shared.currentUser?.email else {
return
}
email.value = emailOfUser
getEnergyConsumedInfo()
}
init(router: BaseRouterProtocol, managerProvider: ManagerProvider = .sharedInstance) {
self.router = router
settingManager = managerProvider.settingManager
userManager = managerProvider.userManager
super.init(managerProvider: managerProvider)
}
func logOut() {
SVProgressHUD.show()
userManager.logOut { [weak self] in
SVProgressHUD.dismiss()
Copilot.instance.report.log(event: LogoutAnalyticsEvent())
self?.router.enqueueRoute(with: MenuSettingsRouter.RouteType.logOut)
}
}
func selectedItem(at index: Int) {
switch index {
case 0:
router.enqueueRoute(with: MenuSettingsRouter.RouteType.roomsConfiguration)
case 1:
router.enqueueRoute(with: MenuSettingsRouter.RouteType.addRoom)
case 2:
router.enqueueRoute(with: MenuSettingsRouter.RouteType.smartScheduling)
case 3:
router.enqueueRoute(with: MenuSettingsRouter.RouteType.updateTariff)
case 4:
router.enqueueRoute(with: MenuSettingsRouter.RouteType.wifiDetail)
case 5:
router.enqueueRoute(with: MenuSettingsRouter.RouteType.modifyModes)
case 6:
if userType == .Guest {
log.info("Leave Sharing Home")
leaveHomeSubject.onNext(())
} else {
log.info("Go Sharing Home Management")
router.enqueueRoute(with: MenuSettingsRouter.RouteType.inviteFriendsDetail)
}
case 7:
router.enqueueRoute(with: MenuSettingsRouter.RouteType.legal)
default:
break
}
}
func leaveHome(completion: @escaping (Bool) -> Void) {
userManager.leaveFromMasterHome(success: {
completion(true)
}) { error in
completion(false)
}
}
func showConfigurationScreen(selectedRoom: Room) {
router.enqueueRoute(with: MenuSettingsRouter.RouteType.configuration(selectedRoom))
}
func showEneryConsume(of type: ConsumeType) {
currentConsumeType = type
let energyConsumedTariff = UserDataManager.shared.energyConsumed
var amount: Double?
switch type {
case .Month:
amount = energyConsumedTariff?.energyConsumedMonth
break
case .Week:
amount = energyConsumedTariff?.energyConsumedWeek
break
case .Day:
amount = energyConsumedTariff?.energyConsumedDay
break
case .Unknow:
break
}
updateTimeTitle()
guard let currencySymbol = UserDataManager.shared.tariff?.currency.kld_getCurrencySymbol(), let consumeValue = amount else {
energyConsumed.value = "$0.0"
return
}
energyConsumed.value = String(format: "%@%@", currencySymbol, consumeValue.currencyFormatter())
}
func updateTempUnit(completion: @escaping () -> Void) {
let selectedUnit: TemperatureUnit = currentTempUnit.value == .C ? .F : .C
settingManager.updateTemperatureUnit(temperatureUnit: selectedUnit.rawValue, success: { [weak self] in
self?.currentTempUnit.value = selectedUnit
UserDataManager.shared.temperatureUnit = selectedUnit
self?.needUpdateAfterTempUnitChanged.onNext(true)
completion()
}) { [weak self] _ in
self?.needUpdateAfterTempUnitChanged.onNext(false)
completion()
}
}
private func updateTimeTitle() {
switch currentConsumeType {
case .Month:
timeTitle.value = "SPENT_TO_FAR_THIS_MONTH_TEXT".app_localized
break
case .Week:
timeTitle.value = "SPENT_TO_FAR_THIS_WEEK_TEXT".app_localized
break
case .Day:
timeTitle.value = "SPENT_TO_FAR_THIS_DAY_TEXT".app_localized
break
case .Unknow:
break
}
}
private func getTariffInfo(completion: @escaping () -> Void) {
settingManager.getTariff(success: {
completion()
}) { _ in
completion()
}
}
private func getEnergyConsumedInfo() {
getTariffInfo { [weak self] in
self?.settingManager.getEnergyConsumed(success: { [weak self] in
guard let type = self?.currentConsumeType else { return }
self?.showEneryConsume(of: type)
}) { _ in
}
}
}
}
struct SettingMenuItem {
let title: String
let icon: UIImage?
init(title: String, icon: UIImage?) {
self.title = title
self.icon = icon
}
static func initSettingMenuItems() -> [SettingMenuItem] {
var settingMenuItems: [SettingMenuItem] = []
settingMenuItems.append(SettingMenuItem(title: "ROOM_CONFIGURATION_TEXT".app_localized, icon: UIImage(named: "ic-menu-room-setting")))
settingMenuItems.append(SettingMenuItem(title: "ADD_ROOM_TEXT".app_localized, icon: UIImage(named: "ic-menu-add-room")))
settingMenuItems.append(SettingMenuItem(title: "SMART_SCHEDULING_TEXT".app_localized, icon: UIImage(named: "ic-menu-smart-scheduling")))
settingMenuItems.append(SettingMenuItem(title: "ENERGY_TARIFF_TEXT".app_localized, icon: UIImage(named: "ic-menu-energy-Tariff")))
settingMenuItems.append(SettingMenuItem(title: "WIFI_SETTINGS_TEXT".app_localized, icon: UIImage(named: "ic-menu-wifi-setting")))
settingMenuItems.append(SettingMenuItem(title: "MODITY_TEMPERATURE_MODES_TEXT".app_localized, icon: UIImage(named: "ic-menu-modify-temperature-modes")))
return settingMenuItems
}
}
<file_sep>
//
// String+Extensions.swift
// Koleda
//
// Created by <NAME> on 6/18/19.
// Copyright © 2019 koleda. All rights reserved.
//
import Foundation
import SwiftRichString
public func isEmpty(_ obj: Any?) -> Bool {
if obj == nil {
return true
} else if ((obj as? String) != nil) {
return (obj as? String)!.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
} else if ((obj as? Array<Any>) != nil) {
return (obj as? Array<Any>)!.count == 0
} else if ((obj as? NSDictionary) != nil) {
return (obj as? NSDictionary)!.count == 0
} else {
return false
}
}
extension String {
init(_ staticString: StaticString) {
self = staticString.withUTF8Buffer {
String(decoding: $0, as: UTF8.self)
}
}
var app_localized: String {
return NSLocalizedString(self, comment: "")
}
var extraWhitespacesRemoved: String {
let text = self.trimmingCharacters(in: .whitespaces)
var result = ""
let whitespace = " "
var previousChar = whitespace
for enumeratedChar in text {
let enumeratedString = String(enumeratedChar)
if !(previousChar == whitespace && enumeratedString == previousChar) {
result.append(enumeratedString)
}
previousChar = enumeratedString
}
return result
}
var fahrenheitTemperature: String {
guard let celsiusTemp = self.kld_doubleValue else {
return "0"
}
let fValue = (celsiusTemp*1.8 + 32).roundToDecimal(1)
return "\(fValue)"
}
var correctLocalTimeStringFormatForDisplay: String {
if self == "23:59:59.999" {
return "24:00:00"
} else if self == "23:59:00" {
return "24:00:00"
}
return self
}
var correctLocalTimeStringFormatForService: String {
if self == "24:00:00" {
return "00:00:00"
}
return self
}
func removingOccurances(_ stringsToRemove:[String]) -> String {
var result = self
stringsToRemove.forEach { enumeratedString in
result = result.replacingOccurrences(of: enumeratedString, with: "")
}
return result
}
func timeValue() -> Time? {
guard self.extraWhitespacesRemoved.count > 0 else {
return nil
}
let arrayTime = self.components(separatedBy: ":")
guard arrayTime.count == 2 else {
return nil
}
let hour = (arrayTime[0] as NSString).integerValue
let minute = (arrayTime[1] as NSString).integerValue
return Time(hour: hour, minute: minute)
}
func removeSecondOfTime() -> String {
guard self.extraWhitespacesRemoved.count > 0 else {
return ""
}
let arrayTime = self.components(separatedBy: ":")
guard arrayTime.count == 3 else {
return self
}
return "\(arrayTime[0]) : \(arrayTime[1])"
}
func kld_localTimeFormat() -> String {
return self.removingOccurances([" "]) + ":00"
}
func app_removePortInUrl() -> String {
guard self.extraWhitespacesRemoved.count > 0 else {
return ""
}
let arrayString = self.components(separatedBy: ":")
guard arrayString.count == 2 else {
return self
}
return arrayString[0].replacingOccurrences(of: "[", with: "")
}
func attributeText(normalSize: CGFloat, boldSize: CGFloat) -> NSAttributedString {
let normal = SwiftRichString.Style{
$0.font = UIFont.app_SFProDisplayRegular(ofSize: normalSize)
$0.color = UIColor.lightGray
}
let bold = SwiftRichString.Style {
$0.font = UIFont.app_SFProDisplayRegular(ofSize: boldSize)
$0.color = UIColor.orange
}
let group = StyleGroup(base: normal, ["h1": bold])
return self.set(style: group)
}
var kld_doubleValue: Double? {
return Double(self)
}
var intValueWithLocalTime: Int? {
return self.removeSecondOfTime().timeValue()?.timeIntValue()
}
func kld_getCurrencySymbol() -> String {
var candidates: [String] = []
let locales: [String] = NSLocale.availableLocaleIdentifiers
for localeID in locales {
guard let symbol = findMatchingSymbol(localeID: localeID, currencyCode: self) else {
continue
}
if symbol.count == 1 {
return symbol
}
candidates.append(symbol)
}
let sorted = sortAscByLength(list: candidates)
if sorted.count < 1 {
return ""
}
return sorted[0]
}
func capitalizingFirstLetter() -> String {
return prefix(1).uppercased() + self.lowercased().dropFirst()
}
mutating func capitalizeFirstLetter() {
self = self.capitalizingFirstLetter()
}
private func findMatchingSymbol(localeID: String, currencyCode: String) -> String? {
let locale = Locale(identifier: localeID as String)
guard let code = locale.currencyCode else {
return nil
}
if code != currencyCode {
return nil
}
guard let symbol = locale.currencySymbol else {
return nil
}
return symbol
}
private func sortAscByLength(list: [String]) -> [String] {
return list.sorted(by: { $0.count < $1.count })
}
func getStringLocalizeDay() -> String {
switch self.uppercased() {
case "MONDAY":
return "MON_TEXT".app_localized
case "TUESDAY":
return "TUE_TEXT".app_localized
case "WEDNESDAY":
return "WED_TEXT".app_localized
case "THURSDAY":
return "THU_TEXT".app_localized
case "FRIDAY":
return "FRI_TEXT".app_localized
case "SATURDAY":
return "SAT_TEXT".app_localized
default:
return "SUN_TEXT".app_localized
}
}
}
<file_sep>//
// RoomType.swift
// Koleda
//
// Created by <NAME> on 7/9/19.
// Copyright © 2019 koleda. All rights reserved.
//
import Foundation
import UIKit
enum RoomCategory: String, Codable {
case unknow
case living = "LIVING_ROOM"
case bed = "BED_ROOM"
case kid = "KID_ROOM"
case kitchen = "KITCHEN"
case music = "MUSIC_ROOM"
case hallway = "HALLWAY"
case reading = "READING_ROOM"
case bathroom = "BATHROOM"
case working = "WORKING_ROOM"
init(fromString string: String) {
guard let value = RoomCategory(rawValue: string) else {
self = .unknow
return
}
self = value
}
}
struct RoomType {
let category: RoomCategory
let title: String
let roomDetailImage: UIImage?
let homeImage: UIImage?
let configurationRoomImage: UIImage?
init(category: RoomCategory, title: String, roomDetailImage: UIImage?, homeImage: UIImage?, configurationRoomImage: UIImage?) {
self.category = category
self.title = title
self.roomDetailImage = roomDetailImage
self.homeImage = homeImage
self.configurationRoomImage = configurationRoomImage
}
static func initRoomTypes() -> [RoomType] {
var roomTypes: [RoomType] = []
roomTypes.append(RoomType(category: .living, title: "LIVING_ROOM_TEXT".app_localized, roomDetailImage: UIImage(named: "detail_room_living"), homeImage: UIImage(named: "home_room_living"), configurationRoomImage: UIImage(named: "config_room_living")))
roomTypes.append(RoomType(category: .music, title: "MUSIC_ROOM_TEXT".app_localized, roomDetailImage: UIImage(named: "detail_room_music"), homeImage: UIImage(named: "home_room_music"), configurationRoomImage: UIImage(named: "config_room_music")))
roomTypes.append(RoomType(category: .hallway, title: "HALLWAY_TEXT".app_localized, roomDetailImage: UIImage(named: "detail_room_hallway"), homeImage: UIImage(named: "home_room_hallway"), configurationRoomImage: UIImage(named: "config_room_hallway")))
roomTypes.append(RoomType(category: .reading, title: "READING_ROOM_TEXT".app_localized, roomDetailImage: UIImage(named: "detail_room_reading"), homeImage: UIImage(named: "home_room_reading"), configurationRoomImage: UIImage(named: "config_room_reading")))
roomTypes.append(RoomType(category: .bed, title: "BED_ROOM_TEXT".app_localized, roomDetailImage: UIImage(named: "detail_room_bed"), homeImage: UIImage(named: "home_room_bed"), configurationRoomImage: UIImage(named: "config_room_bed")))
roomTypes.append(RoomType(category: .kid, title: "KIDS_ROOM_TEXT".app_localized, roomDetailImage: UIImage(named: "detail_room_kid"), homeImage: UIImage(named: "home_room_kid"), configurationRoomImage: UIImage(named: "config_room_kid")))
roomTypes.append(RoomType(category: .bathroom, title: "BATHROOM_TEXT".app_localized, roomDetailImage: UIImage(named: "detail_room_bathroom"), homeImage: UIImage(named: "home_room_bathroom"), configurationRoomImage: UIImage(named: "config_room_bathroom")))
roomTypes.append(RoomType(category: .working, title: "WORKING_ROOM_TEXT".app_localized, roomDetailImage: UIImage(named: "detail_room_working"), homeImage: UIImage(named: "home_room_working"), configurationRoomImage: UIImage(named: "config_room_working")))
roomTypes.append(RoomType(category: .kitchen, title: "KITCHEN_TEXT".app_localized, roomDetailImage: UIImage(named: "detail_room_kitchen"), homeImage: UIImage(named: "home_room_kitchen"), configurationRoomImage: UIImage(named: "config_room_kitchen")))
return roomTypes
}
static func roomDetailImageOf(category: RoomCategory) -> UIImage? {
let roomType = initRoomTypes().filter { $0.category == category}.first
return roomType?.roomDetailImage
}
static func homeImageOf(category: RoomCategory) -> UIImage? {
let roomType = initRoomTypes().filter { $0.category == category}.first
return roomType?.homeImage
}
static func configrurationRoomImageOf(category: RoomCategory) -> UIImage? {
let roomType = initRoomTypes().filter { $0.category == category}.first
return roomType?.configurationRoomImage
}
}
extension RoomType {
static func == (lhs: RoomType, rhs: RoomType) -> Bool {
return lhs.category == rhs.category
}
}
<file_sep>//
// RoomDetailRouter.swift
// Koleda
//
// Created by <NAME> on 7/9/19.
// Copyright © 2019 koleda. All rights reserved.
//
import Foundation
import UIKit
class RoomDetailRouter: BaseRouterProtocol {
enum RouteType {
case deleted
case added(String, String)
case updated
}
weak var baseViewController: UIViewController?
func dismiss(animated: Bool, context: Any?, completion: ((Bool) -> Void)?) {
guard let routeType = context as? RouteType else {
assertionFailure("The route type missmatches")
return
}
guard let baseViewController = baseViewController else {
assertionFailure("baseViewController is not set")
return
}
switch routeType {
case .added:
baseViewController.navigationController?.popToRootViewController(animated: animated)
case .updated:
baseViewController.navigationController?.popToRootViewController(animated: animated)
case .deleted:
baseViewController.navigationController?.popToRootViewController(animated: animated)
}
}
func present(on baseVC: UIViewController, animated: Bool, context: Any?, completion: ((Bool) -> Void)?) {
}
func enqueueRoute(with context: Any?, animated: Bool, completion: ((Bool) -> Void)?) {
guard let routeType = context as? RouteType else {
assertionFailure("The route type missmatches")
return
}
guard let baseViewController = baseViewController else {
assertionFailure("baseViewController is not set")
return
}
switch routeType {
case .added(let roomId, let roomName):
baseViewController.gotoBlock(withStoryboar: "Sensor", aClass: InstructionViewController.self, sendData: { (vc) in
vc?.roomId = roomId
vc?.roomName = roomName
})
default:
break
}
}
}
<file_sep>//
// CocoalumberjackLogger.swift
// Koleda
//
// Created by <NAME> on 7/3/19.
// Copyright © 2019 koleda. All rights reserved.
//
import Foundation
import CocoaLumberjack
typealias GenericAction = () -> Void
func performOnMain(_ action: @escaping GenericAction) {
DispatchQueue.main.async {
action()
}
}
func isRunningTests() -> Bool {
return NSClassFromString("XCTest") != nil
}
class CocoalumberjackLogger: Logger {
enum LogDestination {
case file(config: FileLogConfig)
case crashlytics
case asl
case tty
case os
}
struct FileLogConfig {
let rollingFrequency: TimeInterval
let maxNumOfLogFiles: UInt
let maxFileSize: UInt64
}
static let defaultLogDestinations: [LogDestination] = {
if #available(iOS 10.0, *) {
return [.os, .crashlytics, .file(config: defaultFileLogConfig)]
} else {
return [.asl, .tty, .crashlytics, .file(config: defaultFileLogConfig)]
}
}()
static let defaultLogLevel: LogLevel = {
#if PRODUCTION
return .info
#else
return .verbose
#endif
}()
static let defaultFileLogConfig = FileLogConfig(rollingFrequency: TimeInterval(60 * 60 * 24),
maxNumOfLogFiles: 5,
maxFileSize: UInt64(2 * 1024 * 1024))
var assertsEnabled = !isRunningTests()
init(logDestinations: [LogDestination] = defaultLogDestinations, logLevel: LogLevel = defaultLogLevel) {
logDestinations.forEach { enumeratedLogDestination in
let ddLogLevel = cocoalumberjackLogLevel(for: logLevel)
switch enumeratedLogDestination {
case .file(let config):
let fileLogger = DDFileLogger()
fileLogger.rollingFrequency = config.rollingFrequency
fileLogger.logFileManager.maximumNumberOfLogFiles = config.maxNumOfLogFiles
fileLogger.maximumFileSize = config.maxFileSize
DDLog.add(fileLogger, with: ddLogLevel)
case .crashlytics:
DDLog.add(DDOSLogger.sharedInstance, with: ddLogLevel)
case .asl:
DDLog.add(DDOSLogger.sharedInstance, with: ddLogLevel)
case .tty:
DDLog.add(DDTTYLogger.sharedInstance!, with: ddLogLevel)
case .os:
if #available(iOS 10.0, *) {
DDLog.add(DDOSLogger.sharedInstance, with: ddLogLevel)
} else {
log.error("Trying to enable os logger for iOS earlier then 10.0")
}
}
}
}
func verbose(_ message: String, _ file: StaticString, _ function: StaticString, _ line: UInt) {
DDLogVerbose(message, file: file, function: function, line: line)
}
func debug(_ message: String, _ file: StaticString, _ function: StaticString, _ line: UInt) {
DDLogDebug(message, file: file, function: function, line: line)
}
func info(_ message: String, _ file: StaticString, _ function: StaticString, _ line: UInt) {
DDLogInfo(message, file: file, function: function, line: line)
}
func warning(_ message: String, _ file: StaticString, _ function: StaticString, _ line: UInt) {
DDLogWarn(message, file: file, function: function, line: line)
}
func error(_ message: String, _ file: StaticString, _ function: StaticString, _ line: UInt) {
DDLogError(message, file: file, function: function, line: line)
}
func errorWithAssert(_ message: String,
_ assertId: String,
_ userInfo: [String: Any]?,
_ file: StaticString,
_ function: StaticString,
_ line: UInt)
{
error(message, file, function, line)
DDLog.allLoggers.forEach { enumeratedLogger in
if let assertRecordingLogger = enumeratedLogger as? AssertRecording {
let fileLastPathComponent = (String(file) as NSString).lastPathComponent
let errorInfo = [Constants.messageKey: message,
Constants.fileKey: fileLastPathComponent,
Constants.functionKey: function,
Constants.lineKey: line] as [String: Any]
let error = NSError(domain: "assert \(fileLastPathComponent) \(assertId)", code: 0, userInfo: errorInfo)
assertRecordingLogger.recordAssertionFailure(error, additionalInfo: userInfo)
}
}
assertionFailure(message)
}
func flushLog() {
DDLog.flushLog()
}
private func cocoalumberjackLogLevel(for logLevel: LogLevel) -> DDLogLevel {
switch logLevel {
case .off: return DDLogLevel.off
case .error: return DDLogLevel.error
case .warning: return DDLogLevel.warning
case .info: return DDLogLevel.info
case .debug: return DDLogLevel.debug
case .verbose: return DDLogLevel.verbose
case .all: return DDLogLevel.all
}
}
}
extension CocoalumberjackLogger {
struct Constants {
static let messageKey = "_message"
static let fileKey = "_file"
static let functionKey = "_function"
static let lineKey = "_line"
}
}
<file_sep>//
// UIColor+Extensions.swift
// Koleda
//
// Created by <NAME> on 5/28/19.
// Copyright © 2019 koleda. All rights reserved.
//
import Foundation
import UIKit
extension UIColor {
struct RGBA {
var red: CGFloat
var green: CGFloat
var blue: CGFloat
var alpha: CGFloat
}
convenience init(rgba: RGBA) {
self.init(red: rgba.red,
green: rgba.green,
blue: rgba.blue,
alpha: rgba.alpha)
}
convenience init(r: Int, g: Int, b: Int, alpha: CGFloat = 1) {
self.init(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: alpha)
}
convenience init(hex: Int, alpha: CGFloat = 1) {
let red = (hex >> 16) & 0xFF
let green = (hex >> 8) & 0xFF
let blue = (hex) & 0xFF
self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: alpha)
}
class var app_titleColor: UIColor {
return UIColor.black
}
class var app_contentColor: UIColor {
return UIColor.gray
}
public static let lightLine = UIColor(hex: 0xEAEAEA)
public static let hexB5B5B5 = UIColor(hex: 0xB5B5B5)
public static let hex53565A = UIColor(hex: 0x53565A)
public static let hex1F1B15 = UIColor(hex: 0x1F1B15)
public static let hexFF7020 = UIColor(hex: 0xFF7020)
public static let hex88FFFFFF = UIColor(hex: 0xFFFFFF, alpha: 0.5)
public static let hex44FFFFFF = UIColor(hex: 0xFFFFFF, alpha: 0.25)
public static let hex7e7d80 = UIColor(hex: 0x7e7d80)
public static let purpleLight = UIColor(hex: 0x496CE7)
public static let greenLight = UIColor(hex: 0x20DBAE)
public static let redLight = UIColor(hex: 0xFF8589)
public static let yellowLight = UIColor(hex: 0xFFCF25)
public static let blueLight = UIColor(hex: 0x97E0FF)
func lighter(by percentage: CGFloat = 30.0) -> UIColor? {
return self.adjust(by: abs(percentage) )
}
func darker(by percentage: CGFloat = 30.0) -> UIColor? {
return self.adjust(by: -1 * abs(percentage) )
}
func adjust(by percentage: CGFloat = 30.0) -> UIColor? {
var red: CGFloat = 0, green: CGFloat = 0, blue: CGFloat = 0, alpha: CGFloat = 0
if self.getRed(&red, green: &green, blue: &blue, alpha: &alpha) {
return UIColor(red: min(red + percentage/100, 1.0),
green: min(green + percentage/100, 1.0),
blue: min(blue + percentage/100, 1.0),
alpha: alpha)
} else {
return nil
}
}
}
<file_sep>//
// WebsocketManager.swift
// Koleda
//
// Created by <NAME> on 9/10/19.
// Copyright © 2019 koleda. All rights reserved.
//
import UIKit
import StompClientLib
import SwiftyJSON
enum SocketKeyName : String {
case HUMIDITY
case BATTERY
case TEMPERATURE
case ROOM_STATUS
}
struct WSDataItem: Decodable {
let id : String
var name: String
var value: Any
enum CodingKeys: String, CodingKey {
case id = "id"
case name = "name"
case value = "value"
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.id = try container.decode(String.self, forKey: .id)
self.name = try container.decode(String.self, forKey: .name)
if self.name == SocketKeyName.ROOM_STATUS.rawValue {
self.value = try container.decode(Bool.self, forKey: .value)
} else {
self.value = try container.decode(String.self, forKey: .value)
}
}
}
protocol WebsocketManagerDelegate: class {
func refeshAtRoom(with newData: WSDataItem)
}
class WebsocketManager: NSObject {
var socketClient = StompClientLib()
weak var delegate: WebsocketManagerDelegate?
static let shared : WebsocketManager = {
let instance = WebsocketManager()
return instance
}()
func connect() {
log.info("connecting to Socket")
let headers =
["access_token": LocalAccessToken.restore()!,
"accept-version": "1.1,1.0", "heart-beat":"10000,10000"]
guard let url = NSURL(string: UrlConfigurator.socketUrlString()) else {
return
}
socketClient.openSocketWithURLRequest(request: NSURLRequest(url: url as URL) , delegate: self, connectionHeaders: headers)
}
func joinTopicOfUser() {
if let userId = UserDataManager.shared.currentUser?.id {
let headers = ["id":"sub-0"]
socketClient.subscribeWithHeader(destination: "/ws/topic/\(userId)", withHeader: headers)
}
}
}
extension WebsocketManager: StompClientLibDelegate {
func stompClient(client: StompClientLib!, didReceiveMessageWithJSONBody jsonBody: AnyObject?, akaStringBody stringBody: String?, withHeader header: [String : String]?, withDestination destination: String) {
log.info("Received Data WebSocket: \(stringBody)")
guard let stringData = stringBody else {
return
}
do {
let data = stringData.data(using: .utf8)!
let decodedJSON = try JSONDecoder().decode(WSDataItem.self, from: data)
updateData(data: decodedJSON)
} catch {
log.info("Get parsing error: \(error)")
}
}
private func updateData(data: WSDataItem) {
if [SocketKeyName.TEMPERATURE.rawValue, SocketKeyName.BATTERY.rawValue, SocketKeyName.HUMIDITY.rawValue, SocketKeyName.ROOM_STATUS.rawValue].contains(data.name) {
delegate?.refeshAtRoom(with: data)
}
}
func stompClientDidDisconnect(client: StompClientLib!) {
}
func stompClientDidConnect(client: StompClientLib!) {
joinTopicOfUser()
}
func serverDidSendReceipt(client: StompClientLib!, withReceiptId receiptId: String) {
}
func serverDidSendError(client: StompClientLib!, withErrorMessage description: String, detailedErrorMessage message: String?) {
// socketClient.send
}
func serverDidSendPing() {
}
}
<file_sep>//
// LoginViewController.swift
// Koleda
//
// Created by <NAME> on 6/11/19.
// Copyright © 2019 koleda. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
import FBSDKCoreKit
import FBSDKLoginKit
import GoogleSignIn
import SVProgressHUD
import AuthenticationServices
class LoginViewController: BaseViewController, BaseControllerProtocol, KeyboardAvoidable {
@IBOutlet weak var loginButton: UIButton!
@IBOutlet weak var showPasswordButton: UIButton!
@IBOutlet weak var loginGoogleButton: UIButton!
@IBOutlet weak var loginFacebookButton: UIButton!
@IBOutlet weak var loginAppleButton: UIButton!
@IBOutlet weak var emailTextField: AndroidStyle2TextField!
@IBOutlet weak var passwordTextField: AndroidStyle2TextField!
@IBOutlet weak var appleLoginView: UIView!
@IBOutlet weak var signInTitleLabel: UILabel!
@IBOutlet weak var loginViaGoogeLabel: UILabel!
@IBOutlet weak var loginViaFacebookLabel: UILabel!
@IBOutlet weak var loginViaAppleLabel: UILabel!
@IBOutlet weak var forgotPassLabel: UILabel!
@IBOutlet weak var signInLabel: UILabel!
var viewModel: LoginViewModelProtocol!
private let disposeBag = DisposeBag()
var keyboardHelper: KeyboardHepler?
override func viewDidLoad() {
super.viewDidLoad()
configurationUI()
keyboardHelper = KeyboardHepler(self)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(true, animated: animated)
statusBarStyle(with: .lightContent)
self.edgesForExtendedLayout = UIRectEdge.top
self.automaticallyAdjustsScrollViewInsets = false
viewModel.viewWillAppear()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
viewModel.prepare(for: segue)
}
@IBAction func showOrHidePass(_ sender: Any) {
viewModel.showPassword(isShow: passwordTextField.isSecureTextEntry)
}
@IBAction func forgotPassword(_ sender: Any) {
viewModel.forgotPassword()
}
@IBAction func login(_ sender: Any) {
SVProgressHUD.show()
loginButton.isEnabled = false
viewModel.login { [weak self] isSuccess in
SVProgressHUD.dismiss()
self?.loginButton.isEnabled = true
if !isSuccess {
self?.app_showAlertMessage(title: "LOGIN_FAILED_TEXT".app_localized, message: "EMAIL_OR_PASS_IS_INVALID".app_localized)
}
}
}
@IBAction func backAction(_ sender: Any) {
if self.navigationController?.viewControllers.count == 1 {
viewModel.backOnboardingScreen()
} else {
back()
}
}
func loginUsingGoogle() {
GIDSignIn.sharedInstance()?.delegate = self
GIDSignIn.sharedInstance()?.presentingViewController = self
GIDSignIn.sharedInstance()?.signIn()
}
func loginUsingFacebook() {
let loginFBManager = LoginManager()
loginFBManager.logIn(permissions: [Permission.publicProfile, Permission.email], viewController: self) { [weak self] loginResult in
switch loginResult {
case .failed(let error):
log.error(error.localizedDescription)
self?.loginFacebookButton.isEnabled = true
self?.app_showAlertMessage(title: "LOGIN_FACEBOOK_FAILED_TEXT".app_localized, message: "WE_CAN_NOT_LOGIN_FACEBOOK_MESS".app_localized)
case .cancelled:
log.info("User cancelled login.")
self?.loginFacebookButton.isEnabled = true
self?.app_showAlertMessage(title: "LOGIN_FACEBOOK_FAILED_TEXT".app_localized, message: "WE_CAN_NOT_LOGIN_FACEBOOK_MESS".app_localized)
case .success(_, _, let fbAccessToken):
SVProgressHUD.show()
self?.viewModel.loginWithSocial(type: .facebook, accessToken: fbAccessToken.tokenString, completion: { [weak self] (isSuccess, error) in
self?.loginFacebookButton.isEnabled = true
SVProgressHUD.dismiss()
guard let error = error, !isSuccess else {
return
}
if error == WSError.emailNotExisted {
self?.app_showAlertMessage(title: "LOGIN_FACEBOOK_FAILED_TEXT".app_localized, message: error.errorDescription)
} else {
self?.app_showAlertMessage(title: "LOGIN_FACEBOOK_FAILED_TEXT".app_localized, message: "LOGIN_FAILED_TRY_AGAIN_MESS".app_localized)
}
})
}
}
}
}
extension LoginViewController {
private func configurationUI() {
viewModel?.showPassword.asObservable().subscribe(onNext: { [weak self] value in
self?.passwordTextField.isSecureTextEntry = !value
}).disposed(by: disposeBag)
viewModel.email.asObservable().bind(to: emailTextField.rx.text).disposed(by: disposeBag)
emailTextField.rx.text.orEmpty.bind(to: viewModel.email).disposed(by: disposeBag)
viewModel.password.asObservable().bind(to: passwordTextField.rx.text).disposed(by: disposeBag)
passwordTextField.rx.text.orEmpty.bind(to: viewModel.password).disposed(by: disposeBag)
viewModel.emailErrorMessage.asObservable().subscribe(onNext: { [weak self] message in
self?.emailTextField.errorText = message
if message.isEmpty {
self?.emailTextField.showError(false)
} else {
self?.emailTextField.showError(true)
}
}).disposed(by: disposeBag)
viewModel.passwordErrorMessage.asObservable().subscribe(onNext: { [weak self] message in
self?.passwordTextField.errorText = message
if message.isEmpty {
self?.passwordTextField.showError(false)
} else {
self?.passwordTextField.showError(true)
}
}).disposed(by: disposeBag)
loginGoogleButton.rx.tap.bind { [weak self] _ in
self?.loginGoogleButton.isEnabled = false
self?.loginUsingGoogle()
}.disposed(by: disposeBag)
loginFacebookButton.rx.tap.bind { [weak self] _ in
self?.loginFacebookButton.isEnabled = false
self?.loginUsingFacebook()
}.disposed(by: disposeBag)
setUpSignInAppleButton()
signInTitleLabel.text = "SIGN_IN".app_localized
emailTextField.titleText = "EMAIL_TITLE".app_localized
passwordTextField.titleText = "PASSWORD_TITLE".app_localized
emailTextField.placeholder = "ENTER_EMAIL_HERE_TEXT".app_localized
passwordTextField.placeholder = "ENTER_PASSWORD_TEXT".app_localized
loginViaFacebookLabel.text = "LOGIN_VIA_FACEBOOK".app_localized
loginViaGoogeLabel.text = "LOGIN_VIA_GOOGLE".app_localized
loginViaAppleLabel.text = "LOGIN_VIA_APPLE".app_localized
forgotPassLabel.text = "FORGOT_PASSWORD".app_localized
signInLabel.text = "SIGN_IN".app_localized
}
private func setUpSignInAppleButton() {
if #available(iOS 13.0, *) {
self.appleLoginView.isHidden = false
loginAppleButton.rx.tap.bind { [weak self] _ in
self?.confirmSharingAppleEmail()
}.disposed(by: disposeBag)
} else {
// Fallback on earlier versions
self.appleLoginView.isHidden = true
}
}
private func loginWithApple() {
if #available(iOS 13.0, *) {
let appleIDProvider = ASAuthorizationAppleIDProvider()
let request = appleIDProvider.createRequest()
request.requestedScopes = [.fullName, .email]
let authorizationController = ASAuthorizationController(authorizationRequests: [request])
authorizationController.delegate = self
authorizationController.performRequests()
}
}
private func confirmSharingAppleEmail() {
let OkAction = UIAlertAction(title: "OK".app_localized, style: .default) { [weak self] action in
self?.loginAppleButton.isEnabled = false
self?.loginWithApple()
}
let cancelAction = UIAlertAction(title: "CANCEL".app_localized, style: .cancel) { action in
}
app_showAlertMessage(title: "KOLEDA_TEXT".app_localized.app_localized,
message: "PLEASE_SELECT_SHARE_EMAIL_CONTINUE_WITH_APPLE_SIGN_IN".app_localized, actions: [cancelAction, OkAction])
}
}
extension LoginViewController: ASAuthorizationControllerDelegate {
@available(iOS 13.0, *)
func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {
if let appleIDCredential = authorization.credential as? ASAuthorizationAppleIDCredential {
guard let authorizationCode = appleIDCredential.authorizationCode, let authCodeString = String(bytes: authorizationCode, encoding: .utf8) else {
loginAppleButton.isEnabled = true
app_showAlertMessage(title: "LOGIN_APPLE_FAILED_TEXT".app_localized, message: "WE_CAN_NOT_LOGIN_APPLE_MESS".app_localized)
return
}
SVProgressHUD.show()
viewModel.loginWithSocial(type: .apple, accessToken: authCodeString) { [weak self] (isSuccess, error) in
self?.loginAppleButton.isEnabled = true
SVProgressHUD.dismiss()
guard !isSuccess else {
return
}
if error == WSError.hiddenAppleEmail {
self?.app_showAlertMessage(title: "LOGIN_APPLE_FAILED_TEXT".app_localized, message: error?.errorDescription)
} else {
self?.app_showAlertMessage(title: "LOGIN_APPLE_FAILED_TEXT".app_localized, message: "LOGIN_FAILED_TRY_AGAIN_MESS".app_localized)
}
}
}
}
@available(iOS 13.0, *)
func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: Error) {
loginAppleButton.isEnabled = true
app_showAlertMessage(title: "LOGIN_APPLE_FAILED_TEXT".app_localized, message: "WE_CAN_NOT_LOGIN_APPLE_MESS".app_localized)
}
}
extension LoginViewController: UITextFieldDelegate {
func textField(_ textField: UITextField,
shouldChangeCharactersIn range: NSRange,
replacementString string: String) -> Bool
{
if textField == passwordTextField {
let currentText = textField.text as NSString?
if let resultingText = currentText?.replacingCharacters(in: range, with: string) {
return resultingText.count <= Constants.passwordMaxLength
}
}
return true
}
}
extension LoginViewController: GIDSignInDelegate {
func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!,
withError error: Error!) {
if let error = error {
loginGoogleButton.isEnabled = true
log.error("\(error.localizedDescription)")
app_showAlertMessage(title: "LOGIN_GOOGLE_FAILED_TEXT".app_localized, message: "WE_CAN_NOT_LOGIN_GOOGLE_MESS".app_localized)
} else {
// Perform any operations on signed in user here.
guard let accessToken = user.authentication.accessToken else {
loginGoogleButton.isEnabled = true
app_showAlertMessage(title: "LOGIN_GOOGLE_FAILED_TEXT".app_localized, message: "WE_CAN_NOT_LOGIN_GOOGLE_MESS".app_localized)
return
}
SVProgressHUD.show()
viewModel.loginWithSocial(type: .google, accessToken: accessToken) { [weak self] (isSuccess, error) in
self?.loginGoogleButton.isEnabled = true
SVProgressHUD.dismiss()
if !isSuccess {
self?.app_showAlertMessage(title: "LOGIN_GOOGLE_FAILED_TEXT".app_localized, message: "LOGIN_FAILED_TRY_AGAIN_MESS".app_localized)
}
}
}
}
func sign(_ signIn: GIDSignIn!, didDisconnectWith user: GIDGoogleUser!, withError error: Error!) {
}
func sign(_ signIn: GIDSignIn!, present viewController: UIViewController!) {
self.present(viewController, animated: true, completion: nil)
}
func sign(_ signIn: GIDSignIn!, dismiss viewController: UIViewController!) {
self.dismiss(animated: true, completion: nil)
}
}
<file_sep>//
// UserManager.swift
// Koleda
//
// Created by <NAME> on 7/11/19.
// Copyright © 2019 koleda. All rights reserved.
//
import Foundation
import UIKit
import Alamofire
import PromiseKit
import GoogleSignIn
import SwiftyJSON
protocol UserManager {
func getCurrentUser(success: (() -> Void)?, failure: ((Error) -> Void)?)
func logOut(completion: @escaping () -> Void)
func getFriendsList(success: @escaping () -> Void, failure: @escaping (_ error: Error) -> Void)
func inviteFriend(email: String, success: @escaping () -> Void, failure: @escaping (_ error: Error) -> Void)
func removeFriend(friendEmail: String, success: @escaping () -> Void, failure: @escaping (_ error: Error) -> Void)
func leaveFromMasterHome(success: @escaping () -> Void, failure: @escaping (_ error: Error) -> Void)
func joinHome(name: String, email: String, password: <PASSWORD>, homeId: String, success: @escaping () -> Void, failure: @escaping (_ error: Error) -> Void)
}
class UserManagerImpl: UserManager {
private let sessionManager: Session
private func baseURL() -> URL {
return UrlConfigurator.urlByAdding()
}
init(sessionManager: Session) {
self.sessionManager = sessionManager
}
func getCurrentUser(success: (() -> Void)?, failure: ((Error) -> Void)? = nil) {
guard let request = try? URLRequest(url: baseURL().appendingPathComponent("user/me"), method: .get) else {
assertionFailure()
DispatchQueue.main.async {
failure?(WSError.general)
}
return
}
sessionManager
.request(request).validate().responseData { response in
switch response.result {
case .success(let data):
do {
log.info(try JSON(data: data).description)
let decodedJSON = try JSONDecoder().decode(User.self, from: data)
UserDataManager.shared.currentUser = decodedJSON
UserDataManager.shared.temperatureUnit = TemperatureUnit(fromString: UserDataManager.shared.currentUser?.temperatureUnit ?? "C")
success?()
} catch {
log.info("Get Current User parsing error: \(error)")
failure?(error)
}
case .failure(let error):
log.info("Get Current User fetch error: \(error)")
failure?(error)
}
}
}
func getFriendsList(success: @escaping () -> Void, failure: @escaping (_ error: Error) -> Void){
guard let request = try? URLRequest(url: baseURL().appendingPathComponent("me/partners/getPartnerByList"), method: .get) else {
assertionFailure()
DispatchQueue.main.async {
failure(WSError.general)
}
return
}
sessionManager
.request(request).validate().responseData { response in
switch response.result {
case .success(let data):
do {
// let json = try JSON(data: data)
// log.info(json.description)
// UserDataManager.shared.friendsList = json["partnerEmails"] as? [String] ?? []
let decodedJSON = try JSONDecoder().decode([String].self, from: data)
UserDataManager.shared.friendsList = decodedJSON
success()
} catch {
log.info("Get List Friends parsing error: \(error)")
failure(error)
}
case .failure(let error):
log.info("Get List Friends fetch error: \(error)")
failure(error)
}
}
}
func inviteFriend(email: String, success: @escaping () -> Void, failure: @escaping (_ error: Error) -> Void) {
let params = ["email": email]
let endPointURL = baseURL().appendingPathComponent("me/partners")
guard let request = URLRequest.postRequestWithJsonBody(url: endPointURL, parameters: params) else {
failure(RequestError.error(NSLocalizedString("Failed to send request, please try again later", comment: "")))
return
}
sessionManager.request(request).validate().responseJSON { [weak self] response in
switch response.result {
case .success( _):
log.info("Successfully invite friend")
UserDataManager.shared.friendsList.append(email)
success()
case .failure(let error):
log.error("Failed to invite friend - \(error)")
if let error = error as? URLError, error.code == URLError.notConnectedToInternet {
NotificationCenter.default.post(name: .KLDNotConnectedToInternet, object: error)
failure(error)
} else {
let error = WSError.error(from: response.data, defaultError: WSError.general)
failure(error)
}
}
}
}
func joinHome(name: String, email: String, password: String, homeId: String, success: @escaping () -> Void, failure: @escaping (_ error: Error) -> Void) {
let timezone = TimeZone.current.identifier
let params = ["name": name,
"email": email,
"password": <PASSWORD>,
"homeId":homeId,
"zoneId": timezone]
guard let request = URLRequest.postRequestWithJsonBody(url: baseURL().appendingPathComponent("auth/joinHome"), parameters: params) else {
failure(RequestError.error(NSLocalizedString("Failed to send request, please try again later", comment: "")))
return
}
sessionManager.request(request).validate().responseJSON { response in
switch response.result {
case .success(let result):
log.info("Successfully joining Home")
success()
case .failure(let error):
log.error("Failed to joining Home - \(error)")
if let error = error as? URLError, error.code == URLError.notConnectedToInternet {
NotificationCenter.default.post(name: .KLDNotConnectedToInternet, object: error)
failure(error)
} else {
let error = WSError.error(from: response.data, defaultError: WSError.general)
failure(error)
}
}
}
}
func removeFriend(friendEmail: String, success: @escaping () -> Void, failure: @escaping (_ error: Error) -> Void) {
guard let request = try? URLRequest(url: baseURL().appendingPathComponent("me/partners/\(friendEmail)"), method: .delete) else {
assertionFailure()
DispatchQueue.main.async {
failure(WSError.general)
}
return
}
sessionManager.request(request).validate().response { [weak self] response in
if let error = response.error {
log.info("Removed Friend error: \(error)")
failure(error)
} else {
log.info("Removed Friend successfull")
success()
}
}
}
func leaveFromMasterHome(success: @escaping () -> Void, failure: @escaping (_ error: Error) -> Void) {
guard let request = try? URLRequest(url: baseURL().appendingPathComponent("me/partners/leave"), method: .delete) else {
assertionFailure()
DispatchQueue.main.async {
failure(WSError.general)
}
return
}
sessionManager.request(request).validate().response { [weak self] response in
if let error = response.error {
log.info("Leave Home error: \(error)")
failure(error)
} else {
log.info("Leave Home successfull")
success()
}
}
}
private func logOutRemotely() -> Promise<Void> {
return Promise<Void> { seal -> Void in
let endPointURL = baseURL().appendingPathComponent("auth/logout")
guard let request = URLRequest.postRequestWithJsonBody(url: endPointURL, parameters: [:]) else {
seal.reject(RequestError.error(NSLocalizedString("Failed to send request, please try again later", comment: "")))
return
}
sessionManager.request(request).validate().response { response in
if let error = response.error {
if let error = error as? URLError, error.code == URLError.notConnectedToInternet {
NotificationCenter.default.post(name: .KLDNotConnectedToInternet, object: error)
} else {
log.error("Failed performing logout")
}
seal.reject(error)
} else {
seal.fulfill(())
}
}
}
}
func logOut(completion: @escaping () -> Void) {
firstly {
return cancelAllTasks()
}.then {
return self.logOutRemotely()
}.always {
UserDefaultsManager.removeUserValues()
try? LocalAccessToken.delete()
try? RefreshToken.delete()
UserDataManager.shared.clearUserData()
log.info("Logged out")
completion()
}
}
private func signOutGoogle() {
do {
try GIDSignIn.sharedInstance().signOut()
GIDSignIn.sharedInstance().disconnect()
if let url = NSURL(string: "https://www.google.com/accounts/Logout?continue=https://appengine.google.com/_ah/logout?continue=https://google.com"){
UIApplication.shared.open(url as URL, options: [:]) { (true) in
}
}
} catch let signOutError as NSError {
print ("Error signing out: %@", signOutError)
}
}
private func cancelAllTasks() -> Promise<Void> {
return Promise<Void> { seal -> Void in
sessionManager.session.getAllTasks { tasks in
tasks.forEach { $0.cancel() }
log.info("Cancelled all tasks")
seal.fulfill(())
}
}
}
}
<file_sep>//
// SmartScheduleDetailRouter.swift
// Koleda
//
// Created by <NAME> on 10/31/19.
// Copyright © 2019 koleda. All rights reserved.
//
import Foundation
import UIKit
class SmartScheduleDetailRouter: BaseRouterProtocol {
weak var baseViewController: UIViewController?
func dismiss(animated: Bool, context: Any?, completion: ((Bool) -> Void)?) {
}
func enqueueRoute(with context: Any?, animated: Bool, completion: ((Bool) -> Void)?) {
}
func present(on baseVC: UIViewController, animated: Bool, context: Any?, completion: ((Bool) -> Void)?) {
}
}
<file_sep>//
// FriendTableViewCell.swift
// Koleda
//
// Created by <NAME> on 7/30/20.
// Copyright © 2020 koleda. All rights reserved.
//
import UIKit
class FriendTableViewCell: UITableViewCell {
@IBOutlet weak var abbEmailLabel: UILabel!
@IBOutlet weak var emailLabel: UILabel!
@IBOutlet weak var invitedLabel: UILabel!
@IBOutlet weak var removeButton: UIButton!
var removeButtonHandler: ((String) -> Void)? = nil
@IBAction func remove(_ sender: Any) {
if let email = emailLabel.text {
removeButtonHandler?(email)
}
}
override func awakeFromNib() {
super.awakeFromNib()
}
func loadData(email:String) {
invitedLabel.text = "INVITED_TEXT".app_localized
removeButton.setTitle("REMOVE_TEXT".app_localized, for: .normal)
emailLabel.text = email
abbEmailLabel.text = email.first?.uppercased()
}
}
<file_sep>//
// InstructionForHeaterViewModel.swift
// Koleda
//
// Created by <NAME> on 9/6/19.
// Copyright © 2019 koleda. All rights reserved.
//
import UIKit
import RxSwift
protocol InstructionForHeaterViewModelProtocol: BaseViewModelProtocol {
var typeInstructions: Variable<[TypeInstruction]> { get }
func backToRoot()
func nextToAddHeater(roomId: String, roomName: String, isFromRoomConfiguration: Bool)
}
class InstructionForHeaterViewModel: InstructionForHeaterViewModelProtocol {
var router: BaseRouterProtocol
var typeInstructions: Variable<[TypeInstruction]> = Variable<[TypeInstruction]>([])
init(router: BaseRouterProtocol, typeInstructions: [TypeInstruction]) {
self.router = router
self.typeInstructions.value = typeInstructions
}
func backToRoot() {
if let router = self.router as? InstructionForHeaterRouter {
router.backToRoot()
}
}
func nextToAddHeater(roomId: String, roomName: String, isFromRoomConfiguration: Bool) {
if let router = self.router as? InstructionForHeaterRouter {
router.nextToAddHeater(roomId: roomId, roomName: roomName, isFromRoomConfiguration: isFromRoomConfiguration)
}
}
}
<file_sep>//
// ScheduleHeaderCell.swift
// Koleda
//
// Created by <NAME> on 10/24/19.
// Copyright © 2019 koleda. All rights reserved.
//
import UIKit
class ScheduleHeaderCell: UITableViewCell {
@IBOutlet weak var modeIconImageView: UIImageView!
@IBOutlet weak var modeLabel: UILabel!
@IBOutlet weak var temperatureLabel: UILabel!
@IBOutlet weak var unitLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
func setup(scheduleRow: ScheduleRow) {
modeIconImageView.image = scheduleRow.icon
modeLabel.text = scheduleRow.title + " MODE"
guard let temp = scheduleRow.temperature else {
temperatureLabel.text = "-"
return
}
guard let unit = scheduleRow.temperatureUnit else {
return
}
if TemperatureUnit.C.rawValue == unit {
temperatureLabel.text = temp.toString()
} else {
temperatureLabel.text = temp.fahrenheitTemperature.toString()
}
unitLabel.text = "°\(unit)"
if let mode = ModeItem.getModeItem(with: SmartMode(fromString: scheduleRow.title)) {
modeIconImageView.tintColor = mode.color
}
}
}
<file_sep>//
// LocalAccessManager.swift
// Koleda
//
// Created by <NAME> on 7/2/19.
// Copyright © 2019 koleda. All rights reserved.
//
import Foundation
import LocalAuthentication
enum BiometricType {
case none
case touchID
case faceID
}
class LocalAccessManager {
var isBiometricIDAvailable: Bool {
let context = LAContext()
return isBiometricIDAvailable(context: context)
}
var biometricType: BiometricType {
let context = LAContext()
guard isBiometricIDAvailable(context: context) else {
return .none
}
if #available(iOS 11.0, *), context.responds(to: #selector(getter: LAContext.biometryType)) {
switch context.biometryType {
case .none:
return .none
case .touchID:
return .touchID
case .faceID:
return .faceID
}
} else {
return .touchID
}
}
// MARK: - Public methods
func authenticateUsingBiometricID(success: @escaping () -> Void, failure: @escaping (_ errorDescription: String) -> Void) {
let context = LAContext()
context.localizedFallbackTitle = NSLocalizedString("Enter Passcode", comment: "")
let reasonString = "Access required for authentication with fingerprint".app_localized
log.info("Start authentication using BiometricID")
if isBiometricIDAvailable(context: context) {
context.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: reasonString, reply: { (isSuccess, policyError) in
log.info("Authentication using BiometricID is completed")
if isSuccess {
log.info("BiometricID was recognized")
success()
} else {
if let error = policyError {
log.error("BiometricID NOT was recognized, error: \(error.localizedDescription))")
}
failure(policyError?.localizedDescription ?? NSLocalizedString("Some error appeared", comment: "Unknown error appeared"))
}
})
} else {
failure("BiometricID is NOT supported by the device")
}
}
// func canAuthentificate(withPin pin: String) -> Bool {
// guard let pinFromKeychain = Pin.restore() else {
// return false
// }
//
// return pinFromKeychain == pin
// }
// MARK: - Private methods
/*
As per Apple answer at https://forums.developer.apple.com/thread/89043:
"You need to first call canEvaluatePolicy in order to get the biometry type."
*/
private func isBiometricIDAvailable(context: LAContext) -> Bool {
var error: NSError?
log.info("Check if device support BiometricID")
if context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &error) {
log.info("BiometricID is supported by the device")
return true
}
if let error = error {
log.info("BiometricID is NOT supported by the device, error description: \(error.localizedDescription)")
}
return false
}
}
<file_sep>//
// CustomSlider.swift
// Koleda
//
// Created by <NAME> on 9/15/20.
// Copyright © 2020 koleda. All rights reserved.
//
import Foundation
import UIKit
func delay(_ delay:Double, closure:@escaping ()->()) {
let when = DispatchTime.now() + delay
DispatchQueue.main.asyncAfter(deadline: when, execute: closure)
}
class CustomSlider: UISlider {
required init?(coder: NSCoder) {
super.init(coder:coder)
self.setThumbImage(UIImage(named:"timer-slider_thumb")!, for:.normal)
self.setThumbImage(UIImage(named:"timer-slider_thumb")!, for:.highlighted)
self.setThumbImage(UIImage(named:"timer-slider_thumb")!, for:.focused)
self.setMinimumTrackImage(UIImage(named: "slider-active"), for: .normal)
self.setMaximumTrackImage(UIImage(named: "slider-inactive"), for: .normal)
}
@IBInspectable open var trackWidth: CGFloat = 2 {
didSet {setNeedsDisplay()}
}
override open func trackRect(forBounds bounds: CGRect) -> CGRect {
let defaultBounds = super.trackRect(forBounds: bounds)
return CGRect(
x: defaultBounds.origin.x,
y: defaultBounds.origin.y + defaultBounds.size.height/2 - trackWidth/2,
width: defaultBounds.size.width,
height: trackWidth
)
}
}
<file_sep>//
// HeaterCollectionViewCell.swift
// Koleda
//
// Created by <NAME> on 8/27/19.
// Copyright © 2019 koleda. All rights reserved.
//
import UIKit
class HeaterCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var heaterImageView: UIImageView!
@IBOutlet weak var heaterNameLabel: UILabel!
@IBOutlet weak var statusLabel: UILabel!
func setup(with heater: Heater) {
heaterNameLabel.text = heater.name
if heater.enabled {
statusLabel.text = "ACTIVE_TEXT".app_localized
statusLabel.textColor = UIColor.green
} else {
statusLabel.text = "INACTIVE_TEXT".app_localized
statusLabel.textColor = UIColor.red
}
}
}
<file_sep>//
// TemperatureUnitViewController.swift
// Koleda
//
// Created by <NAME> on 9/17/19.
// Copyright © 2019 koleda. All rights reserved.
//
import UIKit
import RxSwift
class TemperatureUnitViewController: BaseViewController, BaseControllerProtocol {
@IBOutlet weak var progressBarView: ProgressBarView!
@IBOutlet weak var cUnitTempView: TemperatureUnitView!
@IBOutlet weak var fUnitTempView: TemperatureUnitView!
@IBOutlet weak var confirmButton: UIButton!
@IBOutlet weak var cesiusButton: UIButton!
@IBOutlet weak var fahrenheitButton: UIButton!
@IBOutlet weak var temperatureLabel: UILabel!
@IBOutlet weak var descriptionLabel: UILabel!
@IBOutlet weak var confirmLabel: UILabel!
var viewModel: TemperatureUnitViewModelProtocol!
private let disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
configurationUI()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationBarTransparency()
navigationController?.setNavigationBarHidden(true, animated: animated)
setTitleScreen(with: "")
viewModel.viewWillAppear()
}
deinit {
NotificationCenter.default.removeObserver(self)
}
private func configurationUI() {
Style.View.shadowCornerWhite.apply(to: cUnitTempView)
Style.View.shadowCornerWhite.apply(to: fUnitTempView)
cUnitTempView.setUp(unit: .C)
fUnitTempView.setUp(unit: .F)
viewModel.seletedUnit.asObservable().subscribe(onNext: { [weak self] unit in
self?.cUnitTempView.updateStatus(enable: unit == .C)
self?.fUnitTempView.updateStatus(enable: unit == .F)
}).disposed(by: disposeBag)
viewModel.hasChanged.asObservable().subscribe(onNext: { [weak self] changed in
if !changed {
self?.app_showAlertMessage(title: "ERROR_TITLE".app_localized, message: "CAN_NOT_UPDATE_TEMPERATURE_UNIT_MESS".app_localized)
}
}).disposed(by: disposeBag)
confirmButton.rx.tap.bind { [weak self] in
guard let `self` = self else {
return
}
self.viewModel.confirmedAndFinished()
}.disposed(by: disposeBag)
cesiusButton.rx.tap.bind {
self.viewModel.updateUnit(selectedUnit: .C)
}.disposed(by: disposeBag)
fahrenheitButton.rx.tap.bind {
self.viewModel.updateUnit(selectedUnit: .F)
}.disposed(by: disposeBag)
progressBarView.setupNav(viewController: self)
//
temperatureLabel.text = "TEMPERATURE_TEXT".app_localized
descriptionLabel.text = "AND_FINALLY_HOW_WOULD_YOU_MEASURE_TEMP_MESS".app_localized
confirmLabel.text = "CONFIRM_AND_FINISH".app_localized
}
}
<file_sep>//
// AlertConfirmViewController.swift
// Koleda
//
// Created by <NAME> on 9/14/19.
// Copyright © 2019 koleda. All rights reserved.
//
import UIKit
enum TypeAlert {
case deleteRoom(icon: UIImage, roomName: String)
case confirmDeleteRoom
case deleteSensor(sensorName: String)
case confirmDeleteSensor
case deleteHeater(heaterName: String)
case confirmDeleteHeater
}
typealias OnClickLetfButton = () -> Void
typealias OnClickRightButton = () -> Void
class AlertConfirmViewController: UIViewController {
@IBOutlet weak var deleteRoomView: UIView!
@IBOutlet weak var deleteRoomTitleLabel: UILabel!
@IBOutlet weak var roomImageView: UIImageView!
@IBOutlet weak var roomNameLabel: UILabel!
@IBOutlet weak var confirmDeleteRoomView: UIView!
@IBOutlet weak var deleleRoomConfirmContinueLabel: UILabel!
@IBOutlet weak var deleteSensorView: UIView!
@IBOutlet weak var deleteSensorTitleLabel: UILabel!
@IBOutlet weak var confirmDeleteAllSensorsAndHeatersLabel: UILabel!
@IBOutlet weak var sensorImageView: UIImageView!
@IBOutlet weak var sensorNameLabel: UILabel!
@IBOutlet weak var activeSensorLabel: UILabel!
@IBOutlet weak var deleleSensorConfirmContinueLabel: UILabel!
@IBOutlet weak var areYourSureDeleteSensorLabel: UILabel!
@IBOutlet weak var confirmDeleteSensorView: UIView!
@IBOutlet weak var deleteHeaterView: UIView!
@IBOutlet weak var deleteHeaterTitleLabel: UILabel!
@IBOutlet weak var heaterNameLabel: UILabel!
@IBOutlet weak var deleleHeaterConfirmContinueLabel: UILabel!
@IBOutlet weak var confirmDeleteHeaterView: UIView!
@IBOutlet weak var areYourSureDeleteHeaterLabel: UILabel!
@IBOutlet weak var leftButton: UIButton!
@IBOutlet weak var rightButton: UIButton!
var typeAlert: TypeAlert!
var onClickLetfButton: OnClickLetfButton?
var onClickRightButton: OnClickRightButton?
override func viewDidLoad() {
super.viewDidLoad()
updateUI(type: typeAlert)
}
func initView() {
deleteRoomView.isHidden = true
confirmDeleteRoomView.isHidden = true
deleteSensorView.isHidden = true
confirmDeleteSensorView.isHidden = true
deleteHeaterView.isHidden = true
confirmDeleteHeaterView.isHidden = true
deleteRoomTitleLabel.text = "YOU_ARE_ABOUT_TO_DELETE".app_localized
deleleRoomConfirmContinueLabel.text = "DO_YOU_WANT_TO_CONTINUE".app_localized
deleteSensorTitleLabel.text = "YOU_ARE_ABOUT_TO_DELETE".app_localized
confirmDeleteAllSensorsAndHeatersLabel.text = "ALL_SENSORS_HEATERS_WILL_BE_REMOVED_MESS".app_localized
activeSensorLabel.text = "ACTIVE_TEXT".app_localized
deleleSensorConfirmContinueLabel.text = "DO_YOU_WANT_TO_CONTINUE".app_localized
areYourSureDeleteSensorLabel.text = "CONFIRM_DELETE_SENSOR_MESS".app_localized
deleteHeaterTitleLabel.text = "YOU_ARE_ABOUT_TO_DELETE".app_localized
deleleHeaterConfirmContinueLabel.text = "DO_YOU_WANT_TO_CONTINUE".app_localized
areYourSureDeleteHeaterLabel.text = "CONFIRM_DELETE_HEATER_MESS".app_localized
leftButton.setTitle("YES_TEXT".app_localized, for: .normal)
rightButton.setTitle("NO_TEXT".app_localized, for: .normal)
}
private func updateUI(type: TypeAlert) {
initView()
switch type {
case .deleteRoom(let icon, let roomName):
deleteRoomView.isHidden = false
roomImageView.image = icon
roomNameLabel.text = roomName
case .confirmDeleteRoom:
confirmDeleteRoomView.isHidden = false
leftButton.setTitle("CANCEL".app_localized, for: .normal)
rightButton.setTitle("DELETE_TEXT".app_localized, for: .normal)
rightButton.setTitleColor(UIColor(hex: 0xFF7020), for: .normal)
case .deleteSensor(let sensorName):
deleteSensorView.isHidden = false
sensorNameLabel.text = sensorName
case .confirmDeleteSensor:
confirmDeleteSensorView.isHidden = false
leftButton.setTitle("CANCEL".app_localized, for: .normal)
rightButton.setTitle("DELETE_TEXT".app_localized, for: .normal)
rightButton.setTitleColor(UIColor(hex: 0xFF7020), for: .normal)
case .deleteHeater(let heaterName):
deleteHeaterView.isHidden = false
heaterNameLabel.text = heaterName
case .confirmDeleteHeater:
confirmDeleteHeaterView.isHidden = false
leftButton.setTitle("CANCEL".app_localized, for: .normal)
rightButton.setTitle("DELETE_TEXT".app_localized, for: .normal)
rightButton.setTitleColor(UIColor(hex: 0xFF7020), for: .normal)
}
}
@IBAction func leftClickAction(_ sender: Any) {
back(animated: false)
onClickLetfButton?()
}
@IBAction func rightClickAction(_ sender: Any) {
back(animated: false)
onClickRightButton?()
}
}
<file_sep>//
// SettingManager.swift
// Koleda
//
// Created by <NAME> on 8/2/19.
// Copyright © 2019 koleda. All rights reserved.
//
import UIKit
import Alamofire
import SwiftyJSON
import Sync
protocol SettingManager {
func updateTariff(tariff: Tariff, success: @escaping () -> Void, failure: @escaping (_ error: Error) -> Void)
func getTariff(success: (() -> Void)?, failure: ((Error) -> Void)?)
func updateSettingMode(mode: String, roomId: String, success: @escaping () -> Void, failure: @escaping (_ error: Error) -> Void)
func getEnergyConsumed(success: (() -> Void)?, failure: ((Error) -> Void)?)
func resetManualBoost(roomId: String, success: (() -> Void)?, failure: ((Error) -> Void)?)
func loadSettingModes(success: (() -> Void)?, failure: ((Error) -> Void)?)
func updateTemperatureUnit(temperatureUnit: String, success: @escaping () -> Void, failure: @escaping (_ error: Error) -> Void)
func updateTempMode(modeName: String, temp: Double, success: @escaping () -> Void, failure: @escaping (_ error: Error) -> Void)
}
class SettingManagerImpl: SettingManager {
private let sessionManager: Session
private func baseURL() -> URL {
return UrlConfigurator.urlByAdding()
}
init(sessionManager: Session) {
self.sessionManager = sessionManager
}
func updateTariff(tariff: Tariff, success: @escaping () -> Void, failure: @escaping (_ error: Error) -> Void) {
let params: [String : Any] = ["dayTimeStart" : tariff.dayTimeStart.removingOccurances([" "]),
"dayTimeEnd" : tariff.dayTimeEnd.removingOccurances([" "]),
"dayTariff" : tariff.dayTariff,
"nightTimeStart" : tariff.nightTimeStart.removingOccurances([" "]),
"nightTimeEnd" : tariff.nightTimeEnd.removingOccurances([" "]),
"nightTariff" : tariff.nightTariff,
"currency" : tariff.currency]
let endPointURL = baseURL().appendingPathComponent("me/tariff")
guard let request = URLRequest.postRequestWithJsonBody(url: endPointURL, parameters: params) else {
failure(RequestError.error(NSLocalizedString("Failed to send request, please try again later", comment: "")))
return
}
sessionManager.request(request).validate().response { response in
if let error = response.error {
if let error = error as? URLError, error.code == URLError.notConnectedToInternet {
NotificationCenter.default.post(name: .KLDNotConnectedToInternet, object: error)
} else {
log.error("Failed to update Tariff")
}
failure(error)
} else {
log.info("Successfully update Tariff")
success()
}
}
}
func getTariff(success: (() -> Void)?, failure: ((Error) -> Void)? = nil) {
log.info("getTariff")
guard let request = try? URLRequest(url: baseURL().appendingPathComponent("me/tariff"), method: .get) else {
assertionFailure()
DispatchQueue.main.async {
failure?(WSError.general)
}
return
}
sessionManager
.request(request).validate().responseData { response in
switch response.result {
case .success(let data):
do {
log.info(try JSON(data: data).description)
let decodedJSON = try JSONDecoder().decode(Tariff.self, from: data)
UserDataManager.shared.tariff = decodedJSON
success?()
} catch {
log.info("Get Tariff parsing error: \(error)")
failure?(error)
}
case .failure(let error):
log.info("Get Tariff fetch error: \(error)")
failure?(error)
}
}
}
func updateSettingMode(mode: String, roomId: String, success: @escaping () -> Void, failure: @escaping (_ error: Error) -> Void) {
let params: [String : Any] = ["mode" : mode]
let endPointURL = baseURL().appendingPathComponent("setting/rooms/\(roomId)/mode")
guard let request = URLRequest.postRequestWithJsonBody(url: endPointURL, parameters: params) else {
failure(RequestError.error(NSLocalizedString("Failed to send request, please try again later", comment: "")))
return
}
sessionManager.request(request).validate().response { response in
if let error = response.error {
if let error = error as? URLError, error.code == URLError.notConnectedToInternet {
NotificationCenter.default.post(name: .KLDNotConnectedToInternet, object: error)
} else {
log.error("Failed to update Setting Mode")
}
failure(error)
} else {
log.info("Successfully update Setting Mode")
success()
}
}
}
func getEnergyConsumed(success: (() -> Void)?, failure: ((Error) -> Void)? = nil) {
guard let request = try? URLRequest(url: baseURL().appendingPathComponent("me/tariff/energy"), method: .get) else {
assertionFailure()
DispatchQueue.main.async {
failure?(WSError.general)
}
return
}
sessionManager
.request(request).validate().responseData { response in
switch response.result {
case .success(let data):
do {
let json = try JSON(data: data)
UserDataManager.shared.energyConsumed = ConsumeEneryTariff(energyConsumedMonth: json["energyConsumedMonth"].doubleValue, energyConsumedWeek: json["energyConsumedWeek"].doubleValue, energyConsumedDay: json["energyConsumedDay"].doubleValue)
success?()
} catch {
log.info("Get Tariff parsing error: \(error)")
failure?(error)
}
case .failure(let error):
log.info("Get Tariff fetch error: \(error)")
failure?(error)
}
}
}
func resetManualBoost(roomId: String, success: (() -> Void)?, failure: ((Error) -> Void)? = nil) {
guard let request = try? URLRequest(url: baseURL().appendingPathComponent("setting/rooms/\(roomId)/temperature"), method: .delete) else {
assertionFailure()
DispatchQueue.main.async {
failure?(WSError.general)
}
return
}
sessionManager.request(request).validate().response { [weak self] response in
if let error = response.error {
log.error("Failed to manual boost update - \(error)")
failure?(error)
} else {
log.info("reset Manual Boost Successfully")
success?()
}
}
}
func loadSettingModes(success: (() -> Void)?, failure: ((Error) -> Void)? = nil) {
guard let request = try? URLRequest(url: baseURL().appendingPathComponent("modes"), method: .get) else {
assertionFailure()
DispatchQueue.main.async {
failure?(WSError.general)
}
return
}
sessionManager
.request(request).validate().responseData { response in
switch response.result {
case .success(let data):
do {
let json = try JSON(data: data)
guard let jsonArray = json.arrayObject as? [[String: Any]] else {
return
}
print(jsonArray)
self.loadSettingModes(modesDic: jsonArray)
success?()
} catch {
log.info("Get modes parsing error: \(error)")
self.loadDefaultSettingModes()
failure?(error)
}
case .failure(let error):
log.info("Get modes fetch error: \(error)")
self.loadDefaultSettingModes()
failure?(error)
}
}
}
func updateTempMode(modeName: String, temp: Double, success: @escaping () -> Void, failure: @escaping (_ error: Error) -> Void) {
let params: [String : Any] = ["temp" : temp]
let endPointURL = baseURL().appendingPathComponent("modes/\(modeName)")
sessionManager.request(endPointURL,
method: .put,
parameters: params,
encoding: JSONEncoding.default)
.validate()
.response { response in
if let error = response.error {
if let error = error as? URLError, error.code == URLError.notConnectedToInternet {
NotificationCenter.default.post(name: .KLDNotConnectedToInternet, object: error)
} else {
log.error("Failed to update Temperature Mode")
}
failure(error)
} else {
log.info("Successfully update Temperature Mode")
success()
}
}
}
func updateTemperatureUnit(temperatureUnit: String, success: @escaping () -> Void, failure: @escaping (_ error: Error) -> Void) {
let params: [String : Any] = ["temperatureUnit" : temperatureUnit,
"name" : "",
"zoneId" : ""]
let endPointURL = baseURL().appendingPathComponent("user/me")
sessionManager.request(endPointURL,
method: .patch,
parameters: params,
encoding: JSONEncoding.default)
.validate()
.response { response in
if let error = response.error {
if let error = error as? URLError, error.code == URLError.notConnectedToInternet {
NotificationCenter.default.post(name: .KLDNotConnectedToInternet, object: error)
} else {
log.error("Failed to update Temperature Unit")
}
failure(error)
} else {
log.info("Successfully update Temperature Unit")
success()
}
}
}
private func loadSettingModes(modesDic: [[String: Any]]) {
var settingModes: [ModeItem] = []
for dic in modesDic {
let mode = dic["mode"] as? String ?? ""
let temp = dic["temperature"] as? Double ?? 0
let smartMode = SmartMode.init(fromString: mode)
if smartMode != .unknow {
settingModes.append(ModeItem(mode: smartMode, title: ModeItem.titleOf(smartMode: smartMode), icon: ModeItem.imageOf(smartMode: smartMode), temp: temp))
}
}
UserDataManager.shared.settingModes = settingModes
}
private func loadDefaultSettingModes() {
var settingModes: [ModeItem] = []
settingModes.append(ModeItem(mode: .ECO, title: ModeItem.titleOf(smartMode: .ECO), icon: ModeItem.imageOf(smartMode: .ECO), temp: 19.0))
settingModes.append(ModeItem(mode: .NIGHT, title: ModeItem.titleOf(smartMode: .NIGHT), icon: ModeItem.imageOf(smartMode: .NIGHT), temp: 17.0))
settingModes.append(ModeItem(mode: .COMFORT, title: ModeItem.titleOf(smartMode: .COMFORT), icon: ModeItem.imageOf(smartMode: .COMFORT), temp: 21.0))
settingModes.append(ModeItem(mode: .DEFAULT, title: ModeItem.titleOf(smartMode: .DEFAULT), icon: ModeItem.imageOf(smartMode: .DEFAULT), temp: 20.5))
UserDataManager.shared.settingModes = settingModes
}
}
<file_sep>//
// OnboardingRouter.swift
// Koleda
//
// Created by <NAME> on 5/23/19.
// Copyright © 2019 koleda. All rights reserved.
//
import UIKit
class OnboardingRouter: BaseRouterProtocol {
enum RouteType {
case signUp
case logIn
case joinHome
case termAndConditions
case home
case createHome
}
weak var baseViewController: UIViewController?
func enqueueRoute(with context: Any?, animated: Bool, completion: ((Bool) -> Void)?) {
guard let routeType = context as? RouteType else {
assertionFailure("The route type missmatches")
return
}
guard let baseViewController = baseViewController else {
assertionFailure("baseViewController is not set")
return
}
switch routeType {
case .signUp:
baseViewController.performSegue(withIdentifier: SignUpViewController.get_identifier, sender: self)
case .logIn:
let router = LoginRouter()
guard let viewController = StoryboardScene.Login.initialViewController() as? LoginViewController else { return }
let viewModel = LoginViewModel.init(router: router)
viewController.viewModel = viewModel
router.baseViewController = viewController
baseViewController.navigationController?.pushViewController(viewController, animated: true)
case .joinHome:
let router = JoinHomeRouter()
let viewModel = JoinHomeViewModel.init(router: router)
guard let viewController = StoryboardScene.Onboarding.instantiateJoinHomeViewController() as? JoinHomeViewController else {
return
}
viewController.viewModel = viewModel
router.baseViewController = viewController
baseViewController.navigationController?.pushViewController(viewController, animated: true)
case .termAndConditions:
let router = TermAndConditionRouter()
let viewModel = TermAndConditionViewModel.init(router: router)
guard let viewController = StoryboardScene.Setup.instantiateTermAndConditionViewController() as? TermAndConditionViewController else { return }
viewController.viewModel = viewModel
router.baseViewController = viewController
baseViewController.navigationController?.pushViewController(viewController, animated: true)
case .home:
let router = HomeRouter()
let viewModel = HomeViewModel.init(router: router)
let homeNavigationVC = StoryboardScene.Home.instantiateNavigationController()
guard let viewController = homeNavigationVC.topViewController as? HomeViewController else {
assertionFailure("HomeViewController storyboard configured not properly")
return
}
viewController.viewModel = viewModel
router.baseViewController = viewController
if let delegate = UIApplication.shared.delegate as? AppDelegate {
delegate.window?.rootViewController = homeNavigationVC
}
case .createHome:
let router = CreateHomeRouter()
let viewModel = CreateHomeViewModel.init(router: router)
guard let createHomeViewController = StoryboardScene.Setup.instantiateCreateHomeViewController() as? CreateHomeViewController else { return }
createHomeViewController.viewModel = viewModel
router.baseViewController = createHomeViewController
baseViewController.navigationController?.pushViewController(createHomeViewController, animated: true)
}
}
func present(on baseVC: UIViewController, animated: Bool, context: Any?, completion: ((Bool) -> Void)?) {
}
func dismiss(animated: Bool, context: Any?, completion: ((Bool) -> Void)?) {
}
func prepare(for segue: UIStoryboardSegue) {
if let viewController = segue.destination as? SignUpViewController {
let router = SignUpRouter()
let viewModel = SignUpViewModel.init(router: router)
viewController.viewModel = viewModel
router.baseViewController = viewController
}
}
}
<file_sep>//
// SignUpManager.swift
// Koleda
//
// Created by <NAME> on 6/11/19.
// Copyright © 2019 koleda. All rights reserved.
//
import Foundation
import UIKit
import Alamofire
protocol SignUpManager {
func signUp(name: String, email: String, password: String, success: @escaping () -> Void, failure: @escaping (_ error: Error) -> Void)
func resetPassword(email: String, success: @escaping () -> Void, failure: @escaping (_ error: Error) -> Void)
}
class SignUpManagerImpl: SignUpManager {
private let sessionManager: Session
private func baseURL() -> URL {
return UrlConfigurator.urlByAdding()
}
init(sessionManager: Session) {
self.sessionManager = sessionManager
}
func signUp(name: String, email: String, password: String, success: @escaping () -> Void, failure: @escaping (_ error: Error) -> Void) {
let timezone = TimeZone.current.identifier
let params = ["name": name,
"email": email,
"password": <PASSWORD>,
"zoneId": timezone]
guard let request = URLRequest.postRequestWithJsonBody(url: baseURL().appendingPathComponent("auth/signup"), parameters: params) else {
failure(RequestError.error(NSLocalizedString("Failed to send request, please try again later", comment: "")))
return
}
AF.request(request).validate().response { response in
if let error = response.error {
if let error = error as? AFError, error.responseCode == 400 {
failure(WSError.emailExisted)
} else {
failure(WSError.general)
}
} else {
success()
}
}
}
func resetPassword(email: String, success: @escaping () -> Void, failure: @escaping (_ error: Error) -> Void) {
let endpoint = "auth/reset-password?email=\(email)"
guard let url = URL(string: baseURL().absoluteString + endpoint) else {
failure(RequestError.error(NSLocalizedString("Failed to send request, please try again later", comment: "")))
return
}
guard let request = try? URLRequest(url: url, method: .post) else {
assertionFailure()
DispatchQueue.main.async {
failure(WSError.general)
}
return
}
AF.request(request).validate().response { response in
if let error = response.error {
if let error = error as? AFError, error.responseCode == 404 {
failure(WSError.userNotFound)
} else {
failure(WSError.general)
}
} else {
success()
}
}
}
}
<file_sep>
//
// HomeViewModel.swift
// Koleda
//
// Created by <NAME> on 6/27/19.
// Copyright © 2019 koleda. All rights reserved.
//
import Foundation
import RxSwift
import SVProgressHUD
import CopilotAPIAccess
protocol HomeViewModelProtocol: BaseViewModelProtocol {
func addRoom()
func getCurrentUser()
func refreshListRooms()
func refreshSettingModes()
func selectedRoom(at indexPath: IndexPath)
func selectedRoomConfiguration(at indexPath: IndexPath)
func showMenuSettings()
func logOut()
var homeTitle: Variable<String> { get }
var rooms: Variable<[Room]> { get }
var mustLogOutApp: PublishSubject<String> { get }
}
class HomeViewModel: BaseViewModel, HomeViewModelProtocol {
let homeTitle = Variable<String>("")
let rooms = Variable<[Room]>([])
let mustLogOutApp = PublishSubject<String>()
let router: BaseRouterProtocol
private let userManager: UserManager
private let roomManager: RoomManager
private let settingManager: SettingManager
private let websocketManager: WebsocketManager
init(router: BaseRouterProtocol, managerProvider: ManagerProvider = .sharedInstance) {
self.router = router
userManager = managerProvider.userManager
roomManager = managerProvider.roomManager
settingManager = managerProvider.settingManager
websocketManager = managerProvider.websocketManager
super.init(managerProvider: managerProvider)
setup()
getAllRooms()
}
func setup() {
if let currentUser = UserDataManager.shared.currentUser, currentUser.homes.count > 0 {
reloadUser(userInfo: currentUser)
} else {
getCurrentUser()
}
}
func addRoom() {
router.enqueueRoute(with: HomeRouter.RouteType.addRoom)
}
func selectedRoomConfiguration(at indexPath: IndexPath) {
let room = rooms.value[indexPath.section]
router.enqueueRoute(with: HomeRouter.RouteType.selectedRoomConfiguration(room))
}
func selectedRoom(at indexPath: IndexPath) {
let room = rooms.value[indexPath.section]
router.enqueueRoute(with: HomeRouter.RouteType.selectedRoom(room))
}
func getCurrentUser() {
SVProgressHUD.show()
userManager.getCurrentUser(success: { [weak self] in
guard let userId = UserDataManager.shared.currentUser?.id else {
return
}
Copilot.instance
.manage
.yourOwn
.sessionStarted(withUserId: userId,
isCopilotAnalysisConsentApproved: true)
SVProgressHUD.dismiss()
if let currentUser = UserDataManager.shared.currentUser, currentUser.homes.count > 0 {
self?.reloadUser(userInfo: currentUser)
}
},
failure: { error in
SVProgressHUD.dismiss()
})
}
func refreshSettingModes() {
self.settingManager.loadSettingModes(success: { [weak self] in
guard let `self` = self else {
return
}
NotificationCenter.default.post(name: .KLDNeedReLoadModes, object: nil)
self.refreshListRooms()
}, failure: { error in })
}
func getAllRooms() {
SVProgressHUD.show()
roomManager.getRooms(success: { [weak self] in
SVProgressHUD.dismiss()
self?.rooms.value = UserDataManager.shared.rooms
if let rooms = self?.rooms.value, rooms.count > 0 {
self?.websocketManager.delegate = self
self?.websocketManager.connect()
}
self?.getDeviceModelListFromRoomList()
NotificationCenter.default.post(name: .KLDNeedUpdateSelectedRoom, object: nil)
},
failure: { [weak self] error in
SVProgressHUD.dismiss()
if let error = error as? WSError, error == WSError.loginSessionExpired, let errorMessage = error.errorDescription {
self?.mustLogOutApp.onNext((errorMessage))
}
})
}
func refreshListRooms() {
getAllRooms()
}
func showMenuSettings() {
router.enqueueRoute(with: HomeRouter.RouteType.menuSettings)
}
func logOut() {
SVProgressHUD.show()
userManager.logOut { [weak self] in
Copilot.instance
.manage
.yourOwn
.sessionEnded()
SVProgressHUD.dismiss()
self?.router.enqueueRoute(with: HomeRouter.RouteType.logOut)
}
}
private func reloadUser(userInfo: User) {
let userName = userInfo.homes[0].name
homeTitle.value = "<h1>\(userName)</h1>"
UserDefaultsManager.termAndConditionAcceptedUser.value = UserDataManager.shared.currentUser?.email
refreshSettingModes()
}
private func getDeviceModelListFromRoomList() {
UserDataManager.shared.deviceModelList = []
let allRooms = UserDataManager.shared.rooms
var deviceModels: [String] = []
allRooms.compactMap { room in
if let sensor = room.sensor {
deviceModels.append(sensor.deviceModel)
}
if let heaters = room.heaters, heaters.count > 0 {
heaters.compactMap { heater in
deviceModels.append(heater.deviceModel)
}
}
}
UserDataManager.shared.deviceModelList = deviceModels
}
}
extension HomeViewModel: WebsocketManagerDelegate {
func refeshAtRoom(with newData: WSDataItem) {
var listRooms = self.rooms.value
var room = listRooms.filter { $0.sensor?.id == newData.id}.first
let value = newData.value
switch newData.name {
case SocketKeyName.HUMIDITY.rawValue:
room?.humidity = value as? String
case SocketKeyName.BATTERY.rawValue:
room?.battery = value as? String
case SocketKeyName.TEMPERATURE.rawValue:
room?.originalTemperature = value as? String
case SocketKeyName.ROOM_STATUS.rawValue:
room?.enabled = value as? Bool
default:
break
}
if let row = listRooms.index(where: {$0.sensor?.id == newData.id}) , let newRoom = room {
listRooms[row] = newRoom
self.rooms.value = listRooms
}
NotificationCenter.default.post(name: .KLDDidChangeRooms, object: nil)
}
}
<file_sep>//
// InstructionForSensorRouter.swift
// Koleda
//
// Created by <NAME> on 9/6/19.
// Copyright © 2019 koleda. All rights reserved.
//
import UIKit
class InstructionForSensorRouter: BaseRouterProtocol {
var baseViewController: UIViewController?
func enqueueRoute(with context: Any?, animated: Bool, completion: ((Bool) -> Void)?) {
}
func present(on baseVC: UIViewController, animated: Bool, context: Any?, completion: ((Bool) -> Void)?) {
}
func dismiss(animated: Bool, context: Any?, completion: ((Bool) -> Void)?) {
}
func backToRoot() {
baseViewController?.backToRoot(animated: true)
}
func nextToSensorManagement(roomId: String, roomName: String, isFromRoomConfiguration: Bool) {
baseViewController?.gotoBlock(withStoryboar: "Sensor", aClass: SensorManagementViewController.self) { (vc) in
let router = SensorManagementRouter()
let viewModel = SensorManagementViewModel.init(router: router, roomId: roomId, roomName: roomName)
vc?.viewModel = viewModel
vc?.isFromRoomConfiguration = isFromRoomConfiguration
router.baseViewController = vc
}
}
}
<file_sep>//
// TemperatureUnitView.swift
// Koleda
//
// Created by <NAME> on 9/17/19.
// Copyright © 2019 koleda. All rights reserved.
//
import Foundation
import UIKit
class TemperatureUnitView: UIView {
func setUp(unit: TemperatureUnit) {
self.unit = unit
abbUnitLabel.text = unit == .C ? "C °" : "F °"
unitLabel.text = unit == .C ? "CELSIUS_TEXT".app_localized : "FAHRENHEIT_TEXT".app_localized
updateStatus(enable: false)
}
@IBOutlet weak var abbUnitLabel: UILabel!
@IBOutlet weak var lineLabel: UILabel!
@IBOutlet weak var unitLabel: UILabel!
var unit: TemperatureUnit?
override func awakeFromNib() {
super.awakeFromNib()
kld_loadContentFromNib()
}
func updateStatus(enable: Bool) {
abbUnitLabel.textColor = enable ? .black : .lightGray
unitLabel.textColor = enable ? .black : .lightGray
lineLabel.backgroundColor = enable ? .orange : .lightGray
}
}
<file_sep>
//
// UIView+Extensions.swift
// Koleda
//
// Created by <NAME> on 8/27/19.
// Copyright © 2019 koleda. All rights reserved.
//
import UIKit
import Foundation
extension UIView {
func addshadowAllSides(cornerRadius: CGFloat, shadowColor: UIColor, shadowRadius: CGFloat = 5.0, borderWidth: CGFloat = 0, borderColor: UIColor = .white) {
self.layer.cornerRadius = cornerRadius
// border
self.layer.borderWidth = borderWidth
self.layer.borderColor = borderColor.cgColor
// shadow
self.layer.shadowColor = shadowColor.cgColor
self.layer.shadowOffset = CGSize(width: 0, height: 0)
self.layer.shadowOpacity = 0.7
self.layer.shadowRadius = shadowRadius
}
static var kld_nib: UINib {
return UINib(nibName: "\(self)", bundle: nil)
}
func kld_loadContentFromNib() {
guard let contentView = type(of: self).kld_nib.instantiate(withOwner: self, options: nil).last as? UIView else {
return
}
contentView.frame = self.bounds
self.addSubview(contentView)
contentView.translatesAutoresizingMaskIntoConstraints = false
self.addConstraints([
NSLayoutConstraint(item: contentView, attribute: NSLayoutConstraint.Attribute.top, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self, attribute: NSLayoutConstraint.Attribute.top, multiplier: 1, constant: 0),
NSLayoutConstraint(item: contentView, attribute: NSLayoutConstraint.Attribute.bottom, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self, attribute: NSLayoutConstraint.Attribute.bottom, multiplier: 1, constant: 0),
NSLayoutConstraint(item: contentView, attribute: NSLayoutConstraint.Attribute.left, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self, attribute: NSLayoutConstraint.Attribute.left, multiplier: 1, constant: 0),
NSLayoutConstraint(item: contentView, attribute: NSLayoutConstraint.Attribute.right, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self, attribute: NSLayoutConstraint.Attribute.right, multiplier: 1, constant: 0)
])
}
@IBInspectable var borderWidth : CGFloat {
set {
layer.borderWidth = newValue
}
get {
return layer.borderWidth
}
}
@IBInspectable var borderColor : UIColor {
set {
self.layer.borderColor = newValue.cgColor
}
get {
return UIColor(cgColor: self.layer.borderColor ?? UIColor.clear.cgColor)
}
}
@IBInspectable var cornerRadius : CGFloat {
set {
self.layer.cornerRadius = newValue
}
get {
return layer.cornerRadius
}
}
}
<file_sep>//
// NetWorkManager.swift
// Koleda
//
// Created by <NAME> on 7/8/19.
// Copyright © 2019 koleda. All rights reserved.
//
import Foundation
import Reachability
import SystemConfiguration.CaptiveNetwork
struct WifiInfo {
let ssid: String
let ipAddress: String
let subNetMask: String
let gateWay: String
let dns: String
init(ssid: String, ipAddress: String, subNetMask: String, gateWay: String, dns: String) {
self.ssid = ssid
self.ipAddress = ipAddress
self.subNetMask = subNetMask
self.gateWay = gateWay
self.dns = dns
}
static func getWifiInfo() -> WifiInfo? {
guard let ssid = FGRoute.getSSID(), let ip = FGRoute.getIPAddress(), let subNet = FGRoute.getSubnetMask(), let gate = FGRoute.getGatewayIP() else {
return nil
}
return WifiInfo(ssid: ssid, ipAddress: ip, subNetMask: subNet, gateWay: gate, dns: "")
}
}
class NetworkManager: ReachabilityObserverDelegate {
func Connection() -> Bool{
var zeroAddress = sockaddr_in(sin_len: 0, sin_family: 0, sin_port: 0, sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0))
zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)
let defaultRouteReachability = withUnsafePointer(to: &zeroAddress) {
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) {zeroSockAddress in
SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress)
}
}
var flags: SCNetworkReachabilityFlags = SCNetworkReachabilityFlags(rawValue: 0)
if SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) == false {
return false
}
// Working for Cellular and WIFI
let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0
let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
let ret = (isReachable && !needsConnection)
return ret
}
func isWifi() -> Bool {
return reachability?.connection == .wifi
}
required init() {
addReachabilityObserver()
}
deinit {
removeReachabilityObserver()
}
//MARK: Reachability
func reachabilityChanged(_ isReachable: Bool) {
}
}
//Reachability
//declare this property where it won't go out of scope relative to your listener
fileprivate var reachability: Reachability!
protocol ReachabilityActionDelegate {
func reachabilityChanged(_ isReachable: Bool)
}
protocol ReachabilityObserverDelegate: class, ReachabilityActionDelegate {
func addReachabilityObserver()
func removeReachabilityObserver()
}
// Declaring default implementation of adding/removing observer
extension ReachabilityObserverDelegate {
/** Subscribe on reachability changing */
func addReachabilityObserver() {
do {
try reachability = Reachability()
} catch {
print("could not start reachability notifier")
}
reachability.whenReachable = { [weak self] reachability in
self?.reachabilityChanged(true)
}
reachability.whenUnreachable = { [weak self] reachability in
self?.reachabilityChanged(false)
}
do {
try reachability.startNotifier()
} catch {
print("Unable to start notifier")
}
}
/** Unsubscribe */
func removeReachabilityObserver() {
reachability.stopNotifier()
NotificationCenter.default.removeObserver(self, name: Notification.Name.reachabilityChanged, object: reachability)
reachability = nil
}
}
<file_sep>//
// ManySensorsDetectedPopupViewController.swift
// Koleda
//
// Created by <NAME> on 8/7/19.
// Copyright © 2019 koleda. All rights reserved.
//
import UIKit
class ManySensorsDetectedPopupViewController: BaseViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
@IBAction func back(_ sender: Any) {
self.dismiss(animated: true) {
NotificationCenter.default.post(name: .KLDNeedToReSearchDevices, object: nil)
}
}
}
<file_sep>//
// UnderlinePagerOption.swift
// Koleda
//
// Created by <NAME> on 10/30/19.
// Copyright © 2019 koleda. All rights reserved.
//
import Foundation
import Swift_PageMenu
struct UnderlinePagerOption: PageMenuOptions {
var isInfinite: Bool = false
var menuItemSize: PageMenuItemSize {
return .sizeToFit(minWidth: 40, height: 50)
}
var menuTitleColor: UIColor {
return UIColor.white
}
var menuTitleSelectedColor: UIColor {
return Theme.mainColor
}
var menuCursor: PageMenuCursor {
return .underline(barColor: Theme.mainColor, height: 2)
}
var font: UIFont {
return UIFont.app_FuturaPTDemi(ofSize: 9)
}
var menuItemMargin: CGFloat {
return 8
}
var tabMenuBackgroundColor: UIColor {
return UIColor.black
}
public init(isInfinite: Bool = false) {
self.isInfinite = isInfinite
}
}
struct Theme {
static var mainColor = UIColor.orange
}
<file_sep>//
// UIViewController+Alerts.swift
// Koleda
//
// Created by <NAME> on 7/8/19.
// Copyright © 2019 koleda. All rights reserved.
//
import Foundation
import UIKit
extension UIViewController {
func app_showAlertMessage(title: String?, message: String?, actions:[UIAlertAction]? = nil) {
let alertContoller = UIAlertController(title: title, message: message, preferredStyle: .alert)
if actions?.compactMap({alertContoller.addAction($0)}) == nil {
let okAction = UIAlertAction(title: "OK".app_localized, style: .default, handler: nil)
alertContoller.addAction(okAction)
}
present(alertContoller, animated: true, completion: nil)
}
func app_showInfoAlert(_ message: String,
title: String? = nil,
completion: (() -> Void)? = nil) {
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK".app_localized,
style: .default,
handler: { (action) in
if let handler = completion {
handler()
}
})
alertController.addAction(defaultAction)
present(alertController, animated: true, completion: nil)
}
func app_showPromptAlert(title: String? = nil,
message: String, acceptTitle: String?,
dismissTitle: String?,
acceptButtonStyle: UIAlertAction.Style = .cancel,
acceptCompletion: (() -> Void)? = nil,
dismissCompletion: (() -> Void)? = nil) {
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
if let acceptTitle = acceptTitle {
let acceptAction = UIAlertAction(title: acceptTitle, style: acceptButtonStyle) { (alertAction) in
if let action = acceptCompletion {
action()
}
}
alertController.addAction(acceptAction)
}
if let dismissTitle = dismissTitle {
let dismissAction = UIAlertAction(title: dismissTitle, style: .default) { (alertAction) in
if let action = dismissCompletion {
action()
}
}
alertController.addAction(dismissAction)
}
present(alertController, animated: true, completion: nil)
}
func app_showActionSheet(title: String? = nil,
message: String? = nil,
preferredStyle: UIAlertController.Style = .actionSheet,
actionTitles: [String],
actionStyles: [UIAlertAction.Style],
withHandler handlers: [((UIAlertAction) -> Void)?]) {
guard !actionTitles.isEmpty, actionStyles.count == actionTitles.count, handlers.count == actionTitles.count else { return }
let actionSheetController = UIAlertController(title: title, message: message, preferredStyle: preferredStyle)
actionTitles.enumerated().forEach { (index, element) in
actionSheetController.addAction(UIAlertAction(title: element,
style: actionStyles[index],
handler: handlers[index]))
}
present(actionSheetController, animated: true, completion: nil)
}
}
<file_sep>//
// ConfigurationRoomRouter.swift
// Koleda
//
// Created by <NAME> on 8/26/19.
// Copyright © 2019 koleda. All rights reserved.
//
import UIKit
class ConfigurationRoomRouter: BaseRouterProtocol {
enum RouteType {
case editRoom(Room)
case addSensor(String, String)
case editSensor(Room)
case heaterManagement(Room)
}
weak var baseViewController: UIViewController?
func enqueueRoute(with context: Any?, animated: Bool, completion: ((Bool) -> Void)?) {
guard let routeType = context as? RouteType else {
assertionFailure("The route type missmatches")
return
}
guard let baseViewController = baseViewController else {
assertionFailure("baseViewController is not set")
return
}
switch routeType {
case .editRoom(let selectedRoom):
let router = RoomDetailRouter()
let viewModel = RoomDetailViewModel.init(router: router, editingRoom: selectedRoom)
guard let viewController = StoryboardScene.Room.instantiateRoomDetailViewController() as? RoomDetailViewController else {
return
}
viewController.viewModel = viewModel
router.baseViewController = viewController
baseViewController.navigationController?.pushViewController(viewController, animated: true)
case .addSensor(let roomId, let roomName):
baseViewController.gotoBlock(withStoryboar: "Sensor", aClass: InstructionViewController.self, sendData: { (vc) in
vc?.roomId = roomId
vc?.roomName = roomName
vc?.isFromRoomConfiguration = true
})
case .editSensor(let selectedRoom):
let router = EditSensorRouter()
let viewModel = EditSensorViewModel.init(router: router, seletedRoom: selectedRoom)
guard let viewController = StoryboardScene.Sensor.instantiateEditSensorViewController() as? EditSensorViewController else {
return
}
viewController.viewModel = viewModel
router.baseViewController = viewController
baseViewController.navigationController?.pushViewController(viewController, animated: true)
case .heaterManagement(let selectedRoom):
let router = HeatersManagementRouter()
let viewModel = HeatersManagementViewModel.init(router: router, selectedRoom: selectedRoom)
guard let viewController = StoryboardScene.Heater.instantiateHeatersManagementViewController() as? HeatersManagementViewController else {
return
}
viewController.viewModel = viewModel
router.baseViewController = viewController
baseViewController.navigationController?.pushViewController(viewController, animated: true)
}
}
func present(on baseVC: UIViewController, animated: Bool, context: Any?, completion: ((Bool) -> Void)?) {
}
func dismiss(animated: Bool, context: Any?, completion: ((Bool) -> Void)?) {
}
}
<file_sep>//
// WelcomeJoinHomeViewModel.swift
// Koleda
//
// Created by <NAME> on 8/5/20.
// Copyright © 2020 koleda. All rights reserved.
//
import Foundation
protocol WelcomeJoinHomeViewModelProtocol: BaseViewModelProtocol {
func goHome()
}
class WelcomeJoinHomeViewModel: BaseViewModel, WelcomeJoinHomeViewModelProtocol {
let router: BaseRouterProtocol
init(router: BaseRouterProtocol, managerProvider: ManagerProvider = .sharedInstance) {
self.router = router
super.init(managerProvider: managerProvider)
}
func goHome() {
UserDefaultsManager.loggedIn.enabled = true
router.enqueueRoute(with: WelcomeJoinHomeRouter.RouteType.home)
}
}
<file_sep>//
// CreateHomeViewModel.swift
// Koleda
//
// Created by <NAME> on 6/16/20.
// Copyright © 2020 koleda. All rights reserved.
//
import Foundation
import RxSwift
protocol CreateHomeViewModelProtocol: BaseViewModelProtocol {
var welcomeMessage : Variable<String> { get}
var homeName: Variable<String> { get }
var homeNameErrorMessage: Variable<String> { get }
func saveAction(completion: @escaping () -> Void)
}
class CreateHomeViewModel: BaseViewModel, CreateHomeViewModelProtocol {
let router: BaseRouterProtocol
let welcomeMessage = Variable<String>("Welcome to SOLUS!\nCreate your <h1>Home</h1>")
let homeName = Variable<String>("")
let homeNameErrorMessage = Variable<String>("")
private let homeManager: HomeManager
init(router: BaseRouterProtocol, managerProvider: ManagerProvider = .sharedInstance) {
self.router = router
self.homeManager = managerProvider.homeManager
super.init(managerProvider: managerProvider)
}
func saveAction(completion: @escaping () -> Void) {
guard validateRoomName() else {
completion()
return
}
createHome(name: homeName.value.extraWhitespacesRemoved) {
completion()
}
}
private func createHome(name: String, completion: @escaping () -> Void) {
homeManager.createHome(name: name, success: { [weak self] in
guard let `self` = self else {
completion()
return
}
completion()
self.router.enqueueRoute(with: CreateHomeRouter.RouteType.location)
}) { _ in
completion()
}
}
private func validateRoomName() -> Bool {
if homeName.value.extraWhitespacesRemoved.isEmpty {
homeNameErrorMessage.value = "Home Name is not Empty"
return false
} else {
homeNameErrorMessage.value = ""
return true
}
}
}
<file_sep>//
// TemperatureUnitRouter.swift
// Koleda
//
// Created by <NAME> on 9/17/19.
// Copyright © 2019 koleda. All rights reserved.
//
import UIKit
class TemperatureUnitRouter: BaseRouterProtocol {
enum RouteType {
case home
case inviteFriends
}
weak var baseViewController: UIViewController?
func enqueueRoute(with context: Any?, animated: Bool, completion: ((Bool) -> Void)?) {
guard let routeType = context as? RouteType else {
assertionFailure("The route type missmatches")
return
}
guard let baseViewController = baseViewController else {
assertionFailure("baseViewController is not set")
return
}
switch routeType {
case .home:
let router = HomeRouter()
let viewModel = HomeViewModel.init(router: router)
let homeNavigationVC = StoryboardScene.Home.instantiateNavigationController()
guard let viewController = homeNavigationVC.topViewController as? HomeViewController else {
assertionFailure("HomeViewController storyboard configured not properly")
return
}
viewController.viewModel = viewModel
router.baseViewController = viewController
if let delegate = UIApplication.shared.delegate as? AppDelegate {
delegate.window?.rootViewController = homeNavigationVC
}
case .inviteFriends:
let router = InviteFriendsRouter()
let viewModel = InviteFriendsViewModel.init(router: router)
guard let viewController = StoryboardScene.Setup.instantiateInviteFriendsViewController() as? InviteFriendsViewController else {
assertionFailure("InviteFriendsViewController storyboard configured not properly")
return
}
viewController.viewModel = viewModel
router.baseViewController = viewController
baseViewController.navigationController?.pushViewController(viewController, animated: true)
}
}
func present(on baseVC: UIViewController, animated: Bool, context: Any?, completion: ((Bool) -> Void)?) {
}
func dismiss(animated: Bool, context: Any?, completion: ((Bool) -> Void)?) {
}
}
<file_sep>//
// RoomTypeCell.swift
// Koleda
//
// Created by <NAME> on 7/9/19.
// Copyright © 2019 koleda. All rights reserved.
//
import UIKit
class RoomTypeCell: UICollectionViewCell {
@IBOutlet weak var typeImageView: UIImageView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var containView: UIView!
@IBOutlet weak var checkImage: UIImageView!
@IBOutlet weak var backgroundImageView: UIImageView!
var roomType: RoomType?
override var isSelected: Bool {
didSet {
checkImage.isHidden = !isSelected
backgroundImageView.isHidden = !isSelected
typeImageView.tintColor = isSelected ? UIColor.black : UIColor.gray
typeImageView.image = roomType?.roomDetailImage
typeImageView.tintColor = isSelected ? UIColor.black: UIColor.gray
titleLabel.textColor = isSelected ? UIColor.black : UIColor.hexB5B5B5
}
}
func loadData(roomType: RoomType) {
self.roomType = roomType
typeImageView.image = roomType.roomDetailImage
titleLabel.text = roomType.title
}
override func awakeFromNib() {
super.awakeFromNib()
isSelected = false
}
}
<file_sep>//
// String+Range.swift
// Koleda
//
// Created by <NAME> on 6/10/19.
// Copyright © 2019 koleda. All rights reserved.
//
import Foundation
extension String {
func nsRange(from range: Range<String.Index>) -> NSRange {
return NSRange(range, in: self)
}
}
<file_sep>//
// LocationSetupViewController.swift
// Koleda
//
// Created by <NAME> on 7/4/19.
// Copyright © 2019 koleda. All rights reserved.
//
import UIKit
import RxSwift
import Network
class LocationSetupViewController: BaseViewController, BaseControllerProtocol {
var viewModel: LocationSetupViewModelProtocol!
@IBOutlet weak var progressBarView: ProgressBarView!
@IBOutlet weak var noButton: UIButton!
@IBOutlet weak var yesButton: UIButton!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var descriptionLabel: UILabel!
@IBOutlet weak var allowLabel: UILabel!
@IBOutlet weak var declineLabel: UILabel!
private let disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
noButton.rx.tap.bind { [weak self] _ in
self?.viewModel.declineLocationService()
}.disposed(by: disposeBag)
yesButton.rx.tap.bind { [weak self] _ in
self?.yesButton.isEnabled = false
self?.viewModel.requestAccessLocationService {
self?.yesButton.isEnabled = true
}
}.disposed(by: disposeBag)
viewModel.showLocationDisabledPopUp.asObservable().subscribe(onNext: { [weak self] show in
if show {
self?.showLocationDisabledPopUp()
}
}).disposed(by: disposeBag)
progressBarView.setupNav(viewController: self)
titleLabel.text = "ALLOW_SOLUS_USE_YOUR_GEOLOCATION_MESS".app_localized
descriptionLabel.text = "THIS_IS_NECESSARY_FOR_THE_CORRECT_DETECTION_OF_YOUR_LOCATION_MESS".app_localized
allowLabel.text = "ALLOW_TEXT".app_localized
declineLabel.text = "DECLINE_TEXT".app_localized
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(true, animated: animated)
navigationBarTransparency()
setTitleScreen(with: "")
}
private func showLocationDisabledPopUp() {
app_showPromptAlert(title: "ALLOW_ACCESS_LOCATION_IN_SETTING_TITLE".app_localized,
message: "ALLOW_ACCESS_LOCATION_IN_SETTING_MESSAGE".app_localized,
acceptTitle: "OPEN_SETTINGS_TITLE".app_localized,
dismissTitle: "CANCEL".app_localized,
acceptCompletion: {
guard let url = URL(string: UIApplication.openSettingsURLString) else {
return
}
if #available(iOS 10.0, *) {
UIApplication.shared.open(url)
} else {
UIApplication.shared.openURL(url)
}
}, dismissCompletion: nil)
}
}
<file_sep>//
// AppConstants.swift
// Koleda
//
// Created by <NAME> on 5/27/19.
// Copyright © 2019 koleda. All rights reserved.
//
import Foundation
struct AppConstants {
static let introVideoLink = "https://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"
static let privacyPolicyLink = "https://www.websitepolicies.com/policies/view/VfoiBcKV"
static let legalPrivacyPolicyLink = "https://www.websitepolicies.com/policies/view/YnPlPCKN"
static let legalTermAndConditionLink = "https://www.websitepolicies.com/policies/view/RiQksFCY"
static let defaultShellyHostLink = "http://192.168.33.1:80"
static let supportEmail = "<EMAIL>"
}
struct Constants {
static let passwordMinLength = 6
static let passwordMaxLength = 21
static let nameMaxLength = 50
static let MAX_END_TIME_POINT = 36000
static let DEFAULT_BOOSTING_END_TIME_POINT = 5400
static let MIN_TEMPERATURE: Double = 0
static let MAX_TEMPERATURE: Double = 40
static let DEFAULT_TEMPERATURE: Double = 20.5
static let MIN_TEMPERATURE_MODE: Int = 0
static let MAX_TEMPERATURE_MODE: Int = 25
static let MAX_TIME_DAY: Int = 1440
}
<file_sep>
//
// Room.swift
// Koleda
//
// Created by <NAME> on 7/11/19.
// Copyright © 2019 koleda. All rights reserved.
//
import Foundation
enum SettingType: String, Codable {
case unknow
case SMART = "SMART"
case MANUAL = "MANUAL"
case DEFAULT = "DEFAULT"
case SCHEDULE = "SCHEDULE"
init(fromString string: String) {
guard let value = SettingType(rawValue: string) else {
self = .unknow
return
}
self = value
}
}
enum SmartMode: String, Codable {
case unknow
case ECO = "ECO"
case NIGHT = "NIGHT"
case COMFORT = "COMFORT"
case DEFAULT = "DEFAULT"
case SMARTSCHEDULE = "SCHEDULE"
init(fromString string: String) {
guard let value = SmartMode(rawValue: string) else {
self = .unknow
return
}
self = value
}
}
struct Room: Codable {
let id: String
var name: String
var category: String
var heaters: [Heater]?
var sensor: Sensor?
var battery: String?
var originalTemperature: String?
var enabled: Bool?
var humidity: String?
var setting: SettingItem?
enum CodingKeys: String, CodingKey {
case id = "id"
case name = "name"
case category = "category"
case heaters = "heaters"
case sensor = "sensor"
case battery = "battery"
case originalTemperature = "temperature"
case enabled = "enabled"
case humidity = "humidity"
case setting = "setting"
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.id = try container.decode(String.self, forKey: .id)
self.name = try container.decode(String.self, forKey: .name)
self.category = try container.decode(String.self, forKey: .category)
self.heaters = try container.decode([Heater].self, forKey: .heaters)
self.sensor = try container.decodeIfPresent(Sensor.self, forKey: .sensor)
self.battery = try container.decodeIfPresent(String.self, forKey: .battery)
self.originalTemperature = try container.decodeIfPresent(String.self, forKey: .originalTemperature)
self.enabled = try container.decodeIfPresent(Bool.self, forKey: .enabled)
self.humidity = try container.decodeIfPresent(String.self, forKey: .humidity)
self.setting = try container.decodeIfPresent(SettingItem.self, forKey: .setting)
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(self.id, forKey: .id)
try container.encode(self.name, forKey: .name)
try container.encode(self.heaters, forKey: .heaters)
try container.encode(self.category, forKey: .category)
try container.encode(self.battery, forKey: .battery)
try container.encode(self.originalTemperature, forKey: .originalTemperature)
try container.encode(self.enabled, forKey: .enabled)
try container.encode(self.humidity, forKey: .humidity)
try container.encode(self.setting, forKey: .setting)
}
}
extension Room {
var temperature: String? {
if UserDataManager.shared.temperatureUnit == .C {
guard let temp = originalTemperature, let celsiusTemperature = Double(temp) else {
return originalTemperature
}
return "\(celsiusTemperature.roundToDecimal(1))"
} else {
return originalTemperature?.fahrenheitTemperature
}
}
}
struct Sensor: Codable {
let id : String
var deviceModel: String
var name: String
var enabled: Bool
var ipAddress: String?
init(deviceModel: String, name: String, ipAddress: String, enabled: Bool = true) {
self.id = ""
self.deviceModel = deviceModel
self.name = name
self.ipAddress = ipAddress
self.enabled = enabled
}
}
struct Heater: Codable {
let id: String
var deviceModel: String
var name: String
var enabled: Bool
var ipAddress: String?
init(deviceModel: String, name: String, enabled: Bool = false, ipAddress: String?) {
self.id = ""
self.name = name
self.enabled = enabled
self.deviceModel = deviceModel
self.ipAddress = ipAddress
}
}
struct SettingItem: Codable {
let created: String
let mode: String?
let type: String?
let data: DataConfiguration?
let enableSchedule: Bool?
}
struct DataConfiguration: Codable {
let time: Int?
let temp: Double
}
extension DataConfiguration {
var tempBaseOnUnit: Double {
if UserDataManager.shared.temperatureUnit == .C {
return temp
} else {
return temp.fahrenheitTemperature
}
}
}
extension Room {
init(json: [String: Any]) {
id = json["id"] as? String ?? ""
name = json["name"] as? String ?? ""
category = json["category"] as? String ?? ""
sensor = nil
heaters = []
battery = nil
originalTemperature = nil
enabled = nil
humidity = nil
setting = nil
}
}
<file_sep>//
// WifiSetupViewModel.swift
// Koleda
//
// Created by <NAME> on 7/4/19.
// Copyright © 2019 koleda. All rights reserved.
//
import Foundation
import RxSwift
import SVProgressHUD
protocol WifiSetupViewModelProtocol: BaseViewModelProtocol {
var showRetryButton: Variable<Bool> { get }
var disableCloseButton: PublishSubject<Bool> { get }
func checkWifiConnection()
func showWifiDetailScreen()
}
class WifiSetupViewModel: BaseViewModel, WifiSetupViewModelProtocol {
let router: BaseRouterProtocol
let showRetryButton = Variable<Bool>(false)
let disableCloseButton = PublishSubject<Bool>()
private let settingManager: SettingManager
init(router: BaseRouterProtocol, managerProvider: ManagerProvider = .sharedInstance ) {
self.router = router
self.settingManager = managerProvider.settingManager
super.init(managerProvider: managerProvider)
}
func checkWifiConnection() {
self.showRetryButton.value = false
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
let networkManager = NetworkManager()
if networkManager.Connection() && networkManager.isWifi() {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
self.showWifiDetailScreen()
}
} else {
self.showRetryButton.value = true
}
}
}
func showWifiDetailScreen() {
router.enqueueRoute(with: WifiSetupRouter.RouteType.wifiDetail)
}
}
<file_sep>//
// TabContentRouter.swift
// Koleda
//
// Created by <NAME> on 10/31/19.
// Copyright © 2019 koleda. All rights reserved.
//
import Foundation
import UIKit
class TabContentRouter: BaseRouterProtocol {
weak var baseViewController: UIViewController?
enum RouteType {
}
func dismiss(animated: Bool, context: Any?, completion: ((Bool) -> Void)?) {
}
func enqueueRoute(with context: Any?, animated: Bool, completion: ((Bool) -> Void)?) {
guard let routeType = context as? RouteType else {
assertionFailure("The route type missmatches")
return
}
guard let baseViewController = baseViewController else {
assertionFailure("baseViewController is not set")
return
}
}
func present(on baseVC: UIViewController, animated: Bool, context: Any?, completion: ((Bool) -> Void)?) {
}
}
<file_sep>
//
// SensorAnalyticsEvent.swift
// Koleda
//
// Created by <NAME> on 9/4/20.
// Copyright © 2020 koleda. All rights reserved.
//
import Foundation
import CopilotAPIAccess
struct AddSensorAnalyticsEvent: AnalyticsEvent {
private let sensorModel: String
private let roomId: String
private let homeId: String
private let screenName: String
init(sensorModel:String, roomId: String, homeId: String, screenName: String) {
self.sensorModel = sensorModel
self.roomId = roomId
self.homeId = homeId
self.screenName = screenName
}
var customParams: Dictionary<String, String> {
return ["sensorModel" : sensorModel,
"roomId" : roomId,
"homeId" : homeId,
"screenName": screenName]
}
var eventName: String {
return "add_sensor"
}
var eventOrigin: AnalyticsEventOrigin {
return .App
}
var eventGroups: [AnalyticsEventGroup] {
return [.All]
}
}
struct RemoveSensorAnalyticsEvent: AnalyticsEvent {
private let sensorId: String
private let screenName: String
init(sensorId:String, screenName: String) {
self.sensorId = sensorId
self.screenName = screenName
}
var customParams: Dictionary<String, String> {
return ["sensorId" : sensorId,
"screenName": screenName]
}
var eventName: String {
return "remove_sensor"
}
var eventOrigin: AnalyticsEventOrigin {
return .App
}
var eventGroups: [AnalyticsEventGroup] {
return [.All]
}
}
<file_sep>//
// HeatersManagementCollectionViewDataSource.swift
// Koleda
//
// Created by <NAME> on 9/5/19.
// Copyright © 2019 koleda. All rights reserved.
//
import UIKit
import Foundation
class HeatersManagementCollectionViewDataSource: NSObject, UICollectionViewDataSource {
var heaters: [Heater]?
var viewModel: HeatersManagementViewModelProtocol?
func numberOfSections(in collectionView: UICollectionView) -> Int {
return isEmpty(heaters) ? 1 : 2
}
func collectionView(_ collectionView: UICollectionView,
numberOfItemsInSection section: Int) -> Int {
if !isEmpty(heaters) && section == 0 {
return heaters!.count
} else {
return 1
}
}
func collectionView(_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if !isEmpty(heaters) && indexPath.section == 0 {
guard let cell = collectionView
.dequeueReusableCell(withReuseIdentifier: "HeaterManagementCollectionViewCell",
for: indexPath) as? HeaterManagementCollectionViewCell, let heaters = heaters else {
fatalError()
}
let heater = heaters[indexPath.row]
cell.setup(with: heater)
cell.removeHandler = { [weak self] heater in
guard let `self` = self else {
return
}
self.viewModel?.removeHeater(by: heater)
}
return cell
} else {
guard let cell = collectionView
.dequeueReusableCell(withReuseIdentifier: "AddHeaterManagementCollectionViewCell",
for: indexPath) as? AddHeaterManagementCollectionViewCell else {
fatalError()
}
cell.addButton.rx.tap.bind { [weak self] in
self?.viewModel?.addHeaterFlow()
}
cell.setup()
return cell
}
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "header", for: indexPath)
var title:UILabel? = headerView.viewWithTag(100) as? UILabel
if !isEmpty(heaters) && indexPath.section == 0 {
title?.text = "HEATERS_TEXT".app_localized
} else {
title?.text = "ADD_HEATERS_TEXT".app_localized
}
return headerView
}
}
<file_sep>//
// GuideTableViewCell.swift
// Koleda
//
// Created by <NAME> on 6/25/19.
// Copyright © 2019 koleda. All rights reserved.
//
import UIKit
class GuideTableViewCell: UITableViewCell {
@IBOutlet weak var guideImageView: UIImageView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var messageLabel: UILabel!
private var guideItem: GuideItem?
override func awakeFromNib() {
super.awakeFromNib()
}
func setup(with guideItem: GuideItem) {
guideImageView.image = guideItem.image
titleLabel.text = guideItem.title
messageLabel.text = guideItem.message
}
}
<file_sep>//
// HeaterCollectionReusableView.swift
// Koleda
//
// Created by <NAME> on 10/5/20.
// Copyright © 2020 koleda. All rights reserved.
//
import UIKit
class HeaterCollectionReusableView: UICollectionReusableView {
@IBOutlet weak var heaterTitleLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
heaterTitleLabel.text = "HEATERS_TEXT".app_localized
}
}
<file_sep>//
// ScheduleOfDayViewModel.swift
// Koleda
//
// Created by <NAME> on 10/25/19.
// Copyright © 2019 koleda. All rights reserved.
//
import Foundation
enum DayOfWeek: String, Codable {
case unknow
case MONDAY = "MONDAY"
case TUESDAY = "TUESDAY"
case WEDNESDAY = "WEDNESDAY"
case THURSDAY = "THURSDAY"
case FRIDAY = "FRIDAY"
case SATURDAY = "SATURDAY"
case SUNDAY = "SUNDAY"
init(fromString string: String) {
guard let value = DayOfWeek(rawValue: string) else {
self = .unknow
return
}
self = value
}
static var days: Int = 7
var titleOfDay: String {
switch self {
case .MONDAY:
return "MON_ABBR".app_localized
case .TUESDAY:
return "TUE_ABBR".app_localized
case .WEDNESDAY:
return "WED_ABBR".app_localized
case .THURSDAY:
return "THU_ABBR".app_localized
case .FRIDAY:
return "FRI_ABBR".app_localized
case .SATURDAY:
return "SAT_ABBR".app_localized
case .SUNDAY:
return "SUN_ABBR".app_localized
default:
return ""
}
}
static func dayWithIndex(index: Int) -> String {
switch index {
case 0:
return "Monday"
case 1:
return "Tuesday"
case 2:
return "Wednesday"
case 3:
return "Thursday"
case 4:
return "Friday"
case 5:
return "Saturday"
default:
return "Sunday"
}
}
}
enum RowType {
case Header
case Footer
case Detail
}
struct ScheduleRow {
let type: RowType
let icon: UIImage?
let title: String
let temperature: Double?
let temperatureUnit: String?
init(type: RowType, title: String, icon: UIImage?, temp: Double?, unit: String?) {
self.type = type
self.icon = icon
self.title = title
self.temperature = temp
self.temperatureUnit = unit
}
}
struct ScheduleBlock {
let color: UIColor
let scheduleRows: [ScheduleRow]
let rooms: [Room]
let targetTemperature: Double
init(color: UIColor, scheduleRows: [ScheduleRow], rooms: [Room], targetTemperature: Double) {
self.color = color
self.scheduleRows = scheduleRows
self.rooms = rooms
self.targetTemperature = targetTemperature
}
}
class ScheduleOfDayViewModel {
private (set) var scheduleOfDay: ScheduleOfDay?
var rowsMergeData: [(startIndex: Int, numberRows: Int)] = []
var startRowList: [Int] = []
var displayData: [Int : ScheduleBlock] = [:]
let currentTempUnit = UserDataManager.shared.temperatureUnit.rawValue
init(scheduleOfDay: ScheduleOfDay? = nil) {
guard let scheduleOfDay = scheduleOfDay else {
return
}
self.scheduleOfDay = scheduleOfDay
for scheduleOfTime in scheduleOfDay.details {
var detailRoomsPopover: [Room] = []
var dataOfScheduleRow: [ScheduleRow] = []
let smartMode = ModeItem.getModeItem(with: SmartMode(fromString: scheduleOfTime.mode))
let heaterRow = ScheduleRow(type: .Header, title: scheduleOfTime.mode, icon: smartMode?.icon , temp: smartMode?.temperature , unit: currentTempUnit)
dataOfScheduleRow.append(heaterRow)
//Get number of Row for this schedule
guard let startTime = scheduleOfTime.from.removeSecondOfTime().timeValue(), let endTime = scheduleOfTime.to.removeSecondOfTime().timeValue()?.correctLocalTimeFormat() else {
return
}
let startRow = (startTime.hour*60 + startTime.minute)/30
let rowsNeedMerge = ((endTime.hour*60 + endTime.minute) - (startTime.hour*60 + startTime.minute))/30
startRowList.append(startRow)
if rowsNeedMerge > 1 {
let roomsData = scheduleOfTime.rooms
rowsMergeData.append((startRow, rowsNeedMerge))
if roomsData.count <= rowsNeedMerge - 1 {
for room in roomsData {
let detailRow = ScheduleRow(type: .Detail, title: room.name, icon: nil, temp: room.temperature?.kld_doubleValue, unit: currentTempUnit)
dataOfScheduleRow.append(detailRow)
}
} else {
let numberOfRoomsCannotShow = roomsData.count - (rowsNeedMerge - 2)
let numberOfRoomsWillShow = roomsData.count - numberOfRoomsCannotShow
if numberOfRoomsWillShow > 0 {
for indexRow in 0..<numberOfRoomsWillShow {
let room = roomsData[indexRow]
let detailRow = ScheduleRow(type: .Detail, title: room.name, icon: nil, temp: room.temperature?.kld_doubleValue, unit: currentTempUnit)
dataOfScheduleRow.append(detailRow)
}
}
let roomsString = String(format: "NUMBER_ROOMS_CAN_NOT_SHOW_MESSAGE".app_localized, numberOfRoomsCannotShow)
let moreRoomsString = String(format: "MORE_ROOMS_CAN_NOT_SHOW_MESSAGE".app_localized, numberOfRoomsCannotShow)
let title = rowsNeedMerge == 2 ? roomsString : moreRoomsString
let footerRow = ScheduleRow(type: .Footer, title: title, icon: nil, temp: nil, unit: nil)
dataOfScheduleRow.append(footerRow)
detailRoomsPopover = scheduleOfTime.rooms
}
} else {
detailRoomsPopover = scheduleOfTime.rooms
}
let color: UIColor = smartMode?.color ?? UIColor.yellowLight
displayData[startRow] = ScheduleBlock(color: color, scheduleRows: dataOfScheduleRow, rooms: detailRoomsPopover, targetTemperature: smartMode?.temperature ?? 0)
}
}
}
<file_sep>//
// MenuSettingsRouter.swift
// Koleda
//
// Created by <NAME> on 9/9/19.
// Copyright © 2019 koleda. All rights reserved.
//
import Foundation
import UIKit
class MenuSettingsRouter: BaseRouterProtocol {
weak var baseViewController: UIViewController?
enum RouteType {
case backHome
case logOut
case roomsConfiguration
case addRoom
case smartScheduling
case updateTariff
case configuration(Room)
case wifiDetail
case modifyModes
case inviteFriendsDetail
case legal
}
func dismiss(animated: Bool, context: Any?, completion: ((Bool) -> Void)?) {
}
func enqueueRoute(with context: Any?, animated: Bool, completion: ((Bool) -> Void)?) {
guard let routeType = context as? RouteType else {
assertionFailure("The route type missmatches")
return
}
guard let baseViewController = baseViewController else {
assertionFailure("baseViewController is not set")
return
}
switch routeType {
case .backHome:
baseViewController.navigationController?.popToRootViewController(animated: false)
case .logOut:
let router = LoginRouter()
guard let viewController = StoryboardScene.Login.initialViewController() as? LoginViewController else { return }
let viewModel = LoginViewModel.init(router: router)
viewController.viewModel = viewModel
router.baseViewController = viewController
let navigationController = UINavigationController(rootViewController: viewController)
if let delegate = UIApplication.shared.delegate as? AppDelegate {
delegate.window?.rootViewController = navigationController
}
case .roomsConfiguration:
baseViewController.gotoBlock(withStoryboar: "Home", aClass: ListRoomViewController.self) { (vc) in
let router = HomeRouter()
let viewModel = HomeViewModel.init(router: router)
vc?.viewModel = viewModel
router.baseViewController = vc
}
case .addRoom:
let router = RoomDetailRouter()
let viewModel = RoomDetailViewModel.init(router: router)
guard let viewController = StoryboardScene.Room.instantiateRoomDetailViewController() as? RoomDetailViewController else {
return
}
viewController.viewModel = viewModel
router.baseViewController = viewController
baseViewController.navigationController?.pushViewController(viewController, animated: true)
case .smartScheduling:
let router = SmartSchedulingRouter()
let viewModel = SmartSchedulingViewModel.init(router: router)
guard let viewController = StoryboardScene.SmartSchedule.instantiateSmartSchedulingViewController() as? SmartSchedulingViewController else {
assertionFailure("Setup storyboard configured not properly")
return
}
viewController.viewModel = viewModel
router.baseViewController = viewController
baseViewController.navigationController?.pushViewController(viewController, animated: true)
case .updateTariff:
let router = EnergyTariffRouter()
let viewModel = EnergyTariffViewModel.init(router: router)
guard let energyTariffVC = StoryboardScene.Setup.instantiateEnergyTariffViewController() as? EnergyTariffViewController else {
assertionFailure("Setup storyboard configured not properly")
return
}
energyTariffVC.viewModel = viewModel
router.baseViewController = energyTariffVC
baseViewController.navigationController?.pushViewController(energyTariffVC, animated: true)
case .configuration(let selectedRoom):
let router = ConfigurationRoomRouter()
let viewModel = ConfigurationRoomViewModel.init(router: router, seletedRoom: selectedRoom)
guard let viewController = StoryboardScene.Home.instantiateConfigurationRoomViewController() as? ConfigurationRoomViewController else {
return
}
viewController.viewModel = viewModel
router.baseViewController = viewController
baseViewController.navigationController?.pushViewController(viewController, animated: true)
case .wifiDetail:
let router = WifiDetailRouter()
let viewModel = WifiDetailViewModel.init(router: router)
guard let wifiDetailVC = StoryboardScene.Setup.instantiateWifiDetailViewController() as? WifiDetailViewController else {
assertionFailure("Setup storyboard configured not properly")
return
}
wifiDetailVC.viewModel = viewModel
router.baseViewController = wifiDetailVC
baseViewController.navigationController?.pushViewController(wifiDetailVC, animated: true)
case .modifyModes:
let router = ModifyModesRouter()
let viewModel = ModifyModesViewModel.init(router: router)
guard let modifyModesVC = StoryboardScene.Setup.instantiateModifyModesViewController() as? ModifyModesViewController else {
assertionFailure("Setup storyboard configured not properly")
return
}
modifyModesVC.viewModel = viewModel
router.baseViewController = modifyModesVC
baseViewController.navigationController?.pushViewController(modifyModesVC, animated: true)
case .inviteFriendsDetail:
let router = InviteFriendsDetailRouter()
let viewModel = InviteFriendsDetailViewModel.init(router: router)
guard let viewController = StoryboardScene.Setup.instantiateInviteFriendsDetailViewController() as? InviteFriendsDetailViewController else {
assertionFailure("Setup storyboard configured not properly")
return
}
viewController.viewModel = viewModel
router.baseViewController = viewController
baseViewController.navigationController?.pushViewController(viewController, animated: true)
case .legal:
let router = LegalRouter()
let viewModel = LegalViewModel.init(router: router)
guard let viewController = StoryboardScene.Setup.instantiateLegalViewController() as? LegalViewController else {
assertionFailure("Setup storyboard configured not properly")
return
}
viewController.viewModel = viewModel
router.baseViewController = viewController
baseViewController.navigationController?.pushViewController(viewController, animated: true)
}
}
func present(on baseVC: UIViewController, animated: Bool, context: Any?, completion: ((Bool) -> Void)?) {
}
}
<file_sep>
//
// SmartScheduleDetailViewModel.swift
// Koleda
//
// Created by <NAME> on 10/31/19.
// Copyright © 2019 koleda. All rights reserved.
//
import Foundation
import RxSwift
import CopilotAPIAccess
protocol SmartScheduleDetailViewModelProtocol: BaseViewModelProtocol {
var timeslotTitle: Variable<String> { get }
var smartModes: Variable<[ModeItem]> { get }
var startTime: Variable<String> { get }
var endTime: Variable<String> { get }
var selectedRooms: Variable<[Room]> { get }
var selectedMode: Variable<ModeItem?> { get }
var showMessageError: PublishSubject<String> { get }
var hiddenDeleteButton: Variable<Bool> { get }
func didSelectMode(atIndex: Int)
func updateSchedules(completion: @escaping (Bool) -> Void)
func deleteSchedules(completion: @escaping (Bool) -> Void)
}
class SmartScheduleDetailViewModel: BaseViewModel, SmartScheduleDetailViewModelProtocol {
let router: BaseRouterProtocol
private let schedulesManager: SchedulesManager
let timeslotTitle = Variable<String>("")
let smartModes = Variable<[ModeItem]>([])
let startTime = Variable<String>("")
let endTime = Variable<String>("")
let selectedRooms = Variable<[Room]>([])
let selectedMode = Variable<ModeItem?>(ModeItem.getModeItem(with: .ECO))
var showMessageError = PublishSubject<String>()
let hiddenDeleteButton = Variable<Bool>(true)
private var dayOfWeek: String = ""
private var scheduleOfTimesWithoutEditingScheduleTime: [ScheduleOfTime] = []
private var scheduleOfTimesOfDay: [ScheduleOfTime] = []
private var tapedTimeline: Bool = false
init(router: BaseRouterProtocol, managerProvider: ManagerProvider = .sharedInstance, startTime: Time, dayOfWeek: DayOfWeek, tapedTimeline: Bool) {
self.router = router
schedulesManager = managerProvider.schedulesManager
super.init(managerProvider: managerProvider)
smartModes.value = UserDataManager.shared.settingModesWithoutDefaultMode()
self.dayOfWeek = dayOfWeek.rawValue ?? ""
self.tapedTimeline = tapedTimeline
loadView(startTime: startTime)
}
func didSelectMode(atIndex: Int) {
selectedMode.value = smartModes.value[atIndex]
}
func updateSchedules(completion: @escaping (Bool) -> Void) {
guard validateData() else {
completion(false)
return
}
guard let scheduleOfDay = createScheduleOfDay() else {
return
}
callServiceToUpdateSmartScheduleOfDay(scheduleOfDay: scheduleOfDay) { isSuccess in
completion(isSuccess)
}
}
func deleteSchedules(completion: @escaping (Bool) -> Void) {
let scheduleOfDay: ScheduleOfDay = ScheduleOfDay(dayOfWeek: dayOfWeek, details: scheduleOfTimesWithoutEditingScheduleTime)
callServiceToUpdateSmartScheduleOfDay(scheduleOfDay: scheduleOfDay) { isSuccess in
completion(isSuccess)
}
}
private func callServiceToUpdateSmartScheduleOfDay(scheduleOfDay: ScheduleOfDay, completion: @escaping (Bool) -> Void) {
schedulesManager.updateSmartSchedule(schedules: scheduleOfDay, success: {
Copilot.instance.report.log(event: SetSmartScheduleAnalyticsEvent(schedules: scheduleOfDay, screenName: self.screenName))
completion(true)
}) { error in
completion(false)
}
}
private func loadView(startTime: Time) {
guard let scheduleOfDay = UserDataManager.shared.smartScheduleData[dayOfWeek] else {
return
}
self.timeslotTitle.value = String(format:"%@ %@", dayOfWeek.getStringLocalizeDay().capitalizingFirstLetter(), "TIMESLOT_TEXT".app_localized)
if !tapedTimeline, let existScheduleOfTime = checkTimeHasScheduleOrNot(startTime: startTime.timeIntValue(), scheduleOfDay: scheduleOfDay) {
self.startTime.value = existScheduleOfTime.from.removeSecondOfTime()
self.endTime.value = existScheduleOfTime.to.correctLocalTimeStringFormatForDisplay.removeSecondOfTime()
selectedMode.value = ModeItem.getModeItem(with: SmartMode.init(fromString: existScheduleOfTime.mode))
selectedRooms.value = existScheduleOfTime.rooms
hiddenDeleteButton.value = false
scheduleOfTimesOfDay = scheduleOfTimesWithoutEditingScheduleTime
} else {
hiddenDeleteButton.value = true
self.startTime.value = startTime.timeString()
var endTimeSuggest = startTime.add(minutes: 60)
if startTime.hour == 23 && startTime.minute == 30 {
endTimeSuggest = startTime.add(minutes: 30)
} else if let existScheduleOfTime = checkTimeHasScheduleOrNot(startTime: endTimeSuggest.timeIntValue(), scheduleOfDay: scheduleOfDay), let starttimeOfExistBlock = existScheduleOfTime.from.intValueWithLocalTime, starttimeOfExistBlock < endTimeSuggest.timeIntValue() && startTime.timeIntValue() < starttimeOfExistBlock {
endTimeSuggest = startTime.add(minutes: 30)
}
self.endTime.value = endTimeSuggest.timeString()
scheduleOfTimesOfDay = scheduleOfDay.details
}
}
private func checkTimeHasScheduleOrNot(startTime: Int, scheduleOfDay: ScheduleOfDay) -> ScheduleOfTime? {
for detail in scheduleOfDay.details {
if let startOfDetail = detail.from.intValueWithLocalTime,
let endOfDetail = detail.to.intValueWithLocalTime,
startTime >= startOfDetail && startTime < endOfDetail {
// (startTime >= startOfDetail || (startOfDetail - startTime) < 30) && startTime < endOfDetail && (endOfDetail - startTime) >= 30
scheduleOfTimesWithoutEditingScheduleTime = scheduleOfDay.details.filter { $0.from != detail.from && $0.to != detail.to }
return detail
}
}
return nil
}
private func validateData() -> Bool {
if startTime.value.isEmpty {
showMessageError.onNext("START_TIMESLOT_IS_EMPTY_MESS".app_localized)
return false
}
if endTime.value.isEmpty {
showMessageError.onNext("END_TIMESLOT_IS_EMPTY_MESS".app_localized)
return false
}
guard let startIntValue = startTime.value.timeValue()?.timeIntValue(), let endIntValue = endTime.value.timeValue()?.timeIntValue() else {
showMessageError.onNext("INVALID_TIMESLOT_MESS")
return false
}
if startIntValue >= endIntValue && endIntValue != 0 {
showMessageError.onNext("END_TIMESLOT_MUST_BE_GREATER_MESS".app_localized)
return false
}
if selectedRooms.value.count == 0 {
showMessageError.onNext("PLEASE_CHOOSE_AT_LEAST_ONE_ROOM_MESS".app_localized)
return false
}
return true
}
private func createScheduleOfDay() -> ScheduleOfDay? {
guard let selectedMode = selectedMode.value else {
return nil
}
var roomIds: [String] = []
for room in selectedRooms.value {
roomIds.append(room.id)
}
let editingScheduleOfTime = ScheduleOfTime(from: startTime.value.kld_localTimeFormat(), to: endTime.value.kld_localTimeFormat(), mode: selectedMode.mode.rawValue, roomIds: roomIds)
guard let scheduleOfDay = UserDataManager.shared.smartScheduleData[dayOfWeek] else {
return ScheduleOfDay(dayOfWeek: dayOfWeek, details: [editingScheduleOfTime])
}
var newDetailsSchedulesOfDay: [ScheduleOfTime] = []
for detail in scheduleOfTimesOfDay {
guard let startOfDetail = detail.from.removeSecondOfTime().timeValue(), let endOfDetail = detail.to.removeSecondOfTime().timeValue() else {
return nil
}
let scheduleOfTimeAfterSplit = checkToSplitSchedule(start: startOfDetail.timeIntValue(), end: endOfDetail.timeIntValue(), oldSchedule: detail)
newDetailsSchedulesOfDay.append(contentsOf: scheduleOfTimeAfterSplit)
}
newDetailsSchedulesOfDay.append(editingScheduleOfTime)
return ScheduleOfDay(dayOfWeek: dayOfWeek, details: newDetailsSchedulesOfDay)
}
private func checkToSplitSchedule(start: Int, end: Int, oldSchedule: ScheduleOfTime) -> [ScheduleOfTime] {
guard let startTimeValue = startTime.value.timeValue(), let endTimeValue = endTime.value.timeValue() else {
return []
}
let editingStart: Int = startTimeValue.timeIntValue()
let editingEnd: Int = endTimeValue.timeIntValue()
var scheduleOfTimes: [ScheduleOfTime] = []
if start < editingStart {
if end <= editingStart {
scheduleOfTimes.append(oldSchedule)
} else if end > editingStart && end <= editingEnd{
scheduleOfTimes.append(ScheduleOfTime(from: start.fullTimeWithHourAndMinuteFormat(), to: editingStart.fullTimeWithHourAndMinuteFormat(), mode: oldSchedule.mode, roomIds: oldSchedule.roomIds))
} else if end > editingEnd {
scheduleOfTimes.append(ScheduleOfTime(from: start.fullTimeWithHourAndMinuteFormat(), to: editingStart.fullTimeWithHourAndMinuteFormat(), mode: oldSchedule.mode, roomIds: oldSchedule.roomIds))
scheduleOfTimes.append(ScheduleOfTime(from: editingEnd.fullTimeWithHourAndMinuteFormat(), to: end.fullTimeWithHourAndMinuteFormat(), mode: oldSchedule.mode, roomIds: oldSchedule.roomIds))
}
} else if start >= editingStart && start < editingEnd && end > editingEnd {
scheduleOfTimes.append(ScheduleOfTime(from: editingEnd.fullTimeWithHourAndMinuteFormat(), to: end.fullTimeWithHourAndMinuteFormat(), mode: oldSchedule.mode, roomIds: oldSchedule.roomIds))
} else if start >= editingEnd && end >= editingEnd {
scheduleOfTimes.append(oldSchedule)
}
return scheduleOfTimes
}
}
<file_sep>//
// WifiSetupViewController.swift
// Koleda
//
// Created by <NAME> on 7/4/19.
// Copyright © 2019 koleda. All rights reserved.
//
import UIKit
import RxSwift
class WifiSetupViewController: BaseViewController, BaseControllerProtocol {
@IBOutlet weak var wifiImageView: UIImageView!
@IBOutlet weak var retryButton: UIButton!
@IBOutlet weak var skipButton: UIButton!
@IBOutlet weak var buttomsStackView: UIStackView!
@IBOutlet weak var checkingView: UIView!
@IBOutlet weak var noConnectView: UIView!
@IBOutlet weak var wifiConnectionLabel: UILabel!
@IBOutlet weak var loadingLabel: UILabel!
@IBOutlet weak var retryLabel: UILabel!
@IBOutlet weak var skipAndContinueLabel: UILabel!
var viewModel: WifiSetupViewModelProtocol!
private let disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
viewModel.showRetryButton.asObservable().subscribe(onNext: { [weak self] show in
self?.wifiImageView.image = UIImage(named: show ? "ic-not-connected-wifi" : "ic-checking-wifi")
self?.buttomsStackView.isHidden = !show
self?.checkingView.isHidden = show
self?.noConnectView.isHidden = !show
}).disposed(by: disposeBag)
retryButton.rx.tap.bind { [weak self] _ in
self?.viewModel.checkWifiConnection()
}.disposed(by: disposeBag)
skipButton.rx.tap.bind { [weak self] _ in
self?.viewModel.showWifiDetailScreen()
}.disposed(by: disposeBag)
viewModel.disableCloseButton.asObservable().subscribe(onNext: { [weak self] disable in
self?.closeButton?.isEnabled = !disable
}).disposed(by: disposeBag)
wifiConnectionLabel.text = "WIFI_CONNECTION_TEXT".app_localized
loadingLabel.text = "CHECKING_WIFI_CONNECTION_MESS".app_localized
retryLabel.text = "RETRY_TEXT".app_localized
skipAndContinueLabel.text = "SKIP_AND_CONTINUE_TEXT".app_localized
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(true, animated: animated)
navigationBarTransparency()
setTitleScreen(with: "")
statusBarStyle(with: .lightContent)
}
@IBAction func backAction(_ sender: Any) {
closeCurrentScreen()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
viewModel.checkWifiConnection()
}
}
<file_sep>//
// ModifyModesRouter.swift
// Koleda
//
// Created by <NAME> on 2/3/20.
// Copyright © 2020 koleda. All rights reserved.
//
import Foundation
import UIKit
class ModifyModesRouter: BaseRouterProtocol {
weak var baseViewController: UIViewController?
enum RouteType {
case detailMode(ModeItem)
}
func dismiss(animated: Bool, context: Any?, completion: ((Bool) -> Void)?) {
}
func enqueueRoute(with context: Any?, animated: Bool, completion: ((Bool) -> Void)?) {
guard let routeType = context as? RouteType else {
assertionFailure("The route type missmatches")
return
}
guard let baseViewController = baseViewController else {
assertionFailure("baseViewController is not set")
return
}
switch routeType {
case .detailMode(let selectedMode):
let router = DetailModeRouter()
let viewModel = DetailModeViewModel.init(router: router, selectedMode: selectedMode)
guard let detailModeVC = StoryboardScene.Setup.instantiateDetailModeViewController() as? DetailModeViewController else {
assertionFailure("Setup storyboard configured not properly")
return
}
detailModeVC.viewModel = viewModel
router.baseViewController = detailModeVC
baseViewController.navigationController?.pushViewController(detailModeVC, animated: true)
}
}
func present(on baseVC: UIViewController, animated: Bool, context: Any?, completion: ((Bool) -> Void)?) {
}
}
<file_sep>
//
// HeatersManagementViewModel.swift
// Koleda
//
// Created by <NAME> on 9/4/19.
// Copyright © 2019 koleda. All rights reserved.
//
import Foundation
import RxSwift
import CopilotAPIAccess
protocol HeatersManagementViewModelProtocol: BaseViewModelProtocol {
var pairedWithHeatersTitle: Variable<String> { get }
var heaters: Variable<[Heater]> { get }
var showDeleteConfirmMessage: PublishSubject<Bool> { get }
var removingHeaterName: String? { get }
func viewWillAppear()
func updatePairedWithHeatersTitle(heaters: [Heater])
func removeHeater(by heater: Heater)
func callServiceDeleteHeater(completion: @escaping (Bool) -> Void)
func doneAction()
func addHeaterFlow()
func needUpdateSelectedRoom()
}
class HeatersManagementViewModel: BaseViewModel, HeatersManagementViewModelProtocol {
let router: BaseRouterProtocol
let pairedWithHeatersTitle = Variable<String>("")
let heaters = Variable<[Heater]>([])
let showDeleteConfirmMessage = PublishSubject<Bool>()
private let shellyDeviceManager: ShellyDeviceManager
private var selectedRoom: Room
private var removingHeaterId: String?
var removingHeaterName: String?
init(router: BaseRouterProtocol, managerProvider: ManagerProvider = .sharedInstance, selectedRoom: Room) {
self.router = router
self.shellyDeviceManager = managerProvider.shellyDeviceManager
self.selectedRoom = selectedRoom
super.init(managerProvider: managerProvider)
}
func viewWillAppear() {
let roomViewModel = RoomViewModel.init(room: selectedRoom)
if let heaters = roomViewModel.heaters, heaters.count > 0 {
updatePairedWithHeatersTitle(heaters: heaters)
} else {
updatePairedWithHeatersTitle(heaters: [])
}
}
func updatePairedWithHeatersTitle(heaters: [Heater]) {
self.heaters.value = heaters
if heaters.count > 0 {
pairedWithHeatersTitle.value = String(format: "SENSOR_IS_PAIRED_WITH_HEATERS_MESS".app_localized, selectedRoom.name)
} else {
pairedWithHeatersTitle.value = String(format: "SENSOR_IS_NOT_PAIRED_ANY_HEATER_MESS".app_localized, selectedRoom.name)
}
}
func removeHeater(by heater: Heater) {
removingHeaterId = heater.id
removingHeaterName = heater.name
showDeleteConfirmMessage.onNext(true)
}
func callServiceDeleteHeater(completion: @escaping (Bool) -> Void) {
guard let heaterId = removingHeaterId else {
return
}
shellyDeviceManager.deleteDevice(roomId: selectedRoom.id, deviceId: heaterId, success: { [weak self] in
guard var allHeaters = self?.heaters.value, allHeaters.count > 0 else {
completion(true)
return
}
guard let `self` = self else {
return
}
allHeaters.removeAll { $0.id == heaterId }
self.updatePairedWithHeatersTitle(heaters: allHeaters)
Copilot.instance.report.log(event: RemoveHeaterAnalyticsEvent(heaterId: heaterId, screenName: self.screenName))
completion(true)
},failure: { error in
completion(false)
})
}
func doneAction() {
router.enqueueRoute(with: HeatersManagementRouter.RouteType.done)
}
func addHeaterFlow() {
router.enqueueRoute(with: HeatersManagementRouter.RouteType.addHeaterFlow(self.selectedRoom.id, self.selectedRoom.name))
}
func needUpdateSelectedRoom() {
let room = UserDataManager.shared.roomWith(roomId: selectedRoom.id)
guard let updatedRoom = room else {
return
}
selectedRoom = updatedRoom
viewWillAppear()
}
}
<file_sep>//
// GuideViewController.swift
// Koleda
//
// Created by <NAME> on 6/25/19.
// Copyright © 2019 koleda. All rights reserved.
//
import UIKit
import RxSwift
class GuideViewController: BaseViewController, BaseControllerProtocol {
var viewModel: GuideViewModelProtocol!
private let disposeBag = DisposeBag()
@IBOutlet weak var pageControl: UIPageControl!
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var nextButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
Style.Button.primary.apply(to: nextButton)
viewModel.guideItems.asObservable().subscribe(onNext: { [weak self] guideItems in
guard guideItems.count > 0, let guideCollectionViewDataSource = self?.collectionView.dataSource as? GuideCollectionViewDataSource else { return }
guideCollectionViewDataSource.guideItems = guideItems
self?.pageControl.numberOfPages = guideItems.count
self?.collectionView.reloadData()
}).disposed(by: disposeBag)
collectionView.isPagingEnabled = true
nextButton.rx.tap.bind { [weak self] in
self?.viewModel.next()
}.disposed(by: disposeBag)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
viewModel.viewWillAppear()
navigationController?.setNavigationBarHidden(false, animated: animated)
addCloseFunctionality()
}
}
extension GuideViewController : UIScrollViewDelegate {
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if scrollView == collectionView {
let witdh = scrollView.frame.width - (scrollView.contentInset.left*2)
let index = scrollView.contentOffset.x / witdh
let roundedIndex = round(index)
self.pageControl?.currentPage = Int(roundedIndex)
}
}
}
extension GuideViewController : UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath) -> CGSize {
return collectionView.frame.size
}
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
insetForSectionAt section: Int) -> UIEdgeInsets {
return .zero
}
}
<file_sep>//
// EnergyTariffInputViewController.swift
// Koleda
//
// Created by <NAME> on 9/11/19.
// Copyright © 2019 koleda. All rights reserved.
//
import UIKit
enum TypeInput: Int {
case amountPerHourDay = 0
case dayStartTime = 1
case dayEndTime = 2
case amountPerHourNight = 3
case nightStartTime = 4
case nightEndTime = 5
case scheduleStartTime = 6
case scheduleEndTime = 7
}
protocol ScheduleTimeInputDelegate {
func selectedTime(start: String, end: String)
}
protocol EnergyTariffInputDelegate {
func selectedAmountPerHour(isDay: Bool, amount: Double, currencyUnit: String)
func selectedTime(isDay: Bool, startTime: String, endTime: String)
}
class EnergyTariffInputViewController: UIViewController {
var delegate: EnergyTariffInputDelegate?
var scheduleTimeInputDelegate: ScheduleTimeInputDelegate?
@IBOutlet weak var amountPerHourDayPricerView: UIPickerView!
@IBOutlet weak var titleAmountPerHourView: UIView!
@IBOutlet weak var titleTimeView: UIView!
@IBOutlet weak var titleTimeLabel: UILabel!
@IBOutlet weak var amountPerHourView: UIView!
@IBOutlet weak var timePickerView: UIDatePicker!
@IBOutlet weak var startButton: UIButton!
@IBOutlet weak var endButton: UIButton!
@IBOutlet weak var pricePerLabel: UILabel!
@IBOutlet weak var confirmLabel: UILabel!
@IBOutlet weak var cancelLabel: UILabel!
let currencyUnits:[String] = ["CHF", "EUR", "GBP", "USD", "AUD", "CAD"]
var typeInput: TypeInput = .amountPerHourDay
var amountPerHour: Double = 0
var currencyUnit: String = ""
var startTime: Date?
var endTime: Date?
override func viewDidLoad() {
super.viewDidLoad()
initView()
}
func initView() {
titleAmountPerHourView.isHidden = true
titleTimeView.isHidden = true
amountPerHourView.isHidden = true
timePickerView.isHidden = true
if typeInput == .amountPerHourDay || typeInput == .amountPerHourNight {
titleAmountPerHourView.isHidden = false
amountPerHourView.isHidden = false
let index1 = Int(amountPerHour)
let index2 = Int(amountPerHour * 100) % 100
let index3 = currencyUnits.lastIndex(of: currencyUnit) ?? 0
amountPerHourDayPricerView.selectRow(index1, inComponent: 0, animated: true)
amountPerHourDayPricerView.selectRow(index2, inComponent: 2, animated: true)
amountPerHourDayPricerView.selectRow(index3, inComponent: 3, animated: true)
} else {
titleTimeView.isHidden = false
timePickerView.isHidden = false
let isStart: Bool = [.dayStartTime, .nightStartTime, .scheduleStartTime].contains(typeInput)
startButton.isSelected = isStart
endButton.isSelected = !isStart
startButton.isHidden = !isStart
endButton.isHidden = isStart
let startTime: Date = self.startTime ?? Date.init()
let endTime: Date = self.endTime ?? Date.init()
if [.scheduleStartTime, .scheduleEndTime].contains(typeInput) {
timePickerView.minuteInterval = 30
titleTimeLabel.text = "TIMESLOT_TEXT".app_localized
} else {
timePickerView.minuteInterval = 1
let isDayTime: Bool = [.dayStartTime, .dayEndTime].contains(typeInput)
titleTimeLabel.text = isDayTime ? "DAYTIME_TEXT".app_localized : "NIGHTTIME_TEXT".app_localized
}
if isStart {
timePickerView.setDate(startTime, animated: true)
} else {
timePickerView.setDate(endTime, animated: true)
}
}
pricePerLabel.text = "PRICE_FER_KWH".app_localized
startButton.setTitle("START_TEXT".app_localized, for: .normal)
endButton.setTitle("END_TEXT".app_localized, for: .normal)
confirmLabel.text = "CONFIRM_TEXT".app_localized
cancelLabel.text = "CANCEL".app_localized
}
@IBAction func confirmAction(_ sender: Any) {
var startTimeString = ""
if let startTime = self.startTime {
startTimeString = startTime.toString(format: Date.fm_HHmm)
} else if startButton.isSelected {
startTimeString = Date.init().toString(format: Date.fm_HHmm)
}
var endTimeString = ""
if let endTime = self.endTime {
endTimeString = endTime.toString(format: Date.fm_HHmm)
} else if endButton.isSelected {
endTimeString = Date.init().toString(format: Date.fm_HHmm)
}
if [.scheduleStartTime, .scheduleEndTime].contains(typeInput) {
scheduleTimeInputDelegate?.selectedTime(start: startTimeString, end: endTimeString)
back()
} else {
if typeInput == .amountPerHourDay || typeInput == .amountPerHourNight {
let index1 = amountPerHourDayPricerView.selectedRow(inComponent: 0)
let index2 = amountPerHourDayPricerView.selectedRow(inComponent: 2)
let index3 = amountPerHourDayPricerView.selectedRow(inComponent: 3)
let amount = Double(index1) + Double(index2) * 0.01
delegate?.selectedAmountPerHour(isDay: typeInput == .amountPerHourDay, amount: amount, currencyUnit: currencyUnits[index3])
} else if [.dayStartTime, .dayEndTime].contains(typeInput) {
delegate?.selectedTime(isDay: true, startTime: startTimeString, endTime: endTimeString)
} else if [.nightStartTime, .nightEndTime].contains(typeInput) {
delegate?.selectedTime(isDay: false, startTime: startTimeString, endTime: endTimeString)
}
back()
}
}
@IBAction func selectedStartTimeAction(_ sender: Any) {
startButton.isSelected = true
endButton.isSelected = false
timePickerView.setDate(startTime ?? Date.init(), animated: true)
}
@IBAction func selectedEndTimeAction(_ sender: Any) {
startButton.isSelected = false
endButton.isSelected = true
timePickerView.setDate(endTime ?? Date.init(), animated: true)
}
@IBAction func cancelAction(_ sender: Any) {
back()
}
@IBAction func editedTimePicker(_ sender: UIDatePicker) {
if startButton.isSelected == true {
startTime = sender.date
} else {
endTime = sender.date
}
}
}
extension EnergyTariffInputViewController: UIPickerViewDataSource, UIPickerViewDelegate {
func numberOfComponents(in pickerView: UIPickerView) -> Int {
if pickerView == amountPerHourDayPricerView {
return 4
} else {
return 1
}
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if pickerView == amountPerHourDayPricerView {
if component == 0 {
return 2
} else if component == 1 {
return 1
} else if component == 2 {
return 100
} else if component == 3 {
return currencyUnits.count
}
}
return 0
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if pickerView == amountPerHourDayPricerView {
if component == 0 {
return String(format: "%01d", row)
} else if component == 1 {
return "."
} else if component == 2 {
return String(format: "%02d", row)
} else if component == 3 {
return currencyUnits[row]
}
}
return ""
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
}
}
<file_sep>//
// HomeViewController.swift
// Koleda
//
// Created by <NAME> on 6/27/19.
// Copyright © 2019 koleda. All rights reserved.
//
import UIKit
import RxSwift
import SwiftRichString
import SVProgressHUD
import CopilotAPIAccess
class HomeViewController: BaseViewController, BaseControllerProtocol {
var viewModel: HomeViewModelProtocol!
@IBOutlet weak var addARoomButton: UIButton!
@IBOutlet weak var settingButton: UIButton!
private let disposeBag = DisposeBag()
private var refreshControl: UIRefreshControl?
@IBOutlet weak var homeInitialView: UIView!
@IBOutlet weak var userHomeTitle: UILabel!
@IBOutlet weak var roomsTableView: UITableView!
@IBOutlet weak var descriptionTitleLabel: UILabel!
@IBOutlet weak var addRoomLabel: UILabel!
@IBOutlet weak var letsGetStartLabel: UILabel!
@IBOutlet weak var addTheFirstRoomLabel: UILabel!
@IBOutlet var roomsTableViewDataSource: RoomsTableViewDataSource!
override func viewDidLoad() {
super.viewDidLoad()
configurationUI()
addRefreshControl()
}
private func addRefreshControl() {
refreshControl = UIRefreshControl()
refreshControl?.tintColor = UIColor.gray
refreshControl?.addTarget(self, action: #selector(refreshList), for: .valueChanged)
roomsTableView.addSubview(refreshControl!)
}
@objc private func refreshList() {
viewModel.refreshListRooms()
refreshControl?.endRefreshing()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(true, animated: animated)
refreshList()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
}
extension HomeViewController {
@objc private func refreshListRooms(_ notification: NSNotification) {
viewModel.refreshListRooms()
}
@objc private func didChangeWifi() {
guard self.navigationController?.top is HomeViewController else {
return
}
viewModel.refreshListRooms()
guard let userName = UserDataManager.shared.currentUser?.name else {
viewModel.getCurrentUser()
return
}
}
@objc private func refreshTempModes(_ notification: NSNotification) {
viewModel.refreshSettingModes()
}
private func configurationUI() {
NotificationCenter.default.addObserver(self, selector: #selector(refreshListRooms),
name: .KLDDidChangeRooms, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(didChangeWifi),
name: .KLDDidChangeWifi, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(refreshTempModes),
name: .KLDDidUpdateTemperatureModes, object: nil)
settingButton.rx.tap.bind { [weak self] _ in
Copilot.instance.report.log(event: TapMenuItemAnalyticsEvent(menuItem: "Settings"))
self?.viewModel.showMenuSettings()
}.disposed(by: disposeBag)
addARoomButton.rx.tap.bind { [weak self] _ in
self?.viewModel.addRoom()
}.disposed(by: disposeBag)
viewModel.homeTitle.asObservable().bind { [weak self] title in
let normal = SwiftRichString.Style{
$0.font = UIFont.app_FuturaPTLight(ofSize: 32)
$0.color = UIColor.hex1F1B15
}
let bold = SwiftRichString.Style {
$0.font = UIFont.app_FuturaPTDemi(ofSize: 32)
$0.color = UIColor.hex1F1B15
}
let group = StyleGroup(base: normal, ["h1": bold])
self?.userHomeTitle?.attributedText = title.set(style: group)
}.disposed(by: disposeBag)
viewModel.rooms.asObservable().subscribe(onNext: { [weak self] rooms in
if rooms.count > 0 {
self?.roomsTableView.isHidden = false
self?.homeInitialView.isHidden = true
self?.roomsTableViewDataSource.rooms = rooms
self?.roomsTableViewDataSource.viewModel = self?.viewModel
self?.roomsTableView.dataSource = self?.roomsTableViewDataSource
self?.roomsTableView.delegate = self
self?.roomsTableView.reloadData()
} else {
self?.roomsTableView.isHidden = true
self?.homeInitialView.isHidden = false
}
}).disposed(by: disposeBag)
viewModel.mustLogOutApp.asObservable().subscribe(onNext: { [weak self] errorMessage in
self?.app_showInfoAlert(errorMessage, title: "KOLEDA_TEXT".app_localized, completion: {
self?.viewModel.logOut()
})
}).disposed(by: disposeBag)
descriptionTitleLabel.text = "THIS_IS_YOUR_DASHBOARD".app_localized
letsGetStartLabel.text = "LETS_GET_STARTED_SETTING_UP_YOUR_SOLUS".app_localized
addTheFirstRoomLabel.text = "ADD_THE_FIRST_ROOM_MESS".app_localized
addRoomLabel.text = "ADD_A_ROOM_TEXT".app_localized
}
}
extension HomeViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 205
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
viewModel.selectedRoom(at: indexPath)
}
}
<file_sep>//
// WSError.swift
// Koleda
//
// Created by <NAME> on 7/2/19.
// Copyright © 2019 koleda. All rights reserved.
//
import Foundation
import SwiftyJSON
enum GenericError: Error {
case error(String)
}
extension GenericError {
init(_ string: String) {
self = .error(string)
}
}
enum WSError: Error, LocalizedError {
case empty
case general
case loginSessionExpired
case locationServicesUnavailable
case failedToParseJsonData
case failedUpdateRoom
case failedAddRoom
case deviceExisted
case emailExisted
case emailNotExisted
case failedAddHome
case hiddenAppleEmail
case emailNotAvailable
case homeIDInvalid
case emailNotInvited
case emailInvalid
case emailSimilar
case emailGuest
case emailMaster
case userNotFound
var errorDescription: String? {
guard let description = localizedErrors[self] else {
return "ERROR_TITLE".app_localized
}
return description
}
}
extension WSError {
init?(responseData: Data?) {
guard let data = responseData else {
return nil
}
guard let json = try? JSON(data: data), let errorCode = json["errorCode"].string, let error = WSError(JSONValue: errorCode) else {
let jsonString = String(data: data, encoding: .utf8) ?? ""
log.info("Can't construct WSError from JSON: \(jsonString))")
return nil
}
self = error
}
static func error(from responseData: Data?, defaultError: WSError) -> WSError {
return WSError(responseData: responseData) ?? defaultError
}
}
extension WSError {
init?(JSONValue rawValue: String) {
switch rawValue {
case "BAD_REQUEST":
self = .empty
case "DEVICE_EXISTED":
self = .deviceExisted
case "EMAIL_NOT_EXISTED":
self = .emailNotExisted
case "HIDDEN_APPLE_EMAIL":
self = .hiddenAppleEmail
case "EMAIL_EXISTED":
self = .emailNotAvailable
case "HOME_ID_INVALID", "HOME_NOT_CREATED":
self = .homeIDInvalid
case "EMAIL_IS_NOT_INVITED":
self = .emailNotInvited
case "EMAIL_INVALID":
self = .emailInvalid
case "EMAIL_SIMILAR":
self = .emailSimilar
case "EMAIL_MASTER":
self = .emailMaster
case "EMAIL_GUEST":
self = .emailGuest
default:
return nil
}
}
static func error(fromJSONValue rawValue: String, defaultError: WSError) -> WSError {
return WSError(JSONValue: rawValue) ?? defaultError
}
}
private extension WSError {
var localizedErrors: [WSError : String] {
return [.empty: "PLACEHOLDER_ERROR_MESSAGE".app_localized,
.general: "ERROR_GENERAL".app_localized,
.loginSessionExpired: "LOGIN_SESSSION_EXPIRED".app_localized,
.failedUpdateRoom : "FAILED_TO_UPDATE_ROOM".app_localized,
.deviceExisted : "DEVICE_EXISTED_MESSAGE".app_localized,
.emailExisted: "EMAIL_EXISTED_MESSAGE".app_localized,
.emailNotExisted: "EMAIL_NOT_EXISTED_MESSAGE".app_localized,
.hiddenAppleEmail: "SHARE_APPLE_EMAIL_REQUIRED_MESSAGE".app_localized,
.emailNotAvailable: "EMAIL_NOT_AVAILABLE_MESSAGE".app_localized,
.homeIDInvalid: "HOME_ID_INVALID_MESSAGE".app_localized,
.emailNotInvited: "EMAIL_IS_NOT_INVITED_MESSAGE".app_localized,
.emailInvalid: "EMAIL_INVALID_MESSAGE".app_localized,
.emailSimilar: "EMAIL_SIMILAR_MESSAGE".app_localized,
.emailMaster: "EMAIL_MASTER_MESSAGE".app_localized,
.emailGuest: "EMAIL_GUEST_MESSAGE".app_localized,
.userNotFound: "USER_NOT_FOUND_MESSAGE".app_localized ]
}
}
<file_sep>//
// Date+Extensions.swift
// Koleda
//
// Created by <NAME> on 8/29/19.
// Copyright © 2019 koleda. All rights reserved.
//
import Foundation
extension Date {
public static var fm_hhmma = "hh:mm a"
public static var fm_HHmm = "HH:mm"
// returns an integer from 1 - 7, with 1 being Sunday and 7 being Saturday
func dayNumberOfWeek() -> Int {
guard let dayNumber = Calendar.current.dateComponents([.weekday], from: self).weekday else {
return 0
}
return dayNumber == 1 ? 6 : (dayNumber - 2)
}
func fomartAMOrPm() -> String {
let formatter = DateFormatter()
formatter.dateFormat = "hh:mm:ss a"
return formatter.string(from: self)
}
func adding(seconds: Int) -> Date {
guard let newTime = Calendar.current.date(byAdding: .second, value: seconds, to: self) else {
return Date()
}
return newTime
}
public init(str: String, format: String) {
let fmt = DateFormatter()
fmt.dateFormat = format
fmt.timeZone = TimeZone.current
fmt.locale = Locale(identifier: "en_US_POSIX")
if let date = fmt.date(from: str) {
self.init(timeInterval: 0, since: date)
} else {
self.init(timeInterval: 0, since: Date())
}
}
public func toString(format: String) -> String {
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone.current
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = format
return dateFormatter.string(from: self)
}
}
<file_sep>//
// RefreshToken.swift
// Koleda
//
// Created by <NAME> on 7/3/19.
// Copyright © 2019 koleda. All rights reserved.
//
import Foundation
import Locksmith
struct RefreshToken {
static func store(_ token: String) throws {
// Deletion needed for the case when a refresh token with different accessible option is already present in the
// keychain. In that case updating it fails with a duplication error.
try? delete()
try Locksmith.app_updateData(data: ["refreshToken": token],
forUserAccount: userAccountKey,
inService: keychainService,
accessibleOption: .alwaysThisDeviceOnly)
log.info("Stored refresh token")
}
static func restore() -> String? {
if let tokenInfo = Locksmith.loadDataForUserAccount(userAccount: userAccountKey, inService: keychainService) {
log.info("Retrieved refresh token info")
return tokenInfo["refreshToken"] as? String
} else {
log.error("Can't retrieve refresh token")
return nil
}
}
static func isStored() -> Bool {
return restore() != nil
}
static func delete() throws {
do {
try Locksmith.deleteDataForUserAccount(userAccount: userAccountKey, inService: keychainService)
log.info("Deleted refresh token")
} catch LocksmithError.notFound {
log.debug("Item to be deleted is not present in keychain")
}
}
// MARK: - Implementation
private static let userAccountKey = "user.current.account"
private static let keychainService = "com.koleda.refreshToken"
}
<file_sep>//
// PassthroughView.swift
//
// Created by <NAME> on 4/6/18.
//
import UIKit
class PassthroughView: UIView {
override public func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
if let view = super.hitTest(point, with: event), view != self {
return view
}
return nil
}
}
class PassthroughWindow: UIWindow {
override public func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
if let view = super.hitTest(point, with: event), view != self {
return view
}
return nil
}
}
<file_sep>//
// Styles.swift
// Koleda
//
// Created by <NAME> on 5/24/19.
// Copyright © 2019 koleda. All rights reserved.
//
import UIKit
struct Style {
struct ViewStyle<T> {
let styling: (T) -> Void
func apply(to view: T) {
styling(view)
}
static func compose(_ styles: [ViewStyle<T>]) -> ViewStyle<T> {
return ViewStyle { view in
for style in styles {
style.styling(view)
}
}
}
static func compose(styles: [ViewStyle<T>],
styling: @escaping (T) -> Void) -> ViewStyle<T>
{
var allStyles = styles
allStyles.append(ViewStyle(styling: styling))
return compose(allStyles)
}
static func compose(_ styles: ViewStyle<T>...) -> ViewStyle<T> {
return compose(styles)
}
static func compose(_ styles: ViewStyle<T>...,
stylingClosure: @escaping (T) -> Void) -> ViewStyle<T>
{
var allStyles = styles
allStyles.append(ViewStyle(styling: stylingClosure))
return compose(allStyles)
}
}
struct Color {
static let white = UIColor.white
static let black = UIColor.black
static let bgDarkButtonColor = UIColor.init(r: 31, g: 27, b: 21, alpha: 1)
static let denimBlue = UIColor.init(r: 65, g: 93, b: 150, alpha: 1)
static let textGrey = UIColor.init(r: 84, g: 84, b: 84, alpha: 1)
static let textLightGrey = UIColor.init(r: 109, g: 114, b: 120, alpha: 1)
static let borderViewColor = UIColor.init(r: 209, g: 209, b: 209, alpha: 1)
static let menuSettingsBackground = UIColor.init(red: 0.9, green: 0.9, blue: 0.9, alpha: 1)
}
fileprivate struct Size {
static let standardButtonHeight: CGFloat = 57
static let socialButtonHeight: CGFloat = 40
}
fileprivate struct CornerRadius {
static let standardButton: CGFloat = 4
}
fileprivate struct BorderWidth {
static let standardButton: CGFloat = 1
}
fileprivate struct Image {
static var closeLightBackground: UIImage {
return #imageLiteral(resourceName: "closeLightGrey")
}
}
struct Button {
private static let light = ViewStyle<UIButton> { button in
button.backgroundColor = Color.white
button.tintColor = Color.black
button.titleLabel?.textColor = Color.black
button.layer.borderWidth = BorderWidth.standardButton
button.layer.borderColor = Color.black.cgColor
}
private static let dark = ViewStyle<UIButton> { button in
button.backgroundColor = Color.black
button.tintColor = Color.white
button.titleLabel?.textColor = Color.white
}
static let primary = ViewStyle.compose(rounded(height: Size.standardButtonHeight)) { button in
button.setTitleColor(Color.white, for: .normal)
button.titleLabel?.font = UIFont.app_FuturaPTMedium(ofSize: 16)
button.backgroundColor = Color.bgDarkButtonColor
}
static let secondaryWithBorder = ViewStyle.compose(rounded(height: Size.standardButtonHeight)) { button in
button.setTitleColor(Color.textGrey, for: .normal)
button.titleLabel?.font = UIFont.app_FuturaPTDemi(ofSize: 16)
button.backgroundColor = Color.white
button.layer.borderWidth = 1
button.layer.borderColor = UIColor.lightGray.cgColor
}
static let secondary = ViewStyle.compose(rounded(height: Size.standardButtonHeight)) { button in
button.setTitleColor(Color.textGrey, for: .normal)
button.titleLabel?.font = UIFont.app_FuturaPTDemi(ofSize: 16)
button.backgroundColor = Color.white
}
static let halfWithWhite = ViewStyle.compose(rounded(height: Size.standardButtonHeight)) { button in
button.setTitleColor(Color.textLightGrey, for: .normal)
button.titleLabel?.font = UIFont.app_FuturaPTDemi(ofSize: 16)
button.backgroundColor = Color.white
}
static let halfWithBlue = ViewStyle.compose(rounded(height: Size.standardButtonHeight)) { button in
button.setTitleColor(Color.white, for: .normal)
button.titleLabel?.font = UIFont.app_FuturaPTDemi(ofSize: 16)
button.backgroundColor = Color.denimBlue
}
static let halfWithBlackSmall = ViewStyle.compose(rounded(height: Size.socialButtonHeight)) { button in
button.setTitleColor(Color.white, for: .normal)
button.titleLabel?.font = UIFont.app_FuturaPTBook(ofSize: 14)
button.backgroundColor = Color.black
}
static let halfWithWhiteSmall = ViewStyle.compose(rounded(height: Size.socialButtonHeight)) { button in
button.setTitleColor(Color.textLightGrey, for: .normal)
button.titleLabel?.font = UIFont.app_FuturaPTDemi(ofSize: 16)
button.backgroundColor = Color.white
button.layer.borderWidth = 1
button.layer.borderColor = UIColor.lightGray.cgColor
}
static let halfWithBlueSmall = ViewStyle.compose(rounded(height: Size.socialButtonHeight)) { button in
button.setTitleColor(Color.white, for: .normal)
button.titleLabel?.font = UIFont.app_FuturaPTDemi(ofSize: 16)
button.backgroundColor = Color.denimBlue
}
static let closeLightBackground = ViewStyle<UIButton> { item in
item.setImage(Image.closeLightBackground, for: .normal)
}
private static func withHeight(_ height: CGFloat) -> ViewStyle<UIButton> {
return ViewStyle<UIButton> { button in
let heightId = "height_identifier"
button.removeConstraints(
button.constraints.filter { $0.identifier == heightId }
)
let heightConstraint = button.heightAnchor.constraint(equalToConstant: height)
heightConstraint.identifier = heightId
button.addConstraint(heightConstraint)
}
}
private static func rounded(height: CGFloat) -> ViewStyle<UIButton> {
return ViewStyle.compose(withHeight(height), ViewStyle<UIButton> { button in
button.layer.cornerRadius = CornerRadius.standardButton
button.clipsToBounds = true
})
}
}
struct View {
static let cornerRadius = ViewStyle<UIView> { view in
let layer = view.layer
layer.cornerRadius = CornerRadius.standardButton
}
static let borderAndCorner = ViewStyle<UIView> { view in
let layer = view.layer
layer.borderWidth = 1.5
layer.borderColor = Color.borderViewColor.cgColor
layer.cornerRadius = CornerRadius.standardButton
}
static let borderShadow = ViewStyle<UIView> { view in
let layer = view.layer
layer.borderWidth = 1
layer.borderColor = Color.borderViewColor.cgColor
layer.shadowOpacity = 0.6
layer.shadowOffset = CGSize.zero
layer.shadowColor = Color.borderViewColor.cgColor
layer.shadowRadius = 10.0
layer.shadowPath = UIBezierPath(rect: view.bounds).cgPath
layer.shouldRasterize = true
}
static let borderShadowSelected = ViewStyle<UIView> { view in
let layer = view.layer
layer.borderWidth = 1
layer.borderColor = Color.black.cgColor
layer.shadowOpacity = 0.6
layer.shadowOffset = CGSize.zero
layer.shadowColor = Color.borderViewColor.cgColor
layer.shadowRadius = 10.0
layer.shadowPath = UIBezierPath(rect: view.bounds).cgPath
layer.shouldRasterize = true
}
static let shadowStyle1 = ViewStyle<UIView> { view in
let layer = view.layer
layer.shadowOpacity = 0.6
layer.shadowOffset = CGSize.zero
layer.shadowColor = UIColor.black.cgColor
layer.shadowRadius = 8.0
// layer.shadowPath = UIBezierPath(rect: view.bounds).cgPath
layer.shouldRasterize = true
}
static let shadowBlackRemote = ViewStyle<UIView> { view in
view.addshadowAllSides(cornerRadius: CornerRadius.standardButton, shadowColor: Color.textLightGrey, shadowRadius: 10.0)
}
static let shadowCornerWhite = ViewStyle<UIView> { view in
view.addshadowAllSides(cornerRadius: CornerRadius.standardButton, shadowColor: Color.textLightGrey)
}
static let scheduleShadowView = ViewStyle<UIView> { view in
view.addshadowAllSides(cornerRadius: CornerRadius.standardButton, shadowColor: Color.textLightGrey, shadowRadius: 10.0)
}
}
struct BarButtonItem {
static let closeLightBackground = ViewStyle<UIBarButtonItem> { item in
item.image = Image.closeLightBackground
}
}
}
<file_sep>//
// Configuration.swift
// Koleda
//
// Created by <NAME> on 7/1/19.
// Copyright © 2019 koleda. All rights reserved.
//
import Foundation
import Alamofire
extension URLRequest {
static func postRequestWithJsonBody(url: URL, parameters: [String: Any]) -> URLRequest? {
var urlRequest: URLRequest? = nil
var bodyData: Data? = nil
do {
urlRequest = try URLRequest(url: url, method: .post, headers: ["Content-Type":"application/json"])
bodyData = try JSONSerialization.data(withJSONObject: parameters)
} catch {
return nil
}
urlRequest?.httpBody = bodyData
return urlRequest
}
static func requestWithJsonBody(url: URL, method: HTTPMethod, parameters: [String: Any]) -> URLRequest? {
var urlRequest: URLRequest? = nil
var bodyData: Data? = nil
do {
urlRequest = try URLRequest(url: url, method: method, headers: ["Content-Type":"application/json"])
bodyData = try JSONSerialization.data(withJSONObject: parameters)
} catch {
return nil
}
urlRequest?.httpBody = bodyData
return urlRequest
}
}
class UrlConfigurator {
private class func baseUrlString() -> String {
guard let info = Bundle.main.infoDictionary else {
assert(false, "Failed while reading info from settings")
return ""
}
guard let serverURL = info["SERVER_URL"] as? String else {
assert(false, "Failed while reading SERVER_URL from settings")
return ""
}
return serverURL
}
class func mqttUrlString() -> String {
guard let info = Bundle.main.infoDictionary else {
assert(false, "Failed while reading info from settings")
return ""
}
guard let mqttServerURL = info["MQTT_SERVER_URL"] as? String else {
assert(false, "Failed while reading MQTT_SERVER_URL from settings")
return ""
}
return mqttServerURL
}
class func socketUrlString() -> String {
guard let info = Bundle.main.infoDictionary else {
assert(false, "Failed while reading info from settings")
return ""
}
guard let socketURL = info["SOCKET_URL"] as? String else {
assert(false, "Failed while reading SOCKET_URL from settings")
return ""
}
return socketURL
}
class func urlByAdding(port:Int = 5525, path: String = "") -> URL {
assert(port > 0, "Incorrect port value")
guard let url = URL(string: baseUrlString() + ":\(port)") else {
assert(false, "Failed while constructing URL")
return URL.invalidURL
}
return url.appendingPathComponent(path)
}
}
<file_sep>//
// DetailModeRouter.swift
// Koleda
//
// Created by <NAME> on 2/4/20.
// Copyright © 2020 koleda. All rights reserved.
//
import Foundation
import UIKit
class DetailModeRouter: BaseRouterProtocol {
weak var baseViewController: UIViewController?
enum RouteType {
case backModifyModes
}
func dismiss(animated: Bool, context: Any?, completion: ((Bool) -> Void)?) {
}
func enqueueRoute(with context: Any?, animated: Bool, completion: ((Bool) -> Void)?) {
guard let routeType = context as? RouteType else {
assertionFailure("The route type missmatches")
return
}
guard let baseViewController = baseViewController else {
assertionFailure("baseViewController is not set")
return
}
switch routeType {
case .backModifyModes:
baseViewController.navigationController?.popViewController(animated: false)
}
}
func present(on baseVC: UIViewController, animated: Bool, context: Any?, completion: ((Bool) -> Void)?) {
}
}
<file_sep>//
// IntroVideoView.swift
// Koleda
//
// Created by <NAME> on 5/27/19.
// Copyright © 2019 koleda. All rights reserved.
//
import WebKit
import AVFoundation
import UIKit
class IntroVideoView: UIView {
override func awakeFromNib() {
Style.View.cornerRadius.apply(to: self)
loadIntroVideo()
}
override func layoutSubviews() {
super.layoutSubviews()
playerLayer?.frame = self.layer.bounds
NotificationCenter.default.addObserver(self, selector: #selector(videoDidEnd), name:
NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: nil)
}
func viewWillDisAppear() {
if isplaying {
playOrStopVideo()
}
}
func viewWillAppear() {
playOrStopVideo()
}
// MARK - Private
private var isplaying: Bool = false
private var playerLayer: AVPlayerLayer?
private let player: AVPlayer? = {
// guard let url = URL(string: AppConstants.introVideoLink) else { return nil }
guard let path = Bundle.main.path(forResource: "introvideo", ofType:"mp4") else {
debugPrint("introvideo.mp4 not found")
return nil
}
let asset = AVAsset(url: URL(fileURLWithPath: path))
let playerItem = AVPlayerItem(asset: asset)
let player = AVPlayer(playerItem: playerItem)
return player
}()
private func loadIntroVideo() {
playerLayer = AVPlayerLayer(player: player)
guard let playerLayer = playerLayer else {
return
}
self.layer.addSublayer(playerLayer)
playerLayer.videoGravity = .resizeAspectFill
playerLayer.position = self.center
playerLayer.frame = self.bounds
playerLayer.cornerRadius = 10
playerLayer.masksToBounds = true
playerLayer.isHidden = true
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap))
tapGesture.delegate = self
self.addGestureRecognizer(tapGesture)
}
@objc func videoDidEnd(notification: NSNotification) {
isplaying = false
player?.seek(to: CMTime.zero)
playOrStopVideo()
}
private func playOrStopVideo() {
isplaying ? player?.pause() : player?.play()
isplaying = !isplaying
playerLayer?.isHidden = !isplaying
}
deinit {
NotificationCenter.default.removeObserver(self)
}
}
extension IntroVideoView: UIGestureRecognizerDelegate {
@IBAction func handleTap(sender: UIGestureRecognizer) {
// playOrStopVideo()
}
public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldBeRequiredToFailBy otherGestureRecognizer: UIGestureRecognizer) -> Bool {
if let tapGesture = otherGestureRecognizer as? UITapGestureRecognizer {
if tapGesture.numberOfTouchesRequired == 1 {
return true
}
}
return false
}
}
<file_sep>//
// EnergyTariffViewController.swift
// Koleda
//
// Created by <NAME> on 7/31/19.
// Copyright © 2019 koleda. All rights reserved.
//
import UIKit
import RxSwift
import SVProgressHUD
class EnergyTariffViewController: BaseViewController, BaseControllerProtocol, KeyboardAvoidable {
@IBOutlet weak var progressBarView: ProgressBarView!
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var daytimeView: UIView!
@IBOutlet weak var nighttimeView: UIView!
@IBOutlet weak var skipButton: UIButton!
@IBOutlet weak var nextButton: UIButton!
@IBOutlet weak var amountPerHourDayLabel: UILabel!
@IBOutlet weak var currencyUnitDayLabel: UILabel!
@IBOutlet weak var dayStartTimeLabel: UILabel!
@IBOutlet weak var dayEndTimeLabel: UILabel!
@IBOutlet weak var amountPerHourNightLabel: UILabel!
@IBOutlet weak var currencyUnitNightLabel: UILabel!
@IBOutlet weak var nightStartTimeLabel: UILabel!
@IBOutlet weak var nightEndTimeLabel: UILabel!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var daytimeTariffLabel: UILabel!
@IBOutlet weak var dayDescriptionLabel: UILabel!
@IBOutlet weak var dayStartLabel: UILabel!
@IBOutlet weak var dayEndLabel: UILabel!
@IBOutlet weak var nightTimeTariffLabel: UILabel!
@IBOutlet weak var nightDescriptionLabel: UILabel!
@IBOutlet weak var nightStartLabel: UILabel!
@IBOutlet weak var nightEndLabel: UILabel!
@IBOutlet weak var skipAndContinueLabel: UILabel!
var viewModel: EnergyTariffViewModelProtocol!
private let disposeBag = DisposeBag()
private var currentEditingPoint: TimePoint!
private var currentEditingTime: String = ""
var keybroadHelper: KeyboardHepler!
override func viewDidLoad() {
super.viewDidLoad()
configurationUI()
keybroadHelper = KeyboardHepler(scrollView)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
removeKeyboardObservers()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.edgesForExtendedLayout = UIRectEdge.top
self.automaticallyAdjustsScrollViewInsets = false
navigationController?.setNavigationBarHidden(true, animated: animated)
navigationBarTransparency()
setTitleScreen(with: "")
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == TimePickerViewController.get_identifier, let timePickerVC = segue.destination as? TimePickerViewController {
timePickerVC.delegate = self
timePickerVC.initTimePicker(timePoint: currentEditingPoint, time: currentEditingTime)
}
}
@IBAction func amountPerHourDayAction(_ sender: Any) {
gotoBlock(withStoryboar: "Setup", aClass: EnergyTariffInputViewController.self) { (vc) in
vc?.typeInput = .amountPerHourDay
vc?.amountPerHour = Double(amountPerHourDayLabel.text ?? "0.0") ?? 0
vc?.currencyUnit = currencyUnitDayLabel.text!
vc?.delegate = self
}
}
@IBAction func amountPerHourNightAction(_ sender: Any) {
gotoBlock(withStoryboar: "Setup", aClass: EnergyTariffInputViewController.self) { (vc) in
vc?.typeInput = .amountPerHourNight
vc?.amountPerHour = Double(amountPerHourNightLabel.text ?? "0.0") ?? 0
vc?.currencyUnit = currencyUnitNightLabel.text!
vc?.delegate = self
}
}
@IBAction func dayStartTimeAction(_ sender: Any) {
gotoBlock(withStoryboar: "Setup", aClass: EnergyTariffInputViewController.self) { (vc) in
vc?.typeInput = .dayStartTime
vc?.delegate = self
if let startTime = dayStartTimeLabel.text, !startTime.isEmpty {
vc?.startTime = Date(str: startTime, format: Date.fm_HHmm)
}
if let endTime = dayEndTimeLabel.text, !endTime.isEmpty {
vc?.endTime = Date(str: endTime, format: Date.fm_HHmm)
}
}
}
@IBAction func dayEndTimeAction(_ sender: Any) {
gotoBlock(withStoryboar: "Setup", aClass: EnergyTariffInputViewController.self) { (vc) in
vc?.typeInput = .dayEndTime
vc?.delegate = self
if let startTime = dayStartTimeLabel.text, !startTime.isEmpty {
vc?.startTime = Date(str: startTime, format: Date.fm_HHmm)
}
if let endTime = dayEndTimeLabel.text, !endTime.isEmpty {
vc?.endTime = Date(str: endTime, format: Date.fm_HHmm)
}
}
}
@IBAction func nightStartTimeAction(_ sender: Any) {
gotoBlock(withStoryboar: "Setup", aClass: EnergyTariffInputViewController.self) { (vc) in
vc?.typeInput = .nightStartTime
vc?.delegate = self
if let startTime = nightStartTimeLabel.text, !startTime.isEmpty {
vc?.startTime = Date(str: startTime, format: Date.fm_HHmm)
}
if let endTime = nightEndTimeLabel.text, !endTime.isEmpty {
vc?.endTime = Date(str: endTime, format: Date.fm_HHmm)
}
}
}
@IBAction func nightEndTimeAction(_ sender: Any) {
gotoBlock(withStoryboar: "Setup", aClass: EnergyTariffInputViewController.self) { (vc) in
vc?.typeInput = .nightEndTime
vc?.delegate = self
if let startTime = nightStartTimeLabel.text, !startTime.isEmpty {
vc?.startTime = Date(str: startTime, format: Date.fm_HHmm)
}
if let endTime = nightEndTimeLabel.text, !endTime.isEmpty {
vc?.endTime = Date(str: endTime, format: Date.fm_HHmm)
}
}
}
}
extension EnergyTariffViewController {
private func configurationUI() {
Style.Button.primary.apply(to: nextButton)
nextButton.rx.tap.bind { [weak self] _ in
SVProgressHUD.show()
self?.viewModel.next {
SVProgressHUD.dismiss()
}
}.disposed(by: disposeBag)
skipButton.rx.tap.bind { [weak self] _ in
self?.viewModel.showNextScreen()
}.disposed(by: disposeBag)
viewModel.tariffOfDay.asObservable().bind(to: amountPerHourDayLabel.rx.text).disposed(by: disposeBag)
viewModel.startOfDay.asObservable().bind(to: dayStartTimeLabel.rx.text).disposed(by: disposeBag)
viewModel.endOfDay.asObservable().bind(to: dayEndTimeLabel.rx.text).disposed(by: disposeBag)
viewModel.tariffOfNight.asObservable().bind(to: amountPerHourNightLabel.rx.text).disposed(by: disposeBag)
viewModel.startOfNight.asObservable().bind(to: nightStartTimeLabel.rx.text).disposed(by: disposeBag)
viewModel.endOfNight.asObservable().bind(to: nightEndTimeLabel.rx.text).disposed(by: disposeBag)
viewModel.currency.asObservable().bind(to: currencyUnitDayLabel.rx.text).disposed(by: disposeBag)
viewModel.currency.asObservable().bind(to: currencyUnitNightLabel.rx.text).disposed(by: disposeBag)
viewModel.errorMessage.asObservable().subscribe(onNext: { [weak self] message in
if message != "" {
self?.app_showInfoAlert(message)
}
}).disposed(by: disposeBag)
viewModel.updateFinished.asObservable().subscribe(onNext: { [weak self] isSuccess in
if isSuccess {
self?.app_showInfoAlert("UPDATED_TARIFF_INFO_SUCCESS_MESS".app_localized, title: "KOLEDA_TEXT".app_localized, completion: {
self?.viewModel.showNextScreen()
})
} else {
self?.app_showInfoAlert("UPDATED_TARIFF_INFO_FAILED_MESS".app_localized, title: "KOLEDA_TEXT".app_localized, completion: nil)
}
}).disposed(by: disposeBag)
progressBarView.setupNav(viewController: self)
titleLabel.text = "SETUP_YOUR_ENERGY_TARIFF".app_localized
daytimeTariffLabel.text = "DAYTIME_TARIFF_TEXT".app_localized
dayDescriptionLabel.text = "INPUT_DAYTIME_TARIFF_MESS".app_localized
dayStartLabel.text = "START_TEXT".app_localized
dayEndLabel.text = "END_TEXT".app_localized
nightTimeTariffLabel.text = "NIGHTTIME_TARIFF_TEXT".app_localized
nightDescriptionLabel.text = "INPUT_NIGHTTIME_TARIFF_MESS".app_localized
nightStartLabel.text = "START_TEXT".app_localized
nightEndLabel.text = "END_TEXT".app_localized
skipAndContinueLabel.text = "SKIP_AND_CONTINUE_TEXT".app_localized
nextButton.setTitle("CONFIRM_TEXT".app_localized, for: .normal)
}
@objc private func tapDone() {
self.view.endEditing(true)
}
private func validate(point: TimePoint, time: Time) -> (Bool,String) {
switch point {
case .startOfDay:
guard let endOfDayTime = dayEndTimeLabel.text?.timeValue() else {
return (true, "")
}
if time.hour*60 + time.minute == endOfDayTime.hour*60 + endOfDayTime.minute {
return (false, "START_DAYTIME_TARIFF_MUST_DIFFERENT_END_DAYTIME_TARIFF".app_localized)
}
case .endOfDay:
guard let startOfDayTime = dayStartTimeLabel.text?.timeValue() else {
return (true, "")
}
if time.hour*60 + time.minute == startOfDayTime.hour*60 + startOfDayTime.minute {
return (false, "END_DAYTIME_TARIFF_MUST_DIFFERENT_START_DAYTIME_TARIFF".app_localized)
}
case .startOfNight:
guard let endOfNightTime = nightEndTimeLabel.text?.timeValue() else {
return (true, "")
}
if time.hour*60 + time.minute == endOfNightTime.hour*60 + endOfNightTime.minute {
return (false, "START_NIGHTTIME_TARIFF_MUST_DIFFERENT_END_NIGHTTIME_TARIFF".app_localized)
}
case .endOfNight:
guard let startOfNightTime = nightStartTimeLabel.text?.timeValue() else {
return (true, "")
}
if time.hour*60 + time.minute == startOfNightTime.hour*60 + startOfNightTime.minute {
return (false, "END_NIGHTTIME_TARIFF_MUST_DIFFERENT_START_NIGHTTIME_TARIFF".app_localized)
}
}
return (true, "")
}
}
extension EnergyTariffViewController: UITextFieldDelegate {
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
switch textField {
case dayStartTimeLabel:
currentEditingPoint = .startOfDay
case dayEndTimeLabel:
currentEditingPoint = .endOfDay
case nightStartTimeLabel:
currentEditingPoint = .startOfNight
case nightEndTimeLabel:
currentEditingPoint = .endOfNight
default:
return true
}
currentEditingTime = textField.text?.extraWhitespacesRemoved ?? ""
performSegue(withIdentifier: TimePickerViewController.get_identifier, sender: self)
return false
}
}
extension EnergyTariffViewController: TimePickerViewControllerDelegate {
func selectedTime(time: Time) {
self.dismiss(animated: true) {
guard let timePoint = self.currentEditingPoint else {
return
}
let validateResult = self.validate(point: timePoint, time: time)
if validateResult.0 {
self.updateTimes(with: time, point: timePoint, completion: {
self.viewModel.startOfDay.value = self.dayStartTimeLabel.text ?? ""
self.viewModel.endOfDay.value = self.dayEndTimeLabel.text ?? ""
self.viewModel.startOfNight.value = self.nightStartTimeLabel.text ?? ""
self.viewModel.endOfNight.value = self.nightEndTimeLabel.text ?? ""
})
} else {
self.app_showInfoAlert(validateResult.1, title: "ERROR_TITLE".app_localized, completion: {
self.performSegue(withIdentifier: TimePickerViewController.get_identifier, sender: self)
})
}
}
}
private func updateTimes(with editingTime: Time, point: TimePoint, completion: @escaping () -> Void) {
let timeString = editingTime.timeString()
switch point {
case .startOfDay:
self.dayStartTimeLabel.text = timeString
guard let endOfDaytime = self.dayEndTimeLabel.text?.timeValue() else {
completion()
return
}
refillOtherTimes(isDaytime: true, start: editingTime, end: endOfDaytime)
case .endOfDay:
self.dayEndTimeLabel.text = timeString
guard let startOfDaytime = self.dayStartTimeLabel.text?.timeValue() else {
completion()
return
}
refillOtherTimes(isDaytime: true, start: startOfDaytime, end: editingTime)
case .startOfNight:
self.nightStartTimeLabel.text = timeString
guard let endOfNighttime = self.nightEndTimeLabel.text?.timeValue() else {
completion()
return
}
refillOtherTimes(isDaytime: false, start: editingTime, end: endOfNighttime)
case .endOfNight:
self.nightEndTimeLabel.text = timeString
guard let startOfNighttime = self.nightStartTimeLabel.text?.timeValue() else {
completion()
return
}
refillOtherTimes(isDaytime: false, start: startOfNighttime, end: editingTime)
}
completion()
}
private func refillOtherTimes(isDaytime: Bool, start: Time, end: Time) {
if isDaytime {
nightStartTimeLabel.text = end.timeString()
nightEndTimeLabel.text = start.timeString()
} else {
dayStartTimeLabel.text = end.timeString()
dayEndTimeLabel.text = start.timeString()
}
}
}
extension EnergyTariffViewController: EnergyTariffInputDelegate {
func selectedAmountPerHour(isDay: Bool, amount: Double, currencyUnit: String) {
if isDay {
viewModel.updatetTariffOfDay(amount: amount.toString(fractionDigits: 2))
} else {
viewModel.updatetTariffOfNight(amount: amount.toString(fractionDigits: 2))
}
currencyUnitDayLabel.text = currencyUnit
currencyUnitNightLabel.text = currencyUnit
viewModel.currency.value = currencyUnit
}
func selectedTime(isDay: Bool, startTime: String, endTime: String) {
if isDay == true {
viewModel.startOfDay.value = startTime
viewModel.endOfDay.value = endTime
viewModel.startOfNight.value = endTime
viewModel.endOfNight.value = startTime
} else {
viewModel.startOfDay.value = endTime
viewModel.endOfDay.value = startTime
viewModel.startOfNight.value = startTime
viewModel.endOfNight.value = endTime
}
}
}
<file_sep>//
// ForgotPasswordViewController.swift
// Koleda
//
// Created by <NAME> on 6/20/19.
// Copyright © 2019 koleda. All rights reserved.
//
import UIKit
import RxSwift
import SVProgressHUD
class ForgotPasswordViewController: BaseViewController, BaseControllerProtocol, KeyboardAvoidable {
var viewModel: ForgotPassWordViewModelProtocol!
@IBOutlet weak var emailTextField: AndroidStyle2TextField!
@IBOutlet weak var confirmEmailImageView: UIImageView!
@IBOutlet weak var passwordLabel: UILabel!
@IBOutlet weak var descriptionLabel: UILabel!
@IBOutlet weak var sendLinkLabel: UILabel!
private let disposeBag = DisposeBag()
var keyboardHelper: KeyboardHepler?
override func viewDidLoad() {
super.viewDidLoad()
configurationUI()
keyboardHelper = KeyboardHepler(self)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(true, animated: animated)
navigationBarTransparency()
statusBarStyle(with: .lightContent)
self.edgesForExtendedLayout = UIRectEdge.top
self.automaticallyAdjustsScrollViewInsets = false
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
}
@IBAction func backAction(_ sender: Any) {
back()
}
@IBAction func sendLinkAction(_ sender: UIButton) {
sender.isEnabled = false
SVProgressHUD.show()
self.viewModel.getNewPassword(completion: { [weak self] (success, errorMessage) in
sender.isEnabled = true
SVProgressHUD.dismiss()
if success {
self?.app_showInfoAlert("RESET_PASS_SUCCESS_MESS".app_localized, title: "KOLEDA_TEXT".app_localized, completion: {
self?.viewModel.router.dismiss(animated: true, context: nil, completion: nil)
})
} else if !errorMessage.isEmpty {
self?.app_showAlertMessage(title: "ERROR_TITLE".app_localized, message: errorMessage)
}
})
}
}
extension ForgotPasswordViewController {
func configurationUI() {
viewModel.email.asObservable().bind(to: emailTextField.rx.text).disposed(by: disposeBag)
emailTextField.rx.text.orEmpty.bind(to: viewModel.email).disposed(by: disposeBag)
viewModel.email.asObservable().subscribe(onNext: { [weak self] value in
self?.confirmEmailImageView.isHidden = isEmpty(value)
}).disposed(by: disposeBag)
viewModel.emailErrorMessage.asObservable().subscribe(onNext: { [weak self] message in
self?.emailTextField.errorText = message
if message.isEmpty {
self?.emailTextField.showError(false)
} else {
self?.emailTextField.showError(true)
}
}).disposed(by: disposeBag)
passwordLabel.text = "<PASSWORD>".app_localized
descriptionLabel.text = "PLEASE_ENTER_YOUR_EMAIL_FOR_RESET_PASS_MESS".app_localized
emailTextField.titleText = "EMAIL_TITLE".app_localized
emailTextField.placeholder = "ENTER_EMAIL_HERE_TEXT".app_localized
sendLinkLabel.text = "SEND_LINK_TEXT".app_localized
}
}
<file_sep>//
// Double+Extensions.swift
// Koleda
//
// Created by <NAME> on 8/28/19.
// Copyright © 2019 koleda. All rights reserved.
//
import Foundation
extension Double {
func integerPart() -> Int {
let numberString = String(self)
let numberComponent = numberString.components(separatedBy :".")
return Int(numberComponent [0]) ?? 0
}
func fractionalPart() -> Int {
let numberString = String(self)
let numberComponent = numberString.components(separatedBy :".")
guard numberComponent.count == 2 else {
return 0
}
return Int(numberComponent [1]) ?? 0
}
var fahrenheitTemperature: Double {
let fValue = self*1.8 + 32
return fValue.rounded()
}
var celciusTemperature: Double {
let cValue = (self - 32)/1.8
return cValue.roundToDecimal(1)
}
static func valueOf(clusterValue: (Int, Int) ) -> Double {
return Double(clusterValue.0) + Double(clusterValue.1) * 0.1
}
func roundToDecimal(_ fractionDigits: Int) -> Double {
let multiplier = pow(10, Double(fractionDigits))
return Darwin.round(self * multiplier) / multiplier
}
func toString(fractionDigits: Int = 1) -> String {
return String(format: "%.\(fractionDigits)f",self)
}
func currencyFormatter() -> String {
let cf = NumberFormatter()
cf.numberStyle = .decimal
cf.maximumFractionDigits = 2
cf.minimumFractionDigits = 2
cf.locale = Locale(identifier: "en_US")
cf.decimalSeparator = "."
cf.groupingSeparator = ","
return cf.string(for: self) ?? "0.0"
}
}
<file_sep>//
// Home.swift
// Koleda
//
// Created by <NAME> on 6/19/20.
// Copyright © 2020 koleda. All rights reserved.
//
import Foundation
struct Home: Codable {
let id: String
let name: String
private enum CodingKeys: String, CodingKey {
case id
case name
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.id = try container.decode(String.self, forKey: .id)
self.name = try container.decode(String.self, forKey: .name)
}
}
extension Home {
init(json: [String: Any]) {
id = json["id"] as? String ?? ""
name = json["name"] as? String ?? ""
}
}
<file_sep>//
// HeaterAnalyticsEvent.swift
// Koleda
//
// Created by <NAME> on 9/4/20.
// Copyright © 2020 koleda. All rights reserved.
//
import Foundation
import CopilotAPIAccess
struct AddHeaterAnalyticsEvent: AnalyticsEvent {
private let heaterModel: String
private let roomId: String
private let homeId: String
private let screenName: String
init(heaterModel:String, roomId: String, homeId: String, screenName: String) {
self.heaterModel = heaterModel
self.roomId = roomId
self.homeId = homeId
self.screenName = screenName
}
var customParams: Dictionary<String, String> {
return ["heaterModel" : heaterModel,
"roomId" : roomId,
"homeId" : homeId,
"screenName": screenName]
}
var eventName: String {
return "add_heater"
}
var eventOrigin: AnalyticsEventOrigin {
return .App
}
var eventGroups: [AnalyticsEventGroup] {
return [.All]
}
}
struct RemoveHeaterAnalyticsEvent: AnalyticsEvent {
private let heaterId: String
private let screenName: String
init(heaterId:String, screenName: String) {
self.heaterId = heaterId
self.screenName = screenName
}
var customParams: Dictionary<String, String> {
return ["heaterId" : heaterId,
"screenName": screenName]
}
var eventName: String {
return "remove_heater"
}
var eventOrigin: AnalyticsEventOrigin {
return .App
}
var eventGroups: [AnalyticsEventGroup] {
return [.All]
}
}
<file_sep>//
// RoomManager.swift
// Koleda
//
// Created by <NAME> on 7/12/19.
// Copyright © 2019 koleda. All rights reserved.
//
import Foundation
import Alamofire
import Sync
import SwiftyJSON
protocol RoomManager {
func createRoom(category: String, name: String, success: @escaping (_ roomId: String) -> Void, failure: @escaping (_ error: Error) -> Void)
func getRooms(success: (() -> Void)?, failure: ((Error) -> Void)?)
func deleteRoom(roomId: String, success: (() -> Void)?, failure: ((Error) -> Void)?)
func updateRoom(roomId: String, category: String, name: String, success: (() -> Void)?, failure: ((Error) -> Void)?)
func switchRoom(roomId: String, turnOn: Bool, success: @escaping () -> Void, failure: @escaping (_ error: Error) -> Void)
func manualBoostUpdate(roomId: String, temp: Double, time: Int, success: @escaping () -> Void, failure: @escaping (_ error: Error) -> Void)
func getRoom(roomId: String, success: @escaping (Room) -> Void, failure: @escaping (_ error: Error) -> Void)
}
class RoomManagerImpl: RoomManager {
private let sessionManager: Session
private func baseURL() -> URL {
return UrlConfigurator.urlByAdding()
}
init(sessionManager: Session) {
self.sessionManager = sessionManager
}
func createRoom(category: String, name: String, success: @escaping (_ roomId: String) -> Void, failure: @escaping (_ error: Error) -> Void) {
let params = ["category": category,
"name": name]
let endPointURL = baseURL().appendingPathComponent("me/rooms")
guard let request = URLRequest.postRequestWithJsonBody(url: endPointURL, parameters: params) else {
failure(RequestError.error(NSLocalizedString("Failed to send request, please try again later", comment: "")))
return
}
sessionManager.request(request).validate().responseJSON { [weak self] response in
switch response.result {
case .success(let result):
log.info("Successfully add room")
guard let json = JSON(result).dictionaryObject else {
failure(WSError.failedAddRoom)
return
}
let room = Room.init(json: json)
self?.addRoomAtLocal(room: room)
success(room.id)
case .failure(let error):
log.error("Failed to add room - \(error)")
if let error = error as? URLError, error.code == URLError.notConnectedToInternet {
NotificationCenter.default.post(name: .KLDNotConnectedToInternet, object: error)
} else if let error = error as? AFError, error.responseCode == 400 {
failure(error)
} else if let error = error as? AFError, error.responseCode == 401 {
failure(error)
} else {
failure(error)
}
}
}
}
func getRooms(success: (() -> Void)?, failure: ((Error) -> Void)? = nil) {
log.info("getRooms")
guard let request = try? URLRequest(url: baseURL().appendingPathComponent("me/rooms"), method: .get) else {
assertionFailure()
DispatchQueue.main.async {
failure?(WSError.general)
}
return
}
sessionManager
.request(request).validate().responseData { response in
switch response.result {
case .success(let data):
do {
log.info(try JSON(data: data).description)
let decodedJSON = try JSONDecoder().decode([Room].self, from: data)
UserDataManager.shared.rooms = decodedJSON
success?()
} catch {
log.info("Get Rooms parsing error: \(error)")
failure?(error)
}
case .failure(let error):
log.info("Get Rooms fetch error: \(error)")
let statusCode = response.response?.statusCode
if statusCode == 403 {
failure?(WSError.loginSessionExpired)
} else if statusCode == nil && response.response == nil {
NotificationCenter.default.post(name: .KLDNotConnectedToInternet, object: error)
failure?(error)
} else {
failure?(error)
}
}
}
}
func getRoom(roomId: String, success: @escaping (Room) -> Void, failure: @escaping (_ error: Error) -> Void) {
log.info("getRooms")
guard let request = try? URLRequest(url: baseURL().appendingPathComponent("me/rooms/\(roomId)"), method: .get) else {
assertionFailure()
DispatchQueue.main.async {
failure(WSError.general)
}
return
}
sessionManager
.request(request).validate().responseData { response in
switch response.result {
case .success(let data):
do {
log.info(try JSON(data: data).description)
let room = try JSONDecoder().decode(Room.self, from: data)
success(room)
} catch {
log.info("Get Room parsing error: \(error)")
failure(error)
}
case .failure(let error):
log.info("Get Room fetch error: \(error)")
let statusCode = response.response?.statusCode
if statusCode == 403 {
failure(WSError.loginSessionExpired)
} else if statusCode == nil && response.response == nil {
NotificationCenter.default.post(name: .KLDNotConnectedToInternet, object: error)
failure(error)
} else {
failure(error)
}
}
}
}
func deleteRoom(roomId: String, success: (() -> Void)?, failure: ((Error) -> Void)? = nil) {
guard let request = try? URLRequest(url: baseURL().appendingPathComponent("me/rooms/\(roomId)"), method: .delete) else {
assertionFailure()
DispatchQueue.main.async {
failure?(WSError.general)
}
return
}
sessionManager.request(request).validate().response { [weak self] response in
if let error = response.error {
log.info("Delete Room error: \(error)")
failure?(error)
} else {
log.info("Delete Room successfull")
self?.removeRoomAtLocal(roomId: roomId)
success?()
}
}
}
func updateRoom(roomId: String, category: String, name: String, success: (() -> Void)?, failure: ((Error) -> Void)? = nil) {
let params = ["category": category,
"name": name]
let endPointURL = baseURL().appendingPathComponent("me/rooms/\(roomId)")
sessionManager.request(endPointURL,
method: .patch,
parameters: params,
encoding: JSONEncoding.default)
.validate()
.response { [weak self] response in
if let error = response.error {
log.error("Failed updating room, \(error.localizedDescription)")
failure?(WSError.failedUpdateRoom)
} else {
log.info("Successfully updated room")
self?.updateRoomAtLocal(roomId: roomId, name: name, category: category)
success?()
}
}
}
func switchRoom(roomId: String, turnOn: Bool, success: @escaping () -> Void, failure: @escaping (_ error: Error) -> Void) {
let params = ["turn": turnOn ? "ON" : "OFF"]
let endPointURL = baseURL().appendingPathComponent("setting/rooms/\(roomId)")
sessionManager.request(endPointURL,
method: .post,
parameters: params,
encoding: JSONEncoding.default)
.validate()
.response { response in
if let error = response.error {
log.error("Failed to change status of Sensor - \(error)")
failure(WSError.failedUpdateRoom)
} else {
log.info("Successfully change status of Sensor")
success()
}
}
}
func manualBoostUpdate(roomId: String, temp: Double, time: Int, success: @escaping () -> Void, failure: @escaping (_ error: Error) -> Void) {
let params = ["temp": temp,
"time": time] as [String : Any]
let endPointURL = baseURL().appendingPathComponent("setting/rooms/\(roomId)/temperature")
sessionManager.request(endPointURL,
method: .post,
parameters: params,
encoding: JSONEncoding.default)
.validate()
.response { response in
if let error = response.error {
log.error("Failed to manual boost update - \(error)")
failure(WSError.failedUpdateRoom)
} else {
log.info("Successfully manual boost updated")
success()
}
}
}
private func removeRoomAtLocal(roomId: String) {
guard let indexOfRoom = UserDataManager.shared.rooms.firstIndex(where: { $0.id == roomId }) else { return }
UserDataManager.shared.rooms.remove(at: indexOfRoom)
}
private func addRoomAtLocal(room: Room) {
UserDataManager.shared.rooms.insert(room, at: 0)
}
private func updateRoomAtLocal(roomId: String, name: String, category: String) {
guard var room = UserDataManager.shared.roomWith(roomId: roomId) else { return }
room.name = name
room.category = category
guard let indexOfRoom = UserDataManager.shared.rooms.firstIndex(where: { $0.id == roomId }) else { return }
UserDataManager.shared.rooms.remove(at: indexOfRoom)
UserDataManager.shared.rooms.insert(room, at: indexOfRoom)
}
}
<file_sep>//
// AndroidStyleTextField.swift
// Koleda
//
// Created by <NAME> on 5/28/19.
// Copyright © 2019 koleda. All rights reserved.
//
import UIKit
@IBDesignable
class AndroidStyleTextField: UnderlineTextField {
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
private func setup() {
lineColor = .app_contentColor
selectedLineColor = .app_titleColor
titleColor = .app_titleColor
selectedTitleColor = .app_titleColor
lineHeight = 0.5
selectedLineHeight = 1
font = UIFont.app_FuturaPTBook(ofSize: 14)
titleFont = UIFont.app_FuturaPTDemi(ofSize: 13)
titleToTextFieldSpacing = 5
lineToTextFieldSpacing = 5
textColor = .app_titleColor
}
}
@IBDesignable
class AndroidStyle2TextField: UnderlineTextField {
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
private func setup() {
lineColor = UIColor.clear
titleColor = UIColor.white
selectedTitleColor = UIColor.white
lineHeight = 1
selectedLineHeight = 1
font = UIFont.SFProDisplayRegular17
titleFont = UIFont.SFProDisplaySemibold10
titleToTextFieldSpacing = 5
lineToTextFieldSpacing = 5
textColor = UIColor.hexB5B5B5
setNeedsLayout()
layoutIfNeeded()
}
}
@IBDesignable
class AndroidStyle3TextField: UnderlineTextField {
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
private func setup() {
lineColor = UIColor.clear
titleColor = UIColor.black
selectedTitleColor = UIColor.black
lineHeight = 1
selectedLineHeight = 1
font = UIFont.SFProDisplayRegular17
titleFont = UIFont.SFProDisplaySemibold14
titleToTextFieldSpacing = 5
lineToTextFieldSpacing = 5
textColor = UIColor.hexB5B5B5
setNeedsLayout()
layoutIfNeeded()
}
}
<file_sep>//
// ConfigurationRoomViewModel.swift
// Koleda
//
// Created by <NAME> on 8/26/19.
// Copyright © 2019 koleda. All rights reserved.
//
import UIKit
import RxSwift
protocol ConfigurationRoomViewModelProtocol: BaseViewModelProtocol {
var title: Variable<String> { get }
var roomName: Variable<String> { get }
var temperature: Variable<String> { get }
var pairedWithSensorTitle: Variable<String> { get }
var pairedWithHeatersTitle: Variable<String> { get }
var enableHeaterManagement: PublishSubject<Bool> { get }
var imageRoom: PublishSubject<UIImage> { get }
var heaters: Variable<[Heater]> { get }
var imageRoomColor : PublishSubject<UIColor> { get }
func setup()
func editRoom()
func sensorManagement()
func heatersManagement()
func needUpdateSelectedRoom()
}
class ConfigurationRoomViewModel: BaseViewModel, ConfigurationRoomViewModelProtocol {
let title = Variable<String>("")
let roomName = Variable<String>("")
var temperature = Variable<String>("")
let pairedWithSensorTitle = Variable<String>("")
let pairedWithHeatersTitle = Variable<String>("")
let enableHeaterManagement = PublishSubject<Bool>()
let imageRoom = PublishSubject<UIImage>()
let imageRoomColor = PublishSubject<UIColor>()
var heaters = Variable<[Heater]>([])
let router: BaseRouterProtocol
private let roomManager: RoomManager
private var seletedRoom: Room?
init(router: BaseRouterProtocol, managerProvider: ManagerProvider = .sharedInstance, seletedRoom: Room? = nil) {
self.router = router
self.roomManager = managerProvider.roomManager
self.seletedRoom = seletedRoom
super.init(managerProvider: managerProvider)
}
func setup() {
guard let userName = UserDataManager.shared.currentUser?.name, let room = seletedRoom else {
return
}
let roomViewModel = RoomViewModel.init(room: room)
title.value = "\(userName)’s \(roomViewModel.roomName)"
roomName.value = roomViewModel.roomName
if let image = roomViewModel.roomConfigurationImage {
imageRoom.onNext(image)
}
imageRoomColor.onNext(roomViewModel.onOffSwitchStatus ? UIColor.black : UIColor.gray)
guard let sensor = roomViewModel.sensor else {
pairedWithSensorTitle.value = String(format: "ROOM_NOT_CONNECT_TO_ANY_SENSOR_MESS".app_localized, roomViewModel.roomName)
pairedWithHeatersTitle.value = ""
enableHeaterManagement.onNext(false)
return
}
if let temp = roomViewModel.currentTemp {
temperature.value = "\(temp)"
} else {
temperature.value = "-"
}
enableHeaterManagement.onNext(true)
pairedWithSensorTitle.value = String(format: "PAIRED_WITH_SENSOR_MESS".app_localized, roomViewModel.roomName)
guard let heaters = roomViewModel.heaters, heaters.count > 0 else {
pairedWithHeatersTitle.value = String(format: "SENSOR_NOT_CONNECT_TO_ANY_HEATER_MESS".app_localized, roomViewModel.roomName)
self.heaters.value = []
return
}
self.heaters.value = heaters
pairedWithHeatersTitle.value = String(format: "SENSOR_PAIRED_WITH_HEATERS_MESS".app_localized, roomViewModel
.roomName)
}
func editRoom() {
guard let room = seletedRoom else {
return
}
router.enqueueRoute(with: ConfigurationRoomRouter.RouteType.editRoom(room))
}
func sensorManagement() {
guard let room = seletedRoom else {
return
}
guard let sensor = seletedRoom?.sensor else {
router.enqueueRoute(with: ConfigurationRoomRouter.RouteType.addSensor(room.id, room.name))
return
}
router.enqueueRoute(with: ConfigurationRoomRouter.RouteType.editSensor(room))
}
func heatersManagement() {
guard let room = seletedRoom else {
return
}
router.enqueueRoute(with: ConfigurationRoomRouter.RouteType.heaterManagement(room))
}
func needUpdateSelectedRoom() {
if let roomId = seletedRoom?.id, let room = UserDataManager.shared.roomWith(roomId: roomId) {
seletedRoom = room
setup()
}
}
}
<file_sep>
//
// JoinHomeAnalyticsEvent.swift
// Koleda
//
// Created by <NAME> on 9/4/20.
// Copyright © 2020 koleda. All rights reserved.
//
import Foundation
import CopilotAPIAccess
struct JoinHomeAnalyticsEvent: AnalyticsEvent {
private let name: String
private let email: String
private let homeId: String
private let screenName: String
init(name:String, email: String, homeId: String, screenName: String) {
self.name = name
self.email = email
self.homeId = homeId
self.screenName = screenName
}
var customParams: Dictionary<String, String> {
return ["name" : name,
"email" : email,
"homeId" : homeId,
"screenName": screenName]
}
var eventName: String {
return "join_home"
}
var eventOrigin: AnalyticsEventOrigin {
return .App
}
var eventGroups: [AnalyticsEventGroup] {
return [.All]
}
}
<file_sep>//
// Logger.swift
// Koleda
//
// Created by <NAME> on 7/3/19.
// Copyright © 2019 koleda. All rights reserved.
//
import Foundation
enum LogLevel {
case off
case error
case warning
case info
case debug
case verbose
case all
}
protocol AssertRecording {
func recordAssertionFailure(_ error: NSError, additionalInfo: [String: Any]?)
}
protocol Logger {
var assertsEnabled: Bool { get set }
func verbose(_ message: String, _ file: StaticString, _ function: StaticString, _ line: UInt)
func debug(_ message: String, _ file: StaticString, _ function: StaticString, _ line: UInt)
func info(_ message: String, _ file: StaticString, _ function: StaticString, _ line: UInt)
func warning(_ message: String, _ file: StaticString, _ function: StaticString, _ line: UInt)
func error(_ message: String, _ file: StaticString, _ function: StaticString, _ line: UInt)
/**
Logs message with "error" log level and, if "assertsEnabled" property is true, throws assert.
Also additional services can be used in this function to record assert (e.g. Crashlytics non-fatals)
- parameter message: message for logging.
- parameter assertId: id which should be unique within file. This id and filename can be used to group asserts.
- parameter userInfo: optional key value data.
- parameter file: file name.
- parameter function: function name.
- parameter line: line number.
*/
func errorWithAssert(_ message: String,
_ assertId: String,
_ userInfo: [String: Any]?,
_ file: StaticString,
_ function: StaticString,
_ line: UInt)
func flushLog()
}
extension Logger {
func verbose(_ message: String,
_ file: StaticString = #file,
_ function: StaticString = #function,
_ line: UInt = #line)
{
verbose(message, file, function, line)
}
func debug(_ message: String,
_ file: StaticString = #file,
_ function: StaticString = #function,
_ line: UInt = #line)
{
debug(message, file, function, line)
}
func info(_ message: String,
_ file: StaticString = #file,
_ function: StaticString = #function,
_ line: UInt = #line)
{
info(message, file, function, line)
}
func warning(_ message: String,
_ file: StaticString = #file,
_ function: StaticString = #function,
_ line: UInt = #line)
{
warning(message, file, function, line)
}
func error(_ message: String,
_ file: StaticString = #file,
_ function: StaticString = #function,
_ line: UInt = #line)
{
error(message, file, function, line)
}
func errorWithAssert(_ message: String,
_ assertId: String,
_ userInfo: [String: Any]? = nil,
_ file: StaticString = #file,
_ function: StaticString = #function,
_ line: UInt = #line)
{
if assertsEnabled {
errorWithAssert(message, assertId, userInfo, file, function, line)
} else{
error(message, file, function, line)
}
}
}
<file_sep>
//
// UserDataManager.swift
// Koleda
//
// Created by <NAME> on 7/15/19.
// Copyright © 2019 koleda. All rights reserved.
//
import Foundation
enum TemperatureUnit: String{
case F = "F"
case C = "C"
case unknow
init(fromString string: String) {
guard let value = TemperatureUnit(rawValue: string) else {
self = .unknow
return
}
self = value
}
}
struct StepProgressBar {
let totalStep: Int
var currentStep: Int
init(total: Int = 0, step: Int = 0) {
self.totalStep = total
self.currentStep = step
}
}
final class UserDataManager {
static let shared = UserDataManager()
var currentUser: User?
var tariff: Tariff?
var wifiInfo: WifiInfo?
var rooms : [Room]
var deviceModelList: [String]
var temperatureUnit: TemperatureUnit
var energyConsumed: ConsumeEneryTariff?
var settingModes: [ModeItem]
var smartScheduleData: [String:ScheduleOfDay]
var stepProgressBar = StepProgressBar()
var friendsList: [String]
private init() {
rooms = []
deviceModelList = []
temperatureUnit = .C
energyConsumed = nil
smartScheduleData = [:]
settingModes = []
stepProgressBar = StepProgressBar()
friendsList = []
}
func clearUserData() {
rooms = []
deviceModelList = []
temperatureUnit = .C
energyConsumed = nil
smartScheduleData = [:]
settingModes = []
stepProgressBar = StepProgressBar()
friendsList = []
currentUser = nil
tariff = nil
wifiInfo = nil
}
func roomWith(roomId: String) -> Room? {
return rooms.first(where: { $0.id == roomId })
}
func settingModesWithoutDefaultMode() -> [ModeItem] {
return settingModes.filter { $0.mode != .DEFAULT}
}
}
<file_sep>//
// UITextField+Extensions.swift
// Koleda
//
// Created by <NAME> on 8/2/19.
// Copyright © 2019 koleda. All rights reserved.
//
import Foundation
import UIKit
extension UITextField {
func addInputAccessoryView(title: String, target: Any, selector: Selector) {
let toolBar = UIToolbar(frame: CGRect(x: 0.0,
y: 0.0,
width: UIScreen.main.bounds.size.width,
height: 44.0))//1
let flexible = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)//2
let barButton = UIBarButtonItem(title: title, style: .plain, target: target, action: selector)//3
barButton.tintColor = .black
toolBar.setItems([flexible, barButton], animated: false)//4
self.inputAccessoryView = toolBar//5
}
@IBInspectable var placeholderColor : UIColor {
set {
self.attributedPlaceholder = NSAttributedString(string:self.placeholder != nil ? self.placeholder! : "", attributes:[NSAttributedString.Key.foregroundColor: newValue])
}
get {
return UIColor.clear
}
}
}
<file_sep>//
// SmartSchedulingViewModel.swift
// Koleda
//
// Created by <NAME> on 10/22/19.
// Copyright © 2019 koleda. All rights reserved.
//
import Foundation
import RxSwift
protocol SmartSchedulingViewModelProtocol: BaseViewModelProtocol {
func showScheduleDetail(startTime: Time, day: DayOfWeek, tapedTimeline: Bool)
var currentSelectedIndex: Int { set get }
}
class SmartSchedulingViewModel: BaseViewModel, SmartSchedulingViewModelProtocol {
let router: BaseRouterProtocol
private let settingManager: SettingManager
var currentSelectedIndex: Int = 0
init(router: BaseRouterProtocol, managerProvider: ManagerProvider = .sharedInstance) {
self.router = router
settingManager = managerProvider.settingManager
super.init(managerProvider: managerProvider)
}
func showScheduleDetail(startTime: Time, day: DayOfWeek, tapedTimeline: Bool) {
router.enqueueRoute(with: SmartSchedulingRouter.RouteType.scheduleDetail(startTime, day, tapedTimeline), completion: nil)
}
}
<file_sep>//
// User.swift
// Koleda
//
// Created by <NAME> on 7/15/19.
// Copyright © 2019 koleda. All rights reserved.
//
import Foundation
enum UserType: String{
case Master = "MASTER"
case Guest = "GUEST"
case Undefine = "UNDEFINE"
case unknow
init(fromString string: String) {
guard let value = UserType(rawValue: string) else {
self = .unknow
return
}
self = value
}
}
struct User: Codable {
let id: String
let name: String
let email: String?
let emailVerified: Bool?
let imageUrl: String?
let provider: String?
let providerId: String?
let temperatureUnit: String?
let userType: String?
var homes: [Home]
private enum CodingKeys: String, CodingKey {
case id
case name
case email
case emailVerified
case imageUrl
case provider
case providerId
case temperatureUnit
case userType
case homes
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.id = try container.decode(String.self, forKey: .id)
self.name = try container.decode(String.self, forKey: .name)
self.email = try container.decodeIfPresent(String.self, forKey: .email)
self.emailVerified = try container.decodeIfPresent(Bool.self, forKey: .emailVerified)
self.imageUrl = try container.decodeIfPresent(String.self, forKey: .imageUrl)
self.provider = try container.decodeIfPresent(String.self, forKey: .provider)
self.providerId = try container.decodeIfPresent(String.self, forKey: .providerId)
self.temperatureUnit = try container.decodeIfPresent(String.self, forKey: .temperatureUnit)
self.userType = try container.decodeIfPresent(String.self, forKey: .userType)
self.homes = try container.decode([Home].self, forKey: .homes)
}
}
<file_sep>//
// DataValidator.swift
// Koleda
//
// Created by <NAME> on 6/10/19.
// Copyright © 2019 koleda. All rights reserved.
//
import Foundation
class DataValidator {
class func isEmailValid(email: String?) -> Bool {
return matches(string: email, pattern: "[A-Z0-9a-z\\._%+-]+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2,4}")
}
class func isValid(fullName: String) -> Bool {
return matches(string: fullName, pattern: "^[A-Za-z\\s]*$") &&
fullName.components(separatedBy: .whitespaces).count > 1
}
class func isEmailPassword(pass: String?) -> Bool {
return matches(string: pass, pattern: "^[a-zA-Z0-9'@&#-.\\s]{6,21}$")
}
class func isShellyDevice(hostName: String?) -> Bool {
let hostNameUpperCase = hostName?.uppercased()
return matches(string: hostNameUpperCase, pattern: "^(SHELLYHT)+-+[A-Z0-9]") || matches(string: hostNameUpperCase, pattern: "^(SOLUS-SENSOR)+-+[A-Z0-9]")
}
class func isShellyHeaterDevice(hostName: String?) -> Bool {
let hostNameUpperCase = hostName?.uppercased()
return matches(string: hostNameUpperCase, pattern: "^(SHELLY1PM)+-+[A-Z0-9]") || matches(string: hostNameUpperCase, pattern: "^(SOLUS-HEATER)+-+[A-Z0-9]")
}
private class func matches(string: String?, pattern: String) -> Bool {
guard let string = string else { return false }
do {
let regularExpression = try NSRegularExpression(pattern: pattern, options: [])
let range = string.startIndex..<string.endIndex
return regularExpression.matches(in: string, options: [], range: string.nsRange(from: range)).count > 0
} catch {
return false
}
}
}
<file_sep>//
// PageTabMenuViewController.swift
// Koleda
//
// Created by <NAME> on 10/30/19.
// Copyright © 2019 koleda. All rights reserved.
//
import UIKit
import Swift_PageMenu
protocol PageTabMenuViewControllerDelegate: class {
func currentPageIndex(indexPage: Int)
}
class PageTabMenuViewController: PageMenuController {
let titles: [String]
weak var pageTabMenuDelegate: PageTabMenuViewControllerDelegate?
var parentController: SmartSchedulingViewController?
var defaultIndexPage: Int = 0
init(titles: [String], options: PageMenuOptions? = nil) {
self.titles = titles
super.init(options: options)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
self.edgesForExtendedLayout = []
if options.layout == .layoutGuide && options.tabMenuPosition == .bottom {
self.view.backgroundColor = Theme.mainColor
} else {
self.view.backgroundColor = .white
}
if self.options.tabMenuPosition == .custom {
self.view.addSubview(self.tabMenuView)
self.tabMenuView.translatesAutoresizingMaskIntoConstraints = false
self.tabMenuView.heightAnchor.constraint(equalToConstant: self.options.menuItemSize.height).isActive = true
self.tabMenuView.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true
self.tabMenuView.rightAnchor.constraint(equalTo: self.view.rightAnchor).isActive = true
if #available(iOS 11.0, *) {
self.tabMenuView.bottomAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.bottomAnchor).isActive = true
} else {
self.tabMenuView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true
}
}
self.delegate = self
self.dataSource = self
self.parentController?.scrollToNext = { [weak self] value in
guard let `self` = self else {
return
}
if value {
self.scrollToNext(animated: true, completion: { _ in })
} else {
self.scrollToPrevious(animated: true, completion: { _ in })
}
}
}
}
extension PageTabMenuViewController: PageMenuControllerDataSource {
func viewControllers(forPageMenuController pageMenuController: PageMenuController) -> [UIViewController] {
return self.titles.enumerated().map({ (i, title) -> UIViewController in
let daySring = DayOfWeek.dayWithIndex(index: i)
guard let viewController = TabContentViewController.instantiate(dayOfWeek: DayOfWeek.init(fromString: daySring.uppercased())) else {
return UIViewController()
}
viewController.delegate = parentController
return viewController
})
}
func menuTitles(forPageMenuController pageMenuController: PageMenuController) -> [String] {
return self.titles
}
func defaultPageIndex(forPageMenuController pageMenuController: PageMenuController) -> Int {
let currentDay = Date().dayNumberOfWeek()
// pageTabMenuDelegate?.currentPageIndex(indexPage: currentDay)
parentController?.currentPageIndex(indexPage: currentDay)
return currentDay
}
}
extension PageTabMenuViewController: PageMenuControllerDelegate {
func pageMenuController(_ pageMenuController: PageMenuController, didScrollToPageAtIndex index: Int, direction: PageMenuNavigationDirection) {
// The page view controller will begin scrolling to a new page.
print("didScrollToPageAtIndex index:\(index)")
pageTabMenuDelegate?.currentPageIndex(indexPage: index)
}
func pageMenuController(_ pageMenuController: PageMenuController, willScrollToPageAtIndex index: Int, direction: PageMenuNavigationDirection) {
// The page view controller scroll progress between pages.
print("willScrollToPageAtIndex index:\(index)")
}
func pageMenuController(_ pageMenuController: PageMenuController, scrollingProgress progress: CGFloat, direction: PageMenuNavigationDirection) {
// The page view controller did complete scroll to a new page.
print("scrollingProgress progress: \(progress)")
}
func pageMenuController(_ pageMenuController: PageMenuController, didSelectMenuItem index: Int, direction: PageMenuNavigationDirection) {
pageTabMenuDelegate?.currentPageIndex(indexPage: index)
print("didSelectMenuItem index: \(index)")
}
}
<file_sep>//
// RoomTypeDataSource.swift
// Koleda
//
// Created by <NAME> on 7/9/19.
// Copyright © 2019 koleda. All rights reserved.
//
import Foundation
import UIKit
class RoomTypeDataSource: NSObject, UICollectionViewDataSource {
var roomTypes: [RoomType]?
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView,
numberOfItemsInSection section: Int) -> Int {
return roomTypes?.count ?? 0
}
func collectionView(_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "RoomTypeCell", for: indexPath) as? RoomTypeCell, let roomTypes = roomTypes else {
fatalError()
}
let roomType = roomTypes[indexPath.item]
cell.loadData(roomType: roomType)
return cell
}
}
<file_sep>//
// InstructionViewModel.swift
// Koleda
//
// Created by <NAME> on 9/6/19.
// Copyright © 2019 koleda. All rights reserved.
//
import UIKit
import RxSwift
protocol InstructionViewModelProtocol: BaseViewModelProtocol {
var typeInstructions: Variable<[TypeInstruction]> { get }
func backToRoot()
func nextToSensorManagement(roomId: String, roomName: String, isFromRoomConfiguration: Bool)
}
class InstructionViewModel: InstructionViewModelProtocol {
var typeInstructions: Variable<[TypeInstruction]> = Variable<[TypeInstruction]>([])
var router: BaseRouterProtocol
init(router: BaseRouterProtocol, typeInstructions: [TypeInstruction]) {
self.router = router
self.typeInstructions.value = typeInstructions
}
func backToRoot() {
if let router = self.router as? InstructionForSensorRouter {
router.backToRoot()
}
}
func nextToSensorManagement(roomId: String, roomName: String, isFromRoomConfiguration: Bool) {
if let router = self.router as? InstructionForSensorRouter {
router.nextToSensorManagement(roomId: roomId, roomName: roomName, isFromRoomConfiguration: isFromRoomConfiguration)
}
}
}
<file_sep>//
// SensorManagementViewController.swift
// Koleda
//
// Created by <NAME> on 7/17/19.
// Copyright © 2019 koleda. All rights reserved.
//
import UIKit
import SVProgressHUD
import RxSwift
import SwiftRichString
class SensorManagementViewController: BaseViewController, BaseControllerProtocol {
@IBOutlet weak var statusImageView: UIImageView!
@IBOutlet weak var statusTitleLabel: UILabel!
@IBOutlet weak var statusSubTitleLabel: UILabel!
@IBOutlet weak var sensorModelLabel: UILabel!
@IBOutlet weak var sensorView: UIView!
@IBOutlet weak var addedSuccessfullyView: UIView!
@IBOutlet weak var statusView: UIView!
@IBOutlet weak var roomNameLabel: UILabel!
@IBOutlet weak var sensorNameLabel: UILabel!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var detectOneSensorView: UIView!
@IBOutlet weak var addSensorButton: UIButton!
@IBOutlet weak var tryAgainButton: UIButton!
@IBOutlet weak var connectToDeviceHotspotButton: UIButton!
@IBOutlet weak var doneButton: UIButton!
@IBOutlet weak var nextView: UIView!
@IBOutlet weak var cancelButton: UIButton!
var isFromRoomConfiguration: Bool = false
let normal = SwiftRichString.Style{
$0.font = UIFont.SFProDisplaySemibold20
$0.color = UIColor.white
}
let bold = SwiftRichString.Style {
$0.font = UIFont.SFProDisplaySemibold20
$0.color = UIColor.hexFF7020
}
var viewModel: SensorManagementViewModelProtocol!
private let disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
configurationUI()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationBarTransparency()
navigationController?.setNavigationBarHidden(true, animated: animated)
startToDectectDevice()
}
deinit {
NotificationCenter.default.removeObserver(self)
}
@objc private func scanShellyDevices() {
startToDectectDevice()
}
}
extension SensorManagementViewController {
private func startToDectectDevice() {
self.view.endEditing(true)
viewModel.updateUI(with: .search)
let ssid = viewModel.getCurrentWiFiName()
print(ssid)
guard FGRoute.getGatewayIP() != nil else {
if ssid != "" && DataValidator.isShellyDevice(hostName: ssid) {
SVProgressHUD.show()
viewModel.fetchInfoOfSensorAPMode(completion: { [weak self] success in
SVProgressHUD.dismiss()
if success {
self?.viewModel.updateUI(with: .joinDeviceHotSpot)
} else {
self?.viewModel.updateUI(with: .noDevice)
}
})
} else {
NotificationCenter.default.post(name: .KLDNotConnectedToInternet, object: nil)
self.viewModel.updateUI(with: .noDevice)
}
return
}
closeButton?.isEnabled = false
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
SVProgressHUD.show()
self.viewModel.findSensorsOnLocalNetwork { [weak self] in
SVProgressHUD.dismiss()
self?.viewModel.updateStatusAfterSeaching()
self?.closeButton?.isEnabled = true
}
}
}
func configurationUI() {
doneButton.isHidden = true
cancelButton.isHidden = true
nextView.isHidden = true
titleLabel.attributedText = viewModel.titleAttributed
roomNameLabel.text = viewModel.roomNameWithUserName
let group = StyleGroup(base: self.normal, ["h1": self.bold])
canBackToPreviousScreen = false
NotificationCenter.default.addObserver(self, selector: #selector(scanShellyDevices),
name: .KLDDidChangeWifi, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(scanShellyDevices),
name: .KLDNeedToReSearchDevices, object: nil)
viewModel.statusImage.asObservable().subscribe(onNext: { [weak self] image in
guard let statusImage = image else {
self?.statusImageView.isHidden = true
return
}
self?.statusImageView.isHidden = false
self?.statusImageView.image = statusImage
}).disposed(by: disposeBag)
viewModel.statusTitle.asObservable().subscribe(onNext: { [weak self] title in
self?.statusTitleLabel.isHidden = (title == "")
self?.statusTitleLabel.attributedText = title.set(style: group)
}).disposed(by: disposeBag)
viewModel.statusSubTitle.asObservable().subscribe(onNext: { [weak self] title in
self?.statusSubTitleLabel.isHidden = (title == "")
self?.statusSubTitleLabel.text = title
}).disposed(by: disposeBag)
viewModel.statusViewHidden.asObservable().bind(to: statusView.rx.isHidden).disposed(by: disposeBag)
viewModel.tryAgainButtonHidden.asObservable().bind(to: tryAgainButton.rx.isHidden).disposed(by: disposeBag)
viewModel.connectToDeviceHotspotButtonHidden.asObservable().bind(to: connectToDeviceHotspotButton.rx.isHidden).disposed(by: disposeBag)
viewModel.cancelButtonHidden.asObservable().bind(to: cancelButton.rx.isHidden).disposed(by: disposeBag)
viewModel.sensorViewHidden.asObservable().bind(to: sensorView.rx.isHidden).disposed(by: disposeBag)
viewModel.sensorModel.asObservable().bind(to: sensorModelLabel.rx.text).disposed(by: disposeBag)
viewModel.addedSuccessfullyViewHidden.asObservable().subscribe(onNext: { [weak self] isHidden in
guard let `self` = self else {
return
}
self.addedSuccessfullyView.isHidden = isHidden
if !isHidden {
self.doneButton.isHidden = !self.isFromRoomConfiguration
self.nextView.isHidden = self.isFromRoomConfiguration
}
}).disposed(by: disposeBag)
addSensorButton.rx.tap.bind { [weak self] in
self?.addSensorButton.isEnabled = false
self?.viewModel.updateUI(with: .addDevice)
self?.viewModel.addASensorToARoom { error in
self?.addSensorButton.isEnabled = true
self?.sensorNameLabel.text = self?.viewModel.sensorName
guard let error = error else {
NotificationCenter.default.post(name: .KLDDidChangeRooms, object: nil)
self?.viewModel.updateUI(with: .addDeviceSuccess)
return
}
if error == WSError.deviceExisted {
let errorMess = String(format: "%@ %@", "THIS_SENSOR_TEXT".app_localized, error.localizedDescription)
self?.app_showAlertMessage(title: "ERROR_TITLE".app_localized, message: errorMess.app_localized)
} else {
self?.app_showAlertMessage(title: "ERROR_TITLE".app_localized, message: "CAN_NOT_ADD_SENSOR_MESS".app_localized)
}
self?.viewModel.updateStatusAfterSeaching()
}
}.disposed(by: disposeBag)
tryAgainButton.rx.tap.bind { [weak self] in
self?.startToDectectDevice()
}.disposed(by: disposeBag)
connectToDeviceHotspotButton.rx.tap.bind { [weak self] in
self?.goWifiSetting()
}.disposed(by: disposeBag)
viewModel.changeWifiForShellyDevice.asObservable().subscribe(onNext: { [weak self] in
guard let ssid = UserDefaultsManager.wifiSsid.value, let pass = UserDefaultsManager.wifiPass.value else {
self?.app_showAlertMessage(title: "ERROR_TITLE".app_localized, message: "UPDATE_WIFI_SETTINGS_INFO_MESS".app_localized)
return
}
self?.joinSensorToWifiNetwork(ssid: ssid, pass: pass)
}).disposed(by: disposeBag)
connectToDeviceHotspotButton.setTitle("CONNECT_TO_SENSOR_HOTSPOT_TEXT".app_localized, for: .normal)
tryAgainButton.setTitle("TRY_AGAIN_TEXT".app_localized, for: .normal)
cancelButton.setTitle("CANCEL".app_localized, for: .normal)
addSensorButton.setTitle("ADD_TEXT".app_localized, for: .normal)
doneButton.setTitle("DONE_TEXT".app_localized, for: .normal)
}
private func goWifiSetting() {
let OkAction = UIAlertAction(title: "OK".app_localized, style: .default) { action in
guard let url = URL(string: UIApplication.openSettingsURLString) else {
return
}
if UIApplication.shared.canOpenURL(url) {
UIApplication.shared.open(url, options: [:])
}
}
let cancelAction = UIAlertAction(title: "CANCEL".app_localized, style: .cancel) { action in
}
app_showAlertMessage(title: "KOLEDA_TEXT".app_localized,
message: "INSTRUCTION_FOR_SELECT_YOUR_SENSOR_HOTSPOT_MESS".app_localized, actions: [cancelAction, OkAction])
}
private func joinSensorToWifiNetwork(ssid: String, pass: String) {
self.view.endEditing(true)
SVProgressHUD.show()
viewModel.connectSensorLocalWifi(ssid: ssid, pass: pass) { [weak self] isSuccess in
SVProgressHUD.dismiss()
if isSuccess {
self?.viewModel.updateUI(with: .search)
self?.app_showInfoAlert("SENSOR_CONNECTED_TO_YOUR_LOCAL_WIFI_MESS".app_localized, title: "SUCCESSFULL_TEXT".app_localized, completion: {
SVProgressHUD.show()
self?.viewModel.waitingSensorsJoinNetwork(completion: {
SVProgressHUD.dismiss(completion: {
self?.startToDectectDevice()
})
})
})
} else {
self?.viewModel.updateUI(with: .noDevice)
self?.app_showInfoAlert("WIFI_SSID_OR_PASS_IS_INCORRECT_MESS".app_localized, title: "ERROR_TITLE".app_localized, completion: {
self?.viewModel.showWifiDetail()
})
}
}
}
@IBAction func nextAction(_ sender: Any) {
self.viewModel.goAddHeaterFlow()
}
@IBAction func backAction(_ sender: Any) {
if self.addedSuccessfullyView.isHidden == false {
if isFromRoomConfiguration {
backToViewControler(viewController: ConfigurationRoomViewController.self)
} else {
backToRoot()
}
} else {
back()
}
}
}
extension SensorManagementViewController: UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
self.view.endEditing(true)
return true
}
}
<file_sep>//
// BaseControllerProtocol.swift
// Koleda
//
// Created by <NAME> on 5/23/19.
// Copyright © 2019 koleda. All rights reserved.
//
protocol BaseControllerProtocol: class {
associatedtype ViewModelType
var viewModel: ViewModelType! { get set }
}
<file_sep>//
// EditSensorViewModel.swift
// Koleda
//
// Created by <NAME> on 9/4/19.
// Copyright © 2019 koleda. All rights reserved.
//
import Foundation
import RxSwift
import CopilotAPIAccess
protocol EditSensorViewModelProtocol: BaseViewModelProtocol {
var sensorName: Variable<String> { get }
var sensorStatus: Variable<Bool> { get }
var nPairedHeaters:Variable<Int> { get }
var pairedWithHeaters: Variable<String> { get }
var sensorModel: Variable<String> { get }
var roomName: Variable<String> { get }
var temperature: Variable<String> { get }
var humidity: Variable<String> { get }
var battery: Variable<String> { get }
func needUpdateSelectedRoom()
func deleteSensor(completion: @escaping (Bool) -> Void)
func backToHome()
}
class EditSensorViewModel: BaseViewModel, EditSensorViewModelProtocol {
let router: BaseRouterProtocol
let sensorName = Variable<String>("")
let sensorStatus = Variable<Bool>(false)
var nPairedHeaters = Variable<Int>(0)
let pairedWithHeaters = Variable<String>("")
let sensorModel = Variable<String>("")
let roomName = Variable<String>("")
let temperature = Variable<String>("")
let humidity = Variable<String>("")
let battery = Variable<String>("")
private let shellyDeviceManager: ShellyDeviceManager
private var room: Room
init(router: BaseRouterProtocol, managerProvider: ManagerProvider = .sharedInstance, seletedRoom: Room) {
self.router = router
self.shellyDeviceManager = managerProvider.shellyDeviceManager
self.room = seletedRoom
super.init(managerProvider: managerProvider)
setup()
}
private func setup() {
let roomViewModel = RoomViewModel.init(room: room)
if let sensor = roomViewModel.sensor {
sensorStatus.value = sensor.enabled
sensorModel.value = sensor.deviceModel
}
let heatersNumber = roomViewModel.heaters?.count ?? 0
sensorName.value = "\(roomViewModel.roomName) Sensor".app_localized
pairedWithHeaters.value = heatersNumber > 0 ? String(format: "NUMBER_HEATERS_CONNECTED_MESS".app_localized, heatersNumber) : "NOT_PAIRED_WITH_ANY_SOLUS_MESS".app_localized
nPairedHeaters.value = heatersNumber
roomName.value = String(format: "ROOM_SENSOR_TEXT".app_localized, roomViewModel.roomName)
temperature.value = roomViewModel.temprature
temperature.value = roomViewModel.temprature
humidity.value = roomViewModel.humidity
battery.value = roomViewModel.sensorBattery
}
func needUpdateSelectedRoom() {
if let room = UserDataManager.shared.roomWith(roomId: room.id) {
self.room = room
setup()
}
}
func deleteSensor(completion: @escaping (Bool) -> Void) {
guard let sensor = room.sensor else {
return
}
shellyDeviceManager.deleteDevice(roomId: room.id ,deviceId: sensor.id, success: {
Copilot.instance.report.log(event: RemoveSensorAnalyticsEvent(sensorId: sensor.id, screenName: self.screenName))
completion(true)
},
failure: { error in
completion(false)
})
}
func backToHome() {
router.enqueueRoute(with: EditSensorRouter.RouteType.backHome)
}
}
<file_sep>
//
// SmartSchedulingRouter.swift
// Koleda
//
// Created by <NAME> on 10/22/19.
// Copyright © 2019 koleda. All rights reserved.
//
import Foundation
import UIKit
class SmartSchedulingRouter: BaseRouterProtocol {
weak var baseViewController: UIViewController?
enum RouteType {
case scheduleDetail(Time, DayOfWeek, Bool)
}
func dismiss(animated: Bool, context: Any?, completion: ((Bool) -> Void)?) {
}
func enqueueRoute(with context: Any?, animated: Bool, completion: ((Bool) -> Void)?) {
guard let routeType = context as? RouteType else {
assertionFailure("The route type missmatches")
return
}
guard let baseViewController = baseViewController else {
assertionFailure("baseViewController is not set")
return
}
switch routeType {
case .scheduleDetail(let startTime, let day, let tapedTimeline):
let router = SmartScheduleDetailRouter()
let viewModel = SmartScheduleDetailViewModel.init(router: router, startTime: startTime, dayOfWeek: day, tapedTimeline: tapedTimeline)
guard let viewController = StoryboardScene.SmartSchedule.instantiateSmartScheduleDetailViewController() as? SmartScheduleDetailViewController else { return }
viewController.viewModel = viewModel
router.baseViewController = viewController
baseViewController.navigationController?.pushViewController(viewController, animated: true)
default:
break
}
}
func present(on baseVC: UIViewController, animated: Bool, context: Any?, completion: ((Bool) -> Void)?) {
}
}
<file_sep>//
// LocationSetupRouter.swift
// Koleda
//
// Created by <NAME> on 7/4/19.
// Copyright © 2019 koleda. All rights reserved.
//
import Foundation
import UIKit
class LocationSetupRouter: BaseRouterProtocol {
weak var baseViewController: UIViewController?
enum RouteType {
case decline
case wifiSetup
case welcomeJoinHome
}
func dismiss(animated: Bool, context: Any?, completion: ((Bool) -> Void)?) {
}
func enqueueRoute(with context: Any?, animated: Bool, completion: ((Bool) -> Void)?) {
guard let routeType = context as? RouteType else {
assertionFailure("The route type missmatches")
return
}
guard let baseViewController = baseViewController else {
assertionFailure("baseViewController is not set")
return
}
switch routeType {
case .decline:
let router = OnboardingRouter()
let viewModel = OnboardingViewModel.init(with: router)
let onboaringNavigationVC = StoryboardScene.Onboarding.instantiateNavigationController()
guard let viewController = onboaringNavigationVC.topViewController as? OnboardingViewController else {
assertionFailure("OnBoarding storyboard configured not properly")
return
}
viewController.viewModel = viewModel
router.baseViewController = viewController
if let delegate = UIApplication.shared.delegate as? AppDelegate {
delegate.window?.rootViewController = onboaringNavigationVC
}
case .wifiSetup:
let router = WifiSetupRouter()
let viewModel = WifiSetupViewModel.init(router: router)
guard let viewController = StoryboardScene.Setup.instantiateWifiSetupViewController() as? WifiSetupViewController else {
assertionFailure("Setup storyboard configured not properly")
return
}
viewController.viewModel = viewModel
router.baseViewController = viewController
baseViewController.navigationController?.pushViewController(viewController, animated: true)
case .welcomeJoinHome:
let router = WelcomeJoinHomeRouter()
let viewModel = WelcomeJoinHomeViewModel.init(router: router)
guard let viewController = StoryboardScene.Onboarding.instantiateWelcomeJoinHomeViewController() as? WelcomeJoinHomeViewController else {
assertionFailure("Setup storyboard configured not properly")
return
}
viewController.viewModel = viewModel
router.baseViewController = viewController
baseViewController.navigationController?.pushViewController(viewController, animated: true)
}
}
func present(on baseVC: UIViewController, animated: Bool, context: Any?, completion: ((Bool) -> Void)?) {
}
}
<file_sep>//
// SelectedRoomViewModel.swift
// Koleda
//
// Created by <NAME> on 8/26/19.
// Copyright © 2019 koleda. All rights reserved.
//
import Foundation
import RxSwift
import CopilotAPIAccess
protocol SelectedRoomViewModelProtocol: BaseViewModelProtocol {
var homeTitle: Variable<String> { get }
var temperature: Variable<String> { get }
var humidity: Variable<String> { get }
var sensorBattery: Variable<String> { get }
var turnOnRoom: PublishSubject<Bool> { get }
var modeItems: Variable<[ModeItem]> { get }
var ecoModeUpdate: PublishSubject<Bool> { get }
var comfortModeUpdate: PublishSubject<Bool> { get }
var nightModeUpdate: PublishSubject<Bool> { get }
var smartScheduleModeUpdate: PublishSubject<Bool> { get }
var canAdjustTemp: PublishSubject<Bool> { get }
//update
var currentValueSlider: Int { get }
var editingTemprature: Variable<Int> { get }
var editingTempratureSmall: Variable<Int> { get }
var statusText: Variable<String> { get }
var statusImageName: Variable<String> { get }
var startTemprature: Variable<Int> { get }
var endTemprature: Variable<Int> { get }
var timeSliderValue: Variable<Float> { get }
var endTime: Variable<String> { get }
var countDownTime: Variable<String> { get }
var turnOnManualBoost: Variable<Bool> { get }
var temperatureSliderRange: [Int] { get }
var refreshTempCircleSlider: PublishSubject<Void> { get }
var performBoosting: PublishSubject<Void> { get }
var manualBoostTimeout: PublishSubject<Void> { get }
var settingType: SettingType { get }
var heaters: [Heater] { get }
func setup()
func showConfigurationScreen()
func needUpdateSelectedRoom()
func updateSettingMode(mode: SmartMode, completion: @escaping (SmartMode, Bool, String) -> Void)
func changeSmartMode(seletedSmartMode: SmartMode)
func turnOnOrOffRoom(completion: @escaping (_ isTurnOn: Bool, _ isSuccess: Bool) -> Void)
func turnOnOrOffScheduleMode(completion: @escaping (Bool, String) -> Void)
//update
func updateSettingTime(seconds: Int)
func adjustTemprature(increased: Bool)
func temperatureSliderChanged(value: Int)
func manualBoostUpdate(completion: @escaping (Bool) -> Void)
func resetManualBoost(completion: @escaping (Bool, String) -> Void)
func refreshRoom(completion: @escaping (Bool) -> Void)
func checkForAutoUpdateManualBoost(updatedTemp: Bool)
}
class SelectedRoomViewModel: BaseViewModel, SelectedRoomViewModelProtocol {
let homeTitle = Variable<String>("")
let temperature = Variable<String>("")
let humidity = Variable<String>("")
let sensorBattery = Variable<String>("")
let turnOnRoom = PublishSubject<Bool>()
var modeItems = Variable<[ModeItem]>([])
var ecoModeUpdate = PublishSubject<Bool>()
var comfortModeUpdate = PublishSubject<Bool>()
var nightModeUpdate = PublishSubject<Bool>()
var smartScheduleModeUpdate = PublishSubject<Bool>()
let canAdjustTemp = PublishSubject<Bool>()
var currentValueSlider = 0
let editingTemprature = Variable<Int>(0)
let editingTempratureSmall = Variable<Int>(0)
var statusText = Variable<String>("")
var statusImageName = Variable<String>("")
let startTemprature = Variable<Int>(0)
let endTemprature = Variable<Int>(0)
let timeSliderValue = Variable<Float>(0)
let endTime = Variable<String>("")
let countDownTime = Variable<String>("")
let turnOnManualBoost = Variable<Bool>(false)
var temperatureSliderRange: [Int] = []
let refreshTempCircleSlider = PublishSubject<Void>()
let performBoosting = PublishSubject<Void>()
let manualBoostTimeout = PublishSubject<Void>()
let router: BaseRouterProtocol
private let roomManager: RoomManager
private var seletedRoom: Room?
private let schedulesManager: SchedulesManager
private let settingManager: SettingManager
private var currentSelectedMode: SmartMode = .DEFAULT
var settingType: SettingType = .unknow
var heaters: [Heater] = []
var exitingSmartSchedule: Bool?
var enableSchedule: Bool = false
private var timer:Timer?
init(router: BaseRouterProtocol, managerProvider: ManagerProvider = .sharedInstance, seletedRoom: Room? = nil) {
self.router = router
roomManager = managerProvider.roomManager
schedulesManager = managerProvider.schedulesManager
settingManager = managerProvider.settingManager
self.seletedRoom = seletedRoom
super.init(managerProvider: managerProvider)
}
func setup() {
guard let userName = UserDataManager.shared.currentUser?.name, let room = seletedRoom else {
return
}
let roomViewModel = RoomViewModel.init(room: room)
turnOnRoom.onNext(roomViewModel.onOffSwitchStatus)
homeTitle.value = roomViewModel.roomName
temperature.value = roomViewModel.temprature
humidity.value = roomViewModel.humidity
sensorBattery.value = roomViewModel.sensorBattery
settingType = roomViewModel.settingType
heaters = roomViewModel.heaters ?? []
enableSchedule = roomViewModel.enableSchedule
if let heater = roomViewModel.heaters, heater.count > 0 {
canAdjustTemp.onNext(true)
} else {
canAdjustTemp.onNext(false)
}
modeItems.value = UserDataManager.shared.settingModes
getExistingSmartSchedule()
turnOnManualBoost.value = false
switch settingType {
case .MANUAL:
changeSmartMode(seletedSmartMode: .DEFAULT)
turnOnManualBoost.value = true
case .SMART:
changeSmartMode(seletedSmartMode: roomViewModel.smartMode)
default:
if enableSchedule {
changeSmartMode(seletedSmartMode: .SMARTSCHEDULE)
} else {
changeSmartMode(seletedSmartMode: .DEFAULT)
}
}
countDownTime.value = roomViewModel.remainSettingTime.fullTimeFormart()
updateSettingTime(seconds: roomViewModel.endTimePoint)
loadCurrentSliderTemperature(temp: roomViewModel.settingTemprature.0)
}
func turnOnOrOffRoom(completion: @escaping (_ isTurnOn: Bool, _ isSuccess: Bool) -> Void) {
guard let room = seletedRoom else {
completion(false, false)
return
}
let roomViewModel = RoomViewModel.init(room: room)
let status = !roomViewModel.onOffSwitchStatus
roomManager.switchRoom(roomId: room.id, turnOn: status, success: {
NotificationCenter.default.post(name: .KLDDidChangeRooms, object: nil)
Copilot.instance.report.log(event: UpdateRoomStatusAnalyticsEvent(homeId: UserDataManager.shared.currentUser?.homes[0].id ?? "", roomId: room.id, isEnable:status, screenName: self.screenName))
completion(status, true)
}, failure: { _ in
completion(status, false)
})
}
func showConfigurationScreen() {
guard let room = seletedRoom else {
return
}
self.router.enqueueRoute(with: SelectedRoomRouter.RouteType.configuration(room))
}
func needUpdateSelectedRoom() {
let room = UserDataManager.shared.rooms.filter { $0.id == seletedRoom?.id }.first
if room != nil {
seletedRoom = room
setup()
}
}
func changeSmartMode(seletedSmartMode: SmartMode) {
currentSelectedMode = seletedSmartMode
switch seletedSmartMode {
case .ECO:
ecoModeUpdate.onNext(true)
comfortModeUpdate.onNext(false)
nightModeUpdate.onNext(false)
smartScheduleModeUpdate.onNext(false)
case .COMFORT:
ecoModeUpdate.onNext(false)
comfortModeUpdate.onNext(true)
nightModeUpdate.onNext(false)
smartScheduleModeUpdate.onNext(false)
case .NIGHT:
ecoModeUpdate.onNext(false)
comfortModeUpdate.onNext(false)
nightModeUpdate.onNext(true)
smartScheduleModeUpdate.onNext(false)
case .SMARTSCHEDULE:
ecoModeUpdate.onNext(false)
comfortModeUpdate.onNext(false)
nightModeUpdate.onNext(false)
smartScheduleModeUpdate.onNext(true)
default:
ecoModeUpdate.onNext(false)
comfortModeUpdate.onNext(false)
nightModeUpdate.onNext(false)
smartScheduleModeUpdate.onNext(false)
}
}
func updateSettingMode(mode: SmartMode, completion: @escaping (SmartMode, Bool, String) -> Void) {
let modeForUpdate = (mode == currentSelectedMode) ? .DEFAULT : mode
callServiceToUpdateMode(mode: modeForUpdate) { isSuccess in
if isSuccess {
completion(modeForUpdate ,true, "")
} else {
completion(modeForUpdate ,false, "CAN_NOT_UPDATE_SETTING_MODE".app_localized)
}
}
}
//update
func updateSettingTime(seconds: Int) {
timeSliderValue.value = Float(seconds)
guard seconds <= Constants.MAX_END_TIME_POINT else {
endTime.value = ""
countDownTime.value = "BOOSTING_UNTIL_YOU_CANCEL".app_localized
stopTimer()
return
}
if seconds == 0 {
endTime.value = "00:00"
countDownTime.value = seconds.fullTimeFormart()
stopTimer()
} else {
let time = Date().adding(seconds: seconds)
endTime.value = String(format: "BOOSTING_UNTIL_TIME".app_localized, time.fomartAMOrPm())
countDownTime.value = seconds.fullTimeFormart()
runTimer()
}
}
func adjustTemprature(increased: Bool) {
if increased {
increaseTemp()
} else {
decreaseTemp()
}
loadCurrentSliderTemperature(temp: editingTemprature.value)
checkForAutoUpdateManualBoost(updatedTemp: true)
}
func temperatureSliderChanged(value: Int) {
let startTemp = startTemprature.value
if UserDataManager.shared.temperatureUnit == .C {
editingTemprature.value = value/2 + startTemp
editingTempratureSmall.value = 0
} else {
editingTemprature.value = value + startTemp
editingTempratureSmall.value = 0
}
guard let currentTemp = temperature.value.kld_doubleValue else {
return
}
let targetTemp = Double(editingTemprature.value) + 0.1*Double(editingTempratureSmall.value)
statusText.value = targetTemp > currentTemp ? "HEATING_TO_TEXT".app_localized.uppercased() : (targetTemp == currentTemp ? "" : "COOLING_DOWN_TEXT".app_localized.uppercased())
statusImageName.value = targetTemp > currentTemp ? "ic-heating-up-small" : (targetTemp == currentTemp ? "" : "ic-cooling-down-small")
}
func manualBoostUpdate(completion: @escaping (Bool) -> Void) {
guard let roomId = seletedRoom?.id else {
completion(false)
return
}
let time = Int(timeSliderValue.value)
var temprature: Double = Double(editingTemprature.value) + Double(editingTempratureSmall.value) * 0.1
if UserDataManager.shared.temperatureUnit == .F {
temprature = temprature.celciusTemperature
}
let timeSetting = time > Constants.MAX_END_TIME_POINT ? 0 : time
roomManager.manualBoostUpdate(roomId: roomId, temp: temprature, time: timeSetting, success: {
Copilot.instance.report.log(event: UpdateManualBoostAnalyticsEvent(roomId: roomId, temp: temprature, time: timeSetting, screenName: self.screenName))
completion(true)
}, failure: { error in
completion(false)
})
}
func resetManualBoost(completion: @escaping (Bool, String) -> Void) {
guard turnOnManualBoost.value && settingType == .MANUAL else {
completion(false, "")
if turnOnManualBoost.value {
turnOnManualBoost.value = false
refreshTempCircleSlider.onNext(())
updateSettingTime(seconds: 0)
} else {
turnOnManualBoost.value = true
}
return
}
turnOnManualBoost.value = false
if let room = seletedRoom {
let roomViewModel = RoomViewModel.init(room: room)
if roomViewModel.settingType == .MANUAL {
settingManager.resetManualBoost(roomId: room.id, success: { [weak self] in
guard let `self` = self else {
return
}
Copilot.instance.report.log(event: ResetManualBoostAnalyticsEvent(roomId: room.id, screenName: self.screenName))
completion(true, "")
}) { [weak self] _ in
self?.turnOnManualBoost.value = true
completion(false, "MANUAL_BOOST_CAN_NOT_RESET_MESS".app_localized)
}
} else {
setup()
completion(false, "")
}
}
}
func refreshRoom(completion: @escaping (Bool) -> Void) {
guard let roomId = seletedRoom?.id else {
completion(false)
return
}
roomManager.getRoom(roomId: roomId, success: { [weak self] room in
self?.seletedRoom = room
self?.setup()
completion(true)
}, failure: { error in
completion(false)
})
}
func checkForAutoUpdateManualBoost(updatedTemp: Bool) {
guard let room = seletedRoom else {
return
}
let roomViewModel = RoomViewModel.init(room: room)
if updatedTemp {
if settingType != .MANUAL && Int(timeSliderValue.value) == 0 {
updateSettingTime(seconds: Constants.DEFAULT_BOOSTING_END_TIME_POINT)
}
let time = Int(timeSliderValue.value)
let editTemprature: Double = Double(editingTemprature.value) + Double(editingTempratureSmall.value) * 0.1
let currentTemprature: Double = Double(roomViewModel.settingTemprature.0) + Double(roomViewModel.settingTemprature.1) * 0.1
guard time > 0 && currentTemprature != editTemprature else {
return
}
performBoosting.onNext(())
} else if settingType == .MANUAL && roomViewModel.endTimePoint != Int(timeSliderValue.value) {
performBoosting.onNext(())
}
}
private func runTimer() {
stopTimer()
timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(updateCountDown), userInfo: nil, repeats: true )
}
private func stopTimer() {
if timer != nil {
timer?.invalidate()
timer = nil
}
}
@objc private func updateCountDown() {
if(timeSliderValue.value > 0) {
timeSliderValue.value = timeSliderValue.value - 1
countDownTime.value = Int(timeSliderValue.value).fullTimeFormart()
} else {
manualBoostTimeout.onNext(())
stopTimer()
}
}
///-------
private func increaseTemp() {
let maxTemp = UserDataManager.shared.temperatureUnit == .C ? Constants.MAX_TEMPERATURE : Constants.MAX_TEMPERATURE.fahrenheitTemperature
guard editingTemprature.value < Int(maxTemp) else {
return
}
editingTemprature.value = editingTemprature.value + 1
}
private func decreaseTemp() {
let minTemp = UserDataManager.shared.temperatureUnit == .C ? Constants.MIN_TEMPERATURE : Constants.MIN_TEMPERATURE.fahrenheitTemperature
guard editingTemprature.value > Int(minTemp) else {
return
}
editingTemprature.value = editingTemprature.value - 1
}
func turnOnOrOffScheduleMode(completion: @escaping (Bool, String) -> Void) {
if currentSelectedMode != .SMARTSCHEDULE { // will turn on Schedule
guard let isExitingSmartSchedule = exitingSmartSchedule else {
completion(false, "")
return
}
if !isExitingSmartSchedule {
completion(false, "THERE_IS_NO_SCHEDULE_MESS".app_localized)
} else {
turnOnSchedule(afterTurnOffSmartMode: currentSelectedMode != .DEFAULT) { [weak self] isSuccess in
if isSuccess {
completion(true, "")
} else {
completion(false, "CAN_NOT_UPDATE_SCHEDULE_MODE_MESS".app_localized)
}
}
}
} else {
callServiceTurnOnOrOffSmartSchedule(isOn: false) { [weak self] isSuccess in
if isSuccess {
completion(true, "")
} else {
completion(false, "CAN_NOT_UPDATE_SCHEDULE_MODE_MESS".app_localized)
}
}
}
}
private func loadCurrentSliderTemperature(temp: Int) {
if UserDataManager.shared.temperatureUnit == .C {
startTemprature.value = Int(Constants.MIN_TEMPERATURE)
endTemprature.value = Int(Constants.MAX_TEMPERATURE)
temperatureSliderRange = [Int](0...(endTemprature.value - startTemprature.value)*2)
let temp = temp - startTemprature.value
currentValueSlider = temp > 0 ? temp*2 : 0
} else {
startTemprature.value = Int(Constants.MIN_TEMPERATURE.fahrenheitTemperature)
endTemprature.value = Int(Constants.MAX_TEMPERATURE.fahrenheitTemperature)
temperatureSliderRange = [Int](0...(endTemprature.value - startTemprature.value))
let temp = temp - startTemprature.value
currentValueSlider = temp > 0 ? temp : 0
}
refreshTempCircleSlider.onNext(())
}
private func callServiceToUpdateMode(mode: SmartMode, completion: @escaping (Bool) -> Void) {
guard let roomId = seletedRoom?.id else {
completion(false)
return
}
settingManager.updateSettingMode(mode: mode.rawValue, roomId: roomId, success: {
Copilot.instance.report.log(event: SetModeAnalyticsEvent(roomId: roomId, mode: mode.rawValue, screenName: self.screenName))
completion(true)
}) { error in
completion(false)
}
}
private func getExistingSmartSchedule() {
guard let roomId = seletedRoom?.id else {
return
}
schedulesManager.checkExistingSmartSchedules(roomId: roomId) { [weak self] isExisting in
self?.exitingSmartSchedule = isExisting
}
}
private func turnOnSchedule(afterTurnOffSmartMode: Bool, completion: @escaping (Bool) -> Void) {
if afterTurnOffSmartMode {
callServiceToUpdateMode(mode: .DEFAULT) { [weak self] isSuccess in
guard isSuccess else {
completion(false)
return
}
guard let `self` = self else {
completion(false)
return
}
if self.enableSchedule {
completion(isSuccess)
} else {
self.callServiceTurnOnOrOffSmartSchedule(isOn: true, completion: { isSuccess in
completion(isSuccess)
})
}
}
} else {
if self.enableSchedule {
completion(true)
} else {
self.callServiceTurnOnOrOffSmartSchedule(isOn: true, completion: { isSuccess in
completion(isSuccess)
})
}
}
}
private func callServiceTurnOnOrOffSmartSchedule(isOn: Bool, completion: @escaping (Bool) -> Void) {
guard let roomId = seletedRoom?.id else {
return
}
schedulesManager.turnOnOrOffSmartSchedule(roomId: roomId, turnOn: isOn, success: {
completion(true)
}) { error in
completion(false)
}
}
}
<file_sep>//
// RoomViewModel.swift
// Koleda
//
// Created by <NAME> on 9/6/19.
// Copyright © 2019 koleda. All rights reserved.
//
import Foundation
class RoomViewModel {
let isLowBattery: Bool
let roomName: String
let onOffSwitchStatus: Bool
let temprature: String
let infoMessage: String
let roomHomeImage: UIImage?
let roomConfigurationImage: UIImage?
let humidity: String
let sensorBattery: String
let sensor: Sensor?
let settingType: SettingType
let smartMode: SmartMode
let heaters: [Heater]?
let settingTemprature: (Int,Int)
let remainSettingTime: Int
let endTimePoint: Int
var currentTemp: Double? = nil
private (set) var room: Room
init(room: Room) {
self.room = room
roomName = room.name
onOffSwitchStatus = room.enabled ?? false
roomHomeImage = RoomType.homeImageOf(category: RoomCategory(fromString: room.category))
roomConfigurationImage = RoomType.configrurationRoomImageOf(category: RoomCategory(fromString: room.category))
if let battery = room.battery?.kld_doubleValue {
isLowBattery = battery <= 10
sensorBattery = "\(battery)"
} else {
sensorBattery = "-"
isLowBattery = false
}
if let temp = room.temperature {
temprature = "\(temp)"
currentTemp = Double(temp)
} else {
temprature = "-"
currentTemp = nil
}
if let humi = room.humidity {
humidity = "\(humi)"
} else {
humidity = "-"
}
if let sensor = room.sensor {
self.sensor = sensor
} else {
self.sensor = nil
}
if let heaters = room.heaters {
self.heaters = heaters
} else {
self.heaters = nil
}
guard let setting = room.setting, let type = setting.type, let data = setting.data else {
settingType = .unknow
smartMode = .unknow
endTimePoint = 0
remainSettingTime = 0
infoMessage = ""
settingTemprature = (0,0)
return
}
settingType = SettingType.init(fromString: type)
if let mode = setting.mode {
smartMode = SmartMode.init(fromString: mode)
} else {
smartMode = .unknow
}
let temp = data.tempBaseOnUnit
settingTemprature = (temp.integerPart(),temp.fractionalPart())
guard onOffSwitchStatus else {
endTimePoint = 0
remainSettingTime = 0
infoMessage = "Turned off via Smart Scheduling"
return
}
if settingType == .MANUAL, let time = data.time {
endTimePoint = time == 0 ? Constants.MAX_END_TIME_POINT + 1 : time // if time == 0 mean MANUAL BOOST is Unlimit
remainSettingTime = time
infoMessage = "Target temperature: <h1>\(temp)</h1>"
} else {
endTimePoint = 0
remainSettingTime = 0
infoMessage = "\(smartMode.rawValue) mode: <h1>\(temp)</h1>"
}
}
}
<file_sep>//
// AddHeaterManagementCollectionViewCell.swift
// Koleda
//
// Created by <NAME> on 9/9/19.
// Copyright © 2019 koleda. All rights reserved.
//
import UIKit
class AddHeaterManagementCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var addButton: UIButton!
@IBOutlet weak var solusLabel: UILabel!
@IBOutlet weak var freeSlotLabel: UILabel!
func setup() {
solusLabel.text = "SOLUS_TEXT".app_localized
freeSlotLabel.text = "FREE_SLOT_TEXT".app_localized
addButton.setTitle("ADD_TEXT".app_localized, for: .normal)
}
}
<file_sep>//
// FirebaseAnalyticsEventLogProvider.swift
// Koleda
//
// Created by <NAME> on 8/27/20.
// Copyright © 2020 koleda. All rights reserved.
//
import Foundation
import Firebase
import FirebaseAnalytics
import CopilotAPIAccess
class FirebaseAnalyticsEventLogProvider: EventLogProvider {
func enable() {
// No implementation
}
func disable() {
// No implementation
}
func setUserId(userId:String?){
Analytics.setUserID(userId)
}
func transformParameters(parameters: Dictionary<String, String>) -> Dictionary<String, String> {
return parameters
}
func logCustomEvent(eventName: String, transformedParams: Dictionary<String, String>) {
Analytics.logEvent(eventName, parameters: transformedParams)
}
var providerName: String {
return "FirebaseAnalyticsEventLogProvider"
}
var providerEventGroups: [AnalyticsEventGroup] {
return [.All]
}
}
<file_sep>//
// SettingItemtableViewCell.swift
// Koleda
//
// Created by <NAME> on 9/9/19.
// Copyright © 2019 koleda. All rights reserved.
//
import UIKit
class SettingItemtableViewCell: UITableViewCell {
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var iconImageView: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
}
func setup(menuItem: SettingMenuItem) {
titleLabel.text = menuItem.title
iconImageView.image = menuItem.icon
}
}
<file_sep>//
// Launcher.swift
// Koleda
//
// Created by <NAME> on 5/23/19.
// Copyright © 2019 koleda. All rights reserved.
//
import UIKit
import SVProgressHUD
class Launcher {
private var loginAppManager: LoginAppManager {
return ManagerProvider.sharedInstance.loginAppManager
}
func displayScreenBaseOnUserStatus(on window: UIWindow) {
if loginAppManager.isLoggedIn {
presentHomeScreen(on: window)
} else {
presentOnboardingScreen(on: window)
}
}
func presentOnboardingScreen(on window: UIWindow) {
let router = OnboardingRouter()
let navigationVC = StoryboardScene.Onboarding.instantiateNavigationController()
let viewModel = OnboardingViewModel.init(with: router)
guard let viewController = navigationVC.topViewController as? OnboardingViewController else {
assertionFailure("Onboarding storyboard configured not properly")
return
}
viewController.viewModel = viewModel
router.baseViewController = viewController
window.rootViewController = navigationVC
}
func presentHomeScreen(on window: UIWindow) {
let router = HomeRouter()
let viewModel = HomeViewModel.init(router: router)
let homeNavigationVC = StoryboardScene.Home.instantiateNavigationController()
guard let viewController = homeNavigationVC.topViewController as? HomeViewController else {
assertionFailure("Home storyboard configured not properly")
return
}
viewController.viewModel = viewModel
router.baseViewController = viewController
window.rootViewController = homeNavigationVC
}
}
<file_sep>//
// WifiDetailViewModel.swift
// Koleda
//
// Created by <NAME> on 12/4/19.
// Copyright © 2019 koleda. All rights reserved.
//
import Foundation
import RxSwift
protocol WifiDetailViewModelProtocol: BaseViewModelProtocol {
var disableCloseButton: PublishSubject<Bool> { get }
var ssidText: Variable<String> { get }
var wifiPassText: Variable<String> { get }
var ssidErrorMessage: Variable<String> { get }
func setup()
func saveWifiInfo(completion: @escaping () -> Void)
func getTariffInfo(completion: @escaping () -> Void)
}
class WifiDetailViewModel: BaseViewModel, WifiDetailViewModelProtocol {
let router: BaseRouterProtocol
let disableCloseButton = PublishSubject<Bool>()
let ssidText = Variable<String>("")
let wifiPassText = Variable<String>("")
let ssidErrorMessage = Variable<String>("")
private let settingManager: SettingManager
init(router: BaseRouterProtocol, managerProvider: ManagerProvider = .sharedInstance ) {
self.router = router
self.settingManager = managerProvider.settingManager
super.init(managerProvider: managerProvider)
}
func setup() {
if UserDefaultsManager.loggedIn.enabled {
guard let ssid = UserDefaultsManager.wifiSsid.value, let pass = UserDefaultsManager.wifiPass.value else {
return
}
ssidText.value = ssid
wifiPassText.value = pass
} else {
guard let wifiSsid = UserDataManager.shared.wifiInfo?.ssid else {
return
}
ssidText.value = wifiSsid
}
}
func saveWifiInfo(completion: @escaping () -> Void) {
guard validateAll() else {
completion()
return
}
UserDefaultsManager.wifiSsid.value = ssidText.value.extraWhitespacesRemoved
UserDefaultsManager.wifiPass.value = wifiPassText.value.extraWhitespacesRemoved
if UserDefaultsManager.loggedIn.enabled {
router.enqueueRoute(with: WifiDetailRouter.RouteType.back)
completion()
} else {
getTariffInfo {
completion()
}
}
}
func getTariffInfo(completion: @escaping () -> Void) {
disableCloseButton.onNext(true)
settingManager.getTariff(success: { [weak self] in
self?.disableCloseButton.onNext(false)
self?.showEnriffScreen()
completion()
}, failure: { [weak self] _ in
self?.disableCloseButton.onNext(false)
self?.showEnriffScreen()
completion()
})
}
private func validateAll() -> Bool {
let validate = validateSsid()
return validate
}
private func validateSsid() -> Bool {
if ssidText.value.extraWhitespacesRemoved.isEmpty {
ssidErrorMessage.value = "SSID_IS_NOT_EMPTY_MESS".app_localized
return false
}
ssidErrorMessage.value = ""
return true
}
private func showEnriffScreen() {
router.enqueueRoute(with: WifiDetailRouter.RouteType.energyTariff)
}
}
<file_sep>//
// ModesCollectionViewDataSource.swift
// Koleda
//
// Created by <NAME> on 11/4/19.
// Copyright © 2019 koleda. All rights reserved.
//
import UIKit
class ModesCollectionViewDataSource: NSObject, UICollectionViewDataSource {
var smartModes: [ModeItem] = []
var selectedMode: ModeItem?
var fromModifyModesScreen: Bool = false
func numberOfSections(in collectionView: UICollectionView) -> Int {
return smartModes.count
}
func collectionView(_ collectionView: UICollectionView,
numberOfItemsInSection section: Int) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView
.dequeueReusableCell(withReuseIdentifier: "ScheduleModeCell",
for: indexPath) as? ScheduleModeCell else {
fatalError()
}
var isSelected: Bool = false
let mode = smartModes[indexPath.section]
if let selectedMode = selectedMode {
isSelected = (mode.mode == selectedMode.mode)
}
cell.setup(with: mode, isSelected: isSelected, fromModifyModesScreen: fromModifyModesScreen)
return cell
}
}
<file_sep>//
// GuideViewModel.swift
// Koleda
//
// Created by <NAME> on 6/25/19.
// Copyright © 2019 koleda. All rights reserved.
//
import Foundation
import UIKit
import RxSwift
protocol GuideViewModelProtocol: BaseViewModelProtocol {
var guideItems: Variable<[GuideItem]> { get }
func next()
func viewWillAppear()
}
class GuideViewModel: GuideViewModelProtocol {
let guideItems = Variable<[GuideItem]>([])
private let isGuideForAddSensor: Bool
var router: BaseRouterProtocol
private let roomId: String
init(router: BaseRouterProtocol, roomId: String, isGuideForAddSensor: Bool = true) {
self.router = router
self.roomId = roomId
self.isGuideForAddSensor = isGuideForAddSensor
}
func next() {
if isGuideForAddSensor {
router.enqueueRoute(with: GuideRouter.RouteType.addSensor(self.roomId))
} else {
router.enqueueRoute(with: GuideRouter.RouteType.addHeater(self.roomId))
}
}
func viewWillAppear() {
self.guideItems.value = self.initGuidePages()
}
private func initGuidePages() -> [GuideItem] {
var guideItems: [GuideItem] = []
guideItems.append(GuideItem(image: UIImage(named: "managementIcon"), title: "Caution when setting a room, only turn on one sensor at a time", message: "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus."))
guideItems.append(GuideItem(image: UIImage(named: "managementIcon"), title: "Turn sensor on by pressing down button.", message: "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus."))
guideItems.append(GuideItem(image: UIImage(named: "managementIcon"), title: "Close sensor by reattaching top casing and twisting 45 degress.", message: "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. "))
guideItems.append(GuideItem(image: UIImage(named: "managementIcon"), title: "Switch on Heater and press button 5 times", message: "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. "))
return guideItems
}
}
<file_sep>//
// SchedulesManager.swift
// Koleda
//
// Created by <NAME> on 2/28/20.
// Copyright © 2020 koleda. All rights reserved.
//
import UIKit
import Alamofire
import SwiftyJSON
import Sync
protocol SchedulesManager {
func getSmartSchedule(dayString: String, success: @escaping (() -> Void), failure: @escaping ((Error) -> Void))
func checkExistingSmartSchedules(roomId: String, completion: @escaping ((Bool) -> Void))
func updateSmartSchedule(schedules: ScheduleOfDay, success: @escaping () -> Void, failure: @escaping (_ error: Error) -> Void)
func turnOnOrOffSmartSchedule(roomId: String, turnOn: Bool, success: @escaping () -> Void, failure: @escaping (_ error: Error) -> Void)
}
class SchedulesManagerImpl: SchedulesManager {
private let sessionManager: Session
private func baseURL() -> URL {
return UrlConfigurator.urlByAdding()
}
init(sessionManager: Session) {
self.sessionManager = sessionManager
}
func getSmartSchedule(dayString: String, success: @escaping (() -> Void), failure: @escaping ((Error) -> Void)) {
let endpoint = "schedulers?dayOfWeek=\(dayString)"
guard let url = URL(string: baseURL().absoluteString + endpoint) else {
failure(RequestError.error(NSLocalizedString("Failed to send request, please try again later", comment: "")))
return
}
guard let request = try? URLRequest(url: url, method: .get) else {
assertionFailure()
DispatchQueue.main.async {
failure(WSError.general)
}
return
}
sessionManager.request(request).validate().responseData { response in
switch response.result {
case .success(let data):
do {
log.info(try JSON(data: data).description)
let decodedJSON = try JSONDecoder().decode(ScheduleOfDay.self, from: data)
UserDataManager.shared.smartScheduleData[dayString] = decodedJSON
success()
} catch {
log.info("Get Schedule parsing error: \(error)")
failure(error)
}
case .failure(let error):
log.info("Get Schedule fetch error: \(error)")
if let error = error as? URLError, error.code == URLError.notConnectedToInternet {
NotificationCenter.default.post(name: .KLDNotConnectedToInternet, object: error)
failure(error)
} else if let error = error as? AFError, error.responseCode == 400 {
failure(error)
} else if let error = error as? AFError, error.responseCode == 401 || error.responseCode == 403 {
failure(WSError.loginSessionExpired)
} else {
failure(error)
}
}
}
}
func updateSmartSchedule(schedules: ScheduleOfDay, success: @escaping () -> Void, failure: @escaping (_ error: Error) -> Void) {
let params = schedules.convertToDictionary()
print(JSON(params))
guard let request = URLRequest.postRequestWithJsonBody(url: baseURL().appendingPathComponent("schedulers"), parameters: params) else {
failure(RequestError.error(NSLocalizedString("Failed to send request, please try again later", comment: "")))
return
}
sessionManager.request(request).validate().response { response in
if let error = response.error {
if let error = error as? AFError, error.responseCode == 400 {
failure(WSError.empty)
} else {
failure(WSError.general)
}
} else {
NotificationCenter.default.post(name: .KLDNeedToUpdateSchedules, object: nil)
success()
}
}
}
func checkExistingSmartSchedules(roomId: String, completion: @escaping ((Bool) -> Void)) {
let endpoint = "schedulers/rooms/\(roomId)"
guard let url = URL(string: baseURL().absoluteString + endpoint) else {
completion(false)
return
}
guard let request = try? URLRequest(url: url, method: .get) else {
assertionFailure()
DispatchQueue.main.async {
completion(false)
}
return
}
sessionManager.request(request).validate().responseData { response in
switch response.result {
case .success(let data):
do {
let json = try JSON(data: data)
let scheduleStatus = json["scheduleStatus"].boolValue
completion(scheduleStatus)
} catch {
log.info("Get Schedules of room \(error)")
completion(false)
}
case .failure(let error):
log.info("Get Schedules of room error: \(error)")
completion(false)
}
}
}
func turnOnOrOffSmartSchedule(roomId: String, turnOn: Bool, success: @escaping () -> Void, failure: @escaping (_ error: Error) -> Void) {
let params: [String : Any] = ["scheduleAction" : turnOn]
guard let request = URLRequest.postRequestWithJsonBody(url: baseURL().appendingPathComponent("setting/rooms/\(roomId)/schedules"), parameters: params) else {
failure(RequestError.error(NSLocalizedString("Failed to send request, please try again later", comment: "")))
return
}
sessionManager.request(request).validate().response { response in
if let error = response.error {
if let error = error as? AFError, error.responseCode == 400 {
failure(WSError.empty)
} else {
failure(WSError.general)
}
} else {
success()
}
}
}
}
<file_sep>//
// Notifications.swift
// Koleda
//
// Created by <NAME> on 7/2/19.
// Copyright © 2019 koleda. All rights reserved.
//
import Foundation
import UIKit
import UserNotifications
extension NSNotification.Name {
static let KLDNotConnectedToInternet = NSNotification.Name("KLDNotConnectedToInternet")
static let KLDDidChangeRooms = NSNotification.Name("KLDDidChangeRooms")
static let KLDNeedUpdateSelectedRoom = NSNotification.Name("KLDNeedUpdateSelectedRoom")
static let KLDDidChangeWifi = NSNotification.Name("KLDDidChangeWifi")
static let KLDNeedToReSearchDevices = NSNotification.Name("KLDNeedToReSearchDevices")
static let KLDNeedToUpdateSchedules = NSNotification.Name("KLDNeedToUpdateSchedules")
static let KLDDidUpdateTemperatureModes = NSNotification.Name("KLDDidUpdateTemperatureModes")
static let KLDNeedReLoadModes = NSNotification.Name("KLDNeedReLoadModes")
}
<file_sep>//
// BaseViewModel.swift
// Koleda
//
// Created by <NAME> on 7/2/19.
// Copyright © 2019 koleda. All rights reserved.
//
import UIKit
import Alamofire
enum ViewModelActionResult {
case success
case error(String)
}
enum RequestError: Error {
case error(String)
}
class BaseViewModel: NSObject {
override convenience init() {
self.init()
}
init(managerProvider: ManagerProvider = .sharedInstance) {
super.init()
}
var isOffline: Bool {
if let isReachable = NetworkReachabilityManager()?.isReachable {
return !isReachable
}
return true
}
}
<file_sep>//
// TermAndConditionViewController.swift
// Koleda
//
// Created by <NAME> on 7/3/19.
// Copyright © 2019 koleda. All rights reserved.
//
import UIKit
import RxSwift
import SVProgressHUD
import WebKit
import CopilotAPIAccess
class TermAndConditionViewController: BaseViewController, BaseControllerProtocol, WKUIDelegate, WKNavigationDelegate {
@IBOutlet weak var spaceToButton: NSLayoutConstraint!
@IBOutlet weak var spaceToBottom: NSLayoutConstraint!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var agreeButton: UIButton!
@IBOutlet weak var agreeAndContinueView: UIView!
@IBOutlet weak var webViewContainerView: UIView!
private var webView: WKWebView?
@IBOutlet weak var termAndConditionLabel: UILabel!
var viewModel: TermAndConditionViewModelProtocol!
private let disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
addWebView()
agreeButton.isEnabled = false
let stringUrl = getUrlStringLink()
guard let url = URL(string: stringUrl), let webView = self.webView else {
return
}
let requestObj = URLRequest(url: url as URL)
SVProgressHUD.show(withStatus: "LOADING_TEXT".app_localized)
webView.load(requestObj)
agreeAndContinueView.isHidden = (viewModel.legalItem.value == .termAndConditions) ? false : true
spaceToButton.isActive = !agreeAndContinueView.isHidden
spaceToBottom.isActive = agreeAndContinueView.isHidden
agreeButton.rx.tap.bind { [weak self] _ in
Copilot.instance.report.log(event: AcceptTermsAnalyticsEvent(version: "1.0"))
self?.viewModel.showNextScreen()
}.disposed(by: disposeBag)
titleLabel.text = "PRIVACY_POLICY_TEXT".app_localized
termAndConditionLabel.text = "AGREE_AND_CONTINUE_TEXT".app_localized
}
private func getUrlStringLink() -> String {
switch viewModel.legalItem.value {
case .legalPrivacyPolicy:
titleLabel.text = "PRIVACY_POLICY_TEXT".app_localized
return AppConstants.legalPrivacyPolicyLink
case .legalTermAndConditions:
titleLabel.text = "TERMS_AND_CONDITIONS_TEXT".app_localized
return AppConstants.legalTermAndConditionLink
default:
return AppConstants.privacyPolicyLink
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(true, animated: animated)
navigationBarTransparency()
setTitleScreen(with: "")
}
@IBAction func backAction(_ sender: Any) {
closeCurrentScreen()
}
private func addWebView() {
let webConfiguration = WKWebViewConfiguration()
let size = CGSize.init(width: 0.0, height: self.webViewContainerView.frame.size.height)
let customFrame = CGRect.init(origin: CGPoint.zero, size: size)
self.webView = WKWebView (frame: customFrame, configuration: webConfiguration)
if let webView = self.webView {
webView.translatesAutoresizingMaskIntoConstraints = false
self.webViewContainerView.addSubview(webView)
webView.topAnchor.constraint(equalTo: webViewContainerView.topAnchor).isActive = true
webView.rightAnchor.constraint(equalTo: webViewContainerView.rightAnchor).isActive = true
webView.leftAnchor.constraint(equalTo: webViewContainerView.leftAnchor).isActive = true
webView.bottomAnchor.constraint(equalTo: webViewContainerView.bottomAnchor).isActive = true
webView.heightAnchor.constraint(equalTo: webViewContainerView.heightAnchor).isActive = true
webView.uiDelegate = self
webView.navigationDelegate = self
}
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
print("finish loading Term")
agreeButton.isEnabled = true
SVProgressHUD.dismiss()
}
}
<file_sep>//
// UnderlineTextField.swift
// Koleda
//
// Created by <NAME> on 5/28/19.
// Copyright © 2019 koleda. All rights reserved.
//
import UIKit
import Foundation
@IBDesignable
class UnderlineTextField: UITextField {
// WARNING!!! iOS 11 calls textRect(forBounds:) before init(coder:) finishes.
private var titleLabel: UILabel?
private var lineView: UIView?
private var errorLabel: UILabel?
var accessoryView : UIView? {
willSet {
accessoryView?.removeFromSuperview()
}
didSet {
guard let accessoryView = accessoryView else {
return
}
addSubview(accessoryView)
accessoryView.frame = accessoryViewRectForBounds(bounds)
accessoryView.autoresizingMask = [.flexibleLeftMargin, .flexibleBottomMargin]
setNeedsLayout()
layoutIfNeeded()
}
}
var accessoryViewWidth : CGFloat? {
didSet {
setNeedsLayout()
layoutIfNeeded()
}
}
var tapHandler : ((UnderlineTextField) -> Void)? {
didSet {
if tapHandler == nil {
tapView?.removeFromSuperview()
} else if tapView == nil {
let view = UIView(frame: bounds)
tapView = view
tapView?.autoresizingMask = [.flexibleWidth, .flexibleHeight]
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(tap(_:)))
tapView?.backgroundColor = UIColor.clear
tapView?.addGestureRecognizer(tapGesture)
addSubview(view)
}
}
}
private var isErrorVisible = false
private var tapView : UIView?
func showError(_ show: Bool, _ animated: Bool = true) {
if isErrorVisible == show {
return
}
isErrorVisible = show
updateLineColor()
UIView.animate(withDuration: animated ? 0.3 : 0, delay: 0, usingSpringWithDamping: 0.25, initialSpringVelocity: 0.1, options: [], animations: {
self.frame.size.height = self.intrinsicContentSize.height
self.setupSubviewsFrame()
self.invalidateIntrinsicContentSize()
self.superview?.setNeedsLayout()
self.superview?.layoutIfNeeded()
}, completion: nil)
}
// MARK: - Initializers
override init(frame: CGRect) {
super.init(frame: frame)
initialSetup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initialSetup()
}
// MARK: - Helpers
func setAccessoryImage(image: UIImage?) {
if let imageView = accessoryView as? UIImageView {
imageView.image = image
return
}
if image == nil {
accessoryView = nil
return
}
let imageView = UIImageView(image: image)
imageView.contentMode = .scaleAspectFit
accessoryView = imageView
}
// MARK: - Error IBInspectable
@IBInspectable
var errorText: String? {
set {
errorLabel?.text = newValue
}
get {
return errorLabel?.text
}
}
@objc var errorFont: UIFont = .app_FuturaPTBook(ofSize: 10) {
didSet { updateErrorLabel() }
}
@IBInspectable
var errorColor: UIColor = .red {
didSet {
errorLabel?.textColor = errorColor
}
}
// MARK: - Title IBInspectable
@IBInspectable
public var leftSpacer:CGFloat {
get {
return leftView.map{ $0.frame.size.width } ?? 0
} set {
leftViewMode = .always
leftView = UIView(frame: CGRect(x: 0, y: 0, width: newValue, height: frame.size.height))
}
}
@IBInspectable
public var rightSpacer:CGFloat {
get {
return rightView.map{ $0.frame.size.width } ?? 0
} set {
rightViewMode = .always
rightView = UIView(frame: CGRect(x: 0, y: 0, width: newValue, height: frame.size.height))
}
}
@IBInspectable
var titleToTextFieldSpacing: CGFloat = 8 {
didSet {
setNeedsDisplay()
}
}
@IBInspectable
var lineToTextFieldSpacing: CGFloat = 0 {
didSet {
updateLineView()
setNeedsDisplay()
}
}
@IBInspectable
var errorToLineSpacing: CGFloat = 4 {
didSet {
updateErrorLabel()
setNeedsDisplay()
}
}
@IBInspectable
var showTitle: Bool = true {
didSet { updateTitleLabel() }
}
@IBInspectable
var titleText: String? {
didSet { updateTitleLabel() }
}
@objc var titleFont: UIFont = .app_FuturaPTDemi(ofSize: 15) {
didSet { updateTitleLabel() }
}
@IBInspectable
var titleColor: UIColor = .gray {
didSet { updateTitleColor() }
}
@IBInspectable
var selectedTitleColor: UIColor = .blue {
didSet { updateTitleColor() }
}
// MARK: - Line IBInspectable
@IBInspectable
var selectedLineHeight: CGFloat = 1.0 {
didSet {
updateLineView()
setNeedsDisplay()
}
}
@IBInspectable
var lineHeight: CGFloat = 0.5 {
didSet {
updateLineView()
setNeedsDisplay()
}
}
@IBInspectable
var lineColor: UIColor = .lightGray {
didSet { updateLineColor() }
}
@IBInspectable
var selectedLineColor: UIColor = .black {
didSet { updateLineColor() }
}
@IBInspectable
var errorLineColor: UIColor = .red {
didSet { updateLineColor() }
}
}
// MARK: - Overrides
extension UnderlineTextField {
override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
borderStyle = .none
updateControl()
invalidateIntrinsicContentSize()
}
override var isHighlighted: Bool {
didSet { updateControl() }
}
override var isSelected: Bool {
didSet { updateControl() }
}
override var isEnabled: Bool {
didSet { updateControl() }
}
override func becomeFirstResponder() -> Bool {
let result = super.becomeFirstResponder()
updateControl()
return result
}
override func resignFirstResponder() -> Bool {
let result = super.resignFirstResponder()
updateControl()
return result
}
override var intrinsicContentSize: CGSize {
var intristicSize = super.intrinsicContentSize
intristicSize.height = titleHeight + textHeight + titleToTextFieldSpacing + lineToTextFieldSpacing + max(selectedLineHeight, lineHeight) + (isErrorVisible ? errorHeight + errorToLineSpacing : 0)
return intristicSize
}
// MARK: - UITextField positioning overrides
override open func textRect(forBounds bounds: CGRect) -> CGRect {
let superRect = super.textRect(forBounds: bounds)
let titleHeight = self.titleHeight
let rect = CGRect(
x: superRect.origin.x,
y: titleHeight + titleToTextFieldSpacing,
width: superRect.width - (accessoryViewWidth ?? accessoryView?.frame.width ?? 0),
height: superRect.height - titleHeight - max(selectedLineHeight, lineHeight) - lineToTextFieldSpacing - titleToTextFieldSpacing - (isErrorVisible ? errorHeight + errorToLineSpacing : 0)
)
return rect
}
override open func editingRect(forBounds bounds: CGRect) -> CGRect {
let superRect = super.editingRect(forBounds: bounds)
let titleHeight = self.titleHeight
let rect = CGRect(
x: superRect.origin.x,
y: titleHeight + titleToTextFieldSpacing,
width: superRect.size.width - (accessoryViewWidth ?? accessoryView?.frame.size.width ?? 0),
height: textHeight
)
return rect
}
override open func placeholderRect(forBounds bounds: CGRect) -> CGRect {
return textRect(forBounds:bounds)
}
}
// MARK: - Updates
fileprivate extension UnderlineTextField {
var isEditingOrSelected: Bool {
return super.isEditing || isSelected
}
func updateColors() {
updateLineColor()
updateTitleColor()
}
func updateControl() {
updateColors()
updateLineView()
updateTitleLabel()
}
func updateTitleColor() {
titleLabel?.textColor = (isEditingOrSelected || isHighlighted) ? selectedTitleColor : titleColor
}
func updateLineView() {
lineView?.frame = lineViewRectForBounds(bounds, editing: isEditingOrSelected)
updateLineColor()
}
func updateTitleLabel() {
titleLabel?.isHidden = nil == titleText
titleLabel?.text = titleText
titleLabel?.font = titleFont
titleLabel?.frame = titleLabelRectForBounds(bounds)
}
func updateErrorLabel() {
errorLabel?.text = errorText
errorLabel?.font = errorFont
errorLabel?.frame = errorLabelRectForBounds(bounds)
}
func updateLineColor() {
if isErrorVisible {
lineView?.backgroundColor = errorLineColor
} else {
lineView?.backgroundColor = isEditingOrSelected ? selectedLineColor : lineColor
}
}
}
// MARK: -
fileprivate extension UnderlineTextField {
func lineViewRectForBounds(_ bounds: CGRect, editing: Bool) -> CGRect {
let height = editing ? selectedLineHeight : lineHeight
return CGRect(x: 0,
y: bounds.height - height - (isErrorVisible ? errorHeight + errorToLineSpacing : 0),
width: bounds.width,
height: height)
}
func titleLabelRectForBounds(_ bounds: CGRect) -> CGRect {
return CGRect(x: 0, y: 0, width: bounds.size.width, height: titleHeight)
}
func errorLabelRectForBounds(_ bounds: CGRect) -> CGRect {
return CGRect(x: 0,
y: bounds.height - (isErrorVisible ? errorHeight : 0),
width: bounds.size.width,
height: errorHeight)
}
func accessoryViewRectForBounds(_ bounds: CGRect) -> CGRect {
let height = editingRect(forBounds: bounds).height
let intrinsicWidth = accessoryView?.intrinsicContentSize.width ?? -1
let width = accessoryViewWidth ?? ( intrinsicWidth >= 0 ? intrinsicWidth : height)
return CGRect(x: bounds.width - width,
y: titleHeight + titleToTextFieldSpacing,
width: width,
height: height)
}
var titleHeight: CGFloat {
guard let titleLabel = self.titleLabel else {
return 0
}
return showTitle ? titleLabel.intrinsicContentSize.height : 0
}
var errorHeight: CGFloat {
guard let errorLabel = self.errorLabel,
let font = errorLabel.font else {
return 10.0
}
return height(string: errorLabel.text ?? " ", withConstrainedWidth: bounds.size.width, font: font)
}
var textHeight: CGFloat {
guard let font = font else { return 0.0 }
let heightMargin : CGFloat = 7.0
return font.lineHeight + heightMargin
}
private func height(string: String, withConstrainedWidth width: CGFloat, font: UIFont) -> CGFloat {
let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude)
let boundingBox = string.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [.font: font], context: nil)
return ceil(boundingBox.height)
}
}
// MARK: - Initial setup
private extension UnderlineTextField {
func initialSetup() {
borderStyle = .none
clipsToBounds = true
let titleLabel = createTitleLabel()
titleLabel.autoresizingMask = [.flexibleWidth, .flexibleHeight]
addSubview(titleLabel)
self.titleLabel = titleLabel
setupDefaultLineHeight()
let lineView = createLineView()
lineView.autoresizingMask = [.flexibleWidth, .flexibleTopMargin]
addSubview(lineView)
self.lineView = lineView
let errorLabel = createErrorLabel()
errorLabel.autoresizingMask = [.flexibleWidth, .flexibleTopMargin]
addSubview(errorLabel)
self.errorLabel = errorLabel
setupSubviewsFrame()
updateColors()
addEditingChangedObserver()
}
func setupSubviewsFrame() {
guard let titleLabel = self.titleLabel,
let lineView = self.lineView,
let errorLabel = self.errorLabel else
{
assertionFailure()
return
}
titleLabel.frame = titleLabelRectForBounds(bounds)
lineView.frame = lineViewRectForBounds(bounds, editing: isEditingOrSelected)
accessoryView?.frame = accessoryViewRectForBounds(bounds)
errorLabel.frame = errorLabelRectForBounds(bounds)
}
func createTitleLabel() -> UILabel {
let titleLabel = UILabel()
titleLabel.font = titleFont
titleLabel.textColor = titleColor
return titleLabel
}
func createLineView() -> UIView {
let lineView = UIView()
lineView.isUserInteractionEnabled = false
return lineView
}
func createErrorLabel() -> UILabel {
let label = UILabel()
label.font = errorFont
label.textColor = errorColor
label.numberOfLines = 0
label.textAlignment = .right
label.lineBreakMode = .byWordWrapping
return label
}
func addEditingChangedObserver() {
addTarget(self, action: #selector(editingChanged), for: .editingChanged)
}
@objc func editingChanged() {
updateControl()
updateTitleLabel()
}
func setupDefaultLineHeight() {
let onePixel: CGFloat = 1.0 / UIScreen.main.scale
lineHeight = 2.0 * onePixel
selectedLineHeight = 2.0 * lineHeight
}
@objc private func tap(_ sender: UITapGestureRecognizer) {
tapHandler?(self)
}
}
<file_sep>//
// BaseViewController.swift
// Koleda
//
// Created by <NAME> on 5/27/19.
// Copyright © 2019 koleda. All rights reserved.
//
import UIKit
class BaseViewController: UIViewController {
private var isSubscribedToNoInternetNotifications = false
private let noInternetPopupShowDuration = 5.0
var canBackToPreviousScreen: Bool = true
var closeButton: UIBarButtonItem?
var statusBarStyle = UIStatusBarStyle.default {
didSet {
setNeedsStatusBarAppearanceUpdate()
}
}
private lazy var popupWindowManager = ManagerProvider.sharedInstance.popupWindowManager
override var preferredStatusBarStyle: UIStatusBarStyle {
return statusBarStyle
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
view.endEditing(true)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
view.endEditing(true)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if !isSubscribedToNoInternetNotifications {
NotificationCenter.default.addObserver(self, selector: #selector(handleNotConnectedToInternetNotification),
name: .KLDNotConnectedToInternet, object: nil)
isSubscribedToNoInternetNotifications = true
}
}
func addCloseFunctionality(_ tintColor: UIColor = UIColor.black) {
let barButtonItem = UIBarButtonItem(title: nil, style: .plain, target: self, action: #selector(closeCurrentScreen))
self.closeButton = barButtonItem
closeButton?.apply(Style.BarButtonItem.closeLightBackground)
closeButton?.tintColor = tintColor
navigationItem.leftBarButtonItem = barButtonItem
}
func addLogoutButton() {
let barButtonItem = UIBarButtonItem(title: "LOGOUT_TEXT".app_localized, style: .plain, target: self, action: #selector(logout))
barButtonItem.tintColor = UIColor.white
navigationItem.rightBarButtonItem = barButtonItem
}
func setTitleScreen(with title: String) {
self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedString.Key.font: UIFont.app_FuturaPTDemi(ofSize: 30) ]
self.title = title
}
func navigationBarTransparency() {
navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
navigationController?.navigationBar.shadowImage = UIImage()
navigationController?.navigationBar.isTranslucent = true
navigationController?.navigationBar.barStyle = .black
navigationItem.backBarButtonItem = .back_empty
}
func statusBarStyle(with type: UIStatusBarStyle) {
self.statusBarStyle = type
}
@objc func closeCurrentScreen() {
if UserDefaultsManager.loggedIn.enabled {
if canBackToPreviousScreen {
self.navigationController?.popViewController(animated: true)
} else {
self.navigationController?.popToRootViewController(animated: true)
}
} else if let delegate = UIApplication.shared.delegate as? AppDelegate, let window = delegate.window {
Launcher().presentOnboardingScreen(on: window)
}
}
@objc func logout() {
}
@objc private func handleNotConnectedToInternetNotification(_ notification: NSNotification) {
guard let ssid = FGRoute.getSSID(), ssid.contains("shelly") else {
showNoInternetConnectionPopup()
return
}
}
func showNoInternetConnectionPopup() {
let popupWindowManager = self.popupWindowManager
DispatchQueue.main.async {
guard !popupWindowManager.isShown else {
return
}
guard let alertViewController = StoryboardScene.OfflineAlert.instantiateOfflineAlertViewController() as? Popup else { return }
popupWindowManager.show(popup: alertViewController)
DispatchQueue.main.asyncAfter(deadline: .now() + self.noInternetPopupShowDuration, execute: {
popupWindowManager.hide(popup: alertViewController)
})
}
}
}
<file_sep>//
// EditSensorViewController.swift
// Koleda
//
// Created by <NAME> on 9/4/19.
// Copyright © 2019 koleda. All rights reserved.
//
import UIKit
import RxSwift
import SVProgressHUD
class EditSensorViewController: BaseViewController, BaseControllerProtocol {
@IBOutlet weak var sensorNameTextField: AndroidStyle3TextField!
@IBOutlet weak var pairedWithHeatersLabel: UILabel!
@IBOutlet weak var sensorModelLabel: UILabel!
@IBOutlet weak var temperatureLabel: UILabel!
@IBOutlet weak var humidityLabel: UILabel!
@IBOutlet weak var batteryLabel: UILabel!
@IBOutlet weak var isOnCharge: UILabel!
@IBOutlet weak var deleteSensorButton: UIButton!
@IBOutlet weak var nPairedHeaterImageView: UIImageView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var statusTitleLabel: UILabel!
@IBOutlet weak var activeLabel: UILabel!
@IBOutlet weak var batteryTitleLabel: UILabel!
@IBOutlet weak var temperatureTitleLabel: UILabel!
@IBOutlet weak var humidityTitleLabel: UILabel!
var viewModel: EditSensorViewModelProtocol!
private let disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
configurationUI()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationBarTransparency()
navigationController?.setNavigationBarHidden(true, animated: animated)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
@objc private func needUpdateSelectedRoom() {
viewModel.needUpdateSelectedRoom()
}
private func configurationUI() {
NotificationCenter.default.addObserver(self, selector: #selector(needUpdateSelectedRoom),
name: .KLDNeedUpdateSelectedRoom, object: nil)
sensorNameTextField.isEnabled = false
viewModel.sensorName.asObservable().bind(to: sensorNameTextField.rx.text).disposed(by: disposeBag)
sensorNameTextField.rx.text.orEmpty.bind(to: viewModel.sensorName).disposed(by: disposeBag)
viewModel.pairedWithHeaters.asObservable().bind(to: pairedWithHeatersLabel.rx.text).disposed(by: disposeBag)
viewModel.nPairedHeaters.asObservable().bind { [weak self] (nHeaters) in
self?.nPairedHeaterImageView.isHidden = nHeaters == 0
self?.nPairedHeaterImageView.image = UIImage(named: nHeaters > 1 ? "ic-connected-heaters" : "ic-connected-heater")
}
viewModel.sensorModel.asObservable().bind(to: sensorModelLabel.rx.text).disposed(by: disposeBag)
viewModel.temperature.asObservable().bind(to: temperatureLabel.rx.text).disposed(by: disposeBag)
viewModel.humidity.asObservable().bind(to: humidityLabel.rx.text).disposed(by: disposeBag)
viewModel.battery.asObservable().bind(to: batteryLabel.rx.text).disposed(by: disposeBag)
deleteSensorButton.rx.tap.bind { [weak self] in
self?.showPopupToDeleteSensor()
}.disposed(by: disposeBag)
}
func showPopupToDeleteSensor() {
if let vc = getViewControler(withStoryboar: "Room", aClass: AlertConfirmViewController.self) {
vc.onClickLetfButton = {
self.showConfirmPopUp()
}
if let sensorName: String = viewModel.sensorName.value {
vc.typeAlert = .deleteSensor(sensorName: sensorName)
}
showPopup(vc)
}
deleteSensorButton.setTitle("REMOVE_TEXT".app_localized, for: .normal)
titleLabel.text = "EDIT_SENSOR_TEXT".app_localized
sensorNameTextField.titleText = "SENSOR_NAME_TEXT".app_localized
statusTitleLabel.text = "STATUS_TEXT".app_localized
activeLabel.text = "ACTIVE_TEXT".app_localized
batteryTitleLabel.text = "BATTERY_CHARGE_TEXT".app_localized
temperatureTitleLabel.text = "TEMPERATURE_TEXT".app_localized
humidityTitleLabel.text = "HUMIDITY_TEXT".app_localized
}
private func showConfirmPopUp() {
if let vc = getViewControler(withStoryboar: "Room", aClass: AlertConfirmViewController.self) {
vc.onClickRightButton = {
self.viewModel.deleteSensor(completion: { isSuccess in
SVProgressHUD.dismiss()
if isSuccess {
NotificationCenter.default.post(name: .KLDDidChangeRooms, object: nil)
self.app_showInfoAlert("DELETED_SENSOR_SUCCESS_MESS".app_localized, title: "KOLEDA_TEXT".app_localized, completion: {
self.viewModel.backToHome()
})
} else {
self.app_showInfoAlert("CAN_NOT_DELETE_SENSOR_MESS".app_localized)
}
})
}
vc.typeAlert = .confirmDeleteSensor
showPopup(vc)
}
}
@IBAction func backAction(_ sender: Any) {
back()
}
}
<file_sep>//
// MenuSettingsViewController.swift
// Koleda
//
// Created by <NAME> on 9/9/19.
// Copyright © 2019 koleda. All rights reserved.
//
import UIKit
import RxSwift
import MessageUI
import Segmentio
import SVProgressHUD
class MenuSettingsViewController: BaseViewController, BaseControllerProtocol {
@IBOutlet weak var userImageView: UIImageView!
@IBOutlet weak var userNameLabel: UILabel!
@IBOutlet weak var emailLabel: UILabel!
@IBOutlet weak var amountView: UIView!
@IBOutlet weak var amountLabel: UILabel!
@IBOutlet weak var titleAmountLabel: UILabel!
@IBOutlet weak var costMonteringSegment: Segmentio!
@IBOutlet weak var TempUnitLabel: UILabel!
@IBOutlet weak var celsiusToogleImageView: UIImageView!
@IBOutlet weak var celsiusToogleButton: UIButton!
@IBOutlet weak var settingItemsTableView: UITableView!
@IBOutlet weak var reportBugsButton: UIButton!
@IBOutlet weak var tableViewHeightConstraint: NSLayoutConstraint!
@IBOutlet weak var appSettingsLabel: UILabel!
@IBOutlet weak var temperatureUnitLabel: UILabel!
var viewModel: MenuSettingsViewModelProtocol!
private let disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
configurationUI()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(false, animated: animated)
navigationBarTransparency()
addCloseFunctionality(.white)
addLogoutButton()
statusBarStyle(with: .lightContent)
viewModel.viewWillAppear()
}
@IBAction func celsiusButtonAction(_ sender: Any) {
SVProgressHUD.show()
celsiusToogleButton.isEnabled = false
viewModel.updateTempUnit {
SVProgressHUD.dismiss()
self.celsiusToogleButton.isEnabled = true
}
}
private func configurationUI() {
configCostMontoringSegment()
Style.Button.primary.apply(to: reportBugsButton)
userImageView.layer.cornerRadius = userImageView.frame.width / 2.0
userImageView.layer.masksToBounds = true
viewModel?.profileImage.drive(userImageView.rx.image).disposed(by: disposeBag)
Style.View.shadowCornerWhite.apply(to: amountView)
viewModel.settingItems.asObservable().bind { [weak self] modeItems in
self?.settingItemsTableView.reloadData()
}.disposed(by: disposeBag)
viewModel.userName.asObservable().bind { [weak self] value in
self?.userNameLabel.text = value
}.disposed(by: disposeBag)
viewModel.email.asObservable().bind { [weak self] value in
self?.emailLabel.text = value
}.disposed(by: disposeBag)
viewModel.energyConsumed.asObservable().bind { [weak self] value in
self?.amountLabel.text = value
}.disposed(by: disposeBag)
viewModel.timeTitle.asObservable().bind { [weak self] value in
self?.titleAmountLabel.text = value
}.disposed(by: disposeBag)
viewModel.currentTempUnit.asObservable().bind { [weak self] unit in
self?.celsiusToogleImageView.image = unit == .C ? UIImage(named: "ic-switch-on") : UIImage(named: "ic-switch-off")
self?.TempUnitLabel.text = unit == .C ? "CELSIUS_TEXT".app_localized.uppercased() : "FAHRENHEIT_TEXT".app_localized.uppercased()
}.disposed(by: disposeBag)
viewModel.needUpdateAfterTempUnitChanged.asObservable().subscribe(onNext: { [weak self] changed in
if changed {
NotificationCenter.default.post(name: .KLDDidChangeRooms, object: nil)
} else {
self?.app_showAlertMessage(title: "ERROR_TITLE".app_localized, message: "CAN_NOT_UPDATE_TEMPERATURE_UNIT_MESS".app_localized)
}
}).disposed(by: disposeBag)
viewModel.leaveHomeSubject.asObservable().subscribe(onNext: { [weak self] in
SVProgressHUD.show()
self?.viewModel.leaveHome(completion: { success in
SVProgressHUD.dismiss()
if success {
self?.viewModel.logOut()
} else {
self?.app_showAlertMessage(title: "ERROR_TITLE".app_localized, message: "CAN_NOT_LEAVE_MASTER_MESS".app_localized)
}
})
}).disposed(by: disposeBag)
reportBugsButton.rx.tap.bind { [weak self] in
self?.sendEmail()
}.disposed(by: disposeBag)
appSettingsLabel.text = "APP_SETTINGS_TEXT".app_localized
temperatureUnitLabel.text = "TEMPERATURE_UNITS_TEXT".app_localized
reportBugsButton.setTitle("REPORT_BUGS_AND_PROBLEMS".app_localized, for: .normal)
}
private func configCostMontoringSegment() {
let content: [SegmentioItem] = [SegmentioItem(title: "MONTH_TEXT".app_localized, image: nil), SegmentioItem(title: "WEEK_TEXT".app_localized, image: nil), SegmentioItem(title: "DAY_TEXT".app_localized, image: nil)]
let states = SegmentioStates(
defaultState: SegmentioState(
backgroundColor: .clear,
titleFont: UIFont.SFProDisplayRegular(ofSize: 16),
titleTextColor: .gray
),
selectedState: SegmentioState(
backgroundColor: .clear,
titleFont: UIFont.SFProDisplayRegular(ofSize: 16),
titleTextColor: .black
),
highlightedState: SegmentioState(
backgroundColor: .clear,
titleFont: UIFont.SFProDisplayRegular(ofSize: 16),
titleTextColor: .black
)
)
let indicatorOptions = SegmentioIndicatorOptions(
type: .bottom,
ratio: 1,
height: 2,
color: .orange
)
let horizontalSeparatorOptions = SegmentioHorizontalSeparatorOptions(
type: SegmentioHorizontalSeparatorType.bottom, // Top, Bottom, TopAndBottom
height: 1,
color: UIColor.lightLine
)
let options = SegmentioOptions(backgroundColor: .clear, segmentPosition: SegmentioPosition.dynamic, scrollEnabled: false, indicatorOptions: indicatorOptions, horizontalSeparatorOptions: horizontalSeparatorOptions, verticalSeparatorOptions: nil, imageContentMode: UIView.ContentMode.center, labelTextAlignment: .center, labelTextNumberOfLines: 1, segmentStates: states, animationDuration: 0)
costMonteringSegment.setup(content: content, style: SegmentioStyle.onlyLabel, options: options)
costMonteringSegment.selectedSegmentioIndex = 0
costMonteringSegment.valueDidChange = { [weak self] segmentio, segmentIndex in
self?.viewModel.showEneryConsume(of: ConsumeType.init(from: segmentIndex))
}
}
override func logout() {
viewModel.logOut()
}
private func sendEmail() {
if MFMailComposeViewController.canSendMail() {
let mail = MFMailComposeViewController()
mail.mailComposeDelegate = self
mail.setToRecipients([AppConstants.supportEmail])
mail.setSubject("REPORT_BUGS_AND_PROBLEMS".app_localized)
present(mail, animated: true, completion: nil)
} else if let emailUrl = createEmailUrl(to: AppConstants.supportEmail, subject: "", body: "") {
UIApplication.shared.open(emailUrl)
// show failure alert
}
}
private func createEmailUrl(to: String, subject: String, body: String) -> URL? {
let subjectEncoded = subject.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!
let bodyEncoded = body.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!
let gmailUrl = URL(string: "googlegmail://co?to=\(to)&subject=\(subjectEncoded)&body=\(bodyEncoded)")
let outlookUrl = URL(string: "ms-outlook://compose?to=\(to)&subject=\(subjectEncoded)")
let yahooMail = URL(string: "ymail://mail/compose?to=\(to)&subject=\(subjectEncoded)&body=\(bodyEncoded)")
let sparkUrl = URL(string: "readdle-spark://compose?recipient=\(to)&subject=\(subjectEncoded)&body=\(bodyEncoded)")
let defaultUrl = URL(string: "mailto:\(to)?subject=\(subjectEncoded)&body=\(bodyEncoded)")
if let gmailUrl = gmailUrl, UIApplication.shared.canOpenURL(gmailUrl) {
return gmailUrl
} else if let outlookUrl = outlookUrl, UIApplication.shared.canOpenURL(outlookUrl) {
return outlookUrl
} else if let yahooMail = yahooMail, UIApplication.shared.canOpenURL(yahooMail) {
return yahooMail
} else if let sparkUrl = sparkUrl, UIApplication.shared.canOpenURL(sparkUrl) {
return sparkUrl
}
return defaultUrl
}
}
extension MenuSettingsViewController: MFMailComposeViewControllerDelegate {
func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
controller.dismiss(animated: true)
}
}
extension MenuSettingsViewController: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.viewModel.settingItems.value.count
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: SettingItemtableViewCell.get_identifier, for: indexPath) as? SettingItemtableViewCell else {
log.error("Invalid cell type call")
return UITableViewCell()
}
let menuItem = self.viewModel.settingItems.value[indexPath.row]
cell.setup(menuItem: menuItem)
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 50
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
viewModel.selectedItem(at: indexPath.row)
}
}
<file_sep>//
// LoginAppManager.swift
// Koleda
//
// Created by <NAME> on 7/2/19.
// Copyright © 2019 koleda. All rights reserved.
//
import UIKit
import Alamofire
import SwiftyJSON
class LoginAppManager {
var sessionManager: Session
var isLoggedIn: Bool {
return UserDefaultsManager.loggedIn.enabled
}
init() {
let adapter = MyRequestAdapter()
sessionManager = Session(configuration: .default, interceptor: adapter)
}
private func baseURL() -> URL {
return UrlConfigurator.urlByAdding()
}
func login(email: String, password: String, success: @escaping () -> Void, failure: @escaping (_ error: Error) -> Void) {
let timezone = TimeZone.current.identifier
let params = ["email": email,
"password": <PASSWORD>,
"zoneId": timezone]
let endPointURL = baseURL().appendingPathComponent("auth/login")
log.info(endPointURL.description)
guard let request = URLRequest.postRequestWithJsonBody(url: endPointURL, parameters: params) else {
failure(RequestError.error(NSLocalizedString("Failed to send request, please try again later", comment: "")))
return
}
AF.request(request).validate().responseJSON { response in
switch response.result {
case .success(let result):
log.info("Successfully obtained access token")
let json = JSON(result)
let accessToken = json["accessToken"].stringValue
let refreshToken = json["refreshToken"].stringValue
let tokenType = json["tokenType"].stringValue
do {
try LocalAccessToken.store(accessToken, tokenType: tokenType)
try RefreshToken.store(refreshToken)
log.info("Successfully logged in")
success()
} catch let error {
log.error("Failed to store LoginCredentials/Passcode/AccessToken in keychain - \(error.localizedDescription)")
failure(error)
}
case .failure(let error):
log.error("Failed to obtain access token - \(error)")
if let error = error as? URLError, error.code == URLError.notConnectedToInternet {
NotificationCenter.default.post(name: .KLDNotConnectedToInternet, object: error)
failure(error)
} else if let error = error as? AFError, error.responseCode == 400 {
failure(error)
} else if let error = error as? AFError, error.responseCode == 401 {
failure(error)
} else {
failure(error)
}
}
}
}
func loginWithSocial(type: SocialType, accessToken: String, success: @escaping () -> Void, failure: @escaping (_ error: Error) -> Void) {
let timezone = TimeZone.current.identifier
let endPointURL = baseURL().appendingPathComponent("auth/login-social")
log.info(accessToken)
let params = ["provider": type.rawValue,
"token": accessToken,
"zoneId" : timezone]
guard let request = URLRequest.postRequestWithJsonBody(url: endPointURL, parameters: params) else {
failure(RequestError.error(NSLocalizedString("Failed to send request, please try again later", comment: "")))
return
}
AF.request(request).validate().responseJSON { response in
switch response.result {
case .success(let result):
log.info("Successfully obtained access token")
let json = JSON(result)
let accessToken = json["accessToken"].stringValue
let refreshToken = json["refreshToken"].stringValue
let tokenType = json["tokenType"].stringValue
do {
try LocalAccessToken.store(accessToken, tokenType: tokenType)
try RefreshToken.store(refreshToken)
log.info("Successfully logged in")
success()
} catch let error {
log.error("Failed to store LoginCredentials/Passcode/AccessToken in keychain - \(error.localizedDescription)")
failure(error)
}
case .failure(let error):
log.error("Failed to obtain access token - \(error)")
if let error = error as? URLError, error.code == URLError.notConnectedToInternet {
NotificationCenter.default.post(name: .KLDNotConnectedToInternet, object: error)
failure(error)
} else {
let error = WSError.error(from: response.data, defaultError: WSError.general)
failure(error)
}
}
}
}
}
class MyRequestAdapter: Alamofire.RequestInterceptor {
func adapt(_ urlRequest: URLRequest, for session: Session, completion: @escaping (Result<URLRequest, Error>) -> Void) {
guard let accessToken = LocalAccessToken.restore() else {
log.info("No access token for request")
return completion(.success(urlRequest))
}
var result = urlRequest
result.setValue("Bearer " + accessToken , forHTTPHeaderField: "Authorization")
return completion(.success(result))
}
func retry(_ request: Request, for session: Session, dueTo error: Error, completion: @escaping (RetryResult) -> Void) {
guard let response = request.task?.response as? HTTPURLResponse, response.statusCode == 401 else {
/// The request did not fail due to a 401 Unauthorized response.
/// Return the original error and don't retry the request.
return completion(.doNotRetryWithError(error))
}
if request.response?.statusCode == 403 {
completion(.doNotRetryWithError(error))
} else if request.response?.statusCode == 400 {
completion(.doNotRetryWithError(error))
} else {
if let error = error as? URLError, error.code == URLError.notConnectedToInternet {
NotificationCenter.default.post(name: .KLDNotConnectedToInternet, object: error)
}
if let error = error as? URLError, error.code == URLError.networkConnectionLost, request.retryCount < 20 {
completion(.retry)
} else {
completion(.doNotRetryWithError(error))
}
}
}
}
<file_sep>//
// LoginSocialAnalyticsEvent.swift
// Koleda
//
// Created by <NAME> on 9/3/20.
// Copyright © 2020 koleda. All rights reserved.
//
import Foundation
import CopilotAPIAccess
struct LoginSocialAnalyticsEvent: AnalyticsEvent {
private let provider: String
private let token: String
private let zoneId: String
private let screenName: String
init(provider:String, token: String, zoneId: String, screenName: String) {
self.provider = provider
self.token = token
self.zoneId = zoneId
self.screenName = screenName
}
var customParams: Dictionary<String, String> {
return ["provider" : provider,
"token" : token,
"zoneId" : zoneId,
"screenName": screenName]
}
var eventName: String {
return "login_social"
}
var eventOrigin: AnalyticsEventOrigin {
return .App
}
var eventGroups: [AnalyticsEventGroup] {
return [.All]
}
}
<file_sep>//
// LegalViewController.swift
// Koleda
//
// Created by <NAME> on 11/8/20.
// Copyright © 2020 koleda. All rights reserved.
//
import UIKit
import RxSwift
class LegalViewController: BaseViewController, BaseControllerProtocol {
@IBOutlet weak var backButton: UIButton!
@IBOutlet weak var legalTitleLabel: UILabel!
@IBOutlet weak var versionLabel: UILabel!
@IBOutlet weak var bottomTitleLabel: UILabel!
@IBOutlet weak var tableView: UITableView!
var viewModel: LegalViewModelProtocol!
private let disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
bottomTitleLabel.attributedText = "CONTACT_FOR_HELP_MESSAGE".app_localized.attributeText(normalSize: 16, boldSize: 16)
tableView.reloadData()
self.setupLabelTap()
}
@objc func contactTapped(_ sender: UITapGestureRecognizer) {
print("contact Tapped")
}
func setupLabelTap() {
let labelTap = UITapGestureRecognizer(target: self, action: #selector(self.contactTapped(_:)))
self.bottomTitleLabel.isUserInteractionEnabled = true
self.bottomTitleLabel.addGestureRecognizer(labelTap)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationBarTransparency()
navigationController?.setNavigationBarHidden(true, animated: animated)
setTitleScreen(with: "")
viewModel.viewWillAppear()
}
@IBAction func backAction(_ sender: Any) {
back()
}
}
extension LegalViewController: UITableViewDelegate {
}
extension LegalViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 2
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: LegalMenuCell.get_identifier, for: indexPath) as? LegalMenuCell else {
log.error("Invalid cell type call")
return UITableViewCell()
}
let title = viewModel.legalItems.value[indexPath.row]
cell.setText(title: title)
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 52
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
viewModel.selectedItem(index: indexPath.row)
}
}
<file_sep>//
// Styled+Extensions.swift
// Koleda
//
// Created by <NAME> on 5/24/19.
// Copyright © 2019 koleda. All rights reserved.
//
import UIKit
extension UIButton {
func apply(_ style: Style.ViewStyle<UIButton>) {
style.apply(to: self)
}
}
extension UIView {
func apply(_ style: Style.ViewStyle<UIView>) {
style.apply(to: self)
}
}
extension UIBarButtonItem {
func apply(_ style: Koleda.Style.ViewStyle<UIBarButtonItem>) {
style.apply(to: self)
}
}
<file_sep>//
// InviteFriendsFinishedViewController.swift
// Koleda
//
// Created by <NAME> on 6/23/20.
// Copyright © 2020 koleda. All rights reserved.
//
import UIKit
import RxSwift
class InviteFriendsFinishedViewController: BaseViewController, BaseControllerProtocol {
@IBOutlet weak var messageLabel: UILabel!
@IBOutlet weak var gotItButton: UIButton!
@IBOutlet weak var backButton: UIButton!
var viewModel: InviteFriendsFinishedViewModelProtocol!
private let disposeBag = DisposeBag()
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var descriptionLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
configurationUI()
}
private func configurationUI() {
statusBarStyle(with: .lightContent)
Style.Button.primary.apply(to: gotItButton)
gotItButton.rx.tap.bind { [weak self] in
self?.viewModel.showHomeScreen()
}.disposed(by: disposeBag)
backButton.rx.tap.bind { [weak self] in
self?.viewModel.addMoreFriends()
}
titleLabel.text = "YOUR_INVITES_HAVE_BEEN_SENT_MESS".app_localized
descriptionLabel.text = "YOUR_FRIENDS_AND_FAMILY_WILL_BE_ABLE_CONTROL_YOUR_HOUSE_MESS".app_localized
gotItButton.setTitle("NEXT_TEXT".app_localized, for: .normal)
}
}
<file_sep>//
// ConfigurationRoomViewController.swift
// Koleda
//
// Created by <NAME> on 8/26/19.
// Copyright © 2019 koleda. All rights reserved.
//
import UIKit
import RxSwift
class ConfigurationRoomViewController: BaseViewController, BaseControllerProtocol {
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var editRoomButton: UIButton!
@IBOutlet weak var roomImageView: UIImageView!
@IBOutlet weak var devicesInfoView: UIView!
@IBOutlet weak var paireddWithSensorTitleLabel: UILabel!
@IBOutlet weak var sensorManagementButton: UIButton!
@IBOutlet weak var heatersCollectionView: UICollectionView!
@IBOutlet weak var temperatureLabel: UILabel!
@IBOutlet weak var editRoomDetailsLabel: UILabel!
@IBOutlet weak var heatersTitleLabel: UILabel!
@IBOutlet weak var managementTitleLabel: UILabel!
@IBOutlet weak var manageRoomLabel: UILabel!
@IBOutlet weak var heaterManagementLabel: UILabel!
@IBOutlet weak var sensorManagenentLabel: UILabel!
@IBOutlet var heatersDataSource: HeatersCollectionViewDataSource!
private let disposeBag = DisposeBag()
var viewModel: ConfigurationRoomViewModelProtocol!
override func viewDidLoad() {
super.viewDidLoad()
configurationUI()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationBarTransparency()
navigationController?.setNavigationBarHidden(true, animated: animated)
statusBarStyle(with: .lightContent)
viewModel.setup()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
navigationController?.setNavigationBarHidden(true, animated: animated)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
@objc private func needUpdateSelectedRoom() {
viewModel.needUpdateSelectedRoom()
}
private func configurationUI() {
// Room Info view
NotificationCenter.default.addObserver(self, selector: #selector(needUpdateSelectedRoom),
name: .KLDNeedUpdateSelectedRoom, object: nil)
viewModel.temperature.asObservable().bind(to: temperatureLabel.rx.text).disposed(by: disposeBag)
editRoomButton.rx.tap.bind { [weak self] _ in
self?.viewModel.editRoom()
}.disposed(by: disposeBag)
sensorManagementButton.rx.tap.bind { [weak self] _ in
self?.viewModel.sensorManagement()
}.disposed(by: disposeBag)
viewModel.title.asObservable().bind(to: titleLabel.rx.text).disposed(by: disposeBag)
viewModel.imageRoom.asObserver().bind(to: roomImageView.rx.image).disposed(by: disposeBag)
viewModel.imageRoomColor.asObservable().subscribe(onNext: { [weak self] color in
self?.roomImageView.tintColor = color
}).disposed(by: disposeBag)
// Devices Info View
viewModel.heaters.asObservable().subscribe(onNext: { [weak self] heaters in
guard let heatersCollectionViewDataSource = self?.heatersCollectionView.dataSource as? HeatersCollectionViewDataSource else { return }
heatersCollectionViewDataSource.heaters = heaters
self?.heatersCollectionView.reloadData()
}).disposed(by: disposeBag)
viewModel.pairedWithSensorTitle.asObservable().bind(to: paireddWithSensorTitleLabel.rx.text).disposed(by: disposeBag)
editRoomDetailsLabel.text = "EDIT_ROOM_DETAILS_TEXT".app_localized
heatersTitleLabel.text = "HEATERS_TEXT".app_localized
managementTitleLabel.text = "MANAGEMENT_TEXT".app_localized
manageRoomLabel.text = "MANAGE_ROOM_TEXT".app_localized
heaterManagementLabel.text = "HEATER_MANAGEMENT_TEXT".app_localized
sensorManagenentLabel.text = "SENSOR_MANAGEMENT_TEXT".app_localized
}
@IBAction func heaterManagementAction(_ sender: Any) {
self.viewModel.heatersManagement()
}
@IBAction func backAction(_ sender: Any) {
back()
}
}
extension ConfigurationRoomViewController : UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath) -> CGSize {
let numberOfCells = viewModel.heaters.value.count
let widthOfCell: CGFloat = self.heatersCollectionView.frame.width / CGFloat(numberOfCells)
return CGSize(width: 311, height: 98)
}
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
insetForSectionAt section: Int) -> UIEdgeInsets {
return .zero
}
}
<file_sep>//
// TermAndConditionViewModel.swift
// Koleda
//
// Created by <NAME> on 7/3/19.
// Copyright © 2019 koleda. All rights reserved.
//
import Foundation
import RxSwift
import SVProgressHUD
enum LegalItem {
case legalPrivacyPolicy
case legalTermAndConditions
case termAndConditions
}
protocol TermAndConditionViewModelProtocol: BaseViewModelProtocol {
var legalItem: Variable<LegalItem> { get }
func showNextScreen()
}
class TermAndConditionViewModel: BaseViewModel, TermAndConditionViewModelProtocol {
let router: BaseRouterProtocol
private let justSignedUpNewAcc: Bool
let legalItem = Variable<LegalItem>(.termAndConditions)
init(router: BaseRouterProtocol, justSignedUpNewAcc: Bool = false, managerProvider: ManagerProvider = .sharedInstance, legalItem: LegalItem = .termAndConditions) {
self.legalItem.value = legalItem
self.router = router
self.justSignedUpNewAcc = justSignedUpNewAcc
super.init(managerProvider: managerProvider)
}
func showNextScreen() {
if let user = UserDataManager.shared.currentUser, user.homes.count > 0 && !justSignedUpNewAcc {
let userType = UserType.init(fromString: user.userType ?? "")
if userType == .Master {
UserDataManager.shared.stepProgressBar = StepProgressBar(total: 4)
self.router.enqueueRoute(with: TermAndConditionRouter.RouteType.location)
} else {
UserDataManager.shared.stepProgressBar = StepProgressBar(total: 0)
self.router.enqueueRoute(with: TermAndConditionRouter.RouteType.location)
}
} else {
UserDataManager.shared.stepProgressBar = StepProgressBar(total: 5)
self.router.enqueueRoute(with: TermAndConditionRouter.RouteType.createHome)
}
}
}
<file_sep>//
// ScheduleFooterCell.swift
// Koleda
//
// Created by <NAME> on 10/24/19.
// Copyright © 2019 koleda. All rights reserved.
//
import UIKit
class ScheduleFooterCell: UITableViewCell {
@IBOutlet weak var roomsLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
func setup(scheduleRow: ScheduleRow) {
roomsLabel.text = scheduleRow.title
}
}
<file_sep>
//
// ManualBoostViewModel.swift
// Koleda
//
// Created by <NAME> on 8/28/19.
// Copyright © 2019 koleda. All rights reserved.
//
import Foundation
import UIKit
import RxSwift
protocol ManualBoostViewModelProtocol: BaseViewModelProtocol {
var currentTemperature: Variable<String> { get }
var editingTemprature: Variable<Int> { get }
var editingTempratureSmall: Variable<Int> { get }
var statusString: Variable<String> { get }
var sliderValue: Variable<Float> { get }
var endTime: Variable<String> { get }
var countDownTime: Variable<String> { get }
var manualBoostTimeout: PublishSubject<Void> { get }
func adjustTemprature(increased: Bool)
func resetSettingTime(completion: @escaping (Bool, String) -> Void)
func updateSettingTime(seconds: Int)
func manualBoostUpdate(completion: @escaping (Bool) -> Void)
func needUpdateSelectedRoom()
func setup()
func refreshRoom(completion: @escaping (Bool) -> Void)
}
class ManualBoostViewModel: BaseViewModel, ManualBoostViewModelProtocol {
let currentTemperature = Variable<String>("")
let editingTemprature = Variable<Int>(0)
let editingTempratureSmall = Variable<Int>(0)
let statusString = Variable<String>("")
let sliderValue = Variable<Float>(0)
let endTime = Variable<String>("")
let countDownTime = Variable<String>("")
let manualBoostTimeout = PublishSubject<Void>()
let router: BaseRouterProtocol
private let roomManager: RoomManager
private let settingManager: SettingManager
private var seletedRoom: Room?
private var timer:Timer?
init(router: BaseRouterProtocol, managerProvider: ManagerProvider = .sharedInstance, seletedRoom: Room? = nil) {
self.router = router
self.roomManager = managerProvider.roomManager
self.settingManager = managerProvider.settingManager
self.seletedRoom = seletedRoom
super.init(managerProvider: managerProvider)
}
func setup() {
guard let userName = UserDataManager.shared.currentUser?.name, let room = seletedRoom else {
return
}
let roomViewModel = RoomViewModel.init(room: room)
currentTemperature.value = roomViewModel.temprature
editingTemprature.value = roomViewModel.settingTemprature.0
editingTempratureSmall.value = roomViewModel.settingTemprature.1
countDownTime.value = roomViewModel.remainSettingTime.fullTimeFormart()
updateSettingTime(seconds: roomViewModel.endTimePoint)
guard let sensor = roomViewModel.sensor else {
return
}
updateStatusOfTemperature()
}
func adjustTemprature(increased: Bool) {
if increased {
increaseTemp()
} else {
decreaseTemp()
}
updateStatusOfTemperature()
}
func updateSettingTime(seconds: Int) {
sliderValue.value = Float(seconds)
guard seconds <= Constants.MAX_END_TIME_POINT else {
endTime.value = "UNLIMITED_TEXT"
countDownTime.value = ""
stopTimer()
return
}
if seconds == 0 {
endTime.value = "00:00"
countDownTime.value = seconds.fullTimeFormart()
stopTimer()
} else {
let time = Date().adding(seconds: seconds)
endTime.value = String(format: "%@ %@", "UNTIL_TEXT".app_localized,time.fomartAMOrPm())
countDownTime.value = seconds.fullTimeFormart()
runTimer()
}
}
func resetSettingTime(completion: @escaping (Bool, String) -> Void) {
if let room = seletedRoom {
let roomViewModel = RoomViewModel.init(room: room)
if roomViewModel.settingType == .MANUAL {
settingManager.resetManualBoost(roomId: room.id, success: { [weak self] in
completion(true, "")
}) { _ in
completion(false, "MANUAL_BOOST_CAN_NOT_RESET_MESS".app_localized)
}
} else {
setup()
completion(false, "")
}
}
}
func needUpdateSelectedRoom() {
let room = UserDataManager.shared.rooms.filter { $0.id == seletedRoom?.id }.first
if room != nil {
seletedRoom = room
setup()
}
}
func manualBoostUpdate(completion: @escaping (Bool) -> Void) {
guard let roomId = seletedRoom?.id else {
completion(false)
return
}
let time = Int(sliderValue.value)
var temprature: Double = Double(editingTemprature.value) + Double(editingTempratureSmall.value) * 0.1
if UserDataManager.shared.temperatureUnit == .F {
temprature = temprature.celciusTemperature
}
roomManager.manualBoostUpdate(roomId: roomId, temp: temprature, time: time > Constants.MAX_END_TIME_POINT ? 0 : time, success: {
completion(true)
}, failure: { error in
completion(false)
})
}
func refreshRoom(completion: @escaping (Bool) -> Void) {
guard let roomId = seletedRoom?.id else {
completion(false)
return
}
roomManager.getRoom(roomId: roomId, success: { [weak self] room in
self?.seletedRoom = room
self?.setup()
completion(true)
}, failure: { error in
completion(false)
})
}
private func increaseTemp() {
let maxTemp = UserDataManager.shared.temperatureUnit == .C ? Constants.MAX_TEMPERATURE : Constants.MAX_TEMPERATURE.fahrenheitTemperature
guard editingTemprature.value < Int(maxTemp) else {
return
}
if UserDataManager.shared.temperatureUnit == .C {
if editingTempratureSmall.value == 0 {
editingTempratureSmall.value = 5
} else {
editingTempratureSmall.value = 0
editingTemprature.value = editingTemprature.value + 1
}
} else {
editingTemprature.value = editingTemprature.value + 1
}
}
private func decreaseTemp() {
if UserDataManager.shared.temperatureUnit == .C {
guard editingTemprature.value > 5 || (editingTemprature.value == 5 && editingTempratureSmall.value > 0) else {
return
}
if editingTempratureSmall.value == 0 {
editingTempratureSmall.value = 5
editingTemprature.value = editingTemprature.value - 1
} else {
editingTempratureSmall.value = 0
}
} else {
guard editingTemprature.value > 0 else {
return
}
editingTemprature.value = editingTemprature.value - 1
}
}
private func updateStatusOfTemperature() {
let currentTemp = currentTemperature.value.kld_doubleValue ?? 0
let targetTemp: Double = Double(editingTemprature.value) + Double(editingTempratureSmall.value) * 0.1
if targetTemp != 0 && currentTemp != 0 && targetTemp != currentTemp {
statusString.value = targetTemp > currentTemp ? "HEATING_TO_TEXT".app_localized : "COOLING_DOWN_TEXT".app_localized
} else {
statusString.value = "" }
}
private func runTimer() {
stopTimer()
timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(updateCountDown), userInfo: nil, repeats: true )
}
private func stopTimer() {
if timer != nil {
timer?.invalidate()
timer = nil
}
}
@objc private func updateCountDown() {
if(sliderValue.value > 0) {
sliderValue.value = sliderValue.value - 1
countDownTime.value = Int(sliderValue.value).fullTimeFormart()
log.info(countDownTime.value)
} else {
manualBoostTimeout.onNext(())
stopTimer()
}
}
}
<file_sep>//
// DeviceManager.swift
// Koleda
//
// Created by <NAME> on 7/18/19.
// Copyright © 2019 koleda. All rights reserved.
//
import Foundation
import Alamofire
import SwiftyJSON
import PromiseKit
protocol ShellyDeviceManager {
func getDeviceInfoOnAPMode(success: ((String) -> Void)?, failure: ((Error) -> Void)?)
func turnOnSTAOfDeviceInfo(ssid: String, pass: String, success: (() -> Void)?, failure: ((Error) -> Void)?)
func setMQTTForDevice(isSensor: Bool, deviceModel: String, ipAddress: String?, completion: @escaping (Bool) -> Void)
func addDevice(roomId: String, sensor: Sensor?, heater: Heater?, completion: @escaping (WSError?) -> Void)
func deleteDevice(roomId: String, deviceId: String, success: (() -> Void)?, failure: ((Error) -> Void)?)
}
class ShellyDeviceManagerImpl: ShellyDeviceManager {
private let sessionManager: Session
private func baseURL() -> URL {
return UrlConfigurator.urlByAdding()
}
init(sessionManager: Session) {
self.sessionManager = sessionManager
}
func getDeviceInfoOnAPMode(success: ((String) -> Void)?, failure: ((Error) -> Void)?) {
AF.request("\(AppConstants.defaultShellyHostLink)/settings").responseJSON { response in
switch response.result {
case let .success(value):
print(value)
let data = JSON(value)
let deviceModel = data["name"].stringValue
success?(deviceModel)
case let .failure(error):
print(error)
failure?(WSError.general)
}
// if let json = response.result.value {
// print("JSON: \(json)") // serialized json response
// let data = JSON(json)
// let deviceModel = data["name"].stringValue
// success?(deviceModel)
// } else {
//
// }
}
}
func turnOnSTAOfDeviceInfo(ssid: String, pass: String, success: (() -> Void)?, failure: ((Error) -> Void)?) {
let params: Parameters = ["enabled": 1,
"ssid": ssid,
"key": <PASSWORD>,
"ipv4_method": "dhcp",
"ip": "" ,
"gw": "",
"mask": "",
"dns": "" ]
guard let url = URL(string: "\(AppConstants.defaultShellyHostLink)/settings/sta" ) else {
return
}
let sessionManager = Alamofire.Session.default
sessionManager.request(url,
method: .post,
parameters: params,
headers: ["Content-Type": "application/x-www-form-urlencoded"])
.validate()
.responseJSON { [weak self] response in
if let error = response.error {
failure?(WSError.general)
} else {
// if let json = response.result {
// print("JSON: \(json)") // serialized json response
// }
success?()
}
}
}
func addDevice(roomId: String, sensor: Sensor?, heater: Heater?, completion: @escaping (WSError?) -> Void) {
var name: String = ""
var type: String = ""
var deviceModel: String = ""
var ipAddressDevice: String?
if let device = sensor {
name = device.name
deviceModel = device.deviceModel
ipAddressDevice = device.ipAddress
type = "SENSOR"
} else if let device = heater {
name = device.name
deviceModel = device.deviceModel
ipAddressDevice = device.ipAddress
type = "HEATER"
}
let params = ["deviceModel": deviceModel,
"name": name,
"type": type]
let endPointURL = self.baseURL().appendingPathComponent("me/rooms/\(roomId)/device")
guard let request = URLRequest.requestWithJsonBody(url: endPointURL, method: .put, parameters: params) else {
log.error("Failed to send request, please try again later")
completion(WSError.general)
return
}
self.sessionManager.request(request).validate().response { response in
if let error = response.error {
log.info("Failed to add Shelly Device - \(type)")
let error = WSError.error(from: response.data, defaultError: WSError.general)
completion(error)
} else {
log.info("Successfully add Shelly Device - \(type)")
completion(nil)
}
}
}
func setMQTTForDevice(isSensor: Bool, deviceModel: String, ipAddress: String?, completion: @escaping (Bool) -> Void) {
var params: [String : Any] = ["mqtt_enable": 1,
"mqtt_server": UrlConfigurator.mqttUrlString(),
"mqtt_user": "mqtt",
"mqtt_reconnect_timeout_max": 60,
"mqtt_reconnect_timeout_min": 2,
"mqtt_clean_session": true,
"mqtt_keep_alive": 60,
"mqtt_will_topic": "shellies/\(deviceModel)/online",
"mqtt_will_message": true,
"mqtt_max_qos": 0,
"mqtt_pass": "<PASSWORD>",
"external_power": 0]
if isSensor {
params["mqtt_update_period"] = 5
params["mqtt_retain"] = true
params["temperature_threshold"] = 0.5
} else {
params["mqtt_retain"] = false
}
guard let ipAddress = ipAddress else {
completion(false)
return
}
// let originalIPAddress = ipAddress.app_removePortInUrl()
guard let endPointURL = URL(string: "http://\(ipAddress)/settings" ) else {
completion(false)
return
}
let sessionManager = Alamofire.Session.default
sessionManager.request(endPointURL,
method: .post,
parameters: params,
headers: ["Content-Type": "application/x-www-form-urlencoded"])
.validate()
.responseJSON { [weak self] response in
if let error = response.error {
log.info("Failed to set MQTT Shelly Device - \(deviceModel)")
completion(false)
} else {
log.info("Successfull to set MQTT Shelly Device - \(deviceModel)")
if isSensor {
completion(true)
} else {
self?.ignoreManualPressingOnHeater(ipAddress: ipAddress, completion: { success in
completion(success)
})
}
}
}
}
private func ignoreManualPressingOnHeater(ipAddress: String, completion: @escaping (Bool) -> Void) {
setupButtonType(ipAddress: ipAddress) { [weak self] isSuccess in
if isSuccess {
self?.setupButtonReverse(ipAddress: ipAddress, completion: { success in
completion(success)
})
} else {
completion(isSuccess)
}
}
}
private func setupButtonType(ipAddress: String, completion: @escaping (Bool) -> Void) {
guard let url = URL(string: "http://\(ipAddress)/settings/relay/0?btn_type=toggle" ) else {
return
}
let sessionManager = Alamofire.Session.default
sessionManager.request(url,
method: .get,
headers: ["Content-Type": "application/x-www-form-urlencoded"])
.validate()
.responseJSON { [weak self] response in
if let error = response.error {
log.info("Failed to ignoreManualPressingOnHeaterBySetButtonType")
completion(false)
} else {
log.info("Successfull to ignoreManualPressingOnHeaterBySetButtonType")
completion(true)
}
}
}
private func setupButtonReverse(ipAddress: String, completion: @escaping (Bool) -> Void) {
guard let url = URL(string: "http://\(ipAddress)/settings/relay/0?btn_reverse=1" ) else {
return
}
let sessionManager = Alamofire.Session.default
sessionManager.request(url,
method: .get,
headers: ["Content-Type": "application/x-www-form-urlencoded"])
.validate()
.responseJSON { [weak self] response in
if let error = response.error {
log.info("Failed to ignoreManualPressingOnHeaterBySetButtonReverse")
completion(false)
} else {
log.info("Successfull to ignoreManualPressingOnHeaterBySetButtonReverse")
completion(true)
}
}
}
func deleteDevice(roomId: String, deviceId: String, success: (() -> Void)?, failure: ((Error) -> Void)? = nil) {
guard let request = try? URLRequest(url: baseURL().appendingPathComponent("me/rooms/\(roomId)/device/\(deviceId)"), method: .delete) else {
assertionFailure()
DispatchQueue.main.async {
failure?(WSError.general)
}
return
}
sessionManager.request(request).validate().response { [weak self] response in
if let error = response.error {
log.info("Delete Shelly Device error: \(error)")
failure?(error)
} else {
log.info("Delete Shelly Device successfull")
success?()
}
}
}
}
<file_sep>//
// DetailModeViewMode.swift
// Koleda
//
// Created by <NAME> on 2/4/20.
// Copyright © 2020 koleda. All rights reserved.
//
import Foundation
import RxSwift
protocol DetailModeViewModelProtocol: BaseViewModelProtocol {
var selectedMode: Variable<ModeItem?> { set get }
var tempList: [Int] { set get}
var currentTemperature: Int { set get }
var reloadCollectionView: PublishSubject<Void> { get set}
var showErrorMessage: PublishSubject<String> { get set }
func didSelectedTemperature(temp: Int)
func confirmed()
func backToModifyModes()
}
class DetailModeViewModel: BaseViewModel, DetailModeViewModelProtocol {
let router: BaseRouterProtocol
var selectedMode = Variable<ModeItem?>(nil)
var tempList: [Int] = []
var currentTemperature: Int = 0
var reloadCollectionView = PublishSubject<Void>()
var showErrorMessage = PublishSubject<String>()
private let settingManager: SettingManager
init(router: BaseRouterProtocol, managerProvider: ManagerProvider = .sharedInstance, selectedMode: ModeItem) {
self.router = router
settingManager = managerProvider.settingManager
super.init(managerProvider: managerProvider)
self.setup()
self.selectedMode.value = selectedMode
}
private func setup() {
let minTemp = Constants.MIN_TEMPERATURE.integerPart()
let maxTemp = Constants.MAX_TEMPERATURE.integerPart()
for i in (minTemp...maxTemp) {
tempList.append(i)
}
reloadCollectionView.onNext(())
}
func didSelectedTemperature(temp: Int) {
self.currentTemperature = temp
reloadCollectionView.onNext(())
}
func confirmed() {
guard let modeName = selectedMode.value?.mode.rawValue else { return }
let newTempMode = Double(currentTemperature)
let currentTempMode = selectedMode.value?.temperature
if newTempMode != currentTempMode {
settingManager.updateTempMode(modeName: modeName, temp: newTempMode, success: { [weak self] in
NotificationCenter.default.post(name: .KLDDidUpdateTemperatureModes, object: nil)
self?.backToModifyModes()
}) { [weak self] _ in
self?.showErrorMessage.onNext("Can't Update Temperature of Mode now")
}
} else {
backToModifyModes()
}
}
func backToModifyModes() {
router.enqueueRoute(with: DetailModeRouter.RouteType.backModifyModes)
}
}
<file_sep>//
// WelcomeJoinHomeViewController.swift
// Koleda
//
// Created by <NAME> on 8/5/20.
// Copyright © 2020 koleda. All rights reserved.
//
import UIKit
import RxSwift
class WelcomeJoinHomeViewController: BaseViewController, BaseControllerProtocol {
@IBOutlet weak var nextButton: UIButton!
var viewModel: WelcomeJoinHomeViewModelProtocol!
private let disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func nextAction(_ sender: Any) {
viewModel.goHome()
}
}
<file_sep>//
// RoomPopOverCell.swift
// Koleda
//
// Created by <NAME> on 9/10/19.
// Copyright © 2019 koleda. All rights reserved.
//
import UIKit
class RoomPopOverCell: UITableViewCell {
@IBOutlet weak var checkMarkImageView: UIImageView!
@IBOutlet weak var roomNameLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
}
func loadData(room: Room, isSelected: Bool) {
roomNameLabel.text = room.name
checkMarkImageView.isHidden = !isSelected
self.isSelected = isSelected
}
}
<file_sep>//
// ForgotPasswordAnalyticsEvent.swift
// Koleda
//
// Created by <NAME> on 9/4/20.
// Copyright © 2020 koleda. All rights reserved.
//
import Foundation
import CopilotAPIAccess
struct ForgotPasswordAnalyticsEvent: AnalyticsEvent {
private let email: String
private let screenName: String
init(email:String, screenName: String) {
self.email = email
self.screenName = screenName
}
var customParams: Dictionary<String, String> {
return ["email" : email,
"screenName": screenName]
}
var eventName: String {
return "forgot_password"
}
var eventOrigin: AnalyticsEventOrigin {
return .App
}
var eventGroups: [AnalyticsEventGroup] {
return [.All]
}
}
<file_sep>//
// TabContentViewModel.swift
// Koleda
//
// Created by <NAME> on 10/31/19.
// Copyright © 2019 koleda. All rights reserved.
//
import Foundation
import RxSwift
import SpreadsheetView
import SVProgressHUD
protocol TabContentViewModelProtocol: BaseViewModelProtocol {
var hoursData: [String] { get }
var scheduleOfDayViewModel: ScheduleOfDayViewModel { get }
var mergeCellData: [CellRange] { get }
var dayOfWeek: DayOfWeek { get set }
var reloadScheduleView: PublishSubject<Void> { get }
func getScheduleOfDay(comletion: @escaping () -> Void)
}
class TabContentViewModel: BaseViewModel, TabContentViewModelProtocol {
let router: BaseRouterProtocol
var hoursData: [String] = []
var scheduleOfDayViewModel = ScheduleOfDayViewModel.init()
var mergeCellData: [CellRange] = []
var dayOfWeek: DayOfWeek = DayOfWeek.MONDAY
let reloadScheduleView = PublishSubject<Void>()
private let schedulesManager: SchedulesManager
private var scheduleOfDay: ScheduleOfDay?
init(router: BaseRouterProtocol, managerProvider: ManagerProvider = .sharedInstance) {
self.router = router
self.schedulesManager = managerProvider.schedulesManager
super.init(managerProvider: managerProvider)
hoursData = createTimeline()
}
func setup(dayOfWeek: DayOfWeek) {
self.dayOfWeek = dayOfWeek
guard let scheduleOfDay = UserDataManager.shared.smartScheduleData[dayOfWeek.rawValue] else {
return
}
self.scheduleOfDay = scheduleOfDay
updateScheduleView()
}
func getScheduleOfDay(comletion: @escaping () -> Void) {
let dayString = self.dayOfWeek.rawValue
schedulesManager.getSmartSchedule(dayString: dayString, success: { [weak self] in
guard let schedules = UserDataManager.shared.smartScheduleData[dayString] else {
return
}
self?.scheduleOfDay = schedules
self?.updateScheduleView()
comletion()
}) { error in
comletion()
}
}
private func updateScheduleView() {
guard let scheduleOfDay = self.scheduleOfDay else {
return
}
self.scheduleOfDayViewModel = ScheduleOfDayViewModel.init(scheduleOfDay: scheduleOfDay)
self.mergeCellData = self.getMergeCellData(rowsMergeData: scheduleOfDayViewModel.rowsMergeData)
self.reloadScheduleView.onNext(())
}
private func getMergeCellData(rowsMergeData: [(startIndex: Int, numberRows: Int)]) -> [CellRange] {
var mergeData: [CellRange] = []
for data in rowsMergeData {
if data.numberRows > 1 {
let startRow = data.startIndex
let endRow = (data.startIndex + data.numberRows) - 1
mergeData.append(CellRange(from: (row: startRow, column: 1), to: (row: endRow, column: 1)))
}
}
return mergeData
}
private func createTimeline() -> [String] {
var hours: [String] = []
var startValue = 0
while startValue <= 23 {
hours.append("\(startValue) : 00")
hours.append("–")
startValue += 1
}
hours.append("00 : 00")
return hours
}
}
<file_sep>//
// SelectedRoomViewController.swift
// Koleda
//
// Created by <NAME> on 8/26/19.
// Copyright © 2019 koleda. All rights reserved.
//
import UIKit
import RxSwift
import SVProgressHUD
import SwiftRichString
class SelectedRoomViewController: BaseViewController, BaseControllerProtocol {
@IBOutlet weak var onOffSwitchButton: UIButton!
@IBOutlet weak var onOffSwitchLabel: UILabel!
@IBOutlet weak var onOffSwitchImageView: UIImageView!
@IBOutlet weak var userHomeTitle: UILabel!
@IBOutlet weak var temperatuteTitleLabel: UILabel!
@IBOutlet weak var temperatureLabel: UILabel!
@IBOutlet weak var humidityTitleLabel: UILabel!
@IBOutlet weak var humidityLabel: UILabel!
@IBOutlet weak var ecoModeView: ModeView!
@IBOutlet weak var ecoModeButton: UIButton!
@IBOutlet weak var nightModeView: ModeView!
@IBOutlet weak var nightModeButton: UIButton!
@IBOutlet weak var comfortModeView: ModeView!
@IBOutlet weak var comfortModeButton: UIButton!
@IBOutlet weak var smartScheduleModeView: ModeView!
@IBOutlet weak var smartScheduleModeButton: UIButton!
@IBOutlet weak var temperatureCircleSlider: SSCircularRingSlider!
@IBOutlet weak var startTemperatureLabel: UILabel!
@IBOutlet weak var endTemperatureLabel: UILabel!
@IBOutlet weak var statusImageView: UIImageView!
@IBOutlet weak var statusLabel: UILabel!
@IBOutlet weak var editingTempratureLabel: UILabel!
@IBOutlet weak var editingTempraturesmallLabel: UILabel!
@IBOutlet weak var plusTempButton: UIButton!
@IBOutlet weak var minusTempButton: UIButton!
@IBOutlet weak var resetButton: UIButton!
@IBOutlet weak var timerView: UIView!
@IBOutlet weak var timeSlider: CustomSlider!
@IBOutlet weak var endTimeLabel: UILabel!
@IBOutlet weak var countDownTimeLabel: UILabel!
@IBOutlet weak var configurationButton: UIButton!
private let disposeBag = DisposeBag()
var viewModel: SelectedRoomViewModelProtocol!
override func viewDidLoad() {
super.viewDidLoad()
configurationUI()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationBarTransparency()
navigationController?.setNavigationBarHidden(true, animated: animated)
viewModel.setup()
}
fileprivate func setCircularRingSliderColor(arrayValues: [Int]) {
let currentValue = viewModel.currentValueSlider
temperatureCircleSlider.setValues(initialValue: currentValue.toCGFloat(), minValue: arrayValues[0].toCGFloat(), maxValue: arrayValues[arrayValues.count - 1].toCGFloat())
temperatureCircleSlider.setProgressLayerColor(colors: [UIColor.orange.cgColor, UIColor.orange.cgColor])
temperatureCircleSlider.setCircluarRingColor(innerCirlce: UIColor.lightGray, outerCircle: UIColor.orange)
temperatureCircleSlider.setCircularRingWidth(innerRingWidth: 2, outerRingWidth: 2)
viewModel.temperatureSliderChanged(value: currentValue)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
@objc private func needUpdateSelectedRoom() {
viewModel.needUpdateSelectedRoom()
}
@IBAction func turnOnOffAction(_ sender: Any) {
SVProgressHUD.show()
viewModel.turnOnOrOffRoom { [weak self] turnOn, isSuccess in
SVProgressHUD.dismiss()
if !isSuccess {
let status = turnOn ? "TURN_ON_TEXT".app_localized : "TURN_OFF_TEXT".app_localized
let message = String(format: "ADD_ROOM_ERROR_MESSAGE".app_localized, status)
self?.app_showInfoAlert(message)
}
}
}
@objc func changeVlaue(slider: UISlider, event: UIEvent) {
if let touchEvent = event.allTouches?.first {
switch touchEvent.phase {
case .began:
break;
case .moved:
viewModel.updateSettingTime(seconds: Int(slider.value))
case .ended:
viewModel.checkForAutoUpdateManualBoost(updatedTemp: false)
default:
break
}
}
}
private func configurationUI() {
NotificationCenter.default.addObserver(self, selector: #selector(needUpdateSelectedRoom),
name: .KLDNeedUpdateSelectedRoom, object: nil)
configurationButton.rx.tap.bind { [weak self] _ in
self?.viewModel.showConfigurationScreen()
}.disposed(by: disposeBag)
viewModel.homeTitle.asObservable().bind(to: userHomeTitle.rx.text).disposed(by: disposeBag)
viewModel.temperature.asObservable().bind(to: temperatureLabel.rx.text).disposed(by: disposeBag)
viewModel.humidity.asObservable().bind(to: humidityLabel.rx.text).disposed(by: disposeBag)
viewModel.modeItems.asObservable().bind { [weak self] modeItems in
guard let eco = ModeItem.getModeItem(with: .ECO), let night = ModeItem.getModeItem(with: .NIGHT), let comfort = ModeItem.getModeItem(with: .COMFORT) else {
return
}
self?.ecoModeView.setUp(modeItem: eco)
self?.nightModeView.setUp(modeItem: night)
self?.comfortModeView.setUp(modeItem: comfort)
let smartSchedule = ModeItem.getSmartScheduleMode()
self?.smartScheduleModeView.setUp(modeItem: smartSchedule)
}.disposed(by: disposeBag)
ecoModeButton.rx.tap.bind { [weak self] _ in
self?.checkBeforeUpdateSmartMode(selectedMode: .ECO)
}.disposed(by: disposeBag)
comfortModeButton.rx.tap.bind { [weak self] _ in
self?.checkBeforeUpdateSmartMode(selectedMode: .COMFORT)
}.disposed(by: disposeBag)
nightModeButton.rx.tap.bind { [weak self] _ in
self?.checkBeforeUpdateSmartMode(selectedMode: .NIGHT)
}.disposed(by: disposeBag)
smartScheduleModeButton.rx.tap.bind { [weak self] _ in
self?.checkBeforeUpdateSmartMode(selectedMode: .SMARTSCHEDULE)
}.disposed(by: disposeBag)
viewModel.ecoModeUpdate.asObservable().subscribe(onNext: { [weak self] enable in
self?.ecoModeView.updateStatus(enable: enable)
}).disposed(by: disposeBag)
viewModel.comfortModeUpdate.asObservable().subscribe(onNext: { [weak self] enable in
self?.comfortModeView.updateStatus(enable: enable)
}).disposed(by: disposeBag)
viewModel.nightModeUpdate.asObservable().subscribe(onNext: { [weak self] enable in
self?.nightModeView.updateStatus(enable: enable)
}).disposed(by: disposeBag)
viewModel.smartScheduleModeUpdate.asObservable().subscribe(onNext: { [weak self] enable in
self?.smartScheduleModeView.updateStatus(enable: enable)
}).disposed(by: disposeBag)
viewModel.turnOnRoom.asObservable().subscribe(onNext: { [weak self] turnOn in
self?.onOffSwitchImageView.image = UIImage(named: turnOn ? "ic-switch-on": "ic-switch-off")
self?.onOffSwitchButton.isSelected = turnOn
self?.onOffSwitchLabel.text = turnOn ? "ON_TEXT".app_localized.uppercased() : "OFF_TEXT".app_localized.uppercased()
self?.onOffSwitchLabel.textColor = turnOn ? UIColor.black : UIColor.gray
}).disposed(by: disposeBag)
//
timeSlider.maximumValue = Float(Constants.MAX_END_TIME_POINT + 1)
timeSlider.minimumValue = 0
timeSlider.addTarget(self, action: #selector(changeVlaue(slider:event:)), for: .valueChanged)
viewModel.performBoosting.asObservable().subscribe(onNext: { [weak self] _ in
guard let time = self?.viewModel.timeSliderValue.value, Int(time) > 0 else {
self?.app_showInfoAlert("PLEASE_SET_A_TIMER_FOR_MANUAL_BOOST_MESS".app_localized)
return
}
SVProgressHUD.show(withStatus: "UPDATING_MANUAL_BOOST_TEXT".app_localized)
self?.viewModel.manualBoostUpdate(completion: { [weak self] isSuccess in
SVProgressHUD.dismiss()
if isSuccess {
NotificationCenter.default.post(name: .KLDDidChangeRooms, object: nil)
self?.app_showInfoAlert("MANUAL_BOOST_UPDATE_SUCCESS_MESS".app_localized, title: "KOLEDA_TEXT".app_localized, completion: {
self?.dismiss(animated: true, completion: nil)
})
} else {
self?.app_showInfoAlert("MANUAL_BOOST_CAN_NOT_UPDATE_MESS".app_localized)
}})
}).disposed(by: disposeBag)
viewModel.canAdjustTemp.asObservable().subscribe(onNext: { [weak self] value in
self?.resetButton.isEnabled = value
self?.temperatureCircleSlider.isEnable = value
self?.plusTempButton.isEnabled = value
self?.minusTempButton.isEnabled = value
}).disposed(by: disposeBag)
viewModel.refreshTempCircleSlider.asObservable().subscribe(onNext: { [weak self] in
guard let temperatureRange = self?.viewModel.temperatureSliderRange else {
return
}
self?.temperatureCircleSlider.delegate = self
self?.setCircularRingSliderColor(arrayValues: temperatureRange)
}).disposed(by: disposeBag)
viewModel.turnOnManualBoost.asObservable().bind(onNext: { [weak self] turnOn in
self?.timerView.isHidden = !turnOn
}).disposed(by: disposeBag)
resetButton.rx.tap.bind { [weak self] _ in
self?.viewModel.resetManualBoost(completion: { success, errorMessage in
guard success else {
if errorMessage != "" {
self?.app_showInfoAlert(errorMessage)
}
return
}
self?.app_showInfoAlert("RESET_BOOSTING_SUCCESS_MESS".app_localized)
NotificationCenter.default.post(name: .KLDDidChangeRooms, object: nil)
})
}.disposed(by: disposeBag)
viewModel.countDownTime.asObservable().bind { [weak self] value in
self?.countDownTimeLabel.text = value
}.disposed(by: disposeBag)
viewModel.endTime.asObservable().bind(to: endTimeLabel.rx.text).disposed(by: disposeBag)
viewModel.timeSliderValue.asObservable().bind { [weak self] value in
self?.timeSlider.setValue(value, animated: true)
}.disposed(by: disposeBag)
viewModel.startTemprature.asObservable().bind { [weak self] value in
self?.startTemperatureLabel.text = String(value)
}.disposed(by: disposeBag)
viewModel.endTemprature.asObservable().bind { [weak self] value in
self?.endTemperatureLabel.text = String(value)
}.disposed(by: disposeBag)
viewModel.editingTemprature.asObservable().bind { [weak self] value in
self?.editingTempratureLabel.text = String(value)
}.disposed(by: disposeBag)
viewModel.editingTempratureSmall.asObservable().bind { [weak self] value in
self?.editingTempraturesmallLabel.text = value > 0 ? ".\(value)" : ""
}.disposed(by: disposeBag)
viewModel.statusText.asObservable().bind(to: statusLabel.rx.text).disposed(by: disposeBag)
viewModel.statusImageName.asObservable().bind { [weak self] imageName in
self?.statusImageView.isHidden = imageName == ""
self?.statusImageView.image = UIImage(named: imageName)
}.disposed(by: disposeBag)
viewModel.manualBoostTimeout.asObservable().subscribe(onNext: { [weak self] in
SVProgressHUD.show(withStatus: "MANUAL_BOOST_TIMEOUT_TEXT".app_localized)
self?.viewModel.refreshRoom(completion: { success in
SVProgressHUD.dismiss()
})
}).disposed(by: disposeBag)
plusTempButton.rx.tap.bind { [weak self] _ in
self?.viewModel.adjustTemprature(increased: true)
}.disposed(by: disposeBag)
minusTempButton.rx.tap.bind { [weak self] _ in
self?.viewModel.adjustTemprature(increased: false)
}.disposed(by: disposeBag)
configurationButton.setTitle("ROOM_SETTINGS_TEXT".app_localized, for: .normal)
temperatuteTitleLabel.text = "TEMPERATURE_TEXT".app_localized.uppercased()
humidityTitleLabel.text = "HUMIDITY_TEXT".app_localized.uppercased()
resetButton.setTitle("CANCEL".app_localized, for: .normal)
}
private func checkBeforeUpdateSmartMode(selectedMode: SmartMode) {
guard viewModel.heaters.count > 0 else {
app_showInfoAlert("CHANGE_MODE_IS_NOT_POSSIBLE_MESS".app_localized)
return
}
if viewModel.settingType == .MANUAL {
SVProgressHUD.show()
viewModel.resetManualBoost { [weak self] (success, _) in
SVProgressHUD.dismiss()
guard success else {
self?.app_showInfoAlert("CAN_NOT_UPDATE_MODE_MESS".app_localized)
return
}
self?.updateSettingMode(selectedMode: selectedMode)
NotificationCenter.default.post(name: .KLDDidChangeRooms, object: nil)
}
} else if selectedMode == .SMARTSCHEDULE {
updateScheduleMode()
} else {
updateSettingMode(selectedMode: selectedMode)
}
}
private func updateSettingMode(selectedMode: SmartMode) {
SVProgressHUD.show()
viewModel.updateSettingMode(mode: selectedMode) { [weak self] (updatedMode, isSuccess, errorMessage) in
SVProgressHUD.dismiss()
if isSuccess {
NotificationCenter.default.post(name: .KLDDidChangeRooms, object: nil)
self?.viewModel.changeSmartMode(seletedSmartMode: updatedMode)
} else {
if !errorMessage.isEmpty {
self?.app_showInfoAlert(errorMessage)
}
}
}
}
private func updateScheduleMode() {
SVProgressHUD.show()
viewModel.turnOnOrOffScheduleMode(completion: { [weak self] (isSuccess, errorMessage) in
SVProgressHUD.dismiss()
if isSuccess {
NotificationCenter.default.post(name: .KLDDidChangeRooms, object: nil)
self?.viewModel.changeSmartMode(seletedSmartMode: .SMARTSCHEDULE)
} else {
if !errorMessage.isEmpty {
self?.app_showInfoAlert(errorMessage)
}
}
})
}
@IBAction func backAction(_ sender: Any) {
back()
}
}
extension SelectedRoomViewController: SSCircularRingSliderDelegate {
// This function will be called after updating Circular Slider Control value
func controlValueUpdated(value: Int) {
// print("current control value \(value)")
viewModel.temperatureSliderChanged(value: value)
}
func needUpdate() {
viewModel.checkForAutoUpdateManualBoost(updatedTemp: true)
}
}
<file_sep>//
// ScheduleRoomCell.swift
// Koleda
//
// Created by <NAME> on 11/1/19.
// Copyright © 2019 koleda. All rights reserved.
//
import UIKit
class ScheduleRoomCell: UITableViewCell {
@IBOutlet weak var roomName: UILabel!
@IBOutlet weak var closeButton: UIButton!
private var room: Room?
var closeButtonHandler: ((Room) -> Void)? = nil
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
@IBAction func close(_ sender: Any) {
if let room = self.room {
self.closeButtonHandler?(room)
}
}
func setup(withRoom: Room) {
self.room = withRoom
self.roomName.text = withRoom.name
}
}
<file_sep>//
// OnboardingViewModel.swift
// Koleda
//
// Created by <NAME> on 5/23/19.
// Copyright © 2019 koleda. All rights reserved.
//
import Foundation
import UIKit
import CopilotAPIAccess
enum SocialType: String {
case facebook = "facebook"
case google = "google"
case apple = "apple"
}
protocol OnboardingViewModelProtocol: BaseViewModelProtocol {
func prepare(for segue: UIStoryboardSegue)
func startSignUpFlow()
func startSignInFlow()
func joinHome()
func loginWithSocial(type: SocialType, accessToken: String, completion: @escaping (Bool, WSError?) -> Void)
}
class OnboardingViewModel: BaseViewModel, OnboardingViewModelProtocol {
let router: BaseRouterProtocol
private let loginAppManager: LoginAppManager
private let userManager: UserManager
init(with router: BaseRouterProtocol, managerProvider: ManagerProvider = .sharedInstance) {
self.router = router
self.loginAppManager = managerProvider.loginAppManager
self.userManager = managerProvider.userManager
super.init(managerProvider: managerProvider)
}
func prepare(for segue: UIStoryboardSegue) {
router.prepare(for: segue)
}
func loginWithSocial(type: SocialType, accessToken: String, completion: @escaping (Bool, WSError?) -> Void) {
loginAppManager.loginWithSocial(type: type, accessToken: accessToken, success: { [weak self] in
log.info("User signed in successfully")
guard let `self` = self else {
return
}
self.processAfterLoginSuccessfull()
Copilot.instance.report.log(event: LoginSocialAnalyticsEvent(provider: type.rawValue, token: accessToken, zoneId: TimeZone.current.identifier, screenName: self.screenName))
// self?.router.enqueueRoute(with: OnboardingRouter.RouteType.termAndConditions)
completion(true, nil)
}, failure: { error in
completion(false, error as? WSError)
})
}
func startSignUpFlow() {
router.enqueueRoute(with: OnboardingRouter.RouteType.signUp)
}
func startSignInFlow() {
router.enqueueRoute(with: OnboardingRouter.RouteType.logIn)
}
func joinHome() {
router.enqueueRoute(with: OnboardingRouter.RouteType.joinHome)
}
private func processAfterLoginSuccessfull() {
var showTermAndCondition: Bool = true
getCurrentUser { [weak self] in
guard let userId = UserDataManager.shared.currentUser?.id else {
return
}
Copilot.instance
.manage
.yourOwn
.sessionStarted(withUserId: userId,
isCopilotAnalysisConsentApproved: true)
if let termAndConditionAcceptedUser = UserDefaultsManager.termAndConditionAcceptedUser.value?.extraWhitespacesRemoved, termAndConditionAcceptedUser == UserDataManager.shared.currentUser?.email {
showTermAndCondition = false
}
// If User hasn't created a home yet
guard let user = UserDataManager.shared.currentUser, user.homes.count > 0 else {
self?.router.enqueueRoute(with: OnboardingRouter.RouteType.termAndConditions)
return
}
if showTermAndCondition {
self?.router.enqueueRoute(with: OnboardingRouter.RouteType.termAndConditions)
} else {
self?.router.enqueueRoute(with: OnboardingRouter.RouteType.home)
UserDefaultsManager.loggedIn.enabled = true
}
}
}
private func getCurrentUser(completion: @escaping () -> Void) {
userManager.getCurrentUser(success: {
completion()
}, failure: { error in
completion()
})
}
}
<file_sep>//
// DetailModeViewController.swift
// Koleda
//
// Created by <NAME> on 2/4/20.
// Copyright © 2020 koleda. All rights reserved.
//
import UIKit
import RxSwift
class DetailModeViewController: BaseViewController, BaseControllerProtocol {
var viewModel: DetailModeViewModelProtocol!
@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var modeNameTextField: AndroidStyle3TextField!
@IBOutlet weak var confirmButton: UIButton!
@IBOutlet weak var editModeLabel: UILabel!
@IBOutlet weak var targetTemperatureLabel: UILabel!
private let disposeBag = DisposeBag()
private var currentIndexPath: IndexPath?
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationBarTransparency()
navigationController?.setNavigationBarHidden(true, animated: animated)
statusBarStyle(with: .lightContent)
setTitleScreen(with: "")
}
override func viewDidLoad() {
super.viewDidLoad()
configurationUI()
}
@IBAction func backAction(_ sender: Any) {
viewModel.backToModifyModes()
}
override func viewDidLayoutSubviews() {
if let indexPath = currentIndexPath {
collectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)
}
}
@IBAction func confirmAction(_ sender: Any) {
viewModel.confirmed()
}
private func configurationUI() {
viewModel.selectedMode.asObservable().subscribe(onNext: { [weak self] selectedMode in
guard let mode = selectedMode?.mode, let currentTemp = selectedMode?.temperature.integerPart() else {
return
}
self?.modeNameTextField.text = ModeItem.modeNameOf(smartMode: mode)
self?.viewModel?.didSelectedTemperature(temp: currentTemp)
if let index = self?.viewModel.tempList.firstIndex(of: currentTemp) {
self?.currentIndexPath = IndexPath(row: 0, section: index)
}
}).disposed(by: disposeBag)
viewModel.reloadCollectionView.asObservable().subscribe(onNext: { [weak self] in
self?.collectionView.reloadData()
}).disposed(by: disposeBag)
viewModel.showErrorMessage.asObservable().subscribe(onNext: { [weak self] messsage in
self?.app_showAlertMessage(title: "ERROR_TITLE", message: messsage)
}).disposed(by: disposeBag)
editModeLabel.text = "EDIT_MODE_TEXT".app_localized
modeNameTextField.titleText = "MODE_TEXT".app_localized
targetTemperatureLabel.text = "TARGET_TEMPERATURE".app_localized
confirmButton.setTitle("CONFIRM_TEXT".app_localized, for: .normal)
}
}
extension DetailModeViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: 58, height: 58)
}
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
insetForSectionAt section: Int) -> UIEdgeInsets {
return .zero
}
}
extension DetailModeViewController: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let selectedTemp = viewModel.tempList[indexPath.section]
viewModel?.didSelectedTemperature(temp: selectedTemp)
}
}
extension DetailModeViewController: UICollectionViewDataSource {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return viewModel.tempList.count
}
func collectionView(_ collectionView: UICollectionView,
numberOfItemsInSection section: Int) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView
.dequeueReusableCell(withReuseIdentifier: "TemperatureCollectionViewCell",
for: indexPath) as? TemperatureCollectionViewCell else {
fatalError()
}
let temp = viewModel.tempList[indexPath.section]
cell.setup(temp: temp, currentTempOfMode: viewModel.currentTemperature)
return cell
}
}
<file_sep>//
// Int+Extensions.swift
// Koleda
//
// Created by <NAME> on 9/18/19.
// Copyright © 2019 koleda. All rights reserved.
//
import Foundation
extension Int {
func fullTimeFormart() -> String {
var hours: Int = 0
var minutes: Int = 0
var seconds: Int = self
if seconds >= 3600 {
hours = self/3600
seconds = self%3600
}
if seconds >= 60 {
minutes = seconds/60
seconds = seconds%60
}
let hoursString = hours > 9 ? "\(hours)" : "0\(hours)"
let minutesString = minutes > 9 ? "\(minutes)" : "0\(minutes)"
let secondsString = seconds > 9 ? "\(seconds)" : "0\(seconds)"
return "\(hoursString):\(minutesString):\(secondsString)"
}
func fullTimeWithHourAndMinuteFormat() -> String {
var hours: Int = 0
var minutes: Int = self
if minutes >= 60 {
hours = minutes/60
minutes = minutes%60
}
let hoursString = hours > 9 ? "\(hours)":"0\(hours)"
let minutesString = minutes > 9 ? "\(minutes)":"0\(minutes)"
return "\(hoursString):\(minutesString):00"
}
}
<file_sep>//
// RoomsPopOverViewController.swift
// Koleda
//
// Created by <NAME> on 9/10/19.
// Copyright © 2019 koleda. All rights reserved.
//
import UIKit
import RxSwift
protocol RoomsPopOverViewControllerDelegate: class {
func didSelected(rooms: [Room])
}
class RoomsPopOverViewController: UIViewController {
@IBOutlet weak var containerView: UIView!
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var okButton: UIButton!
@IBOutlet weak var titleLabel: UILabel!
weak var delegate: RoomsPopOverViewControllerDelegate?
private let disposeBag = DisposeBag()
var rooms: [Room] = []
var selectedRooms: [Room] = []
override func viewDidLoad() {
super.viewDidLoad()
rooms = UserDataManager.shared.rooms
Style.View.shadowCornerWhite.apply(to: containerView)
tableView.reloadData()
okButton.rx.tap.bind {
self.dismiss(animated: true, completion: {
self.delegate?.didSelected(rooms: self.selectedRooms)
})
}.disposed(by: disposeBag)
titleLabel.text = "PLEASE_SELECT_ROOMS".app_localized
okButton.setTitle("OK".app_localized, for: .normal)
}
}
extension RoomsPopOverViewController: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return rooms.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: RoomPopOverCell.get_identifier, for: indexPath) as? RoomPopOverCell else {
log.error("Invalid cell type call")
return UITableViewCell()
}
let room = rooms[indexPath.row]
cell.accessoryType = .none
let isSelected = selectedRooms.filter {$0.id == room.id}.count > 0
cell.loadData(room: room, isSelected: isSelected)
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 50
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let cell = tableView.cellForRow(at: indexPath) as? RoomPopOverCell {
cell.checkMarkImageView.isHidden = false
updateRooms(isSelected: true, room: rooms[indexPath.row])
}
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
if let cell = tableView.cellForRow(at: indexPath) as? RoomPopOverCell {
cell.checkMarkImageView.isHidden = true
updateRooms(isSelected: false, room: rooms[indexPath.row])
}
}
private func updateRooms(isSelected: Bool, room: Room) {
let hasRoom = selectedRooms.filter {$0.id == room.id}.count > 0
if isSelected && !hasRoom {
selectedRooms.append(room)
} else {
if let indexRoom = self.selectedRooms.firstIndex(where: {$0.id == room.id}), !isSelected {
self.selectedRooms.remove(at: indexRoom)
}
}
}
}
<file_sep>//
// AddHeaterViewModel.swift
// Koleda
//
// Created by <NAME> on 9/4/19.
// Copyright © 2019 koleda. All rights reserved.
//
import Foundation
import RxSwift
import SystemConfiguration.CaptiveNetwork
import NetworkExtension
import CopilotAPIAccess
protocol AddHeaterViewModelProtocol: BaseViewModelProtocol {
var reSearchingHeater: PublishSubject<Bool> { get }
var stepAddHeaters: PublishSubject<AddDeviceStatus> { get }
var detectedHeaters: [Heater] {set get }
var cancelButtonHidden: PublishSubject<Bool> { get }
func getCurrentWiFiName() -> String
var roomName: String { get }
func fetchInfoOfHeaderAPMode(completion: @escaping (Bool) -> Void)
func findHeatersOnLocalNetwork(completion: @escaping () -> Void)
func waitingHeatersJoinNetwork(completion: @escaping () -> Void)
func connectHeaterLocalWifi(ssid: String, pass: String, completion: @escaping (Bool) -> Void)
func addAHeaterToARoom(completion: @escaping (WSError?, String, String) -> Void)
func backToHome()
func showWifiDetail()
}
class AddHeaterViewModel: BaseViewModel, AddHeaterViewModelProtocol {
let router: BaseRouterProtocol
let reSearchingHeater = PublishSubject<Bool>()
var cancelButtonHidden = PublishSubject<Bool>()
var stepAddHeaters = PublishSubject<AddDeviceStatus>()
var detectedHeaters: [Heater] = []
private let shellyDeviceManager: ShellyDeviceManager
private let roomId: String
var roomName: String
private let netServiceClient = NetServiceClient()
private var timer:Timer?
private var timeLeft = 3
private var waiting = true
init(router: BaseRouterProtocol, managerProvider: ManagerProvider = .sharedInstance, roomId: String, roomName: String) {
self.router = router
self.shellyDeviceManager = managerProvider.shellyDeviceManager
self.roomId = roomId
self.roomName = roomName
super.init(managerProvider: managerProvider)
}
func getCurrentWiFiName() -> String {
var ssid: String = ""
if let interfaces = CNCopySupportedInterfaces() as NSArray? {
for interface in interfaces {
if let interfaceInfo = CNCopyCurrentNetworkInfo(interface as! CFString) as NSDictionary? {
ssid = interfaceInfo[kCNNetworkInfoKeySSID as String] as? String ?? ""
break
}
}
}
return ssid
}
func fetchInfoOfHeaderAPMode(completion: @escaping (Bool) -> Void) {
shellyDeviceManager.getDeviceInfoOnAPMode(success: { [weak self] deviceModel in
completion(true)
},
failure: { error in
completion(false)
})
}
func findHeatersOnLocalNetwork(completion: @escaping () -> Void) {
do {
netServiceClient.log = { print("NetService:", $0) }
var services = Set<Service>()
let end = Date() + 7.0
try netServiceClient.discoverServices(of: .http,
in: .local,
shouldContinue: { Date() < end },
foundService: { services.insert($0) })
var heaters: [Heater] = []
guard services.count > 0 else {
completion()
return
}
for service in services {
let hostName = service.name
log.info(hostName)
if DataValidator.isShellyHeaterDevice(hostName: hostName) && !UserDataManager.shared.deviceModelList.contains(hostName) {
// let addresses = try netServiceClient.resolve(service, timeout: 2.0)
// let ipAddress = addresses.description
let ipAddress = String(format: "%@.local",hostName)
log.info(ipAddress)
let heater: Heater = Heater(deviceModel: hostName, name: hostName, ipAddress: ipAddress)
heaters.append(heater)
}
}
if heaters.count == 1 {
setMQTTServerForHeater(heater: heaters[0]) { isSuccess in
self.detectedHeaters = isSuccess ? heaters : []
completion()
}
} else {
detectedHeaters = heaters
completion()
}
}
catch {
log.error("\(error)")
// let heater: Heater = Heater(deviceModel: "Shelly1PM-DEE3EE", name: "Shelly1PM-DEE3EE", ipAddress: "Shelly1PM-DEE3EE")
// let heater1: Heater = Heater(deviceModel: "Shelly1PM-DEE3FG", name: "Shelly1PM-DEE3FG", ipAddress: "Shelly1PM-DEE3FG")
// detectedHeaters = [heater]
// detectedHeaters = []
completion()
}
}
func connectHeaterLocalWifi(ssid: String, pass: String, completion: @escaping (Bool) -> Void) {
self.shellyDeviceManager.turnOnSTAOfDeviceInfo(ssid: ssid, pass: pass, success: {
completion(true)
}, failure: { error in
completion(false)
})
}
func waitingHeatersJoinNetwork(completion: @escaping () -> Void) {
waiting = true
timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(onTimerFires), userInfo: nil, repeats: waiting)
completion()
}
func showWifiDetail() {
router.enqueueRoute(with: AddHeaterRouter.RouteType.wifiDetail)
}
private func setMQTTServerForHeater(heater: Heater, completion: @escaping (Bool) -> Void) {
shellyDeviceManager.setMQTTForDevice(isSensor: false, deviceModel: heater.deviceModel, ipAddress: heater.ipAddress) { isSuccess in
completion(isSuccess)
}
}
@objc private func onTimerFires()
{
timeLeft -= 1
if timeLeft <= 0 {
timer?.invalidate()
timer = nil
waiting = ((FGRoute.getSSID()?.contains("shelly") ?? false) && FGRoute.getGatewayIP() == nil)
}
}
func addAHeaterToARoom(completion: @escaping (WSError?, String, String) -> Void) {
guard detectedHeaters.count > 0 else {
completion(WSError.general, "", "")
return
}
let heater = detectedHeaters[0]
shellyDeviceManager.addDevice(roomId: roomId, sensor: nil, heater: heater) { [weak self] error in
guard let `self` = self else {
return
}
let room = UserDataManager.shared.roomWith(roomId: self.roomId)
guard let roomName = room?.name else {
completion(error, heater.deviceModel, "")
return
}
Copilot.instance.report.log(event: AddHeaterAnalyticsEvent(heaterModel: heater.deviceModel, roomId: self.roomId, homeId: UserDataManager.shared.currentUser?.homes[0].id ?? "", screenName: self.screenName))
completion(error,heater.deviceModel, roomName)
}
}
func backToHome() {
router.enqueueRoute(with: AddHeaterRouter.RouteType.backHome)
}
}
<file_sep>//
// GuideItem.swift
// Koleda
//
// Created by <NAME> on 6/25/19.
// Copyright © 2019 koleda. All rights reserved.
//
import Foundation
import UIKit
struct GuideItem {
let image: UIImage?
let title: String
let message: String
init(image: UIImage?, title: String, message: String) {
self.image = image
self.title = title
self.message = message
}
}
<file_sep>//
// ScheduleModeCell.swift
// Koleda
//
// Created by <NAME> on 11/1/19.
// Copyright © 2019 koleda. All rights reserved.
//
import UIKit
class ScheduleModeCell: UICollectionViewCell {
@IBOutlet weak var modeView: ModeView!
override func awakeFromNib() {
super.awakeFromNib()
}
func setup(with mode: ModeItem, isSelected: Bool, fromModifyModesScreen: Bool) {
modeView.setUp(modeItem: mode)
modeView.updateStatus(enable: isSelected, fromModifyModesScreen: fromModifyModesScreen)
}
}
<file_sep>//
// HeatersManagementViewController.swift
// Koleda
//
// Created by <NAME> on 9/4/19.
// Copyright © 2019 koleda. All rights reserved.
//
import UIKit
import RxSwift
import SVProgressHUD
class HeatersManagementViewController: BaseViewController, BaseControllerProtocol {
var viewModel: HeatersManagementViewModelProtocol!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var heatersLabel: UILabel!
@IBOutlet weak var confirmLabel: UILabel!
@IBOutlet weak var doneButton: UIButton!
@IBOutlet weak var heatersCollectionView: UICollectionView!
private let disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
configurationUI()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationBarTransparency()
navigationController?.setNavigationBarHidden(true, animated: animated)
viewModel.viewWillAppear()
}
deinit {
NotificationCenter.default.removeObserver(self)
}
private func configurationUI() {
NotificationCenter.default.addObserver(self, selector: #selector(needUpdateSelectedRoom),
name: .KLDNeedUpdateSelectedRoom, object: nil)
viewModel.heaters.asObservable().subscribe(onNext: { [weak self] heaters in
guard let viewModel = self?.viewModel, let heatersCollectionViewDataSource = self?.heatersCollectionView.dataSource as? HeatersManagementCollectionViewDataSource else { return }
heatersCollectionViewDataSource.heaters = heaters
heatersCollectionViewDataSource.viewModel = viewModel
self?.heatersCollectionView.reloadData()
}).disposed(by: disposeBag)
doneButton.rx.tap.bind { [weak self] in
self?.viewModel.doneAction()
}.disposed(by: disposeBag)
// addHeaterButton.rx.tap.bind { [weak self] in
// self?.viewModel.addHeaterFlow()
// }
viewModel.showDeleteConfirmMessage.asObservable().subscribe(onNext: { [weak self] show in
if show {
self?.showDeleteConfirmMessage()
}
}).disposed(by: disposeBag)
heatersLabel.text = "EDIT_HEATERS_TEXT".app_localized
confirmLabel.text = "CONFIRM_TEXT".app_localized
// heaterTitleLabel.text = "Heaters".app_localized
}
func showDeleteConfirmMessage() {
if let vc = getViewControler(withStoryboar: "Room", aClass: AlertConfirmViewController.self) {
vc.onClickLetfButton = {
self.showConfirmPopUp()
}
if let removingHeaterName: String = viewModel.removingHeaterName{
vc.typeAlert = .deleteHeater(heaterName: removingHeaterName)
}
showPopup(vc)
}
}
private func showConfirmPopUp() {
if let vc = getViewControler(withStoryboar: "Room", aClass: AlertConfirmViewController.self) {
vc.onClickRightButton = {
SVProgressHUD.show()
self.viewModel.callServiceDeleteHeater(completion: { isSuccess in
SVProgressHUD.dismiss()
if isSuccess {
NotificationCenter.default.post(name: .KLDDidChangeRooms, object: nil)
self.app_showInfoAlert("DELETED_HEATER_SUCCESS_MESS".app_localized)
} else {
self.app_showInfoAlert("CAN_NOT_DELETE_HEATER".app_localized)
}
})
}
vc.typeAlert = .confirmDeleteHeater
showPopup(vc)
}
}
@objc private func needUpdateSelectedRoom() {
viewModel.needUpdateSelectedRoom()
}
@IBAction func backAction(_ sender: Any) {
back()
}
}
extension HeatersManagementViewController : UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: self.heatersCollectionView.frame.width, height: 98)
}
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
insetForSectionAt section: Int) -> UIEdgeInsets {
return .zero
}
}
<file_sep>//
// GeoLocationManager.swift
// Koleda
//
// Created by <NAME> on 7/5/19.
// Copyright © 2019 koleda. All rights reserved.
//
import CoreLocation
import UIKit
struct GeoLocation {
let deviceId: String
let latitude: Double?
let longitude: Double?
let accuracy: Double?
let bearing: Double?
var dictionary: [String: Any] {
var dictionary: [String: Any] = ["deviceId": deviceId]
if let latitude = latitude {
dictionary["latitude"] = String(describing: latitude)
}
if let longitude = longitude {
dictionary["longitude"] = String(describing: longitude)
}
if let accuracy = accuracy {
dictionary["accuracy"] = String(describing: accuracy)
}
if let bearing = bearing {
dictionary["bearing"] = String(describing: bearing)
}
return dictionary
}
}
struct Country {
let name: String
let isoCode: String
let currencyCode: String
init?(isoCode: String) {
guard let name = Locale.app_currentOrDefault.localizedString(forRegionCode: isoCode), let currencyCode = Locale.currencyCode(forCountryIsoCode: isoCode) else {
return nil
}
self.name = name
self.currencyCode = currencyCode
self.isoCode = isoCode
}
}
class GeoLocationManager: NSObject, CLLocationManagerDelegate {
typealias AutorizationCompletion = (CLAuthorizationStatus) -> Void
typealias CLLocationCompletion = (WSResult<CLLocation>) -> Void
typealias GeoLocationCompletion = (GeoLocation) -> Void
private lazy var deviceIdentifier: String = {
if let identifierForVendor = UIDevice.current.identifierForVendor?.uuidString {
return identifierForVendor
} else {
log.error("Failed getting device id")
return UUID().uuidString
}
}()
private let startUpdatesLock = NSLock()
private let locationManager: CLLocationManager
private lazy var geocoder = { return CLGeocoder() }()
private var autorizationCompletion: AutorizationCompletion?
private var geoLocationCompletions = [CLLocationCompletion]()
private var isUpdatingLocation = false
var isGeoLocationEnabled: Bool {
return CLLocationManager.locationServicesEnabled() && (CLLocationManager.authorizationStatus() == .authorizedAlways || CLLocationManager.authorizationStatus() == .authorizedWhenInUse)
}
var isMonitoringGeoLocationEnabled: Bool {
return CLLocationManager.locationServicesEnabled() &&
(CLLocationManager.authorizationStatus() == .authorizedAlways ||
CLLocationManager.authorizationStatus() == .authorizedWhenInUse) &&
CLLocationManager.significantLocationChangeMonitoringAvailable()
}
override init() {
locationManager = CLLocationManager()
super.init()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters
locationManager.allowsBackgroundLocationUpdates = false
locationManager.pausesLocationUpdatesAutomatically = false
}
func requestAlwaysAuthorization(completion: @escaping AutorizationCompletion) {
if CLLocationManager.locationServicesEnabled() && CLLocationManager.authorizationStatus() == .notDetermined {
autorizationCompletion = completion
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
} else {
DispatchQueue.main.async {
completion(CLLocationManager.authorizationStatus())
}
}
}
func currentGeoLocation(completion: @escaping GeoLocationCompletion) {
let deviceId = deviceIdentifier
currentLocation { result in
switch result {
case .success(let location):
let geoLocation = GeoLocation(deviceId: deviceId,
latitude: location.coordinate.latitude,
longitude: location.coordinate.longitude,
accuracy: location.verticalAccuracy,
bearing: location.course)
completion(geoLocation)
case .failure(_):
let geoLocation = GeoLocation(deviceId: deviceId,
latitude: nil,
longitude: nil,
accuracy: nil,
bearing: nil)
completion(geoLocation)
log.error("Geolocation obtaining failed")
}
}
}
// MARK: - Private methods
private func storeLastKnownDeviceCountry(_ country: Country) {
log.info("Last known device country updated")
UserDefaultsManager.lastKnownDeviceLocationCountryCode.value = country.isoCode
}
private func currentLocation(completion: @escaping CLLocationCompletion) {
guard isGeoLocationEnabled else {
completion(WSResult.failure(WSError.locationServicesUnavailable))
return
}
startUpdatesLock.lock()
defer { startUpdatesLock.unlock() }
geoLocationCompletions.append(completion)
guard !isUpdatingLocation else { return }
isUpdatingLocation = true
locationManager.requestLocation()
}
private func finishUpdating(location: CLLocation?) {
startUpdatesLock.lock()
defer { startUpdatesLock.unlock() }
isUpdatingLocation = false
geoLocationCompletions.forEach { location != nil ? $0(WSResult.success(location!)) : $0(WSResult.failure(WSError.locationServicesUnavailable)) }
geoLocationCompletions.removeAll()
if let location = location {
geocoder.reverseGeocodeLocation(location, completionHandler: { [weak self] placemarks, error in
guard let currentPlacemark = placemarks?.first, let countryCode = currentPlacemark.isoCountryCode, let country = Country(isoCode: countryCode), let strongSelf = self else {
log.error("Reverse Geocoding error - \(error?.localizedDescription ?? "Parsing")")
return
}
strongSelf.storeLastKnownDeviceCountry(country)
})
} else {
log.error("can't verify current location")
}
}
// MARK: - CLLocationManagerDelegate
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let location = locations.first else {
log.error("Failed retrieving geolocation")
finishUpdating(location: nil)
return
}
finishUpdating(location: location)
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
log.error(error.localizedDescription)
finishUpdating(location: nil)
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
var allow: String? = nil
switch status {
case .restricted:
allow = "restricted"
case .denied:
allow = "denied"
case .authorizedAlways:
allow = "authorized_always"
case .authorizedWhenInUse:
allow = "authorized_when_in_use"
default:
break
}
autorizationCompletion?(status)
autorizationCompletion = nil
}
}
<file_sep>//
// PopupWindowManager.swift
// Koleda
//
// Created by <NAME> on 8/19/19.
// Copyright © 2019 koleda. All rights reserved.
//
import UIKit
typealias KLDCloseHandler = () -> Void
protocol Popup: class {
func show(in viewController: UIViewController, animated: Bool, closeHandler: KLDCloseHandler?)
func hide(animated: Bool, completion: KLDCloseHandler?)
}
class PopupWindowManager {
var isShown: Bool {
return popup != nil
}
func show(popup: Popup) {
guard !isShown else {
popupWindow?.makeKeyAndVisible()
return
}
popupWindow = PassthroughWindow(frame: UIScreen.main.bounds)
guard let popupContainerWindow = popupWindow else {
return
}
popupContainerWindow.backgroundColor = .clear
popupContainerWindow.windowLevel = UIWindow.Level.normal
let rootViewController = PassthroughViewController()
popupContainerWindow.rootViewController = rootViewController
popup.show(in: rootViewController, animated: true, closeHandler: removePopupContainerWindow)
self.popup = popup
popupContainerWindow.makeKeyAndVisible()
}
func hide(popup: Popup, completion: KLDCloseHandler? = nil) {
if popup === self.popup {
popup.hide(animated: true, completion: completion)
}
}
// MARK: - Implementation
private var popupWindow: UIWindow?
private var popup: Popup?
private func removePopupContainerWindow() {
popup = nil
popupWindow?.rootViewController = nil
popupWindow = nil
UIApplication.shared.delegate?.window??.makeKeyAndVisible()
}
}
<file_sep>//
// SyncViewController.swift
// Koleda
//
// Created by <NAME> on 6/24/19.
// Copyright © 2019 koleda. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
class SyncViewController: BaseViewController, BaseControllerProtocol {
@IBOutlet weak var profileView: UIView!
@IBOutlet weak var profileImageView: UIImageView!
@IBOutlet weak var nameProfileLabel: UILabel!
@IBOutlet weak var noButton: UIButton!
@IBOutlet weak var yesButton: UIButton!
var viewModel: SyncViewModelProtocol!
private let disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
configurationUI()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(false, animated: animated)
addCloseFunctionality()
setTitleScreen(with: "")
}
}
extension SyncViewController {
private func configurationUI() {
Style.View.shadowStyle1.apply(to: profileView)
profileImageView.layer.cornerRadius = profileImageView.frame.width / 2.0
profileImageView.layer.masksToBounds = true
viewModel?.profileImage.drive(profileImageView.rx.image).disposed(by: disposeBag)
noButton.rx.tap.bind { [weak self] _ in
self?.viewModel.showTermAndConditionScreen()
}.disposed(by: disposeBag)
// yesButton.rx.tap.bind { [weak self] _ in
// self?.viewModel.showTermAndConditionScreen()
// }.disposed(by: disposeBag)
}
}
<file_sep>//
// BaseRouterProtocol.swift
// Koleda
//
// Created by <NAME> on 5/23/19.
// Copyright © 2019 koleda. All rights reserved.
//
import UIKit
protocol BaseRouterProtocol {
var baseViewController: UIViewController? { get set }
func present(on baseVC: UIViewController, animated: Bool, context: Any?, completion: ((Bool) -> Void)?)
func enqueueRoute(with context: Any?, animated: Bool, completion: ((Bool) -> Void)?)
func prepare(for segue: UIStoryboardSegue)
func dismiss(animated: Bool, context: Any?, completion: ((Bool) -> Void)?)
}
extension BaseRouterProtocol {
func present(on baseVC: UIViewController) {
self.present(on: baseVC, animated: true, context: nil, completion: nil)
}
func enqueueRoute(with context: Any?) {
self.enqueueRoute(with: context, animated: true, completion: nil)
}
func enqueueRoute(with context: Any?, completion: ((Bool) -> Void)?) {
self.enqueueRoute(with: context, animated: true, completion: completion)
}
func prepare(for segue: UIStoryboardSegue) {
self.prepare(for: segue)
}
}
<file_sep>//
// InviteFriendsViewController.swift
// Koleda
//
// Created by <NAME> on 6/23/20.
// Copyright © 2020 koleda. All rights reserved.
//
import UIKit
import RxSwift
class InviteFriendsViewController: BaseViewController, BaseControllerProtocol {
var viewModel: InviteFriendViewModelProtocol!
private let disposeBag = DisposeBag()
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var messageLabel: UILabel!
@IBOutlet weak var inviteButton: UIButton!
@IBOutlet weak var skipButton: UIButton!
@IBOutlet weak var backButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
configurationUI()
}
@IBAction func backButton(_ sender: Any) {
closeCurrentScreen()
}
private func configurationUI() {
statusBarStyle(with: .lightContent)
Style.Button.primary.apply(to: inviteButton)
skipButton.rx.tap.bind { [weak self] in
self?.viewModel.showHomeScreen()
}.disposed(by: disposeBag)
inviteButton.rx.tap.bind { [weak self] in
self?.viewModel.inviteFriends()
}.disposed(by: disposeBag)
backButton.rx.tap.bind { [weak self] in
self?.closeCurrentScreen()
}.disposed(by: disposeBag)
titleLabel.text = "CONGRATULATIONS_TEXT".app_localized
messageLabel.text = "YOU_JUST_CREATED_HOME_MESS".app_localized
inviteButton.setTitle("INVITE_FRIENDS_TEXT".app_localized, for: .normal)
skipButton.setTitle("SKIP_TEXT".app_localized, for: .normal)
}
}
<file_sep>//
// ModeAnalyticsEvent.swift
// Koleda
//
// Created by <NAME> on 9/4/20.
// Copyright © 2020 koleda. All rights reserved.
//
import Foundation
import CopilotAPIAccess
struct UpdateManualBoostAnalyticsEvent: AnalyticsEvent {
private let roomId: String
private let temp: Double
private let time: Int
private let screenName: String
init(roomId:String, temp: Double, time: Int, screenName: String) {
self.roomId = roomId
self.temp = temp
self.time = time
self.screenName = screenName
}
var customParams: Dictionary<String, String> {
return ["roomId" : roomId,
"temp" : String(temp),
"time" : String(time),
"screenName": screenName]
}
var eventName: String {
return "update_manual_boost"
}
var eventOrigin: AnalyticsEventOrigin {
return .App
}
var eventGroups: [AnalyticsEventGroup] {
return [.All]
}
}
struct ResetManualBoostAnalyticsEvent: AnalyticsEvent {
private let roomId: String
private let screenName: String
init(roomId:String, screenName: String) {
self.roomId = roomId
self.screenName = screenName
}
var customParams: Dictionary<String, String> {
return ["roomId" : roomId,
"screenName": screenName]
}
var eventName: String {
return "reset_manual_boost"
}
var eventOrigin: AnalyticsEventOrigin {
return .App
}
var eventGroups: [AnalyticsEventGroup] {
return [.All]
}
}
struct SetModeAnalyticsEvent: AnalyticsEvent {
private let roomId: String
private let mode: String
private let screenName: String
init(roomId:String, mode: String, screenName: String) {
self.roomId = roomId
self.mode = mode
self.screenName = screenName
}
var customParams: Dictionary<String, String> {
return ["roomId" : roomId,
"mode" : mode,
"screenName": screenName]
}
var eventName: String {
return "set_mode"
}
var eventOrigin: AnalyticsEventOrigin {
return .App
}
var eventGroups: [AnalyticsEventGroup] {
return [.All]
}
}
struct SetSmartScheduleAnalyticsEvent: AnalyticsEvent {
private let schedules: ScheduleOfDay
private let screenName: String
init(schedules: ScheduleOfDay, screenName: String) {
self.schedules = schedules
self.screenName = screenName
}
var customParams: Dictionary<String, String> {
return ["schedules" : schedules.convertToDictionary().description,
"screenName": screenName]
}
var eventName: String {
return "set_smart_schedule"
}
var eventOrigin: AnalyticsEventOrigin {
return .App
}
var eventGroups: [AnalyticsEventGroup] {
return [.All]
}
}
<file_sep>//
// TabContentViewController.swift
// Koleda
//
// Created by <NAME> on 10/31/19.
// Copyright © 2019 koleda. All rights reserved.
//
import UIKit
import RxSwift
import SpreadsheetView
import SVProgressHUD
protocol TabContentViewControllerDelegate: class {
func showScheduleDetailScreen(startTime: Time, day: DayOfWeek, tapedTimeline: Bool)
}
class TabContentViewController: BaseViewController, BaseControllerProtocol {
var viewModel: TabContentViewModelProtocol!
weak var delegate: TabContentViewControllerDelegate?
private let disposeBag = DisposeBag()
@IBOutlet weak var schedulesView: SpreadsheetView!
@IBOutlet weak var addSmartScheduleButton: UIButton!
static func instantiate(dayOfWeek: DayOfWeek) -> TabContentViewController? {
guard let viewController = StoryboardScene.SmartSchedule.instantiateTabContentViewController() as? TabContentViewController else {
assertionFailure("Setup storyboard configured not properly")
return nil
}
let router = TabContentRouter()
let viewModel = TabContentViewModel.init(router: router)
viewModel.setup(dayOfWeek: dayOfWeek)
viewController.viewModel = viewModel
router.baseViewController = viewController
return viewController
}
override func viewDidLoad() {
super.viewDidLoad()
configurationSheetView()
viewModel.reloadScheduleView.asObservable().subscribe(onNext: { [weak self] in
self?.schedulesView.reloadData()
self?.addSmartScheduleButton.isHidden = self?.viewModel.scheduleOfDayViewModel.displayData.count != 0
}).disposed(by: disposeBag)
addSmartScheduleButton.rx.tap.bind { [weak self] in
let startTime = Time(hour: 0, minute: 0)
guard let dayOfWeek = self?.viewModel.dayOfWeek else { return }
self?.delegate?.showScheduleDetailScreen(startTime: startTime, day: dayOfWeek, tapedTimeline: true)
}.disposed(by: disposeBag)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
updateSchedules()
}
private func updateSchedules() {
SVProgressHUD.show()
viewModel.getScheduleOfDay {
SVProgressHUD.dismiss()
}
}
deinit {
NotificationCenter.default.removeObserver(self)
}
@objc private func needRefreshSchedules() {
updateSchedules()
}
private func configurationSheetView() {
NotificationCenter.default.addObserver(self, selector: #selector(needRefreshSchedules),
name: .KLDNeedToUpdateSchedules, object: nil)
self.schedulesView.translatesAutoresizingMaskIntoConstraints = false
self.schedulesView.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true
self.schedulesView.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true
self.schedulesView.rightAnchor.constraint(equalTo: self.view.rightAnchor).isActive = true
self.schedulesView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true
self.schedulesView.isScrollEnabled = true
schedulesView.dataSource = self
schedulesView.delegate = self
schedulesView.contentInset = UIEdgeInsets(top: 4, left: 0, bottom: 4, right: 0)
schedulesView.intercellSpacing = CGSize(width: 0, height: 1)
schedulesView.gridStyle = .none
schedulesView.indicatorStyle = .white
schedulesView.register(TimeCell.self, forCellWithReuseIdentifier: String(describing: TimeCell.self))
schedulesView.register(ScheduleCell.self, forCellWithReuseIdentifier: String(describing: ScheduleCell.self))
addSmartScheduleButton.setTitle("ADD_SMARTSCHEDULE_TEXT".app_localized, for: .normal)
}
}
extension TabContentViewController: SpreadsheetViewDataSource, SpreadsheetViewDelegate {
func numberOfColumns(in spreadsheetView: SpreadsheetView) -> Int {
return 2
}
func numberOfRows(in spreadsheetView: SpreadsheetView) -> Int {
return viewModel.hoursData.count
}
func spreadsheetView(_ spreadsheetView: SpreadsheetView, widthForColumn column: Int) -> CGFloat {
if case 0 = column {
return 100
} else {
return self.view.frame.width - 100 - 20
}
}
func spreadsheetView(_ spreadsheetView: SpreadsheetView, heightForRow row: Int) -> CGFloat {
return 46
}
func frozenColumns(in spreadsheetView: SpreadsheetView) -> Int {
return 1
}
func frozenRows(in spreadsheetView: SpreadsheetView) -> Int {
return 0
}
func spreadsheetView(_ spreadsheetView: SpreadsheetView, cellForItemAt indexPath: IndexPath) -> Cell? {
let scheduleOfDayViewModel = viewModel.scheduleOfDayViewModel
if case (0, 0...viewModel.hoursData.count - 1) = (indexPath.column, indexPath.row) {
let cell = spreadsheetView.dequeueReusableCell(withReuseIdentifier: String(describing: TimeCell.self), for: indexPath) as! TimeCell
cell.label.text = viewModel.hoursData[indexPath.row]
return cell
} else if indexPath.column == 1 && scheduleOfDayViewModel.startRowList.contains(indexPath.row) {
let cell = spreadsheetView.dequeueReusableCell(withReuseIdentifier: String(describing: ScheduleCell.self), for: indexPath) as! ScheduleCell
cell.backgroundView?.backgroundColor = UIColor.gray
guard let blockSchedule = scheduleOfDayViewModel.displayData[indexPath.row] else {
return cell
}
cell.scheduleContent = blockSchedule
return cell
}
return nil
}
func mergedCells(in spreadsheetView: SpreadsheetView) -> [CellRange] {
return viewModel.mergeCellData
}
/// Delegate
func spreadsheetView(_ spreadsheetView: SpreadsheetView, didSelectItemAt indexPath: IndexPath) {
print("Selected: (row: \(indexPath.row), column: \(indexPath.column))")
let hour = indexPath.row/2
let minute = indexPath.row%2 == 0 ? 0 : 30
if hour <= 23 {
let startTime = Time(hour: hour, minute: minute)
delegate?.showScheduleDetailScreen(startTime: startTime, day: viewModel.dayOfWeek, tapedTimeline: indexPath.column == 0 ? true : false)
}
}
}
<file_sep>//
// InviteFriendsDetailViewModel.swift
// Koleda
//
// Created by <NAME> on 6/23/20.
// Copyright © 2020 koleda. All rights reserved.
//
import Foundation
import RxSwift
protocol InviteFriendsDetailViewControllerProtocol: BaseViewModelProtocol {
var emailText: Variable<String> { get }
var emailErrorMessage: Variable<String> { get }
var fiendsEmailList: Variable<[String]> { get }
var showErrorMessage: PublishSubject<String> { get }
func showInviteFriendsFinished()
func invitedAFriend(completion: @escaping (Bool, WSError?) -> Void)
func removeFriendBy(email: String, completion: @escaping () -> Void)
}
class InviteFriendsDetailViewModel: BaseViewModel, InviteFriendsDetailViewControllerProtocol {
var emailText = Variable<String>("")
let emailErrorMessage = Variable<String>("")
let fiendsEmailList = Variable<[String]>([])
let showErrorMessage = PublishSubject<String>()
let router: BaseRouterProtocol
private let userManager: UserManager
init(router: BaseRouterProtocol, managerProvider: ManagerProvider = .sharedInstance) {
self.router = router
self.userManager = managerProvider.userManager
super.init(managerProvider: managerProvider)
self.getFriendsList {}
}
func invitedAFriend(completion: @escaping (Bool, WSError?) -> Void) {
if validateEmail() {
invitedFriend { [weak self] error in
if error == nil {
self?.getFriendsList {
completion(true, nil)
}
} else {
completion(false, error)
}
}
} else {
completion(false, nil)
}
}
func showInviteFriendsFinished() {
router.enqueueRoute(with: InviteFriendsDetailRouter.RouteType.invited)
}
private func invitedFriend(completion: @escaping (WSError?) -> Void) {
let email = emailText.value.extraWhitespacesRemoved
userManager.inviteFriend(email: email, success: {
completion(nil)
}) { [weak self] error in
completion(error as? WSError)
}
}
private func getFriendsList(completion: @escaping () -> Void) {
userManager.getFriendsList(success: { [weak self] in
self?.fiendsEmailList.value = UserDataManager.shared.friendsList
completion()
}) { [weak self] error in
self?.showErrorMessage.onNext(("Can't get Friends List"))
completion()
}
}
private func validateEmail() -> Bool {
if emailText.value.extraWhitespacesRemoved.isEmpty {
emailErrorMessage.value = "Email is not Empty"
return false
}
if DataValidator.isEmailValid(email: emailText.value.extraWhitespacesRemoved) {
emailErrorMessage.value = ""
return true
} else {
emailErrorMessage.value = "Email is invalid"
return false
}
}
func removeFriendBy(email: String, completion: @escaping () -> Void) {
userManager.removeFriend(friendEmail: email, success: { [weak self] in
self?.getFriendsList {
completion()
}
}) {[weak self] error in
self?.showErrorMessage.onNext(("Can't get Friends List"))
completion()
}
}
}
<file_sep>//
// OfflineAlertViewController.swift
//
// Created by <NAME> on 3/23/18.
//
import UIKit
class OfflineAlertViewController: BaseViewController, Popup {
// MARK: - View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
view.translatesAutoresizingMaskIntoConstraints = false
}
override func viewWillDisappear(_ animated: Bool) {
hide(animated: false, completion: nil)
super.viewWillDisappear(animated)
}
// MARK: - Public interface
func show(in viewController: UIViewController, animated: Bool, closeHandler: KLDCloseHandler?) {
self.closeHandler = closeHandler
let containerView = viewController.view!
containerView.addSubview(view)
let topMessageLabelMargin = messageLabelBottomConstraint.constant // Top message label margin from the status bar
let initialTopConstraintHeight: CGFloat = animated ? -view.frame.height - topMessageLabelMargin : 0.0
topConstraint = view.topAnchor.constraint(equalTo: containerView.topAnchor, constant: initialTopConstraintHeight)
topConstraint!.isActive = true
view.leftAnchor.constraint(equalTo: containerView.leftAnchor).isActive = true
view.rightAnchor.constraint(equalTo: containerView.rightAnchor).isActive = true
if #available(iOS 11, *) {
let guide = containerView.safeAreaLayoutGuide
labelConstraint = messageLabel.topAnchor.constraint(equalTo: guide.topAnchor, constant: initialTopConstraintHeight + topMessageLabelMargin)
labelConstraint!.isActive = true
} else {
labelConstraint = messageLabel.topAnchor.constraint(equalTo: containerView.topAnchor, constant: UIApplication.shared.statusBarFrame.height + initialTopConstraintHeight + topMessageLabelMargin)
labelConstraint!.isActive = true
}
viewController.addChild(self)
didMove(toParent: viewController)
if animated {
slide(by: -initialTopConstraintHeight)
}
}
func hide(animated: Bool, completion: KLDCloseHandler?) {
let handler = {
self.app_removeFromContainerView()
self.closeHandler?()
completion?()
}
if animated {
slide(by: -view.frame.size.height, completion: { _ in
handler()
})
} else {
handler()
}
}
// MARK: - Implementation
private let animationDuration = 0.3
private var closeHandler: KLDCloseHandler? = nil
private var topConstraint: NSLayoutConstraint?
private var labelConstraint: NSLayoutConstraint?
@IBOutlet private weak var messageLabelBottomConstraint: NSLayoutConstraint!
@IBOutlet private weak var messageLabel: UILabel!
@IBAction private func close(_ sender: UIButton) {
hide(animated: true, completion: nil)
}
private func slide(by pixels: CGFloat, completion: ((Bool) -> Swift.Void)? = nil) {
DispatchQueue.main.async {
self.view.removeConstraint(self.topConstraint!)
self.topConstraint?.constant += pixels
self.labelConstraint?.constant += pixels
UIView.animate(withDuration: self.animationDuration, animations: {
self.view.superview?.layoutIfNeeded()
}, completion: completion)
}
}
}
<file_sep>//
// LoginAppManager.swift
// Koleda
//
// Created by <NAME> on 7/2/19.
// Copyright © 2019 koleda. All rights reserved.
//
import UIKit
import Alamofire
import SwiftyJSON
class LoginAppManager {
var sessionManager: SessionManager
var isLoggedIn: Bool {
return UserDefaultsManager.loggedIn.enabled
}
private func baseURL() -> URL {
return UrlConfigurator.urlByAdding()
}
init() {
let serverTrustPolicy = ServerTrustPolicy.pinCertificates(
certificates: ServerTrustPolicy.certificates(),
validateCertificateChain: true,
validateHost: true
)
let serverTrustPolicies: [String: ServerTrustPolicy] = [
"10.10.1.80": serverTrustPolicy]
sessionManager = SessionManager(configuration: URLSessionConfiguration.default,
serverTrustPolicyManager: ServerTrustPolicyManager(policies: serverTrustPolicies))
sessionManager.adapter = self
sessionManager.retrier = self
}
func login(email: String, password: String, success: @escaping () -> Void, failure: @escaping (_ error: Error) -> Void) {
let params = ["email": email,
"password": <PASSWORD>]
let endPointURL = baseURL().appendingPathComponent("auth/login")
guard let request = URLRequest.postRequestWithJsonBody(url: endPointURL, parameters: params) else {
failure(RequestError.error(NSLocalizedString("Failed to send request, please try again later", comment: "")))
return
}
sessionManager.request(request).validate().responseJSON { response in
switch response.result {
case .success(let result):
log.info("Successfully obtained access token")
let json = JSON(result)
let accessToken = json["accessToken"].stringValue
let refreshToken = json["refreshToken"].stringValue
let tokenType = json["tokenType"].stringValue
do {
try LocalAccessToken.store(accessToken, tokenType: tokenType)
try RefreshToken.store(refreshToken)
log.info("Successfully logged in")
success()
} catch let error {
log.error("Failed to store LoginCredentials/Passcode/AccessToken in keychain - \(error.localizedDescription)")
failure(error)
}
case .failure(let error):
log.error("Failed to obtain access token - \(error)")
if let error = error as? URLError, error.code == URLError.notConnectedToInternet {
NotificationCenter.default.post(name: .AppNotConnectedToInternet, object: error)
} else if let error = error as? AFError, error.responseCode == 400 {
failure(error)
} else if let error = error as? AFError, error.responseCode == 401 {
failure(error)
} else {
failure(error)
}
}
}
}
func loginWithSocial(type: SocialType, success: @escaping () -> Void, failure: @escaping (_ error: Error) -> Void) {
guard let bundleID = Bundle.main.bundleIdentifier else {
failure(RequestError.error(NSLocalizedString("failed to obtain bundle Identifier", comment: "")))
return
}
let socialString = type == SocialType.facebook ? "facebook" : "google"
let endPointURL = baseURL().appendingPathComponent("oauth2/authorize/\(socialString)?redirect_uri=\(bundleID)://oauth2/redirect")
Alamofire.request(endPointURL).responseJSON { response in
if let json = response.result.value {
print("JSON: \(json)") // serialized json response
success()
}
}
}
}
extension LoginAppManager: RequestAdapter, RequestRetrier {
func adapt(_ urlRequest: URLRequest) throws -> URLRequest {
guard let accessToken = AccessToken.restore() else {
log.info("No access token for request")
return urlRequest
}
var result = urlRequest
result.setValue("Bearer " + accessToken , forHTTPHeaderField: "Authorization")
return result
}
func should(_ manager: SessionManager,
retry request: Request,
with error: Error,
completion: @escaping RequestRetryCompletion)
{
if request.response?.statusCode == 403 {
completion(false, 0)
} else if request.response?.statusCode == 400 {
completion(false, 0)
} else {
if let error = error as? URLError, error.code == URLError.notConnectedToInternet {
NotificationCenter.default.post(name: .AppNotConnectedToInternet, object: error)
}
if let error = error as? URLError, error.code == URLError.networkConnectionLost, request.retryCount < 20 {
completion(true, 3)
} else {
completion(false, 0)
}
}
}
}
<file_sep>//
// SmartSchedulingViewController.swift
// Koleda
//
// Created by <NAME> on 10/22/19.
// Copyright © 2019 koleda. All rights reserved.
//
import UIKit
import RxSwift
class SmartSchedulingViewController: BaseViewController, BaseControllerProtocol {
var viewModel: SmartSchedulingViewModelProtocol!
private let disposeBag = DisposeBag()
@IBOutlet weak var selectedDayLabel: UILabel!
@IBOutlet weak var nextDayLabel: UILabel!
@IBOutlet weak var daysView: UIView!
@IBOutlet weak var swipeView: UIView!
var scrollToNext: ((Bool) -> Void)?
override func viewDidLoad() {
super.viewDidLoad()
configurationUI()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationBarTransparency()
navigationController?.setNavigationBarHidden(true, animated: animated)
statusBarStyle(with: .lightContent)
setTitleScreen(with: "")
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "SchedulingTabsViewController" {
if let schedulingTabsViewController = segue.destination as? SchedulingTabsViewController {
schedulingTabsViewController.parentController = self
}
}
}
@IBAction func backAction(_ sender: Any) {
back()
}
@IBAction func swipeMade(_ sender: UISwipeGestureRecognizer) {
if sender.direction == .left && viewModel.currentSelectedIndex < DayOfWeek.days - 1 {
self.scrollToNext?(true)
}
if sender.direction == .right && viewModel.currentSelectedIndex > 0 {
self.scrollToNext?(false)
}
}
private func configurationUI() {
let leftRecognizer = UISwipeGestureRecognizer(target: self, action:
#selector(swipeMade(_:)))
leftRecognizer.direction = .left
let rightRecognizer = UISwipeGestureRecognizer(target: self, action:
#selector(swipeMade(_:)))
rightRecognizer.direction = .right
self.swipeView.addGestureRecognizer(leftRecognizer)
self.swipeView.addGestureRecognizer(rightRecognizer)
}
private func updateSelectedDay(selectedIndex: Int) {
viewModel.currentSelectedIndex = selectedIndex
self.selectedDayLabel.text = DayOfWeek.dayWithIndex(index: selectedIndex).getStringLocalizeDay()
if selectedIndex == DayOfWeek.days - 1 {
self.nextDayLabel.text = DayOfWeek.dayWithIndex(index: 0).getStringLocalizeDay()
} else {
self.nextDayLabel.text = DayOfWeek.dayWithIndex(index: selectedIndex + 1).getStringLocalizeDay()
}
}
}
extension SmartSchedulingViewController: PageTabMenuViewControllerDelegate {
func currentPageIndex(indexPage: Int) {
updateSelectedDay(selectedIndex: indexPage)
}
}
extension SmartSchedulingViewController: TabContentViewControllerDelegate {
func showScheduleDetailScreen(startTime: Time, day: DayOfWeek, tapedTimeline: Bool) {
self.viewModel.showScheduleDetail(startTime: startTime, day: day, tapedTimeline: tapedTimeline)
}
}
<file_sep>//
// LocalAccessToken.swift
// Koleda
//
// Created by <NAME> on 7/3/19.
// Copyright © 2019 koleda. All rights reserved.
//
import Foundation
import Locksmith
struct LocalAccessToken {
static func store(_ token: String, tokenType: String) throws {
// Deletion needed for the case when an access token with different accessible option is already present in the
// keychain. In that case updating it fails with a duplication error.
try? delete()
try Locksmith.app_updateData(data: [accessTokenKey: token,
tokenTypeKey: tokenType],
forUserAccount: userAccountKey,
inService: keychainService,
accessibleOption: .alwaysThisDeviceOnly)
log.info("Stored access token")
}
static func restore() -> String? {
if let tokenInfo = Locksmith.loadDataForUserAccount(userAccount: userAccountKey, inService: keychainService) {
// log.info("Retrieved access token info")
return tokenInfo[accessTokenKey] as? String
} else {
// log.error("Can't retrieve access token")
return nil
}
}
// static func isExpired() -> Bool {
// guard let tokenInfo = Locksmith.loadDataForUserAccount(userAccount: userAccountKey,
// inService: keychainService),
// let timeIntervalSinceReferenceDate = tokenInfo[expirationDateKey] as? TimeInterval else
// {
// return false
//
// }
//
// let accessTokenExpirationDate = Date(timeIntervalSinceReferenceDate: timeIntervalSinceReferenceDate)
// let currentDate = Date()
// return currentDate >= accessTokenExpirationDate
// }
static func isStored() -> Bool {
return restore() != nil
}
static func delete() throws {
do {
try Locksmith.deleteDataForUserAccount(userAccount: userAccountKey, inService: keychainService)
log.info("Deleted access token")
} catch LocksmithError.notFound {
log.debug("Item to be deleted is not present in keychain")
}
}
// MARK: - Implementation
private static let accessTokenKey = "accessToken"
private static let tokenTypeKey = "tokenType"
private static let userAccountKey = "user.current.account"
private static let keychainService = "com.koleda.accessToken"
}
extension Locksmith {
static func app_updateData(data: [String: Any],
forUserAccount userAccount: String,
inService service: String = LocksmithDefaultService,
accessibleOption: LocksmithAccessibleOption? = nil) throws
{
struct UpdateRequest: GenericPasswordSecureStorable, CreateableSecureStorable {
let service: String
let account: String
let data: [String: Any]
let accessible: LocksmithAccessibleOption?
}
let request = UpdateRequest(service: service,
account: userAccount,
data: data,
accessible: accessibleOption)
try request.updateInSecureStore()
}
}
<file_sep>//
// BaseViewModelProtocol.swift
// Koleda
//
// Created by <NAME> on 5/23/19.
// Copyright © 2019 koleda. All rights reserved.
//
import Foundation
protocol BaseViewModelProtocol {
var router: BaseRouterProtocol { get }
}
<file_sep>//
// UIViewController+Extensions.swift
// Koleda
//
// Created by <NAME> on 5/23/19.
// Copyright © 2019 koleda. All rights reserved.
//
import Foundation
import UIKit
extension UIViewController {
func app_removeFromContainerView() {
guard parent != nil else { return }
willMove(toParent: nil)
removeFromParent()
view.removeFromSuperview()
}
var top: UIViewController? {
if let controller = self as? UINavigationController {
return controller.topViewController?.top
}
if let controller = self as? UISplitViewController {
return controller.viewControllers.last?.top
}
if let controller = self as? UITabBarController {
return controller.selectedViewController?.top
}
if let controller = presentedViewController {
return controller.top
}
return self
}
}
extension UIBarButtonItem {
class var back_empty: UIBarButtonItem {
return UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
}
}
public typealias Identifier = String
public protocol Identifiable: class {
static var get_identifier: Identifier { get }
}
public extension Identifiable {
static var get_identifier: Identifier {
return String(describing: self)
}
}
extension UIViewController: Identifiable {}
extension UITableViewCell: Identifiable {}
extension UIViewController {
func goto(withStoryboar fileName: String, present isPresent: Bool = false) {
let storyboard = UIStoryboard(name: fileName, bundle: nil)
if let controller = storyboard.instantiateInitialViewController() {
if (!isPresent) {
self.navigationController?.pushViewController(controller, animated: true)
} else {
self.present(controller, animated: true, completion: nil)
}
}
}
func goto(withStoryboar fileName: String, present isPresent: Bool = false, finish isFinish: Bool = false) {
let storyboard = UIStoryboard(name: fileName, bundle: nil)
if let controller = storyboard.instantiateInitialViewController() {
if (!isPresent) {
self.navigationController?.pushViewController(controller, animated: true)
if isFinish == true {
self.navigationController?.popViewController(animated: false)
}
} else {
self.present(controller, animated: true) {
self.dismiss(animated: false, completion: nil)
}
}
}
}
func goto(withStoryboar fileName: String, withIndentifier indentifier: String, present isPresent: Bool = false ) {
let storyboard = UIStoryboard(name: fileName, bundle: nil)
let controller = storyboard.instantiateViewController(withIdentifier: indentifier)
if (!isPresent) {
self.navigationController?.pushViewController(controller, animated: true)
} else {
self.present(controller, animated: true, completion: nil)
}
}
func gotoBlock<T: UIViewController>(withStoryboar fileName: String, aClass: T.Type, present isPresent: Bool = false, sendData: ((T?) -> Swift.Void)) {
let className = String(describing: aClass)
let storyboard = UIStoryboard(name: fileName, bundle: nil)
let controller: T = storyboard.instantiateViewController(withIdentifier: className) as! T
if (!isPresent) {
if self.navigationController?.viewControllers.last != self {
return
}
sendData(controller)
self.navigationController?.pushViewController(controller, animated: true)
} else {
self.present(controller, animated: true, completion: nil)
}
}
func goto(withIdentifier seque: String, sender: Any? = nil) {
self.performSegue(withIdentifier: seque, sender: sender)
}
func getViewControler<T: UIViewController>(withStoryboar fileName: String? = nil, aClass: T.Type) -> T? {
let className = String(describing: aClass)
var storyboard: UIStoryboard? = nil
if fileName == nil {
storyboard = self.storyboard
} else {
storyboard = UIStoryboard(name: fileName!, bundle: nil)
}
if storyboard != nil {
let controller: T? = storyboard!.instantiateViewController(withIdentifier: className) as? T
return controller
} else {
return nil
}
}
func getViewControler(withStoryboar fileName: String, identifier: String? = nil) -> UIViewController? {
let storyboard = UIStoryboard(name: fileName, bundle: nil)
if identifier != nil {
let controller: UIViewController? = storyboard.instantiateViewController(withIdentifier: identifier!) as? UIViewController
return controller
} else {
if let controller = storyboard.instantiateInitialViewController() {
return controller
} else {
let controller: UIViewController? = storyboard.instantiateViewController(withIdentifier: "UINavigationController") as? UIViewController
return controller
}
}
}
static func getNavigationController<T: UIViewController>(withStoryboar fileName: String, aClass: T.Type) -> UINavigationController {
let className = String(describing: aClass)
let storyboard = UIStoryboard(name: fileName, bundle: nil)
let vc: UIViewController = storyboard.instantiateViewController(withIdentifier: className)
let navcl = UINavigationController()
navcl.viewControllers = [vc] as! [UIViewController]
return navcl
}
func back(animated: Bool = true, isDismiss: Bool = false) {
if (isDismiss) {
let transition = CATransition()
transition.duration = 0.5
transition.type = CATransitionType.push
transition.subtype = CATransitionSubtype.fromLeft
self.view.window!.layer.add(transition, forKey: kCATransition)
self.dismiss(animated: false)
} else if (self.navigationController != nil) {
self.navigationController?.popViewController(animated: animated)
} else {
self.dismiss(animated: animated)
}
}
func backToViewControler(viewController: AnyClass, animated: Bool = true) {
if let navigationController = self.navigationController {
for var vc in navigationController.viewControllers {
if vc.isKind(of: viewController) {
navigationController.popToViewController(vc, animated: animated)
return
}
}
navigationController.popToRootViewController(animated: animated)
}
}
func backToRoot(animated: Bool = true) {
if let navigationController = self.navigationController {
navigationController.popToRootViewController(animated: animated)
}
}
func backPresentRight(withStoryboar fileName: String, withIndentifier indentifier: String? = nil) {
let transition = CATransition()
transition.duration = 0.5
transition.type = CATransitionType.push
transition.subtype = CATransitionSubtype.fromLeft
// transition.timingFunction = CAMediaTimingFunction(name:CAMediaTimingFunctionName.easeInEaseOut)
view.window!.layer.add(transition, forKey: kCATransition)
let storyboard = UIStoryboard(name: fileName, bundle: nil)
if let indentifier = indentifier {
let controller = storyboard.instantiateViewController(withIdentifier: indentifier)
present(controller, animated: false, completion: nil)
} else {
if let controller = storyboard.instantiateInitialViewController() {
present(controller, animated: false, completion: nil)
}
}
}
func gotoPresentLeft(withStoryboar fileName: String, withIndentifier indentifier: String? = nil) {
let transition = CATransition()
transition.duration = 0.5
transition.type = CATransitionType.push
transition.subtype = CATransitionSubtype.fromRight
transition.timingFunction = CAMediaTimingFunction(name:CAMediaTimingFunctionName.easeInEaseOut)
view.window!.layer.add(transition, forKey: kCATransition)
let storyboard = UIStoryboard(name: fileName, bundle: nil)
if let indentifier = indentifier {
let controller = storyboard.instantiateViewController(withIdentifier: indentifier)
present(controller, animated: false, completion: nil)
} else {
if let controller = storyboard.instantiateInitialViewController() {
present(controller, animated: false, completion: nil)
}
}
}
func gotoPresentLeft<T: UIViewController>(withStoryboar fileName: String? = nil, aClass: T.Type, sendData: ((T?) -> Swift.Void)) {
let transition = CATransition()
transition.duration = 0.5
transition.type = CATransitionType.push
transition.subtype = CATransitionSubtype.fromRight
transition.timingFunction = CAMediaTimingFunction(name:CAMediaTimingFunctionName.easeInEaseOut)
view.window!.layer.add(transition, forKey: kCATransition)
// let storyboard = UIStoryboard(name: fileName, bundle: nil)
if let controller = getViewControler(withStoryboar: fileName, aClass: aClass) {
sendData(controller)
present(controller, animated: false, completion: nil)
}
}
class func getRoot() -> UIViewController {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let viewController = appDelegate.window!.rootViewController as! UIViewController
return viewController;
}
class func setRoot(withStoryboar fileName: String, identifier: String) {
let storyboard = UIStoryboard(name: fileName, bundle: nil)
let controller = storyboard.instantiateViewController(withIdentifier: identifier)
let appDelegate = UIApplication.shared.delegate as! AppDelegate
if let window = appDelegate.window {
window.rootViewController = controller
window.backgroundColor = UIColor.white
window.makeKeyAndVisible()
}
}
class func getVisibleViewController(_ _rootViewController: UIViewController? = nil) -> UIViewController? {
var rootViewController = _rootViewController
if rootViewController == nil {
rootViewController = getRoot()
}
if rootViewController?.presentedViewController == nil {
return rootViewController
}
if let presented = rootViewController?.presentedViewController {
if presented.isKind(of: UINavigationController.self) {
let navigationController = presented as! UINavigationController
return navigationController.viewControllers.last!
} else if presented.isKind(of: UITabBarController.self){
let tabBarController = presented as! UITabBarController
return tabBarController.selectedViewController!
}
return getVisibleViewController(presented)
}
return nil
}
func showPopup(_ vc: UIViewController, transitionStyle: UIModalTransitionStyle = .crossDissolve, animated: Bool = true) {
vc.modalPresentationStyle = .overCurrentContext
vc.modalTransitionStyle = transitionStyle
vc.definesPresentationContext = true
present(vc, animated: animated, completion: nil)
}
func showAlert(title: String?, message: String?, actions: [UIAlertAction] = []) {
let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
for action in actions {
alertController.addAction(action)
}
self.present(alertController, animated: true)
}
}
protocol NameDescribable {
var screenName: String { get }
static var screenName: String { get }
}
extension NameDescribable {
var screenName: String {
return String(describing: type(of: self))
}
static var screenName: String {
return String(describing: self)
}
}
extension NSObject: NameDescribable {}
extension UIViewController: NameDescribable {}
<file_sep>//
// ScheduleTableViewCell.swift
// Koleda
//
// Created by <NAME> on 10/24/19.
// Copyright © 2019 koleda. All rights reserved.
//
import UIKit
class ScheduleTableViewCell: UITableViewCell {
@IBOutlet weak var statusIconImageView: UIImageView!
@IBOutlet weak var roomNameLabel: UILabel!
@IBOutlet weak var temperatureLabel: UILabel!
@IBOutlet weak var unitLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
}
func setup(scheduleRow: ScheduleRow, targetTemperature: Double) {
roomNameLabel.text = scheduleRow.title
guard let temp = scheduleRow.temperature else {
temperatureLabel.text = "-"
return
}
guard let unit = scheduleRow.temperatureUnit else {
return
}
if TemperatureUnit.C.rawValue == unit {
temperatureLabel.text = temp.toString()
} else {
temperatureLabel.text = temp.fahrenheitTemperature.toString()
}
unitLabel.text = "°\(unit)"
statusIconImageView.isHidden = (temp == targetTemperature)
if temp < targetTemperature {
statusIconImageView.image = UIImage(named: "ic-heating-up-small")
} else if temp > targetTemperature {
statusIconImageView.image = UIImage(named: "ic-cooling-down-small")
}
}
}
<file_sep>//
// WifiDetailRouter.swift
// Koleda
//
// Created by <NAME> on 12/4/19.
// Copyright © 2019 koleda. All rights reserved.
//
import Foundation
import UIKit
class WifiDetailRouter: BaseRouterProtocol {
weak var baseViewController: UIViewController?
enum RouteType {
case energyTariff
case back
}
func dismiss(animated: Bool, context: Any?, completion: ((Bool) -> Void)?) {
}
func enqueueRoute(with context: Any?, animated: Bool, completion: ((Bool) -> Void)?) {
guard let routeType = context as? RouteType else {
assertionFailure("The route type missmatches")
return
}
guard let baseViewController = baseViewController else {
assertionFailure("baseViewController is not set")
return
}
switch routeType {
case .energyTariff:
let router = EnergyTariffRouter()
let viewModel = EnergyTariffViewModel.init(router: router)
guard let energyTariffVC = StoryboardScene.Setup.instantiateEnergyTariffViewController() as? EnergyTariffViewController else {
assertionFailure("Setup storyboard configured not properly")
return
}
energyTariffVC.viewModel = viewModel
router.baseViewController = energyTariffVC
baseViewController.navigationController?.pushViewController(energyTariffVC, animated: true)
case .back:
baseViewController.navigationController?.popViewController(animated: true)
}
}
func present(on baseVC: UIViewController, animated: Bool, context: Any?, completion: ((Bool) -> Void)?) {
}
}
<file_sep>//
// UIFont+Extensions.swift
// Koleda
//
// Created by <NAME> on 5/28/19.
// Copyright © 2019 koleda. All rights reserved.
//
import UIKit
extension UIFont {
static func app_FuturaPTDemi(ofSize size: CGFloat) -> UIFont {
return UIFont(name: "FuturaPT-Demi", size: size)!
}
static func app_FuturaPTBook(ofSize size: CGFloat) -> UIFont {
return UIFont(name: "FuturaPT-Book", size: size)!
}
static func app_FuturaPTHeavy(ofSize size: CGFloat) -> UIFont {
return UIFont(name: "FuturaPT-Heavy", size: size)!
}
static func app_FuturaPTLight(ofSize size: CGFloat) -> UIFont {
return UIFont(name: "FuturaPT-Light", size: size)!
}
static func app_FuturaPTMedium(ofSize size: CGFloat) -> UIFont {
return UIFont(name: "FuturaPT-Medium", size: size)!
}
static func app_SFProDisplaySemibold(ofSize size: CGFloat) -> UIFont {
return UIFont(name: "SFProDisplay-Semibold", size: size)!
}
static func app_SFProDisplayRegular(ofSize size: CGFloat) -> UIFont {
return UIFont(name: "SFProDisplay-Regular", size: size)!
}
static func app_SFProDisplayMedium(ofSize size: CGFloat) -> UIFont {
return UIFont(name: "SFProDisplay-Medium", size: size)!
}
static func SFProDisplayRegular(ofSize size: CGFloat) -> UIFont {
return UIFont(name: "SFProDisplay-Regular", size: size)!
}
public static let SFProDisplaySemibold10: UIFont = UIFont(name: "SFProDisplay-Semibold", size: 10)!
public static let SFProDisplaySemibold14: UIFont = UIFont(name: "SFProDisplay-Semibold", size: 14)!
public static let SFProDisplaySemibold20: UIFont = app_SFProDisplaySemibold(ofSize: 20)
public static let SFProDisplayRegular17: UIFont = UIFont(name: "SFProDisplay-Regular", size: 17)!
}
<file_sep>//
// RoomDetailViewModel.swift
// Koleda
//
// Created by <NAME> on 7/9/19.
// Copyright © 2019 koleda. All rights reserved.
//
import Foundation
import UIKit
import RxSwift
import CopilotAPIAccess
protocol RoomDetailViewModelProtocol: BaseViewModelProtocol {
var screenTitle: Variable<String> { get }
var roomTypes: Variable<[RoomType]> { get }
var roomName: Variable<String> { get }
var roomNameErrorMessage: Variable<String> { get }
var showPopUpSelectRoomType: PublishSubject<Bool> { get }
var showPopUpSuccess: PublishSubject<Bool> { get }
var hideDeleteButton: BehaviorSubject<Bool> { get }
var selectedCategory: Variable<String> { get }
var nextButtonTitle: Variable<String> { get }
var currentRoomType: RoomType? { get }
func viewWillAppear()
func roomType(at indexPath: IndexPath?) -> RoomType?
func roomType(with category: String) -> RoomType?
func indexPathOfCategory(with category: String) -> IndexPath?
func next(roomType: RoomType?, completion: @escaping () -> Void)
func deleteRoom()
}
class RoomDetailViewModel: BaseViewModel, RoomDetailViewModelProtocol {
let router: BaseRouterProtocol
var currentRoomType :RoomType?
let screenTitle = Variable<String>("ADD_A_ROOM_TEXT".app_localized)
let roomTypes = Variable<[RoomType]>([])
let roomName = Variable<String>("")
let roomNameErrorMessage = Variable<String>("")
let showPopUpSelectRoomType = PublishSubject<Bool>()
let showPopUpSuccess = PublishSubject<Bool>()
let hideDeleteButton = BehaviorSubject<Bool>(value: true)
let selectedCategory = Variable<String>("")
let nextButtonTitle = Variable<String>("CREATE_ROOM_TEXT".app_localized)
private var editingRoom: Room?
private var roomManager: RoomManager
init(router: BaseRouterProtocol, managerProvider: ManagerProvider = .sharedInstance, editingRoom: Room? = nil) {
self.router = router
self.roomManager = managerProvider.roomManager
self.editingRoom = editingRoom
super.init(managerProvider: managerProvider)
self.roomTypes.value = RoomType.initRoomTypes()
if let category = editingRoom?.category {
self.currentRoomType = roomType(with: category)
}
}
func viewWillAppear() {
guard let name = editingRoom?.name, let category = editingRoom?.category else {
return
}
screenTitle.value = "EDIT_ROOM_TEXT".app_localized
nextButtonTitle.value = "CONFIRM_ROOM_DETAILS_TEXT".app_localized
roomName.value = name
selectedCategory.value = category
hideDeleteButton.onNext(false)
}
func roomType(at indexPath: IndexPath?) -> RoomType? {
guard let selectedIndexpath = indexPath else {
return nil
}
return roomTypes.value[selectedIndexpath.item]
}
func roomType(with category: String) -> RoomType? {
let roomCategory = RoomCategory(fromString: category)
return roomTypes.value.filter { $0.category == roomCategory}.first
}
func indexPathOfCategory(with category: String) -> IndexPath? {
guard let roomType = self.roomType(with: category), let item = roomTypes.value.firstIndex(where: { $0 == roomType }) else { return nil }
return IndexPath(item: item, section: 0)
}
func next(roomType: RoomType?, completion: @escaping () -> Void) {
guard let type = roomType else {
self.showPopUpSelectRoomType.onNext(true)
completion()
return
}
let roomName = self.roomName.value.extraWhitespacesRemoved
let categoryString = type.category.rawValue
if validateRoomName() {
guard let editingRoom = editingRoom else {
addRoom(category: categoryString, name: roomName, completion: {
completion()
})
return
}
if editingRoom.name != roomName || editingRoom.category != type.category.rawValue {
updateRoom(roomId: editingRoom.id, category: categoryString, name: roomName, completion: {
completion()
})
} else {
completion()
}
}
}
func deleteRoom() {
guard let roomId = self.editingRoom?.id else {
return
}
roomManager.deleteRoom(roomId: roomId, success: { [weak self] in
guard let `self` = self else {
return
}
NotificationCenter.default.post(name: .KLDDidChangeRooms, object: nil)
self.router.dismiss(animated:true, context: RoomDetailRouter.RouteType.deleted, completion: nil)
Copilot.instance.report.log(event: removeRoomAnalyticsEvent(roomId: roomId, roomName: self.editingRoom?.name ?? "", homeId: UserDataManager.shared.currentUser?.homes[0].id ?? "" , screenName: self.screenName))
},
failure: { error in })
}
}
extension RoomDetailViewModel {
private func validateRoomName() -> Bool {
if roomName.value.extraWhitespacesRemoved.isEmpty {
roomNameErrorMessage.value = "ROOM_NAME_IS_NOT_EMPTY_MESS".app_localized
return false
} else {
roomNameErrorMessage.value = ""
return true
}
}
private func addRoom(category: String, name: String, completion: @escaping () -> Void) {
roomManager.createRoom(category: category, name: name, success: { [weak self] roomId in
guard let `self` = self else {
return
}
NotificationCenter.default.post(name: .KLDDidChangeRooms, object: nil)
self.router.enqueueRoute(with: RoomDetailRouter.RouteType.added(roomId, name))
Copilot.instance.report.log(event: AddRoomAnalyticsEvent(roomName: name, homeId: UserDataManager.shared.currentUser?.homes[0].id ?? "", screenName: self.screenName))
completion()
},
failure: { _ in
completion()
})
}
private func updateRoom(roomId: String, category: String, name: String, completion: @escaping () -> Void) {
roomManager.updateRoom(roomId: roomId, category: category, name: name, success: { [weak self] in
guard let `self` = self else {
return
}
NotificationCenter.default.post(name: .KLDDidChangeRooms, object: nil)
self.router.dismiss(animated: true, context: RoomDetailRouter.RouteType.updated, completion: nil)
Copilot.instance.report.log(event: editRoomAnalyticsEvent(roomId: roomId, roomName: name, homeId: UserDataManager.shared.currentUser?.homes[0].id ?? "", screenName: self.screenName))
completion()
},
failure: { error in
completion()
})
}
}
<file_sep>//
// InviteFriendsFinishedViewModel.swift
// Koleda
//
// Created by <NAME> on 6/23/20.
// Copyright © 2020 koleda. All rights reserved.
//
import Foundation
protocol InviteFriendsFinishedViewModelProtocol: BaseViewModelProtocol {
func showHomeScreen()
func addMoreFriends()
}
class InviteFriendsFinishedViewModel: BaseViewModel, InviteFriendsFinishedViewModelProtocol {
let router: BaseRouterProtocol
init(router: BaseRouterProtocol, managerProvider: ManagerProvider = .sharedInstance) {
self.router = router
super.init(managerProvider: managerProvider)
}
func showHomeScreen() {
UserDefaultsManager.loggedIn.enabled = true
router.enqueueRoute(with: InviteFriendsFinishedRouter.RouteType.home)
}
func addMoreFriends() {
router.enqueueRoute(with: InviteFriendsFinishedRouter.RouteType.back)
}
}
<file_sep>//
// HomeRouter.swift
// Koleda
//
// Created by <NAME> on 6/27/19.
// Copyright © 2019 koleda. All rights reserved.
//
import UIKit
class HomeRouter: BaseRouterProtocol {
enum RouteType {
case addRoom
case editRoom(Room)
case selectedRoom(Room)
case selectedRoomConfiguration(Room)
case menuSettings
case logOut
}
weak var baseViewController: UIViewController?
func enqueueRoute(with context: Any?, animated: Bool, completion: ((Bool) -> Void)?) {
guard let routeType = context as? RouteType else {
assertionFailure("The route type missmatches")
return
}
guard let baseViewController = baseViewController else {
assertionFailure("baseViewController is not set")
return
}
switch routeType {
case .addRoom:
let router = RoomDetailRouter()
let viewModel = RoomDetailViewModel.init(router: router)
guard let viewController = StoryboardScene.Room.instantiateRoomDetailViewController() as? RoomDetailViewController else {
return
}
viewController.viewModel = viewModel
router.baseViewController = viewController
baseViewController.navigationController?.pushViewController(viewController, animated: true)
case .editRoom(let selectedRoom):
let router = RoomDetailRouter()
let viewModel = RoomDetailViewModel.init(router: router, editingRoom: selectedRoom)
guard let viewController = StoryboardScene.Room.instantiateRoomDetailViewController() as? RoomDetailViewController else {
return
}
viewController.viewModel = viewModel
router.baseViewController = viewController
baseViewController.navigationController?.pushViewController(viewController, animated: true)
case .selectedRoom(let selectedRoom):
let router = SelectedRoomRouter()
let viewModel = SelectedRoomViewModel.init(router: router, seletedRoom: selectedRoom)
guard let viewController = StoryboardScene.Home.instantiateSelectedRoomViewController() as? SelectedRoomViewController else {
return
}
viewController.viewModel = viewModel
router.baseViewController = viewController
baseViewController.navigationController?.pushViewController(viewController, animated: true)
case .selectedRoomConfiguration(let selectedRoom):
let router = ConfigurationRoomRouter()
let viewModel = ConfigurationRoomViewModel.init(router: router, seletedRoom: selectedRoom)
guard let viewController = StoryboardScene.Home.instantiateConfigurationRoomViewController() as? ConfigurationRoomViewController else {
return
}
viewController.viewModel = viewModel
router.baseViewController = viewController
baseViewController.navigationController?.pushViewController(viewController, animated: true)
case .menuSettings:
let router = MenuSettingsRouter()
let viewModel = MenuSettingsViewModel.init(router: router)
guard let viewController = StoryboardScene.Setup.instantiateMenuSettingsViewController() as? MenuSettingsViewController else {
return
}
viewController.viewModel = viewModel
router.baseViewController = viewController
baseViewController.navigationController?.pushViewController(viewController, animated: true)
case .logOut:
let router = OnboardingRouter()
let viewModel = OnboardingViewModel.init(with: router)
let onboaringNavigationVC = StoryboardScene.Onboarding.instantiateNavigationController()
guard let viewController = onboaringNavigationVC.topViewController as? OnboardingViewController else {
assertionFailure("OnBoarding storyboard configured not properly")
return
}
viewController.viewModel = viewModel
router.baseViewController = viewController
if let delegate = UIApplication.shared.delegate as? AppDelegate {
delegate.window?.rootViewController = onboaringNavigationVC
}
}
}
func present(on baseVC: UIViewController, animated: Bool, context: Any?, completion: ((Bool) -> Void)?) {
}
func dismiss(animated: Bool, context: Any?, completion: ((Bool) -> Void)?) {
}
}
<file_sep>//
// InstructionView.swift
// Koleda
//
// Created by <NAME> on 9/14/19.
// Copyright © 2019 koleda. All rights reserved.
//
import UIKit
import SwiftRichString
enum TypeInstruction {
case instructionForSensor1
case instructionForSensor2
case instructionForSensor3
case instructionForSensor4
case instructionForSensor5
case instructionForSensor6
case instructionForHeater1
case instructionForHeater2
case instructionForHeater3
case instructionForHeater4
}
class InstructionView: UIView {
@IBOutlet weak var backgroundView: UIView!
@IBOutlet weak var instructionImageView: UIImageView!
@IBOutlet weak var heighInstructionConstraint: NSLayoutConstraint!
@IBOutlet weak var titelLabel: UILabel!
@IBOutlet weak var subTitleLabel: UITextView!
var styleGroup:StyleGroup!
var styleGroupForSubTitle:StyleGroup!
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func awakeFromNib() {
super.awakeFromNib()
kld_loadContentFromNib()
initView()
}
func initView() {
var fontSize: CGFloat = 24
if UIDevice.screenType == .iPhones_5_5s_5c_SE {
fontSize = 16
heighInstructionConstraint.constant = 275
}
let normal = SwiftRichString.Style {
$0.font = UIFont.app_SFProDisplaySemibold(ofSize: fontSize)
$0.color = UIColor.hex1F1B15
}
let bold = SwiftRichString.Style {
$0.font = UIFont.app_SFProDisplaySemibold(ofSize: fontSize)
$0.color = UIColor.hexFF7020
}
let normalSub = SwiftRichString.Style {
$0.font = UIFont.app_SFProDisplayRegular(ofSize: 14)
$0.color = UIColor.gray
}
let boldAndBlack = SwiftRichString.Style {
$0.font = UIFont.app_SFProDisplaySemibold(ofSize: 14)
$0.color = UIColor.black
}
styleGroup = StyleGroup(base: normal, ["h": bold])
styleGroupForSubTitle = StyleGroup(base: normalSub, ["b" : boldAndBlack])
}
func updateUI(type: TypeInstruction) {
var title: String
var subTitle: String
var instructionImage: String
var backgroundColor: UIColor = .clear
switch type {
case .instructionForSensor1:
backgroundColor = UIColor(hex: 0x252525)
instructionImage = "ic-instruction-sensor-1"
title = "ADD_SENSOR_INSTRUCTION_TITLE_1".app_localized
subTitle = "ADD_SENSOR_INSTRUCTION_SUB_TITLE_1".app_localized
case .instructionForSensor2:
backgroundColor = UIColor(hex: 0x252525)
instructionImage = "ic-instruction-sensor-2"
title = "ADD_SENSOR_INSTRUCTION_TITLE_2".app_localized
subTitle = "ADD_SENSOR_INSTRUCTION_SUB_TITLE_2".app_localized
case .instructionForSensor3:
backgroundColor = UIColor(hex: 0x252525)
instructionImage = "ic-instruction-sensor-3"
title = "ADD_SENSOR_INSTRUCTION_TITLE_3".app_localized
subTitle = "ADD_SENSOR_INSTRUCTION_SUB_TITLE_3".app_localized
case .instructionForSensor4:
backgroundColor = UIColor(hex: 0x252525)
instructionImage = "ic-instruction-sensor-4"
title = "ADD_SENSOR_INSTRUCTION_TITLE_4".app_localized
subTitle = "ADD_SENSOR_INSTRUCTION_SUB_TITLE_4".app_localized
case .instructionForSensor5:
backgroundColor = UIColor(hex: 0x252525)
instructionImage = "ic-instruction-sensor-5"
title = "ADD_SENSOR_INSTRUCTION_TITLE_5".app_localized
subTitle = "ADD_SENSOR_INSTRUCTION_SUB_TITLE_5".app_localized
case .instructionForSensor6:
backgroundColor = UIColor(hex: 0xE6EAF0)
instructionImage = "ic-instruction-sensor-6"
title = "ADD_SENSOR_INSTRUCTION_TITLE_6".app_localized
subTitle = "ADD_SENSOR_INSTRUCTION_SUB_TITLE_6".app_localized
case .instructionForHeater1:
// backgroundColor = UIColor(hex: 0xE6EAF0)
instructionImage = "ic-instruction-heater-1"
title = "ADD_HEATER_INSTRUCTION_TITLE_1".app_localized
subTitle = "ADD_HEATER_INSTRUCTION_SUB_TITLE_1".app_localized
case .instructionForHeater2:
// backgroundColor = UIColor(hex: 0xE6EAF0)
instructionImage = "ic-instruction-heater-2"
title = "ADD_HEATER_INSTRUCTION_TITLE_2".app_localized
subTitle = "ADD_HEATER_INSTRUCTION_SUB_TITLE_2".app_localized
case .instructionForHeater3:
// backgroundColor = UIColor(hex: 0xE6EAF0)
instructionImage = "ic-instruction-heater-3"
title = "ADD_HEATER_INSTRUCTION_TITLE_3".app_localized
subTitle = "ADD_HEATER_INSTRUCTION_SUB_TITLE_3".app_localized
case .instructionForHeater4:
// backgroundColor = UIColor(hex: 0xE6EAF0)
instructionImage = "ic-instruction-heater-4"
title = "ADD_HEATER_INSTRUCTION_TITLE_4".app_localized
subTitle = "ADD_HEATER_INSTRUCTION_SUB_TITLE_4".app_localized
}
backgroundView.backgroundColor = backgroundColor
instructionImageView.image = UIImage(named:instructionImage)
titelLabel.attributedText = title.set(style: styleGroup)
subTitleLabel.attributedText = subTitle.set(style: styleGroupForSubTitle)
}
}
<file_sep>//
// SignUpViewController.swift
// Koleda
//
// Created by <NAME> on 5/27/19.
// Copyright © 2019 koleda. All rights reserved.
//
import UIKit
import RxSwift
import SVProgressHUD
class SignUpViewController: BaseViewController, BaseControllerProtocol, KeyboardAvoidable {
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var nameTextField: AndroidStyle2TextField!
@IBOutlet weak var emailTextField: AndroidStyle2TextField!
@IBOutlet weak var passwordTextField: AndroidStyle2TextField!
@IBOutlet weak var confirmFullNameImageView: UIImageView!
@IBOutlet weak var confirmEmailImageView: UIImageView!
@IBOutlet weak var signUpLabel: UILabel!
@IBOutlet weak var nextLabel: UILabel!
var keyboardHelper: KeyboardHepler?
var viewModel: SignUpViewModelProtocol!
private let disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
initView()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(true, animated: animated)
statusBarStyle(with: .lightContent)
self.edgesForExtendedLayout = UIRectEdge.top
self.automaticallyAdjustsScrollViewInsets = false
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
removeKeyboardObservers()
}
func initView() {
keyboardHelper = KeyboardHepler(scrollView)
viewModel.fullName.asObservable().bind(to: nameTextField.rx.text).disposed(by: disposeBag)
nameTextField.rx.text.orEmpty.bind(to: viewModel.fullName).disposed(by: disposeBag)
viewModel.email.asObservable().bind(to: emailTextField.rx.text).disposed(by: disposeBag)
emailTextField.rx.text.orEmpty.bind(to: viewModel.email).disposed(by: disposeBag)
viewModel.password.asObservable().bind(to: passwordTextField.rx.text).disposed(by: disposeBag)
passwordTextField.rx.text.orEmpty.bind(to: viewModel.password).disposed(by: disposeBag)
viewModel.showPassword.asObservable().subscribe(onNext: { [weak self] value in
self?.passwordTextField.isSecureTextEntry = !value
}).disposed(by: disposeBag)
viewModel.fullName.asObservable().subscribe(onNext: { [weak self] value in
self?.confirmFullNameImageView.isHidden = isEmpty(value)
}).disposed(by: disposeBag)
viewModel.email.asObservable().subscribe(onNext: { [weak self] value in
self?.confirmEmailImageView.isHidden = isEmpty(value)
}).disposed(by: disposeBag)
viewModel.password.asObservable().subscribe(onNext: { [weak self] value in
if !isEmpty(value) && value.count < Constants.passwordMinLength {
self?.passwordTextField.errorText = "TOO_SHORT_TEXT".app_localized
self?.passwordTextField.showError(true)
} else {
self?.passwordTextField.errorText = ""
self?.passwordTextField.showError(false)
}
}).disposed(by: disposeBag)
viewModel.fullNameErrorMessage.asObservable().subscribe(onNext: { [weak self] message in
self?.nameTextField.errorText = message
if message.isEmpty {
self?.nameTextField.showError(false)
} else {
self?.nameTextField.showError(true)
}
}).disposed(by: disposeBag)
viewModel.emailErrorMessage.asObservable().subscribe(onNext: { [weak self] message in
self?.emailTextField.errorText = message
if message.isEmpty {
self?.emailTextField.showError(false)
} else {
self?.emailTextField.showError(true)
}
}).disposed(by: disposeBag)
viewModel.passwordErrorMessage.asObservable().subscribe(onNext: { [weak self] message in
self?.passwordTextField.errorText = message
if message.isEmpty {
self?.passwordTextField.showError(false)
} else {
self?.passwordTextField.showError(true)
}
}).disposed(by: disposeBag)
viewModel.showErrorMessage.asObservable().subscribe(onNext: { [weak self] message in
if !message.isEmpty {
self?.app_showAlertMessage(title: "ERROR_TITLE".app_localized, message: message)
}
}).disposed(by: disposeBag)
//
signUpLabel.text = "SIGN_UP".app_localized
nameTextField.titleText = "NAME_TEXT".app_localized
emailTextField.titleText = "EMAIL_TEXT".app_localized
passwordTextField.titleText = "PASSWORD_TITLE".app_localized
nextLabel.text = "NEXT_TEXT".app_localized
nameTextField.placeholder = "ENTER_YOUR_NAME_TEXT".app_localized
emailTextField.placeholder = "ENTER_EMAIL_HERE_TEXT".app_localized
passwordTextField.placeholder = "ENTER_PASSWORD_TEXT".app_localized
}
@IBAction func next(_ sender: Any) {
if viewModel.validateAll() {
view.endEditing(true)
SVProgressHUD.show()
viewModel.next { [weak self] error in
SVProgressHUD.dismiss()
guard let error = error else {
self?.app_showInfoAlert("SIGN_UP_SUCCESS_MESS".app_localized, title: "KOLEDA_TEXT".app_localized, completion: {
self?.logionApp()
})
return
}
self?.app_showAlertMessage(title: "ERROR_TITLE".app_localized, message: error.localizedDescription)
}
}
}
@IBAction func showOrHidePass(_ sender: Any) {
viewModel?.showPassword(isShow: passwordTextField.isSecureTextEntry)
}
@IBAction func backAction(_ sender: Any) {
back()
}
private func logionApp() {
SVProgressHUD.show()
viewModel.loginAfterSignedUp(completion: { [weak self] errorMessage in
SVProgressHUD.dismiss()
if errorMessage != "" {
self?.app_showInfoAlert(errorMessage, title: "ERROR_TITLE".app_localized, completion: {
self?.back()
})
} else {
self?.viewModel.goTermAndConditions()
}
})
}
}
extension SignUpViewController: UITextFieldDelegate {
func textField(_ textField: UITextField,
shouldChangeCharactersIn range: NSRange,
replacementString string: String) -> Bool
{
if textField == nameTextField {
let currentText = textField.text as NSString?
if let resultingText = currentText?.replacingCharacters(in: range, with: string) {
return resultingText.count <= Constants.nameMaxLength
}
} else if textField == passwordTextField {
let currentText = textField.text as NSString?
if let resultingText = currentText?.replacingCharacters(in: range, with: string) {
return resultingText.count <= Constants.passwordMaxLength
}
}
return true
}
}
<file_sep>//
// LoginRouter.swift
// Koleda
//
// Created by <NAME> on 6/11/19.
// Copyright © 2019 koleda. All rights reserved.
//
import Foundation
import UIKit
class LoginRouter: BaseRouterProtocol {
weak var baseViewController: UIViewController?
enum RouteType {
case home
case syncUser
case termAndConditions
case forgotPassword
case onboaring
}
func enqueueRoute(with context: Any?, animated: Bool, completion: ((Bool) -> Void)?) {
guard let routeType = context as? RouteType else {
assertionFailure("The route type missmatches")
return
}
guard let baseViewController = baseViewController else {
assertionFailure("baseViewController is not set")
return
}
switch routeType {
case .termAndConditions:
let router = TermAndConditionRouter()
let viewModel = TermAndConditionViewModel.init(router: router)
guard let viewController = StoryboardScene.Setup.instantiateTermAndConditionViewController() as? TermAndConditionViewController else { return }
viewController.viewModel = viewModel
router.baseViewController = viewController
baseViewController.navigationController?.pushViewController(viewController, animated: true)
case .syncUser:
let router = SyncRouter()
guard let viewController = StoryboardScene.Setup.initialViewController() as? SyncViewController else { return }
let viewModel = SyncViewModel.init(with: router)
viewController.viewModel = viewModel
router.baseViewController = viewController
baseViewController.navigationController?.pushViewController(viewController, animated: true)
case .forgotPassword:
baseViewController.gotoBlock(withStoryboar: "Login", aClass: ForgotPasswordViewController.self) { (vc) in
if let viewController = vc {
let router = ForgotPasswordRouter()
let viewModel = ForgotPasswordViewModel.init(router: router)
viewController.viewModel = viewModel
router.baseViewController = viewController
}
}
case .home:
let router = HomeRouter()
let viewModel = HomeViewModel.init(router: router)
let homeNavigationVC = StoryboardScene.Home.instantiateNavigationController()
guard let viewController = homeNavigationVC.topViewController as? HomeViewController else {
assertionFailure("HomeViewController storyboard configured not properly")
return
}
viewController.viewModel = viewModel
router.baseViewController = viewController
if let delegate = UIApplication.shared.delegate as? AppDelegate {
delegate.window?.rootViewController = homeNavigationVC
}
case .onboaring:
let router = OnboardingRouter()
let viewModel = OnboardingViewModel.init(with: router)
let onboaringNavigationVC = StoryboardScene.Onboarding.instantiateNavigationController()
guard let viewController = onboaringNavigationVC.topViewController as? OnboardingViewController else {
assertionFailure("OnBoarding storyboard configured not properly")
return
}
viewController.viewModel = viewModel
router.baseViewController = viewController
if let delegate = UIApplication.shared.delegate as? AppDelegate {
delegate.window?.rootViewController = onboaringNavigationVC
}
}
}
func present(on baseVC: UIViewController, animated: Bool, context: Any?, completion: ((Bool) -> Void)?) {
}
func dismiss(animated: Bool, context: Any?, completion: ((Bool) -> Void)?) {
}
func prepare(for segue: UIStoryboardSegue) {
if let viewController = segue.destination as? ForgotPasswordViewController {
let router = ForgotPasswordRouter()
let viewModel = ForgotPasswordViewModel.init(router: router)
viewController.viewModel = viewModel
router.baseViewController = viewController
}
}
}
<file_sep>//
// ModeView.swift
// Koleda
//
// Created by <NAME> on 9/9/19.
// Copyright © 2019 koleda. All rights reserved.
//
import UIKit
struct ModeItem {
let mode: SmartMode
let title: String
let icon: UIImage?
let temperature: Double
let color: UIColor
init(mode: SmartMode, title: String, icon: UIImage?, temp: Double) {
self.mode = mode
self.title = title
self.icon = icon
self.temperature = temp
switch mode {
case .ECO:
self.color = UIColor.purpleLight
case .NIGHT:
self.color = UIColor.redLight
case .COMFORT:
self.color = UIColor.blueLight
case .SMARTSCHEDULE:
self.color = UIColor.yellowLight
default:
self.color = UIColor.yellowLight
}
}
static func imageOf(smartMode: SmartMode) -> UIImage? {
switch smartMode {
case .ECO:
return UIImage.init(named: "ecoMode")
case .COMFORT:
return UIImage.init(named: "comfortMode")
case .NIGHT:
return UIImage.init(named: "nightMode")
case .SMARTSCHEDULE:
return UIImage.init(named: "smartSchedule")
default:
return nil
}
}
static func titleOf(smartMode: SmartMode) -> String {
switch smartMode {
case .ECO:
return "ECO_MODE_TEXT".app_localized.uppercased()
case .COMFORT:
return "COMFORT_MODE_TEXT".app_localized.uppercased()
case .NIGHT:
return "NIGHT_MODE_TEXT".app_localized.uppercased()
case .SMARTSCHEDULE:
return "SCHEDULE_TEXT".app_localized.uppercased()
default:
return ""
}
}
static func modeNameOf(smartMode: SmartMode) -> String {
switch smartMode {
case .ECO:
return "ECO_MODE_TEXT".app_localized
case .COMFORT:
return "COMFORT_MODE_TEXT".app_localized
case .NIGHT:
return "NIGHT_MODE_TEXT".app_localized
default:
return ""
}
}
static func getModeItem(with smartMode: SmartMode) -> ModeItem? {
let modeItems = UserDataManager.shared.settingModes
return modeItems.filter { $0.mode == smartMode}.first
}
static func getSmartScheduleMode() -> ModeItem {
return ModeItem(mode: .SMARTSCHEDULE, title: ModeItem.titleOf(smartMode: .SMARTSCHEDULE), icon: ModeItem.imageOf(smartMode: .SMARTSCHEDULE), temp: Constants.DEFAULT_TEMPERATURE)
}
}
class ModeView: UIView {
func setUp(modeItem: ModeItem) {
self.modeItem = modeItem
updateStatus(enable: false)
}
@IBOutlet weak var modeIconImageView: UIImageView!
@IBOutlet weak var titleModeLabel: UILabel!
@IBOutlet weak var lineLabel: UILabel!
var modeItem: ModeItem?
override func awakeFromNib() {
super.awakeFromNib()
kld_loadContentFromNib()
}
func updateStatus(enable: Bool, fromModifyModesScreen: Bool = false) {
guard let modeItem = modeItem else {
return
}
self.titleModeLabel.text = modeItem.title
self.modeIconImageView.image = modeItem.icon
self.modeIconImageView.tintColor = (enable || fromModifyModesScreen) ? modeItem.color : UIColor.gray
self.backgroundColor = enable ? UIColor.white : UIColor.clear
self.titleModeLabel.textColor = enable ? UIColor.black : UIColor.lightGray
self.lineLabel.backgroundColor = enable ? modeItem.color : UIColor.clear
}
}
<file_sep>//
// GuideCollectionViewCell.swift
// Koleda
//
// Created by <NAME> on 6/25/19.
// Copyright © 2019 koleda. All rights reserved.
//
import UIKit
class GuideCollectionViewCell: UICollectionViewCell , UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableView: UITableView!
private var guideItem: GuideItem?
override func awakeFromNib() {
super.awakeFromNib()
tableView.delegate = self
tableView.dataSource = self
tableView.rowHeight = UITableView.automaticDimension
tableView.estimatedRowHeight = 200
let cellNib = UINib(nibName: GuideTableViewCell.get_identifier, bundle: nil)
tableView.register(cellNib, forCellReuseIdentifier: GuideTableViewCell.get_identifier)
}
func reloadPage(with guideItem: GuideItem) {
self.guideItem = guideItem
tableView.reloadData()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let guideItem = guideItem, let cell = tableView.dequeueReusableCell(withIdentifier: GuideTableViewCell.get_identifier, for: indexPath) as? GuideTableViewCell else {
return UITableViewCell()
}
cell.setup(with: guideItem)
return cell
}
}
<file_sep>//
// UIViewController+Keyboard.swift
// Koleda
//
// Created by <NAME> on 6/3/19.
// Copyright © 2019 koleda. All rights reserved.
//
import UIKit
protocol KeyboardAvoidable: class {
/*
Provide array of constraints, which should be adjusted to keyboard height value on its appear. After keyboard
hidding, initial constants values will be applied.
*/
func addKeyboardObservers(forConstraints constraints: [NSLayoutConstraint])
/*
Adding of custom action on keyboard appearance. Keyboard height will be transfered as a parameter.
*/
func addKeyboardObservers(forCustomBlock block: @escaping (CGFloat) -> Void)
func addKeyboardObservers(forConstraints constraints: [NSLayoutConstraint]?,
customBlock block: ((CGFloat) -> Void)?)
func removeKeyboardObservers()
}
fileprivate var KeyboardShowObserverObjectKey: UInt8 = 1
fileprivate var KeyboardHideObserverObjectKey: UInt8 = 2
fileprivate var ConstraintsDictionaryKey: UInt8 = 3
extension KeyboardAvoidable where Self: UIViewController {
private var keyboardShowObserverObject: NSObjectProtocol? {
get {
return objc_getAssociatedObject(self, &KeyboardShowObserverObjectKey) as? NSObjectProtocol
}
set {
objc_setAssociatedObject(self, &KeyboardShowObserverObjectKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
private var keyboardHideObserverObject: NSObjectProtocol? {
get {
return objc_getAssociatedObject(self, &KeyboardHideObserverObjectKey) as? NSObjectProtocol
}
set {
objc_setAssociatedObject(self, &KeyboardHideObserverObjectKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
private var constraintsAndValues: [NSLayoutConstraint: CGFloat]? {
get {
return objc_getAssociatedObject(self, &ConstraintsDictionaryKey) as? [NSLayoutConstraint: CGFloat]
}
set {
objc_setAssociatedObject(self, &ConstraintsDictionaryKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
// MARK: - Public methods
func addKeyboardObservers(forConstraints constraints: [NSLayoutConstraint]) {
addKeyboardObservers(forConstraints: constraints, customBlock: nil)
}
func addKeyboardObservers(forCustomBlock block: @escaping (CGFloat) -> Void) {
addKeyboardObservers(forConstraints: nil, customBlock: block)
}
func addKeyboardObservers(forConstraints constraints: [NSLayoutConstraint]?,
customBlock block: ((CGFloat) -> Void)?)
{
removeKeyboardObservers()
if let constraints = constraints {
constraintsAndValues = constraints.reduce([NSLayoutConstraint: CGFloat]()) {
(result, constraint) -> [NSLayoutConstraint: CGFloat] in
var result = result
result[constraint] = constraint.constant
return result
}
}
keyboardShowObserverObject = NotificationCenter.default.addObserver(forName: UIResponder.keyboardWillShowNotification,
object: nil,
queue: nil)
{ [weak self] notification in
guard let notificationParameters = self?.getKeyboardShowParameters(fromNotification: notification) else {
// log.error("Cant extract keyboard notification parameters")
return
}
if let block = block {
block(notificationParameters.height)
return
}
self?.animateLayout(parameters: notificationParameters, animations: {
self?.constraintsAndValues?.forEach {
if #available(iOS 11.0, *) {
$0.key.constant = notificationParameters.height + $0.value - ( self?.view.safeAreaInsets.bottom ?? 0 )
} else {
$0.key.constant = notificationParameters.height + $0.value
}
}
})
}
keyboardHideObserverObject = NotificationCenter.default.addObserver(forName: UIResponder.keyboardWillHideNotification,
object: nil,
queue: nil)
{ [weak self] notification in
guard let notificationParameters = self?.getKeyboardShowParameters(fromNotification: notification) else {
// log.error("Cant extract keyboard notification parameters")
return
}
if let block = block {
block(notificationParameters.height)
return
}
self?.animateLayout(parameters: notificationParameters, animations: {
self?.constraintsAndValues?.forEach {
$0.key.constant = $0.value
}
})
}
}
func removeKeyboardObservers() {
if let keyboardShowObserverObject = keyboardShowObserverObject {
NotificationCenter.default.removeObserver(keyboardShowObserverObject)
}
if let keyboardHideObserverObject = keyboardHideObserverObject {
NotificationCenter.default.removeObserver(keyboardHideObserverObject)
}
keyboardShowObserverObject = nil
keyboardHideObserverObject = nil
constraintsAndValues = nil
}
// MARK: - Private methods
typealias KeyboardNotificationParameters = (height: CGFloat,
duration: TimeInterval,
animationOptions: UIView.AnimationOptions)
private func getKeyboardShowParameters(fromNotification notification: Notification) -> KeyboardNotificationParameters? {
guard let info = notification.userInfo,
let heightValue = info[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect,
let durationValue = info[UIResponder.keyboardAnimationDurationUserInfoKey] as? TimeInterval,
let animationCurveValue = info[UIResponder.keyboardAnimationCurveUserInfoKey] as? UInt else
{
return nil
}
return (heightValue.size.height, durationValue, UIView.AnimationOptions(rawValue: animationCurveValue << 16))
}
private func animateLayout(parameters: KeyboardNotificationParameters, animations: @escaping () -> Void) {
UIView.animate(withDuration: parameters.duration,
delay: 0,
options: [parameters.animationOptions, .beginFromCurrentState],
animations: {
animations()
self.view.layoutIfNeeded()
}, completion: nil)
}
}
protocol EditingEndable: class {
func endEditing()
}
extension EditingEndable where Self: UIViewController {
func endEditing() {
view.endEditing(true)
}
}
<file_sep>//
// DetailRoomsPopoverView.swift
// Koleda
//
// Created by <NAME> on 11/25/19.
// Copyright © 2019 koleda. All rights reserved.
//
import UIKit
class DetailRoomsPopoverView: UIViewController {
@IBOutlet weak var tableView: UITableView!
var rooms: [Room] = []
var targetTemperature: Double = 0
private let currentTempUnit = UserDataManager.shared.temperatureUnit.rawValue
override func viewDidLoad() {
super.viewDidLoad()
tableView.reloadData()
}
func reloadData(rooms: [Room]) {
self.rooms = rooms
tableView.reloadData()
}
@IBAction func okAction(_ sender: Any) {
self.dismiss(animated: true)
}
}
extension DetailRoomsPopoverView: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return rooms.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: ScheduleTableViewCell.get_identifier, for: indexPath) as? ScheduleTableViewCell else {
log.error("Invalid cell type call")
return UITableViewCell()
}
let room = self.rooms[indexPath.row]
let scheduleRow = ScheduleRow(type: .Detail, title: room.name, icon: nil, temp: room.temperature?.kld_doubleValue, unit: currentTempUnit)
cell.setup(scheduleRow: scheduleRow, targetTemperature: targetTemperature)
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 45
}
}
<file_sep>//
// TemperatureCollectionViewCell.swift
// Koleda
//
// Created by <NAME> on 2/4/20.
// Copyright © 2020 koleda. All rights reserved.
//
import UIKit
class TemperatureCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var temperatureView: UIView!
@IBOutlet weak var selectedTemperatureView: UIView!
@IBOutlet weak var tempLabel: UILabel!
@IBOutlet weak var selectedTempLabel: UILabel!
@IBOutlet weak var tempUnitLabel: UILabel!
func setup(temp: Int, currentTempOfMode: Int) {
let isSelected = (temp == currentTempOfMode)
let currentTempUnit = UserDataManager.shared.temperatureUnit.rawValue
temperatureView.isHidden = isSelected
selectedTemperatureView.isHidden = !isSelected
var tempDisplay = Double(temp)
if TemperatureUnit.F.rawValue == currentTempUnit {
tempDisplay = tempDisplay.fahrenheitTemperature
}
tempUnitLabel.text = "°\(currentTempUnit)"
if isSelected {
selectedTempLabel.text = String(format: "%.f", tempDisplay)
} else {
tempLabel.text = String(format: "%.f", tempDisplay)
}
}
}
<file_sep>//
// InstructionForHeaterRouter.swift
// Koleda
//
// Created by <NAME> on 9/6/19.
// Copyright © 2019 koleda. All rights reserved.
//
import UIKit
class InstructionForHeaterRouter: BaseRouterProtocol {
var baseViewController: UIViewController?
func enqueueRoute(with context: Any?, animated: Bool, completion: ((Bool) -> Void)?) {
}
func present(on baseVC: UIViewController, animated: Bool, context: Any?, completion: ((Bool) -> Void)?) {
}
func dismiss(animated: Bool, context: Any?, completion: ((Bool) -> Void)?) {
}
func backToRoot() {
baseViewController?.backToRoot(animated: true)
}
func nextToAddHeater(roomId: String, roomName: String, isFromRoomConfiguration: Bool) {
baseViewController?.gotoBlock(withStoryboar: "Heater", aClass: AddHeaterViewController.self) { (vc) in
let router = AddHeaterRouter()
let viewModel = AddHeaterViewModel.init(router: router, roomId: roomId, roomName: roomName)
vc?.viewModel = viewModel
vc?.isFromRoomConfiguration = isFromRoomConfiguration
router.baseViewController = vc
}
}
}
<file_sep>//
// SensorManagementViewModel.swift
// Koleda
//
// Created by <NAME> on 7/17/19.
// Copyright © 2019 koleda. All rights reserved.
//
import Foundation
import RxSwift
import SystemConfiguration.CaptiveNetwork
import NetworkExtension
import SwiftRichString
import CopilotAPIAccess
enum AddDeviceStatus {
case search
case noDevice
case oneDevice
case moreThanOneDevice
case addDevice
case addDeviceSuccess
case joinDeviceHotSpot
}
protocol SensorManagementViewModelProtocol: BaseViewModelProtocol {
var addedSuccessfullyViewHidden: PublishSubject<Bool> { get }
var statusViewHidden: PublishSubject<Bool> { get }
var tryAgainButtonHidden: PublishSubject<Bool> { get }
var connectToDeviceHotspotButtonHidden: PublishSubject<Bool> { get }
var cancelButtonHidden: PublishSubject<Bool> { get }
var sensorViewHidden: PublishSubject<Bool> { get }
var changeWifiForShellyDevice: PublishSubject<Void> { get }
var updatedStatus: PublishSubject<AddDeviceStatus> { get }
var detectedSensors: [Sensor] { get }
var statusImage: PublishSubject<UIImage?> { get }
var statusTitle: PublishSubject<String> { get }
var statusSubTitle: PublishSubject<String> { get }
var titleAttributed: NSAttributedString { get }
var sensorModel: Variable<String> { get }
var roomName: String { get }
var sensorName: String { get }
var roomNameWithUserName: String { get }
func updateUI(with status: AddDeviceStatus)
func updateStatusAfterSeaching()
func getCurrentWiFiName() -> String
func fetchInfoOfSensorAPMode(completion: @escaping (Bool) -> Void)
func findSensorsOnLocalNetwork(completion: @escaping () -> Void)
func waitingSensorsJoinNetwork(completion: @escaping () -> Void)
func connectSensorLocalWifi(ssid: String, pass: String, completion: @escaping (Bool) -> Void)
func addASensorToARoom(completion: @escaping (WSError?) -> Void)
func goAddHeaterFlow()
func showWifiDetail()
}
class SensorManagementViewModel: BaseViewModel, SensorManagementViewModelProtocol {
let router: BaseRouterProtocol
var addedSuccessfullyViewHidden = PublishSubject<Bool>()
var statusViewHidden = PublishSubject<Bool>()
var tryAgainButtonHidden = PublishSubject<Bool>()
var connectToDeviceHotspotButtonHidden = PublishSubject<Bool>()
var cancelButtonHidden = PublishSubject<Bool>()
var sensorViewHidden = PublishSubject<Bool>()
var changeWifiForShellyDevice = PublishSubject<Void>()
let updatedStatus = PublishSubject<AddDeviceStatus>()
var detectedSensors: [Sensor] = []
let statusImage = PublishSubject<UIImage?>()
let statusTitle = PublishSubject<String>()
let statusSubTitle = PublishSubject<String>()
var titleAttributed: NSAttributedString
let sensorModel = Variable<String>("")
var roomName: String
var roomNameWithUserName: String
private let shellyDeviceManager: ShellyDeviceManager
private let roomId: String
var sensorName: String = ""
private let netServiceClient = NetServiceClient()
private var timer:Timer?
private var timeLeft = 3
private var waiting = true
init(router: BaseRouterProtocol, managerProvider: ManagerProvider = .sharedInstance, roomId: String, roomName: String) {
self.router = router
self.shellyDeviceManager = managerProvider.shellyDeviceManager
self.roomId = roomId
self.roomName = roomName
let normal = SwiftRichString.Style{
$0.font = UIFont.app_FuturaPTLight(ofSize: 30)
$0.color = UIColor.hex1F1B15
}
let bold = SwiftRichString.Style {
$0.font = UIFont.app_FuturaPTDemi(ofSize: 30)
$0.color = UIColor.hex1F1B15
}
if let userName = UserDataManager.shared.currentUser?.name {
roomNameWithUserName = "\(userName)’s \(roomName)"
} else {
roomNameWithUserName = "\(roomName)"
}
let group = StyleGroup(base: normal, ["h1": bold])
let string = String(format: "ADD_A_SENSOR_TO_ROOM_TEXT".app_localized, roomNameWithUserName)
self.titleAttributed = string.set(style: group)
super.init(managerProvider: managerProvider)
}
func updateUI(with status: AddDeviceStatus) {
switch status {
case .search:
statusImage.onNext(nil)
statusTitle.onNext("")
statusSubTitle.onNext("SEARCHING_FOR_SENSOR_TEXT".app_localized)
cancelButtonHidden.onNext(false)
case .noDevice:
statusImage.onNext(nil)
statusTitle.onNext("NO_SENSOR_IN_THIS_ROOM".app_localized)
statusSubTitle.onNext("INSTRUCTION_FOR_SET_UP_SENSOR_MESS".app_localized)
cancelButtonHidden.onNext(true)
case .oneDevice:
statusImage.onNext(nil)
statusTitle.onNext("DETECT_ONE_SENSOR_MESS".app_localized)
statusSubTitle.onNext("TAP_TO_CONNECT".app_localized)
sensorModel.value = self.detectedSensors[0].deviceModel
cancelButtonHidden.onNext(true)
case .moreThanOneDevice:
statusImage.onNext(nil)
statusTitle.onNext("THERE_IS_MORE_THAN_ONE_SENSOR_MESS".app_localized)
statusSubTitle.onNext("FOLLOW_THE_INSTRUCTION_TO_CONNECT".app_localized)
cancelButtonHidden.onNext(true)
case .addDevice:
statusImage.onNext(UIImage(named: "ic-adding-sensor"))
statusTitle.onNext("ADDING_SENSOR_TEXT".app_localized)
statusSubTitle.onNext("PLEASE_WAIT_TEXT".app_localized)
cancelButtonHidden.onNext(false)
case .addDeviceSuccess:
statusImage.onNext(UIImage(named: "ic-addedSuccessfully"))
statusTitle.onNext("SENSOR_ADDED_SUCCES_MESS".app_localized)
statusSubTitle.onNext("")
cancelButtonHidden.onNext(true)
case .joinDeviceHotSpot:
statusImage.onNext(nil)
statusTitle.onNext("NO_SENSOR_IN_THIS_ROOM".app_localized)
statusSubTitle.onNext("INSTRUCTION_FOR_SET_UP_SENSOR_MESS".app_localized)
cancelButtonHidden.onNext(true)
changeWifiForShellyDevice.onNext(())
}
statusViewHidden.onNext(status == .joinDeviceHotSpot)
tryAgainButtonHidden.onNext(![.noDevice, .moreThanOneDevice].contains(status))
connectToDeviceHotspotButtonHidden.onNext(![.noDevice].contains(status))
sensorViewHidden.onNext(![.oneDevice, .addDevice].contains(status))
addedSuccessfullyViewHidden.onNext(status != .addDeviceSuccess)
}
func waitingSensorsJoinNetwork(completion: @escaping () -> Void) {
waiting = true
timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(onTimerFires), userInfo: nil, repeats: waiting)
completion()
}
@objc private func onTimerFires()
{
timeLeft -= 1
if timeLeft <= 0 {
timer?.invalidate()
timer = nil
waiting = ((FGRoute.getSSID()?.contains("shelly") ?? false) && FGRoute.getGatewayIP() == nil)
}
}
func addASensorToARoom(completion: @escaping (WSError?) -> Void) {
guard detectedSensors.count > 0 else {
completion(WSError.general)
return
}
let sensor = detectedSensors[0]
shellyDeviceManager.addDevice(roomId: roomId, sensor: sensor, heater: nil) { [weak self] error in
guard let `self` = self else {
return
}
self.sensorName = self.detectedSensors[0].deviceModel
Copilot.instance.report.log(event: AddSensorAnalyticsEvent(sensorModel: sensor.deviceModel, roomId: self.roomId, homeId: UserDataManager.shared.currentUser?.homes[0].id ?? "", screenName: self.screenName))
completion(error)
}
}
func goAddHeaterFlow() {
router.enqueueRoute(with: SensorManagementRouter.RouteType.addHeaterFlow(self.roomId, self.roomName))
}
private func setMQTTServerForSensor(sensor: Sensor, completion: @escaping (Bool) -> Void) {
shellyDeviceManager.setMQTTForDevice(isSensor: true, deviceModel: sensor.deviceModel, ipAddress: sensor.ipAddress) { isSuccess in
completion(isSuccess)
}
}
private func changeWifiForDevice(ssid: String, pass: String){
if TARGET_IPHONE_SIMULATOR == 0 {
if #available(iOS 11.0, *) {
let configuration = NEHotspotConfiguration(ssid: ssid, passphrase: <PASSWORD>, isWEP: false)
configuration.joinOnce = false
NEHotspotConfigurationManager.shared.apply(configuration, completionHandler: { (err: Error?) in
print(err)
})
} else {
// Fallback on earlier versions
}
}// if TARGET_IPHONE_SIMULATOR == 0
}
}
extension SensorManagementViewModel {
func updateStatusAfterSeaching() {
let detectedSensorsNumber = detectedSensors.count
let status: AddDeviceStatus = detectedSensorsNumber == 0 ? .noDevice : (detectedSensorsNumber == 1 ? .oneDevice : .moreThanOneDevice)
updateUI(with: status)
}
func getCurrentWiFiName() -> String {
var ssid: String = ""
if let interfaces = CNCopySupportedInterfaces() as NSArray? {
for interface in interfaces {
if let interfaceInfo = CNCopyCurrentNetworkInfo(interface as! CFString) as NSDictionary? {
ssid = interfaceInfo[kCNNetworkInfoKeySSID as String] as? String ?? ""
break
}
}
}
return ssid
}
func fetchInfoOfSensorAPMode(completion: @escaping (Bool) -> Void) {
shellyDeviceManager.getDeviceInfoOnAPMode(success: { deviceModel in
completion(true)
},
failure: { error in
completion(false)
})
}
func findSensorsOnLocalNetwork(completion: @escaping () -> Void) {
do {
netServiceClient.log = { print("NetService:", $0) }
var services = Set<Service>()
let end = Date() + 7.0
try netServiceClient.discoverServices(of: .http,
in: .local,
shouldContinue: { Date() < end },
foundService: { services.insert($0) })
var sensors: [Sensor] = []
guard services.count > 0 else {
completion()
return
}
for service in services {
let hostName = service.name
log.info(hostName)
if DataValidator.isShellyDevice(hostName: hostName) && !UserDataManager.shared.deviceModelList.contains(hostName) {
// let addresses = try netServiceClient.resolve(service, timeout: 1.0)
// let ipAddress = addresses.description
let ipAddress = String(format: "%@.local",hostName)
log.info(ipAddress)
let sensor: Sensor = Sensor(deviceModel: hostName, name: hostName, ipAddress: ipAddress)
sensors.append(sensor)
}
}
if sensors.count == 1 {
setMQTTServerForSensor(sensor: sensors[0]) { isSuccess in
self.detectedSensors = isSuccess ? sensors : []
completion()
}
} else {
detectedSensors = sensors
completion()
}
}
catch {
log.error("\(error)")
detectedSensors = []
// let sensor: Sensor = Sensor(deviceModel: "Shellyht-DEEDD3", name: "Shellyht-DEEDD3", ipAddress: "Shellyht-DEEDD3")
// let sensor1: Sensor = Sensor(deviceModel: "Shellyht-DEE3FG", name: "Shellyht-DEE3FG", ipAddress: "Shellyht-DEE3FG")
// detectedSensors = [sensor]
completion()
}
}
func connectSensorLocalWifi(ssid: String, pass: String, completion: @escaping (Bool) -> Void) {
self.shellyDeviceManager.turnOnSTAOfDeviceInfo(ssid: ssid, pass: pass, success: { [weak self] in
self?.changeWifiForDevice(ssid: ssid, pass: pass)
completion(true)
}, failure: { error in
completion(false)
})
}
func showWifiDetail() {
router.enqueueRoute(with: SensorManagementRouter.RouteType.wifiDetail)
}
}
<file_sep>//
// PassthroughViewController.swift
//
// Created by <NAME> on 4/6/18.
//
//
import UIKit
class PassthroughViewController: UIViewController {
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
override open func loadView() {
super.loadView()
view = PassthroughView()
view.backgroundColor = .clear
}
}
<file_sep>//
// LocationSetupViewModel.swift
// Koleda
//
// Created by <NAME> on 7/4/19.
// Copyright © 2019 koleda. All rights reserved.
//
import Foundation
import RxSwift
protocol LocationSetupViewModelProtocol: BaseViewModelProtocol {
func declineLocationService()
func requestAccessLocationService(completion: @escaping () -> Void)
var showLocationDisabledPopUp: Variable<Bool> { get }
}
class LocationSetupViewModel: BaseViewModel, LocationSetupViewModelProtocol {
let router: BaseRouterProtocol
private let geoLocationManager: GeoLocationManager
let showLocationDisabledPopUp = Variable<Bool>(false)
init(router: BaseRouterProtocol, managerProvider: ManagerProvider = .sharedInstance ) {
self.router = router
self.geoLocationManager = managerProvider.geoLocationManager
super.init(managerProvider: managerProvider)
}
private func showNextScreen() {
let userType = UserType.init(fromString: UserDataManager.shared.currentUser?.userType ?? "")
if userType == .Master {
router.enqueueRoute(with: LocationSetupRouter.RouteType.wifiSetup)
} else {
router.enqueueRoute(with: LocationSetupRouter.RouteType.welcomeJoinHome)
}
}
func declineLocationService() {
router.enqueueRoute(with: LocationSetupRouter.RouteType.decline)
}
func requestAccessLocationService(completion: @escaping () -> Void) {
requestlocationService(completion: {
completion()
})
}
private func requestlocationService(completion: @escaping () -> Void) {
geoLocationManager.requestAlwaysAuthorization { [weak self] autorizationStatus in
guard let `self` = self else {
return
}
switch autorizationStatus {
case .authorizedAlways:
log.info("authorizedAlways")
self.showNextScreen()
completion()
case .authorizedWhenInUse:
log.info("authorizedWhenInUse")
self.showNextScreen()
completion()
case .notDetermined:
log.info("notDetermined")
self.showLocationDisabledPopUp.value = true
completion()
case .restricted:
log.info("restricted")
self.showLocationDisabledPopUp.value = true
completion()
case .denied:
self.showLocationDisabledPopUp.value = true
log.info("denied")
completion()
}
}
}
// private func getCurrentLocation(completion: @escaping () -> Void) {
// geoLocationManager.currentGeoLocation { [weak self] currentGeoLocation in
// let currentLocation = currentGeoLocation.dictionary
// log.info(currentLocation.description)
// DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
// completion()
// self?.showWifiScreen()
// }
// }
// }
}
<file_sep>//
// ListRoomViewController.swift
// Koleda
//
// Created by <NAME> on 9/10/19.
// Copyright © 2019 koleda. All rights reserved.
//
import UIKit
import RxSwift
import SwiftRichString
class ListRoomViewController: BaseViewController, BaseControllerProtocol {
var viewModel: HomeViewModel!
@IBOutlet weak var settingButton: UIButton!
private let disposeBag = DisposeBag()
private var refreshControl: UIRefreshControl?
@IBOutlet weak var homeInitialView: UIView!
@IBOutlet weak var roomsTableView: UITableView!
@IBOutlet var roomsTableViewDataSource: RoomsTableViewDataSource!
override func viewDidLoad() {
super.viewDidLoad()
configurationUI()
addRefreshControl()
}
private func addRefreshControl() {
refreshControl = UIRefreshControl()
refreshControl?.tintColor = UIColor.gray
refreshControl?.addTarget(self, action: #selector(refreshList), for: .valueChanged)
roomsTableView.addSubview(refreshControl!)
}
@objc private func refreshList() {
viewModel.refreshListRooms()
refreshControl?.endRefreshing()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(true, animated: animated)
refreshList()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
}
extension ListRoomViewController {
@objc private func refreshListRooms(_ notification: NSNotification) {
viewModel.refreshListRooms()
}
@objc private func didChangeWifi() {
viewModel.refreshListRooms()
guard let userName = UserDataManager.shared.currentUser?.name else {
viewModel.getCurrentUser()
return
}
}
private func configurationUI() {
NotificationCenter.default.addObserver(self, selector: #selector(refreshListRooms),
name: .KLDDidChangeRooms, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(didChangeWifi),
name: .KLDDidChangeWifi, object: nil)
settingButton.rx.tap.bind { [weak self] _ in
self?.back()
}.disposed(by: disposeBag)
viewModel.rooms.asObservable().subscribe(onNext: { [weak self] rooms in
if rooms.count > 0 {
self?.roomsTableView.isHidden = false
self?.homeInitialView.isHidden = true
self?.roomsTableViewDataSource.rooms = rooms
self?.roomsTableViewDataSource.viewModel = self?.viewModel
self?.roomsTableView.dataSource = self?.roomsTableViewDataSource
self?.roomsTableView.delegate = self
self?.roomsTableView.reloadData()
} else {
self?.roomsTableView.isHidden = true
self?.homeInitialView.isHidden = false
}
}).disposed(by: disposeBag)
}
}
extension ListRoomViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 205
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
viewModel.selectedRoomConfiguration(at: indexPath)
}
}
<file_sep>//
// RoomAnalyticsEvent.swift
// Koleda
//
// Created by <NAME> on 9/4/20.
// Copyright © 2020 koleda. All rights reserved.
//
import Foundation
import CopilotAPIAccess
struct AddRoomAnalyticsEvent: AnalyticsEvent {
private let roomName: String
private let homeId: String
private let screenName: String
init(roomName:String,homeId: String, screenName: String) {
self.roomName = roomName
self.homeId = homeId
self.screenName = screenName
}
var customParams: Dictionary<String, String> {
return ["roomName" : roomName,
"homeId" : homeId,
"screenName": screenName]
}
var eventName: String {
return "add_room"
}
var eventOrigin: AnalyticsEventOrigin {
return .App
}
var eventGroups: [AnalyticsEventGroup] {
return [.All]
}
}
struct editRoomAnalyticsEvent: AnalyticsEvent {
private let roomId: String
private let roomName: String
private let homeId: String
private let screenName: String
init(roomId: String, roomName: String, homeId: String, screenName: String) {
self.roomId = roomId
self.roomName = roomName
self.homeId = homeId
self.screenName = screenName
}
var customParams: Dictionary<String, String> {
return ["roomId" : roomId,
"roomName" : roomName,
"homeId" : homeId,
"screenName": screenName]
}
var eventName: String {
return "edit_room"
}
var eventOrigin: AnalyticsEventOrigin {
return .App
}
var eventGroups: [AnalyticsEventGroup] {
return [.All]
}
}
struct removeRoomAnalyticsEvent: AnalyticsEvent {
private let roomId: String
private let roomName: String
private let homeId: String
private let screenName: String
init(roomId: String, roomName: String, homeId: String, screenName: String) {
self.roomId = roomId
self.roomName = roomName
self.homeId = homeId
self.screenName = screenName
}
var customParams: Dictionary<String, String> {
return ["roomId" : roomId,
"roomName" : roomName,
"homeId" : homeId,
"screenName": screenName]
}
var eventName: String {
return "remove_room"
}
var eventOrigin: AnalyticsEventOrigin {
return .App
}
var eventGroups: [AnalyticsEventGroup] {
return [.All]
}
}
struct UpdateRoomStatusAnalyticsEvent: AnalyticsEvent {
private let homeId: String
private let roomId: String
private let isEnable: Bool
private let screenName: String
init(homeId: String, roomId: String, isEnable: Bool, screenName: String) {
self.roomId = roomId
self.homeId = homeId
self.isEnable = isEnable
self.screenName = screenName
}
var customParams: Dictionary<String, String> {
return ["roomId" : roomId,
"homeId" : homeId,
"isEnable" : String(isEnable),
"screenName": screenName]
}
var eventName: String {
if isEnable {
return "turn_on_room"
} else {
return "turn_off_room"
}
}
var eventOrigin: AnalyticsEventOrigin {
return .App
}
var eventGroups: [AnalyticsEventGroup] {
return [.All]
}
}
<file_sep>platform :ios, '10.0'
source 'https://github.com/CocoaPods/Specs.git'
source 'https://bitbucket.org/teamcopilot/copilot-sdk-ios-specs.git'
def common_pods
pod 'Alamofire', '~> 5.1'
pod 'RxSwift', '~> 5'
pod 'RxCocoa', '~> 5'
pod 'Sync', '~> 5'
pod 'SVProgressHUD'
pod 'CocoaLumberjack'
pod 'CocoaLumberjack/Swift'
pod 'SwiftyJSON', '~> 4.0'
pod 'PromiseKit'
pod 'Locksmith'
pod 'ReachabilitySwift'
pod 'FBSDKCoreKit'
pod 'FBSDKLoginKit'
pod 'FBSDKShareKit'
pod 'FBSDKCoreKit/Swift'
pod 'FBSDKLoginKit/Swift'
pod 'FBSDKShareKit/Swift'
pod 'GoogleSignIn'
pod "StompClientLib"
pod 'SwiftRichString'
pod 'SpreadsheetView'
pod 'Swift_PageMenu', '~> 1.4'
pod 'Segmentio'
pod 'Copilot', '4.7.1'
pod 'Firebase/Analytics'
pod 'Firebase/Auth'
pod 'Firebase/Firestore'
end
target 'Koleda' do
use_frameworks!
common_pods
end<file_sep>//
// KeyboardHepler.swift
// Koleda
//
// Created by <NAME> on 9/4/19.
// Copyright © 2019 koleda. All rights reserved.
//
import Foundation
import UIKit
class KeyboardHepler {
fileprivate var view: UIView?
fileprivate var scrollView: UIScrollView?
fileprivate var tabDismissKeyboard: UITapGestureRecognizer?
init(_ scrollView: UIScrollView) {
tabDismissKeyboard = UITapGestureRecognizer(target: self, action: #selector(KeyboardHepler.dismissKeyboard))
view = scrollView.superview
self.scrollView = scrollView
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)
}
init(vc: UIViewController, scrollView: UIScrollView) {
tabDismissKeyboard = UITapGestureRecognizer(target: self, action: #selector(KeyboardHepler.dismissKeyboard))
self.view = vc.view
self.scrollView = scrollView
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)
}
init(_ viewController: UIViewController) {
tabDismissKeyboard = UITapGestureRecognizer(target: self, action: #selector(KeyboardHepler.dismissKeyboard))
self.view = viewController.view
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil)
}
@objc func keyboardWillShow(_ notification: Notification) {
self.view?.addGestureRecognizer(tabDismissKeyboard!)
if self.scrollView == nil {
return
}
let userInfo = (notification as NSNotification).userInfo as! Dictionary<String, AnyObject>
let animationDuration = userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as! TimeInterval
let keyboardFrame = userInfo[UIResponder.keyboardFrameEndUserInfoKey]?.cgRectValue
let keyboardFrameConvertedToViewFrame = self.scrollView?.superview?.convert(keyboardFrame!, from: nil)
let options = UIView.AnimationOptions.beginFromCurrentState
UIView.animate(withDuration: animationDuration, delay: 0, options:options, animations: { () -> Void in
let insetHeight = ((self.scrollView?.frame.height)! + (self.scrollView?.frame.origin.y)!) - (keyboardFrameConvertedToViewFrame?.origin.y)!
self.scrollView?.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: insetHeight, right: 0)
self.scrollView?.scrollIndicatorInsets = UIEdgeInsets(top: 0, left: 0, bottom: insetHeight, right: 0)
}) { (complete) -> Void in
}
}
@objc func keyboardWillHide(_ notification: Notification) {
self.view?.removeGestureRecognizer(tabDismissKeyboard!)
if self.scrollView == nil {
return
}
let userInfo = (notification as NSNotification).userInfo as! Dictionary<String, AnyObject>
let animationDuration = userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as! TimeInterval
let options = UIView.AnimationOptions.beginFromCurrentState
UIView.animate(withDuration: animationDuration, delay: 0, options:options, animations: { () -> Void in
self.scrollView?.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
self.scrollView?.scrollIndicatorInsets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
}) { (complete) -> Void in
}
}
@objc func dismissKeyboard() {
self.view?.endEditing(true)
}
}
<file_sep>//
// Extentions.swift
// Koleda
//
// Created by <NAME> on 11/20/19.
// Copyright © 2019 koleda. All rights reserved.
//
// MARK: -
// MARK: - Gradient layer extensions
extension CAGradientLayer {
func removeIfAdded() {
if self.superlayer != nil {
self.removeFromSuperlayer()
}
}
}
// MARK: - Shapelayer extenxions
extension CAShapeLayer {
func setBorder(color: UIColor, borderWidth: CGFloat) {
self.borderColor = color.cgColor
self.borderWidth = borderWidth
}
func setShadow(color: UIColor, opacity: Float, offset: CGFloat, radius: CGFloat) {
shadowColor = color.cgColor
shadowOpacity = opacity
shadowOffset = CGSize(width: offset, height: offset)
shadowRadius = radius
}
func removeIfAdded() {
if self.superlayer != nil {
self.removeFromSuperlayer()
}
}
}
// MARK: - View extension
extension UIView {
func setShadow(color: UIColor, opacity: Float, offset: CGFloat, radius: CGFloat) {
layer.shadowColor = color.cgColor
layer.shadowOpacity = opacity
layer.shadowOffset = CGSize(width: offset, height: offset)
layer.shadowRadius = radius
}
func getGradientLayerOf(frame: CGRect, colors: [CGColor]) -> CAGradientLayer {
let gradientLayer = CAGradientLayer()
gradientLayer.type = CAGradientLayerType.axial
gradientLayer.frame = frame
gradientLayer.colors = colors
return gradientLayer
}
func removeIfAdded() {
if self.superview != nil {
self.removeFromSuperview()
}
}
}
// MARK: - Integer extension
extension Int {
public func toCGFloat() -> CGFloat {
return CGFloat(self)
}
}
// MARK: - binary integer extension
extension BinaryInteger {
public var toRadians: CGFloat { return CGFloat(Int(self)) * .pi / 180 }
}
// MARK: - Floating point extension
extension FloatingPoint {
public var toRadians: Self { return self * .pi / 180 }
public var toDegree: Self { return self * 180 / .pi }
}
<file_sep>//
// Cells.swift
// Koleda
//
// Created by <NAME> on 10/22/19.
// Copyright © 2019 koleda. All rights reserved.
//
import UIKit
import SpreadsheetView
class DateCell: Cell {
let label = UILabel()
override init(frame: CGRect) {
super.init(frame: frame)
label.frame = bounds
label.autoresizingMask = [.flexibleWidth, .flexibleHeight]
label.font = UIFont.boldSystemFont(ofSize: 10)
label.textAlignment = .center
contentView.addSubview(label)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
class TimeCell: Cell {
let label = VerticalTopAlignLabel()
override init(frame: CGRect) {
super.init(frame: frame)
label.frame = bounds
label.autoresizingMask = [.flexibleWidth, .flexibleHeight]
label.font = UIFont.app_SFProDisplayMedium(ofSize: 15)
label.textAlignment = .center
label.textColor = .gray
contentView.addSubview(label)
}
override var frame: CGRect {
didSet {
label.frame = bounds.insetBy(dx: 6, dy: 0)
}
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
class ScheduleCell: Cell {
let scheduleViewController = StoryboardScene.SmartSchedule.instantiateScheduleViewController() as? ScheduleViewController
var scheduleContent: ScheduleBlock? {
didSet {
scheduleViewController?.reloadData(content: scheduleContent)
}
}
override init(frame: CGRect) {
super.init(frame: frame)
scheduleViewController?.view.frame = bounds
scheduleViewController?.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
guard let view = scheduleViewController?.view else {
return
}
contentView.addSubview(view)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
class VerticalTopAlignLabel: UILabel {
override func drawText(in rect:CGRect) {
guard let labelText = text else { return super.drawText(in: rect) }
let attributedText = NSAttributedString(string: labelText, attributes: [NSAttributedString.Key.font: font])
var newRect = rect
newRect.size.height = attributedText.boundingRect(with: rect.size, options: .usesLineFragmentOrigin, context: nil).size.height
if numberOfLines != 0 {
newRect.size.height = min(newRect.size.height, CGFloat(numberOfLines) * font.lineHeight)
}
super.drawText(in: newRect)
}
}
<file_sep>//
// TimePickerViewController.swift
// Koleda
//
// Created by <NAME> on 8/1/19.
// Copyright © 2019 koleda. All rights reserved.
//
import UIKit
import Foundation
import RxSwift
struct Time {
let hour: Int
let minute: Int
init(hour: Int, minute: Int) {
self.hour = hour
self.minute = minute
}
func timeString() -> String {
var hourString = "\(hour)"
var minuteString = "\(minute)"
if hour < 10 {
hourString = "0\(hour)"
}
if minute < 10 {
minuteString = "0\(minute)"
}
return "\(hourString):\(minuteString)"
}
func timeIntValue() -> Int {
return hour*60 + minute
}
func correctLocalTimeFormat() -> Time {
if self.hour == 23 && self.minute == 59 {
return Time(hour: 24, minute: 0)
} else {
return self
}
}
func add(minutes: Int) -> Time {
let totalMinutes = self.minute + minutes
if totalMinutes >= 60 {
return Time(hour: self.hour + 1, minute: totalMinutes - 60)
} else {
return Time(hour: self.hour, minute: totalMinutes)
}
}
}
enum TimePoint {
case startOfDay
case endOfDay
case startOfNight
case endOfNight
}
protocol TimePickerViewControllerDelegate: class {
func selectedTime(time: Time)
}
class TimePickerViewController: UIViewController {
weak var delegate: TimePickerViewControllerDelegate?
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var dateTimePicker: UIDatePicker!
@IBOutlet weak var setButton: UIButton!
@IBOutlet weak var contentView: UIView!
private let disposeBag = DisposeBag()
private var timePoint: TimePoint = .startOfDay
private var time: Time? = nil
override func viewDidLoad() {
super.viewDidLoad()
Style.Button.primary.apply(to: setButton)
Style.View.cornerRadius.apply(to: contentView)
dateTimePicker.datePickerMode = .time
setup()
}
func initTimePicker(timePoint: TimePoint, time: String) {
self.timePoint = timePoint
self.time = time.timeValue()
}
@IBAction func setTime(_ sender: Any) {
let date = dateTimePicker.date
let components = Calendar.current.dateComponents([.hour, .minute], from: date)
guard let hour = components.hour, let minute = components.minute else {
return
}
delegate?.selectedTime(time: Time(hour: hour, minute: minute))
}
private func setup() {
switch timePoint {
case .startOfDay:
titleLabel.text = "Set start daytime tariff"
case .endOfDay:
titleLabel.text = "Set end daytime tariff"
case .startOfNight:
titleLabel.text = "Set start nighttime tariff"
case .endOfNight:
titleLabel.text = "Set end nighttime tariff"
}
guard let time = self.time else {
return
}
let calendar = Calendar.current
var components = DateComponents()
components.hour = time.hour
components.minute = time.minute
dateTimePicker.setDate(calendar.date(from: components)!, animated: false)
}
}
<file_sep>//
// GuideCollectionViewDataSource.swift
// Koleda
//
// Created by <NAME> on 6/25/19.
// Copyright © 2019 koleda. All rights reserved.
//
import Foundation
import UIKit
class GuideCollectionViewDataSource: NSObject, UICollectionViewDataSource {
var guideItems: [GuideItem]?
func numberOfSections(in collectionView: UICollectionView) -> Int {
return guideItems?.count ?? 0
}
func collectionView(_ collectionView: UICollectionView,
numberOfItemsInSection section: Int) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView
.dequeueReusableCell(withReuseIdentifier: "GuideCollectionViewCell",
for: indexPath) as? GuideCollectionViewCell,
let guidePages = guideItems else {
fatalError()
}
let guidePage = guidePages[indexPath.section]
cell.reloadPage(with: guidePage)
return cell
}
}
<file_sep>//
// UserDefaultsManager.swift
// Koleda
//
// Created by <NAME> on 7/2/19.
// Copyright © 2019 koleda. All rights reserved.
//
import Foundation
import Foundation
import RxSwift
private enum ValueKeys: String {
case biometricID = "touchID"
case loggedIn = "login.loggedIn"
case termAndConditionAcceptedUser = "termAndCondition.accepted.user"
case lastKnownDeviceLocationCountryCode = "app.lastKnownDeviceLocationCountryCode"
case wifiSsid = "app.wifiSsid"
case wifiPass = "<PASSWORD>Pass"
}
class SettingsItem {
fileprivate let key: String
var exist: Bool {
return UserDefaultsManager.restoreValue(key: key) != nil
}
fileprivate init(_ key: ValueKeys) {
self.key = key.rawValue
}
}
final class BoolSettingsItem: SettingsItem {
static let defaultValue = false
var enabled: Bool {
get {
guard let value = UserDefaultsManager.restoreValue(key: key) as? Bool else {
return BoolSettingsItem.defaultValue
}
return value
}
set {
UserDefaultsManager.storeValue(value: newValue, key: key)
}
}
var asObservable: Observable<Bool> {
return UserDefaultsManager.userDefaults
.observeValue(forKey: key)
.map { return ($0 as? Bool) ?? BoolSettingsItem.defaultValue }
}
}
final class StringSettingsItem: SettingsItem {
var value: String? {
get {
return UserDefaultsManager.restoreValue(key: key) as? String
}
set {
UserDefaultsManager.storeValue(value: newValue, key: key)
}
}
}
final class UserDefaultsManager {
// Store value to user defaults
class func storeValue(value: Any?, key: String) {
userDefaults.set(value, forKey: key)
userDefaults.synchronize()
}
// Return stored value from user defaults
class func restoreValue(key: String) -> Any? {
return userDefaults.value(forKey: key)
}
static var userDefaultsOverride: UserDefaultsProtocol? = nil
class var userDefaults: UserDefaultsProtocol {
return userDefaultsOverride ?? UserDefaults.standard
}
private static func removeValue(key: String) {
userDefaults.removeObject(forKey: key)
userDefaults.synchronize()
}
private static func removeValue(key: ValueKeys) {
userDefaults.removeObject(forKey: key.rawValue)
userDefaults.synchronize()
}
private static func removeValues(_ keys: ValueKeys...) {
keys.forEach(removeValue)
}
static func removeUserValues() {
removeValues(
.biometricID,
.loggedIn,
.lastKnownDeviceLocationCountryCode
)
}
static func synchronize() {
self.userDefaults.synchronize()
}
static let biometricID = BoolSettingsItem(.biometricID)
static let loggedIn = BoolSettingsItem(.loggedIn)
static let termAndConditionAcceptedUser = StringSettingsItem(.termAndConditionAcceptedUser)
static let lastKnownDeviceLocationCountryCode = StringSettingsItem(.lastKnownDeviceLocationCountryCode)
static let wifiSsid = StringSettingsItem(.wifiSsid)
static let wifiPass = StringSettingsItem(.wifiPass)
}
/*
* Captures subset of UserDefaults interface that we use for mocking.
*/
protocol UserDefaultsProtocol : AnyObject {
func removeObject(forKey defaultName: String)
func value(forKey key: String) -> Any?
func string(forKey defaultName: String) -> String?
func set(_ value: Any?, forKey defaultName: String)
/** Provides initial value for the underlying variable. */
func observeValue(forKey key: String) -> Observable<Any?>
@discardableResult
func synchronize() -> Bool
}
extension UserDefaultsProtocol {
func codable<T: Codable>(forKey key: String, type: T.Type) -> T? {
guard let data = value(forKey: key) as? Data else {
return nil
}
return try? JSONDecoder().decode(T.self, from: data)
}
func setCodable<T: Codable>(_ value: T?, forKey key: String) {
if let value = value {
guard let data = try? JSONEncoder().encode(value) else {
assertionFailure()
return
}
set(data, forKey: key)
} else {
removeObject(forKey: key)
}
synchronize()
}
func codableObservable<T: Codable>(for key: String, type: T.Type) -> Observable<T?> {
return observeValue(forKey: key).map { value in
guard let data = value as? Data else { return nil }
let result = try? JSONDecoder().decode(T.self, from: data)
return result
}
}
}
extension UserDefaults : UserDefaultsProtocol {
func observeValue(forKey key: String) -> Observable<Any?> {
return rx.observe(Any.self, key, options: [.new, .initial])
}
}
<file_sep>//
// SmartScheduleDetailViewController.swift
// Koleda
//
// Created by <NAME> on 10/31/19.
// Copyright © 2019 koleda. All rights reserved.
//
import UIKit
import RxSwift
class SmartScheduleDetailViewController: BaseViewController, BaseControllerProtocol {
var viewModel: SmartScheduleDetailViewModelProtocol!
@IBOutlet weak var modifyTimeslotLabel: UILabel!
@IBOutlet weak var timeslotTitleLabel: UILabel!
@IBOutlet weak var leftLineImageView: UIImageView!
@IBOutlet weak var startTimeTitleLabel: UILabel!
@IBOutlet weak var startTimeLabel: UILabel!
@IBOutlet weak var endTimeTitleLabel: UILabel!
@IBOutlet weak var endTimeLabel: UILabel!
@IBOutlet weak var modeIconImageView: UIImageView!
@IBOutlet weak var modeTitleLabel: UILabel!
@IBOutlet weak var modeTemperatureLabel: UILabel!
@IBOutlet weak var modeUnitOfTempLabel: UILabel!
@IBOutlet weak var roomsLabel: UILabel!
@IBOutlet weak var selectModeLabel: UILabel!
@IBOutlet weak var roomsTableView: UITableView!
@IBOutlet weak var addRoomButton: UIButton!
@IBOutlet weak var modesCollectionView: UICollectionView!
@IBOutlet weak var applyToAllRoomsButton: UIButton!
@IBOutlet weak var deleteButton: UIButton!
@IBOutlet weak var okayButton: UIButton!
private let disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
initView()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(true, animated: animated)
navigationBarTransparency()
statusBarStyle(with: .lightContent)
setTitleScreen(with: "")
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let viewController = segue.destination as? RoomsPopOverViewController {
viewController.delegate = self
viewController.selectedRooms = viewModel.selectedRooms.value
}
}
@IBAction func backAction(_ sender: Any) {
back()
}
@IBAction func startTimeAction(_ sender: Any) {
gotoBlock(withStoryboar: "Setup", aClass: EnergyTariffInputViewController.self) { (vc) in
vc?.typeInput = .scheduleStartTime
guard let startTime = startTimeLabel.text, let endTime = endTimeLabel.text else {
return
}
vc?.startTime = Date(str: startTime, format: Date.fm_HHmm)
vc?.endTime = Date(str: endTime, format: Date.fm_HHmm)
vc?.scheduleTimeInputDelegate = self
}
}
@IBAction func endTimeAction(_ sender: Any) {
gotoBlock(withStoryboar: "Setup", aClass: EnergyTariffInputViewController.self) { (vc) in
vc?.typeInput = .scheduleEndTime
guard let startTime = startTimeLabel.text, var endTime = endTimeLabel.text else {
return
}
vc?.startTime = Date(str: startTime, format: Date.fm_HHmm)
if endTime.timeValue()?.timeIntValue() == Constants.MAX_TIME_DAY {
endTime = "00:00"
}
vc?.endTime = Date(str: endTime, format: Date.fm_HHmm)
vc?.scheduleTimeInputDelegate = self
}
}
private func initView() {
viewModel.timeslotTitle.asObservable().bind(to: timeslotTitleLabel.rx.text).disposed(by: disposeBag)
viewModel.hiddenDeleteButton.asObservable().bind(to: deleteButton.rx.isHidden).disposed(by: disposeBag)
applyToAllRoomsButton.rx.tap.bind { [weak self] in
self?.viewModel.selectedRooms.value = UserDataManager.shared.rooms
}.disposed(by: disposeBag)
addRoomButton.rx.tap.bind { [weak self] in
self?.performSegue(withIdentifier: RoomsPopOverViewController.get_identifier, sender: self)
}.disposed(by: disposeBag)
okayButton.rx.tap.bind { [weak self] in
self?.okayButton.isEnabled = false
self?.viewModel.updateSchedules { [weak self] isSuccess in
self?.okayButton.isEnabled = true
if isSuccess {
self?.back()
} else {
self?.app_showAlertMessage(title: "ERROR_TITLE".app_localized, message: "CAN_NOT_UPDATE_SMART_SCHEDULE_MESS".app_localized)
}
}
}.disposed(by: disposeBag)
deleteButton.rx.tap.bind { [weak self] in
self?.okayButton.isEnabled = false
self?.viewModel.deleteSchedules { [weak self] isSuccess in
self?.okayButton.isEnabled = true
if isSuccess {
self?.back()
}
}
}.disposed(by: disposeBag)
viewModel.selectedRooms.asObservable().subscribe(onNext: { [weak self] _ in
self?.roomsTableView.reloadData()
}).disposed(by: disposeBag)
viewModel.smartModes.asObservable().subscribe(onNext: { [weak self] smartModes in
guard let modesCollectionViewDataSource = self?.modesCollectionView.dataSource as? ModesCollectionViewDataSource else { return }
modesCollectionViewDataSource.smartModes = smartModes
}).disposed(by: disposeBag)
viewModel.selectedMode.asObservable().subscribe(onNext: { [weak self] _ in
guard let viewModel = self?.viewModel, let modesCollectionViewDataSource = self?.modesCollectionView.dataSource as? ModesCollectionViewDataSource else { return }
modesCollectionViewDataSource.smartModes = viewModel.smartModes.value
modesCollectionViewDataSource.selectedMode = viewModel.selectedMode.value
self?.modesCollectionView.reloadData()
guard let selectedMode = viewModel.selectedMode.value else {
return
}
self?.updateModeView(mode: selectedMode)
}).disposed(by: disposeBag)
//
viewModel.startTime.asObservable().bind(to: startTimeLabel.rx.text).disposed(by: disposeBag)
viewModel.endTime.asObservable().bind(to: endTimeLabel.rx.text).disposed(by: disposeBag)
viewModel.showMessageError.asObservable().subscribe(onNext: { [weak self] errorMessage in
self?.app_showAlertMessage(title: "ERROR_TITLE".app_localized, message: errorMessage)
}).disposed(by: disposeBag)
deleteButton.setTitle("DELETE".app_localized, for: .normal)
modifyTimeslotLabel.text = "MODIFY_TIMESLOT_TEXT".app_localized
applyToAllRoomsButton.setTitle("APPLIED_TO_ALL_ROOMS".app_localized, for: .normal)
startTimeTitleLabel.text = "START_TEXT".app_localized
endTimeTitleLabel.text = "END_TEXT".app_localized
roomsLabel.text = "ROOMS_TEXT".app_localized
addRoomButton.setTitle("ADD_ROOM_TO_TIMESLOT".app_localized, for:.normal)
selectModeLabel.text = "SELECT_MODE_TEXT".app_localized
okayButton.setTitle("CONFIRM_TEXT".app_localized, for: .normal)
}
private func updateModeView(mode: ModeItem) {
modeIconImageView.image = mode.icon
modeIconImageView.tintColor = mode.color
leftLineImageView.tintColor = mode.color
modeTitleLabel.text = mode.title
if UserDataManager.shared.temperatureUnit == .C {
modeTemperatureLabel.text = mode.temperature.toString()
modeUnitOfTempLabel.text = "°C"
} else {
modeTemperatureLabel.text = mode.temperature.fahrenheitTemperature.toString()
modeUnitOfTempLabel.text = "°F"
}
}
}
extension SmartScheduleDetailViewController: ScheduleTimeInputDelegate {
func selectedTime(start: String, end: String) {
viewModel.startTime.value = start
if end == "00:00" {
viewModel.endTime.value = "24:00"
} else {
viewModel.endTime.value = end
}
}
}
extension SmartScheduleDetailViewController: RoomsPopOverViewControllerDelegate {
func didSelected(rooms: [Room]) {
viewModel.selectedRooms.value = rooms
}
}
extension SmartScheduleDetailViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return viewModel.selectedRooms.value.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = roomsTableView.dequeueReusableCell(withIdentifier: ScheduleRoomCell.get_identifier, for: indexPath) as? ScheduleRoomCell else {
log.error("Invalid cell type call")
return UITableViewCell()
}
let room = viewModel.selectedRooms.value[indexPath.row]
cell.setup(withRoom: room)
cell.closeButtonHandler = { [weak self] (room) in
if let indexRoom = self?.viewModel.selectedRooms.value.firstIndex(where: {$0.id == room.id}) {
self?.viewModel.selectedRooms.value.remove(at: indexRoom)
self?.roomsTableView.reloadData()
}
}
return cell
}
}
extension SmartScheduleDetailViewController : UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath) -> CGSize {
let numberOfCells = viewModel.smartModes.value.count
let widthOfCell: CGFloat = self.modesCollectionView.frame.width / CGFloat(numberOfCells)
return CGSize(width: (widthOfCell > 88) ? widthOfCell : 88, height: self.modesCollectionView.frame.height)
}
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
insetForSectionAt section: Int) -> UIEdgeInsets {
return .zero
}
}
extension SmartScheduleDetailViewController: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
viewModel?.didSelectMode(atIndex: indexPath.section)
}
}
<file_sep>
//
// TemperatureUnitViewModel.swift
// Koleda
//
// Created by <NAME> on 9/17/19.
// Copyright © 2019 koleda. All rights reserved.
//
import Foundation
import RxSwift
protocol TemperatureUnitViewModelProtocol: BaseViewModelProtocol {
func viewWillAppear()
func confirmedAndFinished()
func updateUnit(selectedUnit: TemperatureUnit)
var seletedUnit: Variable<TemperatureUnit> { get }
var hasChanged: PublishSubject<Bool> { get }
}
class TemperatureUnitViewModel: BaseViewModel, TemperatureUnitViewModelProtocol {
let router: BaseRouterProtocol
let seletedUnit = Variable<TemperatureUnit>(.C)
var hasChanged = PublishSubject<Bool>()
private var lastestUnit: TemperatureUnit = UserDataManager.shared.temperatureUnit
private let settingManager: SettingManager
init(router: BaseRouterProtocol, managerProvider: ManagerProvider = .sharedInstance) {
self.router = router
self.settingManager = managerProvider.settingManager
super.init(managerProvider: managerProvider)
}
func viewWillAppear() {
seletedUnit.value = lastestUnit
}
func confirmedAndFinished() {
let selectedUnit = seletedUnit.value
if lastestUnit != selectedUnit {
settingManager.updateTemperatureUnit(temperatureUnit: selectedUnit.rawValue, success: { [weak self] in
UserDataManager.shared.temperatureUnit = selectedUnit
self?.hasChanged.onNext(true)
self?.goHome()
}) { [weak self] _ in
self?.hasChanged.onNext(false)
}
} else {
goHome()
}
}
func updateUnit(selectedUnit: TemperatureUnit) {
lastestUnit = self.seletedUnit.value
self.seletedUnit.value = selectedUnit
}
private func goHome() {
if UserDataManager.shared.stepProgressBar.totalStep == 5 {
router.enqueueRoute(with: TemperatureUnitRouter.RouteType.inviteFriends)
} else {
UserDefaultsManager.loggedIn.enabled = true
router.enqueueRoute(with: TemperatureUnitRouter.RouteType.home)
}
}
}
<file_sep>//
// URL+Extensions.swift
// Koleda
//
// Created by <NAME> on 7/1/19.
// Copyright © 2019 koleda. All rights reserved.
//
import Foundation
extension URL {
static func bp_temporaryFileURL(for filename: String) -> URL {
let temporaryFileURL = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(filename)
return temporaryFileURL
}
func parameter(forName name: String) -> String? {
guard let url = URLComponents(string: self.absoluteString) else { return nil }
return url.queryItems?.first(where: { $0.name == name })?.value
}
/**
Returns url in ".invalid" top domain, which may not be installed as a top-level domain in the Domain Name System
(DNS) of the Internet.
- wikipedia: https://en.wikipedia.org/wiki/.invalid
*/
static var invalidURL: URL {
return URL(string: "https://this.url.is.invalid")!
}
}
<file_sep>//
// NetServiceClient.swift
// NetService
//
// Created by <NAME> on 11/5/18.
// Copyright © 2018 PureSwift. All rights reserved.
//
import Foundation
/// Bonjour Net Service Client
public protocol NetServiceClientProtocol: class {
/// Discover services of the specified type in the specified domain.
func discoverServices(of type: NetServiceType,
in domain: NetServiceDomain,
shouldContinue: () -> Bool,
foundService: @escaping (Service) -> ()) throws
/// Resolve the address of the specified net service.
func resolve(_ service: Service, timeout: TimeInterval) throws -> [NetServiceAddress]
}
/// Net Service Error
public enum NetServiceClientError: Error {
/// Operation timed out.
case timeout
/// Invalid / Unknown service specified.
case invalidService(Service)
#if os(macOS) || os(iOS) || canImport(NetService)
///
case notDiscoverServices([String: NSNumber])
///
case notResolveAddress([String: NSNumber])
#endif
}
<file_sep>//
// SchedulingTabsViewController.swift
// Koleda
//
// Created by <NAME> on 10/30/19.
// Copyright © 2019 koleda. All rights reserved.
//
import UIKit
import SpreadsheetView
class SchedulingTabsViewController: UIViewController {
var parentController: SmartSchedulingViewController?
var pageTabMenuViewController: PageTabMenuViewController?
override func viewDidLoad() {
super.viewDidLoad()
let items = [DayOfWeek.MONDAY.titleOfDay, DayOfWeek.TUESDAY.titleOfDay, DayOfWeek.WEDNESDAY.titleOfDay, DayOfWeek.THURSDAY.titleOfDay, DayOfWeek.FRIDAY.titleOfDay, DayOfWeek.SATURDAY.titleOfDay, DayOfWeek.SUNDAY.titleOfDay ]
let pageTabMenuViewController = PageTabMenuViewController(titles: items, options: UnderlinePagerOption())
pageTabMenuViewController.parentController = parentController
self.addChild(pageTabMenuViewController)
self.view.addSubview(pageTabMenuViewController.view)
self.pageTabMenuViewController = pageTabMenuViewController
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if let parentController = self.parentController, let pageController = self.pageTabMenuViewController {
pageController.pageTabMenuDelegate = parentController
}
}
private func getMergeCellData(rowsMergeData: [(startIndex: Int, numberRows: Int)]) -> [CellRange] {
var mergeData: [CellRange] = []
for data in rowsMergeData {
if data.numberRows > 1 {
let startRow = data.startIndex
let endRow = (data.startIndex + data.numberRows) - 1
mergeData.append(CellRange(from: (row: startRow, column: 1), to: (row: endRow, column: 1)))
}
}
return mergeData
}
}
<file_sep>//
// Tariff.swift
// Koleda
//
// Created by <NAME> on 8/2/19.
// Copyright © 2019 koleda. All rights reserved.
//
import Foundation
import UIKit
struct Tariff: Codable {
let dayTimeStart: String
let dayTimeEnd: String
let dayTariff: Double
let nightTimeStart: String
let nightTimeEnd: String
let nightTariff: Double
let currency: String
init(dayTimeStart: String, dayTimeEnd: String, dayTariff: Double, nightTimeStart: String, nightTimeEnd: String, nightTariff: Double, currency: String) {
self.dayTimeStart = dayTimeStart
self.dayTimeEnd = dayTimeEnd
self.dayTariff = dayTariff
self.nightTimeStart = nightTimeStart
self.nightTimeEnd = nightTimeEnd
self.nightTariff = nightTariff
self.currency = currency
}
private enum CodingKeys: String, CodingKey {
case dayTimeStart
case dayTimeEnd
case dayTariff
case nightTimeStart
case nightTimeEnd
case nightTariff
case currency
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.dayTimeStart = try container.decode(String.self, forKey: .dayTimeStart).removeSecondOfTime()
self.dayTimeEnd = try container.decode(String.self, forKey: .dayTimeEnd).removeSecondOfTime()
self.dayTariff = try container.decode(Double.self, forKey: .dayTariff)
self.nightTimeStart = try container.decode(String.self, forKey: .nightTimeStart).removeSecondOfTime()
self.nightTimeEnd = try container.decode(String.self, forKey: .nightTimeEnd).removeSecondOfTime()
self.nightTariff = try container.decode(Double.self, forKey: .nightTariff)
self.currency = try container.decode(String.self, forKey: .currency)
}
}
struct ConsumeEneryTariff {
let energyConsumedMonth: Double
let energyConsumedWeek: Double
let energyConsumedDay: Double
init(energyConsumedMonth: Double, energyConsumedWeek: Double, energyConsumedDay: Double) {
self.energyConsumedMonth = energyConsumedMonth
self.energyConsumedWeek = energyConsumedWeek
self.energyConsumedDay = energyConsumedDay
}
}
| 5f162c5676a8f48fe5057d9e51d7d7a16aec6c4c | [
"Swift",
"Ruby"
] | 209 | Swift | oanhtranha/Korelda_re | aa76fb6d1ad3dfd82ea220319c9dfdefcaa2ddd9 | 6b4996e7818dfbacdd9eea33f00736ef4a09ee7f |
refs/heads/main | <repo_name>scikit-image/scikit-image<file_sep>/doc/source/conf.py
# Configuration file for the Sphinx documentation builder.
#
# For the full list of built-in configuration values, see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
from datetime import date
import inspect
import os
import sys
from warnings import filterwarnings
import plotly.io as pio
import skimage
from packaging.version import parse
from plotly.io._sg_scraper import plotly_sg_scraper
from sphinx_gallery.sorting import ExplicitOrder
from sphinx_gallery.utils import _has_optipng
filterwarnings(
"ignore", message="Matplotlib is currently using agg", category=UserWarning
)
# -- Project information -----------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information
project = "skimage"
copyright = f"2013-{date.today().year}, the scikit-image team"
with open("../../skimage/__init__.py") as f:
setup_lines = f.readlines()
version = "vUndefined"
for l in setup_lines:
if l.startswith("__version__"):
version = l.split("'")[1]
break
release = version
# -- General configuration ---------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration
curpath = os.path.dirname(__file__)
sys.path.append(os.path.join(curpath, "..", "ext"))
extensions = [
"sphinx.ext.autodoc",
"sphinx.ext.autosummary",
"sphinx.ext.intersphinx",
"sphinx.ext.linkcode",
"sphinx.ext.mathjax",
"sphinx_copybutton",
"sphinx_gallery.gen_gallery",
"doi_role",
"numpydoc",
"sphinx_design",
"matplotlib.sphinxext.plot_directive",
"myst_parser",
"skimage_extensions",
]
autosummary_generate = True
templates_path = ["_templates"]
source_suffix = ".rst"
# -- Options for HTML output -------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output
exclude_trees = []
default_role = "autolink"
pygments_style = "sphinx"
# -- Sphinx-gallery configuration --------------------------------------------
v = parse(release)
if v.release is None:
raise ValueError(f"Ill-formed version: {version!r}. Version should follow PEP440")
if v.is_devrelease:
binder_branch = "main"
else:
major, minor = v.release[:2]
binder_branch = f"v{major}.{minor}.x"
# set plotly renderer to capture _repr_html_ for sphinx-gallery
pio.renderers.default = "sphinx_gallery_png"
sphinx_gallery_conf = {
"doc_module": ("skimage",),
"examples_dirs": "../examples",
"gallery_dirs": "auto_examples",
"backreferences_dir": "api",
"reference_url": {"skimage": None},
"image_scrapers": ("matplotlib", plotly_sg_scraper),
"subsection_order": ExplicitOrder(
[
"../examples/data",
"../examples/numpy_operations",
"../examples/color_exposure",
"../examples/edges",
"../examples/transform",
"../examples/registration",
"../examples/filters",
"../examples/features_detection",
"../examples/segmentation",
"../examples/applications",
"../examples/developers",
]
),
"binder": {
# Required keys
"org": "scikit-image",
"repo": "scikit-image",
"branch": binder_branch, # Can be any branch, tag, or commit hash
"binderhub_url": "https://mybinder.org", # Any URL of a binderhub.
"dependencies": ["../../.binder/requirements.txt", "../../.binder/runtime.txt"],
# Optional keys
"use_jupyter_lab": False,
},
# Remove sphinx_gallery_thumbnail_number from generated files
"remove_config_comments": True,
}
if _has_optipng():
# This option requires optipng to compress images
# Optimization level between 0-7
# sphinx-gallery default: -o7
# optipng default: -o2
# We choose -o1 as it produces a sufficient optimization
# See #4800
sphinx_gallery_conf["compress_images"] = ("images", "thumbnails", "-o1")
# -- Options for HTML output -------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output
# https://pydata-sphinx-theme.readthedocs.io/en/latest/user_guide/branding.html
html_theme = "pydata_sphinx_theme"
html_favicon = "_static/favicon.ico"
html_static_path = ["_static"]
html_logo = "_static/logo.png"
html_css_files = ['theme_overrides.css']
html_theme_options = {
# Navigation bar
"logo": {
"alt_text": (
"scikit-image's logo, showing a snake's head overlayed with green "
"and orange"
),
"text": "scikit-image",
"link": "https://scikit-image.org",
},
"header_links_before_dropdown": 6,
"icon_links": [
{
"name": "PyPI",
"url": "https://pypi.org/project/scikit-image/",
"icon": "fa-solid fa-box",
},
],
"navbar_end": ["version-switcher", "navbar-icon-links"],
"show_prev_next": False,
"switcher": {
"json_url": "https://scikit-image.org/docs/dev/_static/version_switcher.json",
"version_match": "dev" if "dev" in version else version,
},
"github_url": "https://github.com/scikit-image/scikit-image",
# Footer
"footer_start": ["copyright"],
"footer_end": ["sphinx-version", "theme-version"],
# Other
"pygment_light_style": "default",
"pygment_dark_style": "github-dark",
}
# Custom sidebar templates, maps document names to template names.
html_sidebars = {
# "**": ["sidebar-nav-bs", "sidebar-ethical-ads"],
"auto_examples/index": [] # Hide sidebar in example gallery
}
# Output file base name for HTML help builder.
htmlhelp_basename = "scikitimagedoc"
# -- Options for LaTeX output --------------------------------------------------
latex_font_size = "10pt"
latex_documents = [
(
"index",
"scikit-image.tex",
"The scikit-image Documentation",
"scikit-image development team",
"manual",
),
]
latex_elements = {}
latex_elements[
"preamble"
] = r"""
\usepackage{enumitem}
\setlistdepth{100}
\usepackage{amsmath}
\DeclareUnicodeCharacter{00A0}{\nobreakspace}
% In the parameters section, place a newline after the Parameters header
\usepackage{expdlist}
\let\latexdescription=\description
\def\description{\latexdescription{}{} \breaklabel}
% Make Examples/etc section headers smaller and more compact
\makeatletter
\titleformat{\paragraph}{\normalsize\py@HeaderFamily}%
{\py@TitleColor}{0em}{\py@TitleColor}{\py@NormalColor}
\titlespacing*{\paragraph}{0pt}{1ex}{0pt}
\makeatother
"""
latex_domain_indices = False
# -- numpydoc extension -------------------------------------------------------
numpydoc_show_class_members = False
numpydoc_class_members_toctree = False
# -- intersphinx --------------------------------------------------------------
intersphinx_mapping = {
"python": ("https://docs.python.org/3/", None),
"numpy": ("https://numpy.org/doc/stable/", None),
"neps": ("https://numpy.org/neps/", None),
"scipy": ("https://docs.scipy.org/doc/scipy/", None),
"sklearn": ("https://scikit-learn.org/stable/", None),
"matplotlib": ("https://matplotlib.org/stable/", None),
}
# -- Source code links -------------------------------------------------------
# Function courtesy of NumPy to return URLs containing line numbers
def linkcode_resolve(domain, info):
"""
Determine the URL corresponding to Python object
"""
if domain != "py":
return None
modname = info["module"]
fullname = info["fullname"]
submod = sys.modules.get(modname)
if submod is None:
return None
obj = submod
for part in fullname.split("."):
try:
obj = getattr(obj, part)
except AttributeError:
return None
# Strip decorators which would resolve to the source of the decorator
obj = inspect.unwrap(obj)
try:
fn = inspect.getsourcefile(obj)
except TypeError:
fn = None
if not fn:
return None
try:
source, start_line = inspect.getsourcelines(obj)
except OSError:
linespec = ""
else:
stop_line = start_line + len(source) - 1
linespec = f"#L{start_line}-L{stop_line}"
fn = os.path.relpath(fn, start=os.path.dirname(skimage.__file__))
if "dev" in skimage.__version__:
return (
"https://github.com/scikit-image/scikit-image/blob/"
f"main/skimage/{fn}{linespec}"
)
else:
return (
"https://github.com/scikit-image/scikit-image/blob/"
f"v{skimage.__version__}/skimage/{fn}{linespec}"
)
# -- MyST --------------------------------------------------------------------
myst_enable_extensions = [
# Enable fieldlist to allow for Field Lists like in rST (e.g., :orphan:)
"fieldlist",
]
<file_sep>/doc/examples/applications/plot_3d_image_processing.py
"""
============================
Explore 3D images (of cells)
============================
This tutorial is an introduction to three-dimensional image processing.
For a quick intro to 3D datasets, please refer to
:ref:`sphx_glr_auto_examples_data_plot_3d.py`.
Images
are represented as `numpy` arrays. A single-channel, or grayscale, image is a
2D matrix of pixel intensities of shape ``(n_row, n_col)``, where ``n_row``
(resp. ``n_col``) denotes the number of `rows` (resp. `columns`). We can
construct a 3D volume as a series of 2D `planes`, giving 3D images the shape
``(n_plane, n_row, n_col)``, where ``n_plane`` is the number of planes.
A multichannel, or RGB(A), image has an additional
`channel` dimension in the final position containing color information.
These conventions are summarized in the table below:
=============== =================================
Image type Coordinates
=============== =================================
2D grayscale ``[row, column]``
2D multichannel ``[row, column, channel]``
3D grayscale ``[plane, row, column]``
3D multichannel ``[plane, row, column, channel]``
=============== =================================
Some 3D images are constructed with equal resolution in each dimension (e.g.,
synchrotron tomography or computer-generated rendering of a sphere).
But most experimental data are captured
with a lower resolution in one of the three dimensions, e.g., photographing
thin slices to approximate a 3D structure as a stack of 2D images.
The distance between pixels in each dimension, called spacing, is encoded as a
tuple and is accepted as a parameter by some `skimage` functions and can be
used to adjust contributions to filters.
The data used in this tutorial were provided by the Allen Institute for Cell
Science. They were downsampled by a factor of 4 in the `row` and `column`
dimensions to reduce their size and, hence, computational time. The spacing
information was reported by the microscope used to image the cells.
"""
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
import numpy as np
import plotly
import plotly.express as px
from skimage import (
exposure, util
)
from skimage.data import cells3d
#####################################################################
# Load and display 3D images
# ==========================
data = util.img_as_float(cells3d()[:, 1, :, :]) # grab just the nuclei
print(f'shape: {data.shape}')
print(f'dtype: {data.dtype}')
print(f'range: ({data.min()}, {data.max()})')
# Report spacing from microscope
original_spacing = np.array([0.2900000, 0.0650000, 0.0650000])
# Account for downsampling of slices by 4
rescaled_spacing = original_spacing * [1, 4, 4]
# Normalize spacing so that pixels are a distance of 1 apart
spacing = rescaled_spacing / rescaled_spacing[2]
print(f'microscope spacing: {original_spacing}\n')
print(f'rescaled spacing: {rescaled_spacing} (after downsampling)\n')
print(f'normalized spacing: {spacing}\n')
#####################################################################
# Let us try and visualize our 3D image. Unfortunately, many image viewers,
# such as matplotlib's `imshow`, are only capable of displaying 2D data. We
# can see that they raise an error when we try to view 3D data:
try:
fig, ax = plt.subplots()
ax.imshow(data, cmap='gray')
except TypeError as e:
print(str(e))
#####################################################################
# The `imshow` function can only display grayscale and RGB(A) 2D images.
# We can thus use it to visualize 2D planes. By fixing one axis, we can
# observe three different views of the image.
def show_plane(ax, plane, cmap="gray", title=None):
ax.imshow(plane, cmap=cmap)
ax.axis("off")
if title:
ax.set_title(title)
(n_plane, n_row, n_col) = data.shape
_, (a, b, c) = plt.subplots(ncols=3, figsize=(15, 5))
show_plane(a, data[n_plane // 2], title=f'Plane = {n_plane // 2}')
show_plane(b, data[:, n_row // 2, :], title=f'Row = {n_row // 2}')
show_plane(c, data[:, :, n_col // 2], title=f'Column = {n_col // 2}')
#####################################################################
# As hinted before, a three-dimensional image can be viewed as a series of
# two-dimensional planes. Let us write a helper function, `display`, to create
# a montage of several planes. By default, every other plane is displayed.
def display(im3d, cmap='gray', step=2):
data_montage = util.montage(im3d[::step], padding_width=4, fill=np.nan)
_, ax = plt.subplots(figsize=(16, 14))
ax.imshow(data_montage, cmap=cmap)
ax.set_axis_off()
display(data)
#####################################################################
# Alternatively, we can explore these planes (slices) interactively using
# Jupyter widgets. Let the user select which slice to display and show the
# position of this slice in the 3D dataset.
# Note that you cannot see the Jupyter widget at work in a static HTML page,
# as is the case in the online version of this example. For the following
# piece of code to work, you need a Jupyter kernel running either locally or
# in the cloud: see the bottom of this page to either download the Jupyter
# notebook and run it on your computer, or open it directly in Binder. On top
# of an active kernel, you need a web browser: running the code in pure Python
# will not work either.
def slice_in_3D(ax, i):
# From https://stackoverflow.com/questions/44881885/python-draw-3d-cube
Z = np.array([[0, 0, 0],
[1, 0, 0],
[1, 1, 0],
[0, 1, 0],
[0, 0, 1],
[1, 0, 1],
[1, 1, 1],
[0, 1, 1]])
Z = Z * data.shape
r = [-1, 1]
X, Y = np.meshgrid(r, r)
# Plot vertices
ax.scatter3D(Z[:, 0], Z[:, 1], Z[:, 2])
# List sides' polygons of figure
verts = [[Z[0], Z[1], Z[2], Z[3]],
[Z[4], Z[5], Z[6], Z[7]],
[Z[0], Z[1], Z[5], Z[4]],
[Z[2], Z[3], Z[7], Z[6]],
[Z[1], Z[2], Z[6], Z[5]],
[Z[4], Z[7], Z[3], Z[0]],
[Z[2], Z[3], Z[7], Z[6]]]
# Plot sides
ax.add_collection3d(
Poly3DCollection(
verts,
facecolors=(0, 1, 1, 0.25),
linewidths=1,
edgecolors="darkblue"
)
)
verts = np.array([[[0, 0, 0],
[0, 0, 1],
[0, 1, 1],
[0, 1, 0]]])
verts = verts * (60, 256, 256)
verts += [i, 0, 0]
ax.add_collection3d(
Poly3DCollection(
verts,
facecolors="magenta",
linewidths=1,
edgecolors="black"
)
)
ax.set_xlabel("plane")
ax.set_xlim(0, 100)
ax.set_ylabel("row")
ax.set_zlabel("col")
# Autoscale plot axes
scaling = np.array([getattr(ax,
f'get_{dim}lim')() for dim in "xyz"])
ax.auto_scale_xyz(* [[np.min(scaling), np.max(scaling)]] * 3)
def explore_slices(data, cmap="gray"):
from ipywidgets import interact
N = len(data)
@interact(plane=(0, N - 1))
def display_slice(plane=34):
fig, ax = plt.subplots(figsize=(20, 5))
ax_3D = fig.add_subplot(133, projection="3d")
show_plane(ax, data[plane], title=f'Plane {plane}', cmap=cmap)
slice_in_3D(ax_3D, plane)
plt.show()
return display_slice
explore_slices(data)
#####################################################################
# Adjust exposure
# ===============
# Scikit-image's `exposure` module contains a number of functions for
# adjusting image contrast. These functions operate on pixel values.
# Generally, image dimensionality or pixel spacing doesn't need to be
# considered. In local exposure correction, though, one might want to
# adjust the window size to ensure equal size in *real* coordinates along
# each axis.
#####################################################################
# `Gamma correction <https://en.wikipedia.org/wiki/Gamma_correction>`_
# brightens or darkens an image. A power-law transform, where `gamma` denotes
# the power-law exponent, is applied to each pixel in the image: `gamma < 1`
# will brighten an image, while `gamma > 1` will darken an image.
def plot_hist(ax, data, title=None):
# Helper function for plotting histograms
ax.hist(data.ravel(), bins=256)
ax.ticklabel_format(axis="y", style="scientific", scilimits=(0, 0))
if title:
ax.set_title(title)
gamma_low_val = 0.5
gamma_low = exposure.adjust_gamma(data, gamma=gamma_low_val)
gamma_high_val = 1.5
gamma_high = exposure.adjust_gamma(data, gamma=gamma_high_val)
_, ((a, b, c), (d, e, f)) = plt.subplots(nrows=2, ncols=3, figsize=(12, 8))
show_plane(a, data[32], title='Original')
show_plane(b, gamma_low[32], title=f'Gamma = {gamma_low_val}')
show_plane(c, gamma_high[32], title=f'Gamma = {gamma_high_val}')
plot_hist(d, data)
plot_hist(e, gamma_low)
plot_hist(f, gamma_high)
# sphinx_gallery_thumbnail_number = 4
#####################################################################
# `Histogram
# equalization <https://en.wikipedia.org/wiki/Histogram_equalization>`_
# improves contrast in an image by redistributing pixel intensities. The most
# common pixel intensities get spread out, increasing contrast in low-contrast
# areas. One downside of this approach is that it may enhance background
# noise.
equalized_data = exposure.equalize_hist(data)
display(equalized_data)
#####################################################################
# As before, if we have a Jupyter kernel running, we can explore the above
# slices interactively.
explore_slices(equalized_data)
#####################################################################
# Let us now plot the image histogram before and after histogram equalization.
# Below, we plot the respective cumulative distribution functions (CDF).
_, ((a, b), (c, d)) = plt.subplots(nrows=2, ncols=2, figsize=(16, 8))
plot_hist(a, data, title="Original histogram")
plot_hist(b, equalized_data, title="Equalized histogram")
cdf, bins = exposure.cumulative_distribution(data.ravel())
c.plot(bins, cdf, "r")
c.set_title("Original CDF")
cdf, bins = exposure.cumulative_distribution(equalized_data.ravel())
d.plot(bins, cdf, "r")
d.set_title("Histogram equalization CDF")
#####################################################################
# Most experimental images are affected by salt and pepper noise. A few bright
# artifacts can decrease the relative intensity of the pixels of interest. A
# simple way to improve contrast is to clip the pixel values on the lowest and
# highest extremes. Clipping the darkest and brightest 0.5% of pixels will
# increase the overall contrast of the image.
vmin, vmax = np.percentile(data, q=(0.5, 99.5))
clipped_data = exposure.rescale_intensity(
data,
in_range=(vmin, vmax),
out_range=np.float32
)
display(clipped_data)
#####################################################################
# Alternatively, we can explore these planes (slices) interactively using
# `Plotly Express <https://plotly.com/python/sliders/>`_.
# Note that this works in a static HTML page!
fig = px.imshow(data, animation_frame=0, binary_string=True)
fig.update_xaxes(showticklabels=False)
fig.update_yaxes(showticklabels=False)
fig.update_layout(
autosize=False,
width=500,
height=500,
coloraxis_showscale=False
)
# Drop animation buttons
fig['layout'].pop('updatemenus')
plotly.io.show(fig)
plt.show()
<file_sep>/doc/examples/edges/plot_ridge_filter.py
"""
===============
Ridge operators
===============
Ridge filters can be used to detect ridge-like structures, such as neurites
[1]_, tubes [2]_, vessels [3]_, wrinkles [4]_ or rivers.
Different ridge filters may be suited for detecting different structures,
e.g., depending on contrast or noise level.
The present class of ridge filters relies on the eigenvalues of
the Hessian matrix of image intensities to detect ridge structures where the
intensity changes perpendicular but not along the structure.
References
----------
.. [1] <NAME>., <NAME>., <NAME>., <NAME>., <NAME>.,
<NAME>. (2004). Design and validation of a tool for neurite tracing
and analysis in fluorescence microscopy images. Cytometry Part A, 58(2),
167-176.
:DOI:`10.1002/cyto.a.20022`
.. [2] <NAME>., <NAME>., <NAME>., <NAME>., <NAME>.,
<NAME>., ..., <NAME>. (1998). Three-dimensional multi-scale line
filter for segmentation and visualization of curvilinear structures in
medical images. Medical image analysis, 2(2), 143-168.
:DOI:`10.1016/S1361-8415(98)80009-1`
.. [3] <NAME>., <NAME>., <NAME>., & <NAME>. (1998,
October). Multiscale vessel enhancement filtering. In International
Conference on Medical Image Computing and Computer-Assisted Intervention
(pp. 130-137). Springer Berlin Heidelberg.
:DOI:`10.1007/BFb0056195`
.. [4] Ng, <NAME>., <NAME>., <NAME>., & <NAME>. (2014, November). Automatic
wrinkle detection using hybrid Hessian filter. In Asian Conference on
Computer Vision (pp. 609-622). Springer International Publishing.
:DOI:`10.1007/978-3-319-16811-1_40`
"""
from skimage import data
from skimage import color
from skimage.filters import meijering, sato, frangi, hessian
import matplotlib.pyplot as plt
def original(image, **kwargs):
"""Return the original image, ignoring any kwargs."""
return image
image = color.rgb2gray(data.retina())[300:700, 700:900]
cmap = plt.cm.gray
plt.rcParams["axes.titlesize"] = "medium"
axes = plt.figure(figsize=(10, 4)).subplots(2, 9)
for i, black_ridges in enumerate([True, False]):
for j, (func, sigmas) in enumerate([
(original, None),
(meijering, [1]),
(meijering, range(1, 5)),
(sato, [1]),
(sato, range(1, 5)),
(frangi, [1]),
(frangi, range(1, 5)),
(hessian, [1]),
(hessian, range(1, 5)),
]):
result = func(image, black_ridges=black_ridges, sigmas=sigmas)
axes[i, j].imshow(result, cmap=cmap)
if i == 0:
title = func.__name__
if sigmas:
title += f"\n\N{GREEK SMALL LETTER SIGMA} = {list(sigmas)}"
axes[i, j].set_title(title)
if j == 0:
axes[i, j].set_ylabel(f'{black_ridges = }')
axes[i, j].set_xticks([])
axes[i, j].set_yticks([])
plt.tight_layout()
plt.show()
<file_sep>/skimage/io/_plugins/imageio_plugin.py
__all__ = ['imread', 'imsave']
from functools import wraps
import numpy as np
from imageio.v3 import imread as imageio_imread, imwrite as imsave
@wraps(imageio_imread)
def imread(*args, **kwargs):
out = np.asarray(imageio_imread(*args, **kwargs))
if not out.flags['WRITEABLE']:
out = out.copy()
return out
<file_sep>/skimage/transform/__init__.py
"""This module includes tools to transform images and volumetric data.
- Geometric transformation:
These transforms change the shape or position of an image.
They are useful for tasks such as image registration,
alignment, and geometric correction.
Examples: :class:`~skimage.transform.AffineTransform`,
:class:`~skimage.transform.ProjectiveTransform`,
:class:`~skimage.transform.EuclideanTransform`.
- Image resizing and rescaling:
These transforms change the size or resolution of an image.
They are useful for tasks such as down-sampling an image to
reduce its size or up-sampling an image to increase its resolution.
Examples: :func:`~skimage.transform.resize`,
:func:`~skimage.transform.rescale`.
- Feature detection and extraction:
These transforms identify and extract specific features or
patterns in an image. They are useful for tasks such as object
detection, image segmentation, and feature matching.
Examples: :func:`~skimage.transform.hough_circle`,
:func:`~skimage.transform.pyramid_expand`,
:func:`~skimage.transform.radon`.
- Image transformation:
These transforms change the appearance of an image without changing its
content. They are useful for tasks such a creating image mosaics,
applying artistic effects, and visualizing image data.
Examples: :func:`~skimage.transform.warp`,
:func:`~skimage.transform.iradon`.
"""
import lazy_loader as lazy
__getattr__, __dir__, __all__ = lazy.attach_stub(__name__, __file__)
<file_sep>/skimage/data/__init__.py
"""
Test images and datasets.
A curated set of general purpose and scientific images used in tests, examples,
and documentation.
Newer datasets are no longer included as part of the package, but are
downloaded on demand. To make data available offline, use :func:`download_all`.
"""
import lazy_loader as lazy
__getattr__, __dir__, __all__ = lazy.attach_stub(__name__, __file__)
<file_sep>/.spin/cmds.py
import os
import shutil
import sys
import click
from spin.cmds import meson
from spin import util
@click.command()
@click.option(
"--clean", is_flag=True,
default=False,
help="Clean previously built docs before building"
)
@click.option(
"--install-deps/--no-install-deps",
default=True,
help="Install dependencies before building"
)
@click.option(
'--build/--no-build',
default=True,
help="Build skimage before generating docs"
)
@click.pass_context
def docs(ctx, clean, install_deps, build):
"""📖 Build documentation
By default, SPHINXOPTS="-W", raising errors on warnings.
To build without raising on warnings:
SPHINXOPTS="" spin docs
"""
if clean:
doc_dirs = [
"./doc/build/",
"./doc/source/api/",
"./doc/source/auto_examples/",
"./doc/source/jupyterlite_contents/",
]
for doc_dir in doc_dirs:
if os.path.isdir(doc_dir):
print(f"Removing {doc_dir!r}")
shutil.rmtree(doc_dir)
if build:
click.secho(
"Invoking `build` prior to running tests:", bold=True, fg="bright_green"
)
ctx.invoke(meson.build)
try:
site_path = meson._get_site_packages()
except FileNotFoundError:
print("No built scikit-image found; run `spin build` first.")
sys.exit(1)
if install_deps:
util.run(['pip', 'install', '-q', '-r', 'requirements/docs.txt'])
os.environ['SPHINXOPTS'] = os.environ.get('SPHINXOPTS', "-W")
os.environ['PYTHONPATH'] = f'{site_path}{os.sep}:{os.environ.get("PYTHONPATH", "")}'
util.run(['make', '-C', 'doc', 'html'], replace=True)
@click.command()
@click.argument("asv_args", nargs=-1)
def asv(asv_args):
"""🏃 Run `asv` to collect benchmarks
ASV_ARGS are passed through directly to asv, e.g.:
spin asv -- dev -b TransformSuite
Please see CONTRIBUTING.txt
"""
site_path = meson._get_site_packages()
if site_path is None:
print("No built scikit-image found; run `spin build` first.")
sys.exit(1)
os.environ['PYTHONPATH'] = f'{site_path}{os.sep}:{os.environ.get("PYTHONPATH", "")}'
util.run(['asv'] + list(asv_args))
@click.command()
def coverage():
"""📊 Generate coverage report
"""
util.run(['python', '-m', 'spin', 'test', '--', '-o', 'python_functions=test_*', 'skimage', '--cov=skimage'], replace=True)
@click.command()
def sdist():
"""📦 Build a source distribution in `dist/`.
"""
util.run(['python', '-m', 'build', '.', '--sdist'])
<file_sep>/doc/examples/features_detection/plot_sift.py
"""
==============================================
SIFT feature detector and descriptor extractor
==============================================
This example demonstrates the SIFT feature detection and its description
algorithm.
The scale-invariant feature transform (SIFT) [1]_ was published in 1999 and is
still one of the most popular feature detectors available, as its promises to
be "invariant to image scaling, translation, and rotation, and partially
in-variant to illumination changes and affine or 3D projection" [2]_. Its
biggest drawback is its runtime, that's said to be "at two orders of
magnitude" [3]_ slower than ORB, which makes it unsuitable for real-time
applications.
References
----------
.. [1] https://en.wikipedia.org/wiki/Scale-invariant_feature_transform
.. [2] <NAME>. "Object recognition from local scale-invariant
features", Proceedings of the Seventh IEEE International
Conference on Computer Vision, 1999, vol.2, pp. 1150-1157.
:DOI:`10.1109/ICCV.1999.790410`
.. [3] <NAME>, <NAME>, <NAME> and <NAME>
"ORB: An efficient alternative to SIFT and SURF"
http://www.gwylab.com/download/ORB_2012.pdf
"""
import matplotlib.pyplot as plt
from skimage import data
from skimage import transform
from skimage.color import rgb2gray
from skimage.feature import match_descriptors, plot_matches, SIFT
img1 = rgb2gray(data.astronaut())
img2 = transform.rotate(img1, 180)
tform = transform.AffineTransform(scale=(1.3, 1.1), rotation=0.5,
translation=(0, -200))
img3 = transform.warp(img1, tform)
descriptor_extractor = SIFT()
descriptor_extractor.detect_and_extract(img1)
keypoints1 = descriptor_extractor.keypoints
descriptors1 = descriptor_extractor.descriptors
descriptor_extractor.detect_and_extract(img2)
keypoints2 = descriptor_extractor.keypoints
descriptors2 = descriptor_extractor.descriptors
descriptor_extractor.detect_and_extract(img3)
keypoints3 = descriptor_extractor.keypoints
descriptors3 = descriptor_extractor.descriptors
matches12 = match_descriptors(descriptors1, descriptors2, max_ratio=0.6,
cross_check=True)
matches13 = match_descriptors(descriptors1, descriptors3, max_ratio=0.6,
cross_check=True)
fig, ax = plt.subplots(nrows=2, ncols=2, figsize=(11, 8))
plt.gray()
plot_matches(ax[0, 0], img1, img2, keypoints1, keypoints2, matches12)
ax[0, 0].axis('off')
ax[0, 0].set_title("Original Image vs. Flipped Image\n"
"(all keypoints and matches)")
plot_matches(ax[1, 0], img1, img3, keypoints1, keypoints3, matches13)
ax[1, 0].axis('off')
ax[1, 0].set_title("Original Image vs. Transformed Image\n"
"(all keypoints and matches)")
plot_matches(ax[0, 1], img1, img2, keypoints1, keypoints2, matches12[::15],
only_matches=True)
ax[0, 1].axis('off')
ax[0, 1].set_title("Original Image vs. Flipped Image\n"
"(subset of matches for visibility)")
plot_matches(ax[1, 1], img1, img3, keypoints1, keypoints3, matches13[::15],
only_matches=True)
ax[1, 1].axis('off')
ax[1, 1].set_title("Original Image vs. Transformed Image\n"
"(subset of matches for visibility)")
plt.tight_layout()
plt.show()
<file_sep>/skimage/registration/__init__.py
import lazy_loader as lazy
__getattr__, __dir__, __all__ = lazy.attach_stub(__name__, __file__)
<file_sep>/doc/source/release_notes/release_0.3.rst
scikits.image 0.3 release notes
===============================
After a brief (!) absence, we're back with a new and shiny version of
scikits.image, the image processing toolbox for SciPy.
This release runs under all major operating systems where
Python (>=2.6 or 3.x), NumPy and SciPy can be installed.
For more information, visit our website
http://scikits-image.org
or the examples gallery at
http://scikits-image.org/docs/0.3/auto_examples/
New Features
------------
- Shortest paths
- Total variation denoising
- Hough and probabilistic Hough transforms
- Radon transform with reconstruction
- Histogram of gradients
- Morphology, including watershed, connected components
- Faster homography transformations (rotations, zoom, etc.)
- Image dtype conversion routines
- Line drawing
- Better image collection handling
- Constant time median filter
- Edge detection (canny, sobel, etc.)
- IO: Freeimage, FITS, Qt and other image loaders; video support.
- SIFT feature loader
- Example data-sets
... as well as many bug fixes and minor updates.
Contributors for this release
-----------------------------
<NAME>
<NAME>
<NAME>
<NAME>
<NAME>
<NAME>
<NAME>
<NAME>
Thouis (<NAME>
<NAME>
<NAME>
<NAME>
<NAME>
<NAME>
<NAME>
<NAME>
<NAME>
<NAME>
<NAME>
<file_sep>/skimage/util/tests/test_labels.py
import numpy as np
from skimage._shared import testing
from skimage._shared.testing import assert_equal
from skimage.util._label import label_points
def test_label_points_coords_dimension():
coords, output_shape = np.array([[1, 2], [3, 4]]), (5, 5, 2)
with testing.raises(ValueError):
label_points(coords, output_shape)
def test_label_points_coords_range():
coords, output_shape = np.array([[0, 0],
[5, 5]]), (5, 5)
with testing.raises(IndexError):
label_points(coords, output_shape)
def test_label_points_coords_negative():
coords, output_shape = np.array([[-1, 0],
[5, 5]]), (5, 5)
with testing.raises(ValueError):
label_points(coords, output_shape)
def test_label_points_two_dimensional_output():
coords, output_shape = np.array([[0, 0],
[1, 1],
[2, 2],
[3, 3],
[4, 4]]), (5, 5)
mask = label_points(coords, output_shape)
assert_equal(mask, np.array([[1, 0, 0, 0, 0],
[0, 2, 0, 0, 0],
[0, 0, 3, 0, 0],
[0, 0, 0, 4, 0],
[0, 0, 0, 0, 5]]))
def test_label_points_multi_dimensional_output():
coords, output_shape = np.array([[0, 0, 0],
[1, 1, 1],
[2, 2, 2],
[3, 3, 0],
[4, 4, 1]]), (5, 5, 3)
mask = label_points(coords, output_shape)
result = np.array([
[
[1, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]
],
[
[0, 0, 0], [0, 2, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]
],
[
[0, 0, 0], [0, 0, 0], [0, 0, 3], [0, 0, 0], [0, 0, 0]
],
[
[0, 0, 0], [0, 0, 0], [0, 0, 0], [4, 0, 0], [0, 0, 0]
],
[
[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 5, 0]
]
])
assert_equal(mask, result)
<file_sep>/skimage/measure/tests/test_colocalization.py
import numpy as np
import pytest
from skimage.measure import (intersection_coeff, manders_coloc_coeff,
manders_overlap_coeff, pearson_corr_coeff)
def test_invalid_input():
# images are not same size
img1 = np.array([[i + j for j in range(4)] for i in range(4)])
img2 = np.ones((3, 5, 6))
mask = np.array([[i <= 1 for i in range(5)] for _ in range(5)])
non_binary_mask = np.array([[2 for __ in range(4)] for _ in range(4)])
with pytest.raises(ValueError, match=". must have the same dimensions"):
pearson_corr_coeff(img1, img1, mask)
with pytest.raises(ValueError, match=". must have the same dimensions"):
pearson_corr_coeff(img1, img2)
with pytest.raises(ValueError, match=". must have the same dimensions"):
pearson_corr_coeff(img1, img1, mask)
with pytest.raises(ValueError, match=". array is not of dtype boolean"):
pearson_corr_coeff(img1, img1, non_binary_mask)
with pytest.raises(ValueError, match=". must have the same dimensions"):
manders_coloc_coeff(img1, mask)
with pytest.raises(ValueError, match=". array is not of dtype boolean"):
manders_coloc_coeff(img1, non_binary_mask)
with pytest.raises(ValueError, match=". must have the same dimensions"):
manders_coloc_coeff(img1, img1 > 0, mask)
with pytest.raises(ValueError, match=". array is not of dtype boolean"):
manders_coloc_coeff(img1, img1 > 0, non_binary_mask)
with pytest.raises(ValueError, match=". must have the same dimensions"):
manders_overlap_coeff(img1, img1, mask)
with pytest.raises(ValueError, match=". must have the same dimensions"):
manders_overlap_coeff(img1, img2)
with pytest.raises(ValueError, match=". must have the same dimensions"):
manders_overlap_coeff(img1, img1, mask)
with pytest.raises(ValueError, match=". array is not of dtype boolean"):
manders_overlap_coeff(img1, img1, non_binary_mask)
with pytest.raises(ValueError, match=". must have the same dimensions"):
intersection_coeff(img1 > 2, img2 > 1, mask)
with pytest.raises(ValueError, match=". array is not of dtype boolean"):
intersection_coeff(img1, img2)
with pytest.raises(ValueError, match=". must have the same dimensions"):
intersection_coeff(img1 > 2, img1 > 1, mask)
with pytest.raises(ValueError, match=". array is not of dtype boolean"):
intersection_coeff(img1 > 2, img1 > 1, non_binary_mask)
def test_pcc():
# simple example
img1 = np.array([[i + j for j in range(4)] for i in range(4)])
assert pearson_corr_coeff(img1, img1) == (1.0, 0.0)
img2 = np.where(img1 <= 2, 0, img1)
np.testing.assert_almost_equal(pearson_corr_coeff(img1, img2), (0.944911182523068, 3.5667540654536515e-08))
# change background of roi and see if values are same
roi = np.where(img1 <= 2, 0, 1)
np.testing.assert_almost_equal(pearson_corr_coeff(img1, img1, roi), pearson_corr_coeff(img1, img2, roi))
def test_mcc():
img1 = np.array([[j for j in range(4)] for i in range(4)])
mask = np.array([[i <= 1 for j in range(4)]for i in range(4)])
assert manders_coloc_coeff(img1, mask) == 0.5
# test negative values
img_negativeint = np.where(img1 == 1, -1, img1)
img_negativefloat = img_negativeint / 2.0
with pytest.raises(ValueError):
manders_coloc_coeff(img_negativeint, mask)
with pytest.raises(ValueError):
manders_coloc_coeff(img_negativefloat, mask)
def test_moc():
img1 = np.ones((4, 4))
img2 = 2 * np.ones((4, 4))
assert manders_overlap_coeff(img1, img2) == 1
# test negative values
img_negativeint = np.where(img1 == 1, -1, img1)
img_negativefloat = img_negativeint / 2.0
with pytest.raises(ValueError):
manders_overlap_coeff(img_negativeint, img2)
with pytest.raises(ValueError):
manders_overlap_coeff(img1, img_negativeint)
with pytest.raises(ValueError):
manders_overlap_coeff(img_negativefloat, img2)
with pytest.raises(ValueError):
manders_overlap_coeff(img1, img_negativefloat)
with pytest.raises(ValueError):
manders_overlap_coeff(img_negativefloat, img_negativefloat)
def test_intersection_coefficient():
img1_mask = np.array([[j <= 1 for j in range(4)] for i in range(4)])
img2_mask = np.array([[i <= 1 for j in range(4)] for i in range(4)])
img3_mask = np.array([[1 for j in range(4)] for i in range(4)])
assert intersection_coeff(img1_mask, img2_mask) == 0.5
assert intersection_coeff(img1_mask, img3_mask) == 1
<file_sep>/skimage/feature/_canny.py
"""
canny.py - Canny Edge detector
Reference: <NAME>., A Computational Approach To Edge Detection, IEEE Trans.
Pattern Analysis and Machine Intelligence, 8:679-714, 1986
"""
import numpy as np
import scipy.ndimage as ndi
from ..util.dtype import dtype_limits
from .._shared.filters import gaussian
from .._shared.utils import _supported_float_type, check_nD
from ._canny_cy import _nonmaximum_suppression_bilinear
def _preprocess(image, mask, sigma, mode, cval):
"""Generate a smoothed image and an eroded mask.
The image is smoothed using a gaussian filter ignoring masked
pixels and the mask is eroded.
Parameters
----------
image : array
Image to be smoothed.
mask : array
Mask with 1's for significant pixels, 0's for masked pixels.
sigma : scalar or sequence of scalars
Standard deviation for Gaussian kernel. The standard
deviations of the Gaussian filter are given for each axis as a
sequence, or as a single number, in which case it is equal for
all axes.
mode : str, {'reflect', 'constant', 'nearest', 'mirror', 'wrap'}
The ``mode`` parameter determines how the array borders are
handled, where ``cval`` is the value when mode is equal to
'constant'.
cval : float, optional
Value to fill past edges of input if `mode` is 'constant'.
Returns
-------
smoothed_image : ndarray
The smoothed array
eroded_mask : ndarray
The eroded mask.
Notes
-----
This function calculates the fractional contribution of masked pixels
by applying the function to the mask (which gets you the fraction of
the pixel data that's due to significant points). We then mask the image
and apply the function. The resulting values will be lower by the
bleed-over fraction, so you can recalibrate by dividing by the function
on the mask to recover the effect of smoothing from just the significant
pixels.
"""
gaussian_kwargs = dict(
sigma=sigma,
mode=mode,
cval=cval,
preserve_range=False
)
compute_bleedover = (mode == 'constant' or mask is not None)
float_type = _supported_float_type(image.dtype)
if mask is None:
if compute_bleedover:
mask = np.ones(image.shape, dtype=float_type)
masked_image = image
eroded_mask = np.ones(image.shape, dtype=bool)
eroded_mask[:1, :] = 0
eroded_mask[-1:, :] = 0
eroded_mask[:, :1] = 0
eroded_mask[:, -1:] = 0
else:
mask = mask.astype(bool, copy=False)
masked_image = np.zeros_like(image)
masked_image[mask] = image[mask]
# Make the eroded mask. Setting the border value to zero will wipe
# out the image edges for us.
s = ndi.generate_binary_structure(2, 2)
eroded_mask = ndi.binary_erosion(mask, s, border_value=0)
if compute_bleedover:
# Compute the fractional contribution of masked pixels by applying
# the function to the mask (which gets you the fraction of the
# pixel data that's due to significant points)
bleed_over = gaussian(mask.astype(float_type, copy=False),
**gaussian_kwargs) + np.finfo(float_type).eps
# Smooth the masked image
smoothed_image = gaussian(masked_image, **gaussian_kwargs)
# Lower the result by the bleed-over fraction, so you can
# recalibrate by dividing by the function on the mask to recover
# the effect of smoothing from just the significant pixels.
if compute_bleedover:
smoothed_image /= bleed_over
return smoothed_image, eroded_mask
def canny(image, sigma=1., low_threshold=None, high_threshold=None,
mask=None, use_quantiles=False, *, mode='constant', cval=0.0):
"""Edge filter an image using the Canny algorithm.
Parameters
----------
image : 2D array
Grayscale input image to detect edges on; can be of any dtype.
sigma : float, optional
Standard deviation of the Gaussian filter.
low_threshold : float, optional
Lower bound for hysteresis thresholding (linking edges).
If None, low_threshold is set to 10% of dtype's max.
high_threshold : float, optional
Upper bound for hysteresis thresholding (linking edges).
If None, high_threshold is set to 20% of dtype's max.
mask : array, dtype=bool, optional
Mask to limit the application of Canny to a certain area.
use_quantiles : bool, optional
If ``True`` then treat low_threshold and high_threshold as
quantiles of the edge magnitude image, rather than absolute
edge magnitude values. If ``True`` then the thresholds must be
in the range [0, 1].
mode : str, {'reflect', 'constant', 'nearest', 'mirror', 'wrap'}
The ``mode`` parameter determines how the array borders are
handled during Gaussian filtering, where ``cval`` is the value when
mode is equal to 'constant'.
cval : float, optional
Value to fill past edges of input if `mode` is 'constant'.
Returns
-------
output : 2D array (image)
The binary edge map.
See also
--------
skimage.filters.sobel
Notes
-----
The steps of the algorithm are as follows:
* Smooth the image using a Gaussian with ``sigma`` width.
* Apply the horizontal and vertical Sobel operators to get the gradients
within the image. The edge strength is the norm of the gradient.
* Thin potential edges to 1-pixel wide curves. First, find the normal
to the edge at each point. This is done by looking at the
signs and the relative magnitude of the X-Sobel and Y-Sobel
to sort the points into 4 categories: horizontal, vertical,
diagonal and antidiagonal. Then look in the normal and reverse
directions to see if the values in either of those directions are
greater than the point in question. Use interpolation to get a mix of
points instead of picking the one that's the closest to the normal.
* Perform a hysteresis thresholding: first label all points above the
high threshold as edges. Then recursively label any point above the
low threshold that is 8-connected to a labeled point as an edge.
References
----------
.. [1] <NAME>., A Computational Approach To Edge Detection, IEEE Trans.
Pattern Analysis and Machine Intelligence, 8:679-714, 1986
:DOI:`10.1109/TPAMI.1986.4767851`
.. [2] William Green's Canny tutorial
https://en.wikipedia.org/wiki/Canny_edge_detector
Examples
--------
>>> from skimage import feature
>>> rng = np.random.default_rng()
>>> # Generate noisy image of a square
>>> im = np.zeros((256, 256))
>>> im[64:-64, 64:-64] = 1
>>> im += 0.2 * rng.random(im.shape)
>>> # First trial with the Canny filter, with the default smoothing
>>> edges1 = feature.canny(im)
>>> # Increase the smoothing for better results
>>> edges2 = feature.canny(im, sigma=3)
"""
# Regarding masks, any point touching a masked point will have a gradient
# that is "infected" by the masked point, so it's enough to erode the
# mask by one and then mask the output. We also mask out the border points
# because who knows what lies beyond the edge of the image?
if np.issubdtype(image.dtype, np.int64) or np.issubdtype(image.dtype, np.uint64):
raise ValueError("64-bit integer images are not supported")
check_nD(image, 2)
dtype_max = dtype_limits(image, clip_negative=False)[1]
if low_threshold is None:
low_threshold = 0.1
elif use_quantiles:
if not(0.0 <= low_threshold <= 1.0):
raise ValueError("Quantile thresholds must be between 0 and 1.")
else:
low_threshold /= dtype_max
if high_threshold is None:
high_threshold = 0.2
elif use_quantiles:
if not(0.0 <= high_threshold <= 1.0):
raise ValueError("Quantile thresholds must be between 0 and 1.")
else:
high_threshold /= dtype_max
if high_threshold < low_threshold:
raise ValueError("low_threshold should be lower then high_threshold")
# Image filtering
smoothed, eroded_mask = _preprocess(image, mask, sigma, mode, cval)
# Gradient magnitude estimation
jsobel = ndi.sobel(smoothed, axis=1)
isobel = ndi.sobel(smoothed, axis=0)
magnitude = isobel * isobel
magnitude += jsobel * jsobel
np.sqrt(magnitude, out=magnitude)
if use_quantiles:
low_threshold, high_threshold = np.percentile(magnitude,
[100.0 * low_threshold,
100.0 * high_threshold])
# Non-maximum suppression
low_masked = _nonmaximum_suppression_bilinear(
isobel, jsobel, magnitude, eroded_mask, low_threshold
)
# Double thresholding and edge tracking
#
# Segment the low-mask, then only keep low-segments that have
# some high_mask component in them
#
low_mask = low_masked > 0
strel = np.ones((3, 3), bool)
labels, count = ndi.label(low_mask, strel)
if count == 0:
return low_mask
high_mask = low_mask & (low_masked >= high_threshold)
nonzero_sums = np.unique(labels[high_mask])
good_label = np.zeros((count + 1,), bool)
good_label[nonzero_sums] = True
output_mask = good_label[labels]
return output_mask
<file_sep>/skimage/io/_plugins/tifffile_plugin.py
from tifffile import imread as tifffile_imread
from tifffile import imwrite as tifffile_imwrite
__all__ = ['imread', 'imsave']
def imsave(fname, arr, **kwargs):
"""Load a tiff image to file.
Parameters
----------
fname : str or file
File name or file-like object.
arr : ndarray
The array to write.
kwargs : keyword pairs, optional
Additional keyword arguments to pass through (see ``tifffile``'s
``imwrite`` function).
Notes
-----
Provided by the tifffile library [1]_, and supports many
advanced image types including multi-page and floating-point.
This implementation will set ``photometric='RGB'`` when writing if the first
or last axis of `arr` has length 3 or 4. To override this, explicitly
pass the ``photometric`` kwarg.
This implementation will set ``planarconfig='SEPARATE'`` when writing if the
first axis of arr has length 3 or 4. To override this, explicitly
specify the ``planarconfig`` kwarg.
References
----------
.. [1] https://pypi.org/project/tifffile/
"""
if arr.shape[0] in [3, 4]:
if 'planarconfig' not in kwargs:
kwargs['planarconfig'] = 'SEPARATE'
rgb = True
else:
rgb = arr.shape[-1] in [3, 4]
if rgb and 'photometric' not in kwargs:
kwargs['photometric'] = 'RGB'
return tifffile_imwrite(fname, arr, **kwargs)
def imread(fname, **kwargs):
"""Load a tiff image from file.
Parameters
----------
fname : str or file
File name or file-like-object.
kwargs : keyword pairs, optional
Additional keyword arguments to pass through (see ``tifffile``'s
``imread`` function).
Notes
-----
Provided by the tifffile library [1]_, and supports many
advanced image types including multi-page and floating point.
References
----------
.. [1] https://pypi.org/project/tifffile/
"""
if 'img_num' in kwargs:
kwargs['key'] = kwargs.pop('img_num')
return tifffile_imread(fname, **kwargs)
<file_sep>/skimage/measure/tests/test_moments.py
import itertools
import numpy as np
import pytest
from scipy import ndimage as ndi
from skimage import draw
from skimage._shared import testing
from skimage._shared.testing import (assert_allclose, assert_almost_equal,
assert_equal)
from skimage._shared.utils import _supported_float_type
from skimage.measure import (centroid, inertia_tensor, inertia_tensor_eigvals,
moments, moments_central, moments_coords,
moments_coords_central, moments_hu,
moments_normalized)
def compare_moments(m1, m2, thresh=1e-8):
"""Compare two moments arrays.
Compares only values in the upper-left triangle of m1, m2 since
values below the diagonal exceed the specified order and are not computed
when the analytical computation is used.
Also, there the first-order central moments will be exactly zero with the
analytical calculation, but will not be zero due to limited floating point
precision when using a numerical computation. Here we just specify the
tolerance as a fraction of the maximum absolute value in the moments array.
"""
m1 = m1.copy()
m2 = m2.copy()
# make sure location of any NaN values match and then ignore the NaN values
# in the subsequent comparisons
nan_idx1 = np.where(np.isnan(m1.ravel()))[0]
nan_idx2 = np.where(np.isnan(m2.ravel()))[0]
assert len(nan_idx1) == len(nan_idx2)
assert np.all(nan_idx1 == nan_idx2)
m1[np.isnan(m1)] = 0
m2[np.isnan(m2)] = 0
max_val = np.abs(m1[m1 != 0]).max()
for orders in itertools.product(*((range(m1.shape[0]),) * m1.ndim)):
if sum(orders) > m1.shape[0] - 1:
m1[orders] = 0
m2[orders] = 0
continue
abs_diff = abs(m1[orders] - m2[orders])
rel_diff = abs_diff / max_val
assert rel_diff < thresh
@pytest.mark.parametrize('anisotropic', [False, True, None])
def test_moments(anisotropic):
image = np.zeros((20, 20), dtype=np.float64)
image[14, 14] = 1
image[15, 15] = 1
image[14, 15] = 0.5
image[15, 14] = 0.5
if anisotropic:
spacing = (1.4, 2)
else:
spacing = (1, 1)
if anisotropic is None:
m = moments(image)
else:
m = moments(image, spacing=spacing)
assert_equal(m[0, 0], 3)
assert_almost_equal(m[1, 0] / m[0, 0], 14.5 * spacing[0])
assert_almost_equal(m[0, 1] / m[0, 0], 14.5 * spacing[1])
@pytest.mark.parametrize('anisotropic', [False, True, None])
def test_moments_central(anisotropic):
image = np.zeros((20, 20), dtype=np.float64)
image[14, 14] = 1
image[15, 15] = 1
image[14, 15] = 0.5
image[15, 14] = 0.5
if anisotropic:
spacing = (2, 1)
else:
spacing = (1, 1)
if anisotropic is None:
mu = moments_central(image, (14.5, 14.5))
# check for proper centroid computation
mu_calc_centroid = moments_central(image)
else:
mu = moments_central(image, (14.5 * spacing[0], 14.5 * spacing[1]),
spacing=spacing)
# check for proper centroid computation
mu_calc_centroid = moments_central(image, spacing=spacing)
compare_moments(mu, mu_calc_centroid, thresh=1e-14)
# shift image by dx=2, dy=2
image2 = np.zeros((20, 20), dtype=np.double)
image2[16, 16] = 1
image2[17, 17] = 1
image2[16, 17] = 0.5
image2[17, 16] = 0.5
if anisotropic is None:
mu2 = moments_central(image2, (14.5 + 2, 14.5 + 2))
else:
mu2 = moments_central(
image2,
((14.5 + 2) * spacing[0], (14.5 + 2) * spacing[1]),
spacing=spacing
)
# central moments must be translation invariant
compare_moments(mu, mu2, thresh=1e-14)
def test_moments_coords():
image = np.zeros((20, 20), dtype=np.float64)
image[13:17, 13:17] = 1
mu_image = moments(image)
coords = np.array([[r, c] for r in range(13, 17)
for c in range(13, 17)], dtype=np.float64)
mu_coords = moments_coords(coords)
assert_almost_equal(mu_coords, mu_image)
@pytest.mark.parametrize('dtype', [np.float16, np.float32, np.float64])
def test_moments_coords_dtype(dtype):
image = np.zeros((20, 20), dtype=dtype)
image[13:17, 13:17] = 1
expected_dtype = _supported_float_type(dtype)
mu_image = moments(image)
assert mu_image.dtype == expected_dtype
coords = np.array([[r, c] for r in range(13, 17)
for c in range(13, 17)], dtype=dtype)
mu_coords = moments_coords(coords)
assert mu_coords.dtype == expected_dtype
assert_almost_equal(mu_coords, mu_image)
def test_moments_central_coords():
image = np.zeros((20, 20), dtype=np.float64)
image[13:17, 13:17] = 1
mu_image = moments_central(image, (14.5, 14.5))
coords = np.array([[r, c] for r in range(13, 17)
for c in range(13, 17)], dtype=np.float64)
mu_coords = moments_coords_central(coords, (14.5, 14.5))
assert_almost_equal(mu_coords, mu_image)
# ensure that center is being calculated normally
mu_coords_calc_centroid = moments_coords_central(coords)
assert_almost_equal(mu_coords_calc_centroid, mu_coords)
# shift image by dx=3 dy=3
image = np.zeros((20, 20), dtype=np.float64)
image[16:20, 16:20] = 1
mu_image = moments_central(image, (14.5, 14.5))
coords = np.array([[r, c] for r in range(16, 20)
for c in range(16, 20)], dtype=np.float64)
mu_coords = moments_coords_central(coords, (14.5, 14.5))
assert_almost_equal(mu_coords, mu_image)
def test_moments_normalized():
image = np.zeros((20, 20), dtype=np.float64)
image[13:17, 13:17] = 1
mu = moments_central(image, (14.5, 14.5))
nu = moments_normalized(mu)
# shift image by dx=-2, dy=-2 and scale non-zero extent by 0.5
image2 = np.zeros((20, 20), dtype=np.float64)
# scale amplitude by 0.7
image2[11:13, 11:13] = 0.7
mu2 = moments_central(image2, (11.5, 11.5))
nu2 = moments_normalized(mu2)
# central moments must be translation and scale invariant
assert_almost_equal(nu, nu2, decimal=1)
@pytest.mark.parametrize('anisotropic', [False, True])
def test_moments_normalized_spacing(anisotropic):
image = np.zeros((20, 20), dtype=np.double)
image[13:17, 13:17] = 1
if not anisotropic:
spacing1 = (1, 1)
spacing2 = (3, 3)
else:
spacing1 = (1, 2)
spacing2 = (2, 4)
mu = moments_central(image, spacing=spacing1)
nu = moments_normalized(mu, spacing=spacing1)
mu2 = moments_central(image, spacing=spacing2)
nu2 = moments_normalized(mu2, spacing=spacing2)
# result should be invariant to absolute scale of spacing
compare_moments(nu, nu2)
def test_moments_normalized_3d():
image = draw.ellipsoid(1, 1, 10)
mu_image = moments_central(image)
nu = moments_normalized(mu_image)
assert nu[0, 0, 2] > nu[0, 2, 0]
assert_almost_equal(nu[0, 2, 0], nu[2, 0, 0])
coords = np.where(image)
mu_coords = moments_coords_central(coords)
assert_almost_equal(mu_image, mu_coords)
@pytest.mark.parametrize('dtype', [np.uint8, np.int32, np.float32, np.float64])
@pytest.mark.parametrize('order', [1, 2, 3, 4])
@pytest.mark.parametrize('ndim', [2, 3, 4])
def test_analytical_moments_calculation(dtype, order, ndim):
if ndim == 2:
shape = (256, 256)
elif ndim == 3:
shape = (64, 64, 64)
else:
shape = (16, ) * ndim
rng = np.random.default_rng(1234)
if np.dtype(dtype).kind in 'iu':
x = rng.integers(0, 256, shape, dtype=dtype)
else:
x = rng.standard_normal(shape, dtype=dtype)
# setting center=None will use the analytical expressions
m1 = moments_central(x, center=None, order=order)
# providing explicit centroid will bypass the analytical code path
m2 = moments_central(x, center=centroid(x), order=order)
# ensure numeric and analytical central moments are close
thresh = 1e-4 if x.dtype == np.float32 else 1e-9
compare_moments(m1, m2, thresh=thresh)
def test_moments_normalized_invalid():
with testing.raises(ValueError):
moments_normalized(np.zeros((3, 3)), 3)
with testing.raises(ValueError):
moments_normalized(np.zeros((3, 3)), 4)
def test_moments_hu():
image = np.zeros((20, 20), dtype=np.float64)
image[13:15, 13:17] = 1
mu = moments_central(image, (13.5, 14.5))
nu = moments_normalized(mu)
hu = moments_hu(nu)
# shift image by dx=2, dy=3, scale by 0.5 and rotate by 90deg
image2 = np.zeros((20, 20), dtype=np.float64)
image2[11, 11:13] = 1
image2 = image2.T
mu2 = moments_central(image2, (11.5, 11))
nu2 = moments_normalized(mu2)
hu2 = moments_hu(nu2)
# central moments must be translation and scale invariant
assert_almost_equal(hu, hu2, decimal=1)
@pytest.mark.parametrize('dtype', [np.float16, np.float32, np.float64])
def test_moments_dtype(dtype):
image = np.zeros((20, 20), dtype=dtype)
image[13:15, 13:17] = 1
expected_dtype = _supported_float_type(dtype)
mu = moments_central(image, (13.5, 14.5))
assert mu.dtype == expected_dtype
nu = moments_normalized(mu)
assert nu.dtype == expected_dtype
hu = moments_hu(nu)
assert hu.dtype == expected_dtype
@pytest.mark.parametrize('dtype', [np.float16, np.float32, np.float64])
def test_centroid(dtype):
image = np.zeros((20, 20), dtype=dtype)
image[14, 14:16] = 1
image[15, 14:16] = 1/3
image_centroid = centroid(image)
if dtype == np.float16:
rtol = 1e-3
elif dtype == np.float32:
rtol = 1e-5
else:
rtol = 1e-7
assert_allclose(image_centroid, (14.25, 14.5), rtol=rtol)
@pytest.mark.parametrize('dtype', [np.float16, np.float32, np.float64])
def test_inertia_tensor_2d(dtype):
image = np.zeros((40, 40), dtype=dtype)
image[15:25, 5:35] = 1 # big horizontal rectangle (aligned with axis 1)
expected_dtype = _supported_float_type(image.dtype)
T = inertia_tensor(image)
assert T.dtype == expected_dtype
assert T[0, 0] > T[1, 1]
np.testing.assert_allclose(T[0, 1], 0)
v0, v1 = inertia_tensor_eigvals(image, T=T)
assert v0.dtype == expected_dtype
assert v1.dtype == expected_dtype
np.testing.assert_allclose(np.sqrt(v0/v1), 3, rtol=0.01, atol=0.05)
def test_inertia_tensor_3d():
image = draw.ellipsoid(10, 5, 3)
T0 = inertia_tensor(image)
eig0, V0 = np.linalg.eig(T0)
# principal axis of ellipse = eigenvector of smallest eigenvalue
v0 = V0[:, np.argmin(eig0)]
assert np.allclose(v0, [1, 0, 0]) or np.allclose(-v0, [1, 0, 0])
imrot = ndi.rotate(image.astype(float), 30, axes=(0, 1), order=1)
Tr = inertia_tensor(imrot)
eigr, Vr = np.linalg.eig(Tr)
vr = Vr[:, np.argmin(eigr)]
# Check that axis has rotated by expected amount
pi, cos, sin = np.pi, np.cos, np.sin
R = np.array([[ cos(pi/6), -sin(pi/6), 0],
[ sin(pi/6), cos(pi/6), 0],
[ 0, 0, 1]])
expected_vr = R @ v0
assert (np.allclose(vr, expected_vr, atol=1e-3, rtol=0.01) or
np.allclose(-vr, expected_vr, atol=1e-3, rtol=0.01))
def test_inertia_tensor_eigvals():
# Floating point precision problems could make a positive
# semidefinite matrix have an eigenvalue that is very slightly
# negative. Check that we have caught and fixed this problem.
image = np.array([[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]])
# mu = np.array([[3, 0, 98], [0, 14, 0], [2, 0, 98]])
eigvals = inertia_tensor_eigvals(image=image)
assert (min(eigvals) >= 0)
<file_sep>/benchmarks/benchmark_interpolation.py
# See "Writing benchmarks" in the asv docs for more information.
# https://asv.readthedocs.io/en/latest/writing_benchmarks.html
import numpy as np
from skimage import transform
class InterpolationResize:
param_names = ['new_shape', 'order', 'mode', 'dtype', 'anti_aliasing']
params = [
((500, 800), (2000, 4000), (80, 80, 80), (150, 150, 150)), # new_shape
(0, 1, 3, 5), # order
('symmetric',), # mode
(np.float64, ), # dtype
(True,), # anti_aliasing
]
"""Benchmark for filter routines in scikit-image."""
def setup(self, new_shape, order, mode, dtype, anti_aliasing):
ndim = len(new_shape)
if ndim == 2:
image = np.random.random((1000, 1000))
else:
image = np.random.random((100, 100, 100))
self.image = image.astype(dtype, copy=False)
def time_resize(self, new_shape, order, mode, dtype, anti_aliasing):
transform.resize(self.image, new_shape, order=order, mode=mode,
anti_aliasing=anti_aliasing)
def time_rescale(self, new_shape, order, mode, dtype, anti_aliasing):
scale = tuple(s2 / s1 for s2, s1 in zip(new_shape, self.image.shape))
transform.rescale(self.image, scale, order=order, mode=mode,
anti_aliasing=anti_aliasing)
def peakmem_resize(self, new_shape, order, mode, dtype, anti_aliasing):
transform.resize(self.image, new_shape, order=order, mode=mode,
anti_aliasing=anti_aliasing)
def peakmem_reference(self, *args):
"""Provide reference for memory measurement with empty benchmark.
Peakmem benchmarks measure the maximum amount of RAM used by a
function. However, this maximum also includes the memory used
during the setup routine (as of asv 0.2.1; see [1]_).
Measuring an empty peakmem function might allow us to disambiguate
between the memory used by setup and the memory used by target (see
other ``peakmem_`` functions below).
References
----------
.. [1]: https://asv.readthedocs.io/en/stable/writing_benchmarks.html#peak-memory
""" # noqa
pass
<file_sep>/doc/examples/data/plot_specific.py
"""
===============
Specific images
===============
"""
import matplotlib.pyplot as plt
import matplotlib
from skimage import data
matplotlib.rcParams["font.size"] = 18
######################################################################
#
# Stereo images
# =============
fig, axes = plt.subplots(1, 2, figsize=(8, 4))
ax = axes.ravel()
cycle_images = data.stereo_motorcycle()
ax[0].imshow(cycle_images[0])
ax[1].imshow(cycle_images[1])
fig.tight_layout()
plt.show()
######################################################################
#
# PIV images
# =============
fig, axes = plt.subplots(1, 2, figsize=(8, 4))
ax = axes.ravel()
vortex_images = data.vortex()
ax[0].imshow(vortex_images[0])
ax[1].imshow(vortex_images[1])
fig.tight_layout()
plt.show()
######################################################################
#
# Faces and non-faces dataset
# ===========================
#
# A sample of 20 over 200 images is displayed.
fig, axes = plt.subplots(4, 5, figsize=(20, 20))
ax = axes.ravel()
lfw_images = data.lfw_subset()
for i in range(20):
ax[i].imshow(lfw_images[90 + i], cmap=plt.cm.gray)
ax[i].axis("off")
fig.tight_layout()
plt.show()
######################################################################
# Thumbnail image for the gallery
# sphinx_gallery_thumbnail_number = -1
from matplotlib.offsetbox import AnchoredText
# Create a gridspec with two images in the first and 4 in the second row
fig, axd = plt.subplot_mosaic(
[["stereo", "stereo", "piv", "piv"], ["lfw0", "lfw1", "lfw2", "lfw3"]],
)
axd["stereo"].imshow(cycle_images[0])
axd["stereo"].add_artist(
AnchoredText(
"Stereo",
prop=dict(size=20),
frameon=True,
borderpad=0,
loc="upper left",
)
)
axd["piv"].imshow(vortex_images[0])
axd["piv"].add_artist(
AnchoredText(
"PIV",
prop=dict(size=20),
frameon=True,
borderpad=0,
loc="upper left",
)
)
axd["lfw0"].imshow(lfw_images[91], cmap="gray")
axd["lfw1"].imshow(lfw_images[92], cmap="gray")
axd["lfw2"].imshow(lfw_images[93], cmap="gray")
axd["lfw3"].imshow(lfw_images[94], cmap="gray")
for ax in axd.values():
ax.axis("off")
fig.tight_layout()
plt.show()
<file_sep>/tools/generate_requirements.py
#!/usr/bin/env python
"""Generate requirements/*.txt files from pyproject.toml."""
import sys
from pathlib import Path
try: # standard module since Python 3.11
import tomllib as toml
except ImportError:
try: # available for older Python via pip
import tomli as toml
except ImportError:
sys.exit("Please install `tomli` first: `pip install tomli`")
script_pth = Path(__file__)
repo_dir = script_pth.parent.parent
script_relpth = script_pth.relative_to(repo_dir)
header = [
f"# Generated via {script_relpth.as_posix()} and pre-commit hook.",
"# Do not edit this file; modify pyproject.toml instead.",
]
def generate_requirement_file(name: str, req_list: list[str]) -> None:
req_fname = repo_dir / "requirements" / f"{name}.txt"
req_fname.write_text("\n".join(header + req_list) + "\n")
def main() -> None:
pyproject = toml.loads((repo_dir / "pyproject.toml").read_text())
generate_requirement_file("default", pyproject["project"]["dependencies"])
for key, opt_list in pyproject["project"]["optional-dependencies"].items():
generate_requirement_file(key, opt_list)
if __name__ == "__main__":
main()
<file_sep>/benchmarks/benchmark_exposure.py
# See "Writing benchmarks" in the asv docs for more information.
# https://asv.readthedocs.io/en/latest/writing_benchmarks.html
import math
import numpy as np
from skimage import data, img_as_float
from skimage.transform import rescale
from skimage import exposure
class ExposureSuite:
"""Benchmark for exposure routines in scikit-image."""
def setup(self):
self.image_u8 = data.moon()
self.image = img_as_float(self.image_u8)
self.image = rescale(self.image, 2.0, anti_aliasing=False)
# for Contrast stretching
self.p2, self.p98 = np.percentile(self.image, (2, 98))
def time_equalize_hist(self):
# Run 10x to average out performance
# note that this is not needed as asv does this kind of averaging by
# default, but this loop remains here to maintain benchmark continuity
for i in range(10):
exposure.equalize_hist(self.image)
def time_equalize_adapthist(self):
exposure.equalize_adapthist(self.image, clip_limit=0.03)
def time_rescale_intensity(self):
exposure.rescale_intensity(self.image,
in_range=(self.p2, self.p98))
def time_histogram(self):
# Running it 10 times to achieve significant performance time.
for i in range(10):
exposure.histogram(self.image)
def time_gamma_adjust_u8(self):
for i in range(10):
_ = exposure.adjust_gamma(self.image_u8)
class MatchHistogramsSuite:
param_names = ["shape", "dtype", "multichannel"]
params = [
((64, 64), (256, 256), (1024, 1024)),
(np.uint8, np.uint32, np.float32, np.float64),
(False, True),
]
def _tile_to_shape(self, image, shape, multichannel):
n_tile = tuple(math.ceil(s / n) for s, n in zip(shape, image.shape))
if multichannel:
image = image[..., np.newaxis]
n_tile = n_tile + (3,)
image = np.tile(image, n_tile)
sl = tuple(slice(s) for s in shape)
return image[sl]
"""Benchmark for exposure routines in scikit-image."""
def setup(self, shape, dtype, multichannel):
self.image = data.moon().astype(dtype, copy=False)
self.reference = data.camera().astype(dtype, copy=False)
self.image = self._tile_to_shape(self.image, shape, multichannel)
self.reference = self._tile_to_shape(self.reference, shape,
multichannel)
channel_axis = -1 if multichannel else None
self.kwargs = {'channel_axis': channel_axis}
def time_match_histogram(self, *args):
exposure.match_histograms(self.image, self.reference, **self.kwargs)
def peakmem_reference(self, *args):
"""Provide reference for memory measurement with empty benchmark.
Peakmem benchmarks measure the maximum amount of RAM used by a
function. However, this maximum also includes the memory used
during the setup routine (as of asv 0.2.1; see [1]_).
Measuring an empty peakmem function might allow us to disambiguate
between the memory used by setup and the memory used by target (see
other ``peakmem_`` functions below).
References
----------
.. [1]: https://asv.readthedocs.io/en/stable/writing_benchmarks.html#peak-memory # noqa
"""
pass
def peakmem_match_histogram(self, *args):
exposure.match_histograms(self.image, self.reference, **self.kwargs)
<file_sep>/skimage/io/tests/test_simpleitk.py
import numpy as np
import pytest
from skimage.io import imread, imsave, use_plugin, reset_plugins, plugin_order
from skimage._shared import testing
pytest.importorskip('SimpleITK')
@pytest.fixture(autouse=True)
def use_simpleitk_plugin():
"""Ensure that SimpleITK plugin is used."""
use_plugin('simpleitk')
yield
reset_plugins()
def test_prefered_plugin():
order = plugin_order()
assert order["imread"][0] == "simpleitk"
assert order["imsave"][0] == "simpleitk"
assert order["imread_collection"][0] == "simpleitk"
def test_imread_as_gray():
img = imread(testing.fetch('data/color.png'), as_gray=True)
assert img.ndim == 2
assert img.dtype == np.float64
img = imread(testing.fetch('data/camera.png'), as_gray=True)
# check that conversion does not happen for a gray image
assert np.sctype2char(img.dtype) in np.typecodes['AllInteger']
def test_bilevel():
expected = np.zeros((10, 10))
expected[::2] = 255
img = imread(testing.fetch('data/checker_bilevel.png'))
np.testing.assert_array_equal(img, expected)
def test_imread_truncated_jpg():
with pytest.raises(RuntimeError):
imread(testing.fetch('data/truncated.jpg'))
def test_imread_uint16():
expected = np.load(testing.fetch('data/chessboard_GRAY_U8.npy'))
img = imread(testing.fetch('data/chessboard_GRAY_U16.tif'))
assert np.issubdtype(img.dtype, np.uint16)
np.testing.assert_array_almost_equal(img, expected)
def test_imread_uint16_big_endian():
expected = np.load(testing.fetch('data/chessboard_GRAY_U8.npy'))
img = imread(testing.fetch('data/chessboard_GRAY_U16B.tif'))
np.testing.assert_array_almost_equal(img, expected)
@pytest.mark.parametrize("shape", [(10, 10), (10, 10, 3), (10, 10, 4)])
@pytest.mark.parametrize("dtype", [np.uint8, np.uint16, np.float32, np.float64])
def test_imsave_roundtrip(shape, dtype, tmp_path):
if np.issubdtype(dtype, np.floating):
info_func = np.finfo
else:
info_func = np.iinfo
expected = np.linspace(
info_func(dtype).min, info_func(dtype).max,
endpoint=True,
num=np.prod(shape),
dtype=dtype
)
expected = expected.reshape(shape)
file_path = tmp_path / "roundtrip.mha"
imsave(file_path, expected)
actual = imread(file_path)
np.testing.assert_array_almost_equal(actual, expected)
<file_sep>/doc/examples/applications/plot_fluorescence_nuclear_envelope.py
"""
======================================================
Measure fluorescence intensity at the nuclear envelope
======================================================
This example reproduces a well-established workflow in bioimage data analysis
for measuring the fluorescence intensity localized to the nuclear envelope, in
a time sequence of cell images (each with two channels and two spatial
dimensions) which shows a process of protein re-localization from the
cytoplasmic area to the nuclear envelope. This biological application was
first presented by <NAME> and collaborators in [1]_; it was used in a
textbook by K<NAME> [2]_ as well as in other works ([3]_, [4]_).
In other words, we port this workflow from ImageJ Macro to Python with
scikit-image.
.. [1] <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME> (2015)
"Live imaging and modeling of inner nuclear membrane targeting reveals
its molecular requirements in mammalian cells" J Cell Biol
209(5):705–720. ISSN: 0021-9525.
:DOI:`10.1083/jcb.201409133`
.. [2] <NAME> (2020) "Measurements of Intensity Dynamics at the Periphery of
the Nucleus" in: <NAME>, Sladoje N (eds) Bioimage Data Analysis
Workflows. Learning Materials in Biosciences. Springer, Cham.
:DOI:`10.1007/978-3-030-22386-1_2`
.. [3] <NAME> (2020) "ImageJ/Fiji Macro Language" NEUBIAS Academy Online
Course: https://www.youtube.com/watch?v=o8tfkdcd3DA
.. [4] <NAME> and <NAME> (2020) "GPU-accelerating ImageJ Macro image
processing workflows using CLIJ" https://arxiv.org/abs/2008.11799
"""
import matplotlib.pyplot as plt
import numpy as np
import plotly.io
import plotly.express as px
from scipy import ndimage as ndi
from skimage import (
filters, measure, morphology, segmentation
)
from skimage.data import protein_transport
#####################################################################
# We start with a single cell/nucleus to construct the workflow.
image_sequence = protein_transport()
print(f'shape: {image_sequence.shape}')
#####################################################################
# The dataset is a 2D image stack with 15 frames (time points) and 2 channels.
vmin, vmax = 0, image_sequence.max()
fig = px.imshow(
image_sequence,
facet_col=1,
animation_frame=0,
zmin=vmin,
zmax=vmax,
binary_string=True,
labels={'animation_frame': 'time point', 'facet_col': 'channel'}
)
plotly.io.show(fig)
#####################################################################
# To begin with, let us consider the first channel of the first image (step
# ``a)`` in the figure below).
image_t_0_channel_0 = image_sequence[0, 0, :, :]
#####################################################################
# Segment the nucleus rim
# =======================
# Let us apply a Gaussian low-pass filter to this image in order to smooth it
# (step ``b)``).
# Next, we segment the nuclei, finding the threshold between the background
# and foreground with Otsu's method: We get a binary image (step ``c)``). We
# then fill the holes in the objects (step ``c-1)``).
smooth = filters.gaussian(image_t_0_channel_0, sigma=1.5)
thresh_value = filters.threshold_otsu(smooth)
thresh = smooth > thresh_value
fill = ndi.binary_fill_holes(thresh)
#####################################################################
# Following the original workflow, let us remove objects which touch the image
# border (step ``c-2)``). Here, we can see that part of another nucleus was
# touching the bottom right-hand corner.
clear = segmentation.clear_border(fill)
clear.dtype
#####################################################################
# We compute both the morphological dilation of this binary image
# (step ``d)``) and its morphological erosion (step ``e)``).
dilate = morphology.binary_dilation(clear)
erode = morphology.binary_erosion(clear)
#####################################################################
# Finally, we subtract the eroded from the dilated to get the nucleus rim
# (step ``f)``). This is equivalent to selecting the pixels which are in
# ``dilate``, but not in ``erode``:
mask = np.logical_and(dilate, ~erode)
#####################################################################
# Let us visualize these processing steps in a sequence of subplots.
fig, ax = plt.subplots(2, 4, figsize=(12, 6), sharey=True)
ax[0, 0].imshow(image_t_0_channel_0, cmap=plt.cm.gray)
ax[0, 0].set_title('a) Raw')
ax[0, 1].imshow(smooth, cmap=plt.cm.gray)
ax[0, 1].set_title('b) Blur')
ax[0, 2].imshow(thresh, cmap=plt.cm.gray)
ax[0, 2].set_title('c) Threshold')
ax[0, 3].imshow(fill, cmap=plt.cm.gray)
ax[0, 3].set_title('c-1) Fill in')
ax[1, 0].imshow(clear, cmap=plt.cm.gray)
ax[1, 0].set_title('c-2) Keep one nucleus')
ax[1, 1].imshow(dilate, cmap=plt.cm.gray)
ax[1, 1].set_title('d) Dilate')
ax[1, 2].imshow(erode, cmap=plt.cm.gray)
ax[1, 2].set_title('e) Erode')
ax[1, 3].imshow(mask, cmap=plt.cm.gray)
ax[1, 3].set_title('f) Nucleus Rim')
for a in ax.ravel():
a.set_axis_off()
fig.tight_layout()
#####################################################################
# Apply the segmented rim as a mask
# =================================
# Now that we have segmented the nuclear membrane in the first channel, we use
# it as a mask to measure the intensity in the second channel.
image_t_0_channel_1 = image_sequence[0, 1, :, :]
selection = np.where(mask, image_t_0_channel_1, 0)
fig, (ax0, ax1) = plt.subplots(1, 2, figsize=(12, 6), sharey=True)
ax0.imshow(image_t_0_channel_1)
ax0.set_title('Second channel (raw)')
ax0.set_axis_off()
ax1.imshow(selection)
ax1.set_title('Selection')
ax1.set_axis_off()
fig.tight_layout()
#####################################################################
# Measure the total intensity
# ===========================
# The mean intensity is readily available as a region property in a labeled
# image.
props = measure.regionprops_table(
mask.astype(np.uint8),
intensity_image=image_t_0_channel_1,
properties=('label', 'area', 'intensity_mean')
)
#####################################################################
# We may want to check that the value for the total intensity
selection.sum()
#####################################################################
# can be recovered from:
props['area'] * props['intensity_mean']
#####################################################################
# Process the entire image sequence
# =================================
# Instead of iterating the workflow for each time point, we process the
# multidimensional dataset directly (except for the thresholding step).
# Indeed, most scikit-image functions support nD images.
n_z = image_sequence.shape[0] # number of frames
smooth_seq = filters.gaussian(image_sequence[:, 0, :, :], sigma=(0, 1.5, 1.5))
thresh_values = [filters.threshold_otsu(s) for s in smooth_seq[:]]
thresh_seq = [smooth_seq[k, ...] > val for k, val in enumerate(thresh_values)]
#####################################################################
# Alternatively, we could compute ``thresh_values`` without using a list
# comprehension, by reshaping ``smooth_seq`` to make it 2D (where the first
# dimension still corresponds to time points, but the second and last
# dimension now contains all pixel values), and applying the thresholding
# function on the image sequence along its second axis:
#
# .. code-block:: python
#
# thresh_values = np.apply_along_axis(filters.threshold_otsu,
# axis=1,
# arr=smooth_seq.reshape(n_z, -1))
#
# We use the following flat structuring element for morphological
# computations (``np.newaxis`` is used to prepend an axis of size 1 for time):
footprint = ndi.generate_binary_structure(2, 1)[np.newaxis, ...]
footprint
#####################################################################
# This way, each frame is processed independently (pixels from consecutive
# frames are never spatial neighbors).
fill_seq = ndi.binary_fill_holes(thresh_seq, structure=footprint)
#####################################################################
# When clearing objects which touch the image border, we want to make sure
# that the bottom (first) and top (last) frames are not considered as borders.
# In this case, the only relevant border is the edge at the greatest (x, y)
# values. This can be seen in 3D by running the following code:
#
# .. code-block:: python
#
# import plotly.graph_objects as go
#
# sample = fill_seq
# (n_Z, n_Y, n_X) = sample.shape
# Z, Y, X = np.mgrid[:n_Z, :n_Y, :n_X]
#
# fig = go.Figure(
# data=go.Volume(
# x=X.flatten(),
# y=Y.flatten(),
# z=Z.flatten(),
# value=sample.flatten(),
# opacity=0.5,
# slices_z=dict(show=True, locations=[n_z // 2])
# )
# )
# fig.show()
border_mask = np.ones_like(fill_seq)
border_mask[n_z // 2, -1, -1] = False
clear_seq = segmentation.clear_border(fill_seq, mask=border_mask)
dilate_seq = morphology.binary_dilation(clear_seq, footprint=footprint)
erode_seq = morphology.binary_erosion(clear_seq, footprint=footprint)
mask_sequence = np.logical_and(dilate_seq, ~erode_seq)
#####################################################################
# Let us give each mask (corresponding to each time point) a different label,
# running from 1 to 15. We use ``np.min_scalar_type`` to determine the
# minimum-size integer dtype needed to represent the number of time points:
label_dtype = np.min_scalar_type(n_z)
mask_sequence = mask_sequence.astype(label_dtype)
labels = np.arange(1, n_z + 1, dtype=label_dtype)
mask_sequence *= labels[:, np.newaxis, np.newaxis]
#####################################################################
# Let us compute the region properties of interest for all these labeled
# regions.
props = measure.regionprops_table(
mask_sequence,
intensity_image=image_sequence[:, 1, :, :],
properties=('label', 'area', 'intensity_mean')
)
np.testing.assert_array_equal(props['label'], np.arange(n_z) + 1)
fluorescence_change = [props['area'][i] * props['intensity_mean'][i]
for i in range(n_z)]
fluorescence_change /= fluorescence_change[0] # normalization
fig, ax = plt.subplots()
ax.plot(fluorescence_change, 'rs')
ax.grid()
ax.set_xlabel('Time point')
ax.set_ylabel('Normalized total intensity')
ax.set_title('Change in fluorescence intensity at the nuclear envelope')
fig.tight_layout()
plt.show()
#####################################################################
# Reassuringly, we find the expected result: The total fluorescence
# intensity at the nuclear envelope increases 1.3-fold in the initial five
# time points, and then becomes roughly constant.
<file_sep>/doc/examples/filters/plot_butterworth.py
"""
===================
Butterworth Filters
===================
The Butterworth filter is implemented in the frequency domain and is designed
to have no passband or stopband ripple. It can be used in either a lowpass or
highpass variant. The ``cutoff_frequency_ratio`` parameter is used to set the
cutoff frequency as a fraction of the sampling frequency. Given that the
Nyquist frequency is half the sampling frequency, this means that this
parameter should be a positive floating point value < 0.5. The ``order`` of the
filter can be adjusted to control the transition width, with higher values
leading to a sharper transition between the passband and stopband.
"""
#####################################################################
# Butterworth filtering example
# =============================
# Here we define a `get_filtered` helper function to repeat lowpass and
# highpass filtering at a specified series of cutoff frequencies.
import matplotlib.pyplot as plt
from skimage import data, filters
image = data.camera()
# cutoff frequencies as a fraction of the maximum frequency
cutoffs = [.02, .08, .16]
def get_filtered(image, cutoffs, squared_butterworth=True, order=3.0, npad=0):
"""Lowpass and highpass butterworth filtering at all specified cutoffs.
Parameters
----------
image : ndarray
The image to be filtered.
cutoffs : sequence of int
Both lowpass and highpass filtering will be performed for each cutoff
frequency in `cutoffs`.
squared_butterworth : bool, optional
Whether the traditional Butterworth filter or its square is used.
order : float, optional
The order of the Butterworth filter
Returns
-------
lowpass_filtered : list of ndarray
List of images lowpass filtered at the frequencies in `cutoffs`.
highpass_filtered : list of ndarray
List of images highpass filtered at the frequencies in `cutoffs`.
"""
lowpass_filtered = []
highpass_filtered = []
for cutoff in cutoffs:
lowpass_filtered.append(
filters.butterworth(
image,
cutoff_frequency_ratio=cutoff,
order=order,
high_pass=False,
squared_butterworth=squared_butterworth,
npad=npad,
)
)
highpass_filtered.append(
filters.butterworth(
image,
cutoff_frequency_ratio=cutoff,
order=order,
high_pass=True,
squared_butterworth=squared_butterworth,
npad=npad,
)
)
return lowpass_filtered, highpass_filtered
def plot_filtered(lowpass_filtered, highpass_filtered, cutoffs):
"""Generate plots for paired lists of lowpass and highpass images."""
fig, axes = plt.subplots(2, 1 + len(cutoffs), figsize=(12, 8))
fontdict = dict(fontsize=14, fontweight='bold')
axes[0, 0].imshow(image, cmap='gray')
axes[0, 0].set_title('original', fontdict=fontdict)
axes[1, 0].set_axis_off()
for i, c in enumerate(cutoffs):
axes[0, i + 1].imshow(lowpass_filtered[i], cmap='gray')
axes[0, i + 1].set_title(f'lowpass, c={c}', fontdict=fontdict)
axes[1, i + 1].imshow(highpass_filtered[i], cmap='gray')
axes[1, i + 1].set_title(f'highpass, c={c}', fontdict=fontdict)
for ax in axes.ravel():
ax.set_xticks([])
ax.set_yticks([])
plt.tight_layout()
return fig, axes
# Perform filtering with the (squared) Butterworth filter at a range of
# cutoffs.
lowpasses, highpasses = get_filtered(image, cutoffs, squared_butterworth=True)
fig, axes = plot_filtered(lowpasses, highpasses, cutoffs)
titledict = dict(fontsize=18, fontweight='bold')
fig.text(0.5, 0.95, '(squared) Butterworth filtering (order=3.0, npad=0)',
fontdict=titledict, horizontalalignment='center')
#####################################################################
# Avoiding boundary artifacts
# ===========================
#
# It can be seen in the images above that there are artifacts near the edge of
# the images (particularly for the smaller cutoff values). This is due to the
# periodic nature of the DFT and can be reduced by applying some amount of
# padding to the edges prior to filtering so that there are not sharp eges in
# the periodic extension of the image. This can be done via the ``npad``
# argument to ``butterworth``.
#
# Note that with padding, the undesired shading at the image edges is
# substantially reduced.
lowpasses, highpasses = get_filtered(image, cutoffs, squared_butterworth=True,
npad=32)
fig, axes = plot_filtered(lowpasses, highpasses, cutoffs)
fig.text(0.5, 0.95, '(squared) Butterworth filtering (order=3.0, npad=32)',
fontdict=titledict, horizontalalignment='center')
#####################################################################
# True Butterworth filter
# =======================
#
# To use the traditional signal processing definition of the Butterworth filter,
# set ``squared_butterworth=False``. This variant has an amplitude profile in
# the frequency domain that is the square root of the default case. This causes
# the transition from the passband to the stopband to be more gradual at any
# given `order`. This can be seen in the following images which appear a bit
# sharper in the lowpass case than their squared Butterworth counterparts
# above.
lowpasses, highpasses = get_filtered(image, cutoffs, squared_butterworth=False,
npad=32)
fig, axes = plot_filtered(lowpasses, highpasses, cutoffs)
fig.text(0.5, 0.95, 'Butterworth filtering (order=3.0, npad=32)',
fontdict=titledict, horizontalalignment='center')
plt.show()
<file_sep>/doc/source/release_notes/release_0.20.rst
scikit-image 0.20.0 release notes
=================================
scikit-image is an image processing toolbox built on SciPy that
includes algorithms for segmentation, geometric transformations, color
space manipulation, analysis, filtering, morphology, feature
detection, and more.
For more information, examples, and documentation, please visit our website:
https://scikit-image.org
With this release, many of the functions in ``skimage.measure`` now support
anisotropic images with different voxel spacings.
Many performance improvements were made, such as support for footprint
decomposition in ``skimage.morphology``
Four new gallery examples were added to the documentation, including
the new interactive example "Track solidification of a metallic
alloy".
This release completes the transition to a more flexible
``channel_axis`` parameter for indicating multi-channel images, and
includes several other deprecations that make the API more consistent and
expressive.
Finally, in preparation for the removal of `distutils` in the upcoming
Python 3.12 release, we replaced our build system with `meson` and a
static `pyproject.toml` specification.
This release supports Python 3.8–3.11.
New features and improvements
-----------------------------
- Support footprint decomposition to several footprint generating and consuming functions in ``skimage.morphology``.
By decomposing a footprint into several smaller ones, morphological operations can potentially be sped up.
The decomposed footprint can be generated with the new ``decomposition`` parameter of the functions ``rectangle``, ``diamond``, ``disk``, ``cube``, ``octahedron``, ``ball``, and ``octagon`` in ``skimage.morphology``.
The ``footprint`` parameter of the functions ``binary_erosion``, ``binary_dilation``, ``binary_opening``, ``binary_closing``, ``erosion``, ``dilation``, ``opening``, ``closing``, ``white_tophat``, and ``black_tophat`` in ``skimage.morphology`` now accepts a sequence of 2-element tuples ``(footprint_i, num_iter_i)`` where each entry, ``i``, of the sequence contains a footprint and the number of times it should be iteratively applied. This is the form produced by the footprint decompositions mentioned above
(`#5482 <https://github.com/scikit-image/scikit-image/pull/5482>`_, `#6151 <https://github.com/scikit-image/scikit-image/pull/6151>`_).
- Support anisotropic images with different voxel spacings.
Spacings can be defined with the new parameter ``spacing`` of the following functions in ``skimage.measure``: ``regionprops``, ``regionprops_table``, ``moments``, ``moments_central``, ``moments_normalized``, ``centroid``, ``inertia_tensor``, and ``inertia_tensor_eigvals``.
Voxel spacing is taken into account for the following existing properties in ``skimage.measure.regionprops``: ``area``, ``area_bbox``, ``centroid``, ``area_convex``, ``extent``, ``feret_diameter_max``, ``area_filled``, ``inertia_tensor``, ``moments``, ``moments_central``, ``moments_hu``, ``moments_normalized``, ``perimeter``, ``perimeter_crofton``, ``solidity``, ``moments_weighted_central``, and ``moments_weighted_hu``.
The new properties ``num_pixels`` and ``coords_scaled`` are available as well.
See the respective docstrings for more details
(`#6296 <https://github.com/scikit-image/scikit-image/pull/6296>`_).
- Add isotropic binary morphological operators ``isotropic_closing``, ``isotropic_dilation``, ``isotropic_erosion``, and ``isotropic_opening`` in ``skimage.morphology``.
These functions return the same results as their non-isotropic counterparts but perform faster for large circular structuring elements
(`#6492 <https://github.com/scikit-image/scikit-image/pull/6492>`_).
- Add new colocalization metrics ``pearson_corr_coeff``, ``manders_coloc_coeff``, ``manders_overlap_coeff`` and ``intersection_coeff`` to ``skimage.measure``
(`#6189 <https://github.com/scikit-image/scikit-image/pull/6189>`_).
- Support the Modified Hausdorff Distance (MHD) metric in ``skimage.metrics.hausdorff_distance`` via the new parameter ``method``.
The MHD can be more robust against outliers than the directed Hausdorff Distance (HD)
(`#5581 <https://github.com/scikit-image/scikit-image/pull/5581>`_).
- Add two datasets ``skimage.data.protein_transport`` and ``skimage.data.nickel_solidification``
(`#6087 <https://github.com/scikit-image/scikit-image/pull/6087>`_).
- Add new parameter ``use_gaussian_derivatives`` to ``skimage.feature.hessian_matrix`` which allows the computation of the Hessian matrix by convolving with Gaussian derivatives
(`#6149 <https://github.com/scikit-image/scikit-image/pull/6149>`_).
- Add new parameters ``squared_butterworth`` and ``npad`` to ``skimage.filters.butterworth``, which support traditional or squared filtering and edge padding, respectively
(`#6251 <https://github.com/scikit-image/scikit-image/pull/6251>`_).
- Support construction of a ``skimage.io.ImageCollection`` from a ``load_pattern`` with an arbitrary sequence as long as a matching ``load_func`` is provided
(`#6276 <https://github.com/scikit-image/scikit-image/pull/6276>`_).
- Add new parameter ``alpha`` to ``skimage.metrics.adapted_rand_error`` allowing control over the weight given to precision and recall
(`#6472 <https://github.com/scikit-image/scikit-image/pull/6472>`_).
- Add new parameter ``binarize`` to ``skimage.measure.grid_points_in_poly`` to optionally return labels that tell whether a pixel is inside, outside, or on the border of the polygon
(`#6515 <https://github.com/scikit-image/scikit-image/pull/6515>`_).
- Add new parameter ``include_borders`` to ``skimage.measure.convex_hull_image`` to optionally exclude vertices or edges from the final hull mask
(`#6515 <https://github.com/scikit-image/scikit-image/pull/6515>`_).
- Add new parameter ``offsets`` to ``skimage.measure.regionprops`` that optionally allows specifying the coordinates of the origin and affects the properties ``coords_scaled`` and ``coords``
(`#3706 <https://github.com/scikit-image/scikit-image/pull/3706>`_).
- Add new parameter ``disambiguate`` to ``skimage.registration.phase_cross_correlation`` to optionally disambiguate periodic shifts
(`#6617 <https://github.com/scikit-image/scikit-image/pull/6617>`_).
- Support n-dimensional images in ``skimage.filters.farid`` (Farid & Simoncelli filter)
(`#6257 <https://github.com/scikit-image/scikit-image/pull/6257>`_).
- Support n-dimensional images in ``skimage.restoration.wiener``
(`#6454 <https://github.com/scikit-image/scikit-image/pull/6454>`_).
- Support three dimensions for the properties ``rotation`` and ``translation`` in ``skimage.transform.EuclideanTransform`` as well as for ``skimage.transform.SimilarityTransform.scale``
(`#6367 <https://github.com/scikit-image/scikit-image/pull/6367>`_).
- Allow footprints with non-adjacent pixels as neighbors in ``skimage.morphology.flood_fill``
(`#6236 <https://github.com/scikit-image/scikit-image/pull/6236>`_).
- Support array-likes consistently in ``AffineTransform``, ``EssentialMatrixTransform``, ``EuclideanTransform``, ``FundamentalMatrixTransform``, ``GeometricTransform``, ``PiecewiseAffineTransform``, ``PolynomialTransform``, ``ProjectiveTransform``, ``SimilarityTransform``, ``estimate_transform``, and ``matrix_transform`` in ``skimage.transform``
(`#6270 <https://github.com/scikit-image/scikit-image/pull/6270>`_).
Performance
^^^^^^^^^^^
- Improve performance (~2x speedup) of ``skimage.feature.canny`` by porting a part of its implementation to Cython
(`#6387 <https://github.com/scikit-image/scikit-image/pull/6387>`_).
- Improve performance (~2x speedup) of ``skimage.feature.hessian_matrix_eigvals`` and 2D ``skimage.feature.structure_tensor_eigenvalues``
(`#6441 <https://github.com/scikit-image/scikit-image/pull/6441>`_).
- Improve performance of ``skimage.measure.moments_central`` by avoiding redundant computations
(`#6188 <https://github.com/scikit-image/scikit-image/pull/6188>`_).
- Reduce import time of ``skimage.io`` by loading the matplotlib plugin only when required
(`#6550 <https://github.com/scikit-image/scikit-image/pull/6550>`_).
- Incorporate RANSAC improvements from scikit-learn into ``skimage.measure.ransac`` which decrease the number of iterations
(`#6046 <https://github.com/scikit-image/scikit-image/pull/6046>`_).
- Improve histogram matching performance on unsigned integer data with ``skimage.exposure.match_histograms``.
(`#6209 <https://github.com/scikit-image/scikit-image/pull/6209>`_, `#6354 <https://github.com/scikit-image/scikit-image/pull/6354>`_).
- Reduce memory consumption of the ridge filters ``meijering``, ``sato``, ``frangi``, and ``hessian`` in ``skimage.filters``
(`#6509 <https://github.com/scikit-image/scikit-image/pull/6509>`_).
- Reduce memory consumption of ``blob_dog``, ``blob_log``, and ``blob_doh`` in ``skimage.feature``
(`#6597 <https://github.com/scikit-image/scikit-image/pull/6597>`_).
- Use minimal required unsigned integer size internally in ``skimage.morphology.reconstruction`` which allows to operate the function with higher precision or on larger arrays.
Previously, int32 was used.
(`#6342 <https://github.com/scikit-image/scikit-image/pull/6342>`_).
- Use minimal required unsigned integer size in ``skimage.filters.rank_order`` which allows to operate the function with higher precision or on larger arrays.
Previously, the returned ``labels`` and ``original_values`` were always of type uint32.
(`#6342 <https://github.com/scikit-image/scikit-image/pull/6342>`_).
Changes and new deprecations
----------------------------
- Set Python 3.8 as the minimal supported version
(`#6679 <https://github.com/scikit-image/scikit-image/pull/6679>`_).
- Rewrite ``skimage.filters.meijering``, ``skimage.filters.sato``,
``skimage.filters.frangi``, and ``skimage.filters.hessian`` to match the published algorithms more closely.
This change is backward incompatible and will lead to different output values compared to the previous implementation.
The Hessian matrix calculation is now done more accurately.
The filters will now be correctly set to zero whenever one of the Hessian eigenvalues has a sign which is incompatible with a ridge of the desired polarity.
The gamma constant of the Frangi filter is now set adaptively based on the maximum Hessian norm
(`#6446 <https://github.com/scikit-image/scikit-image/pull/6446>`_).
- Move functions in ``skimage.future.graph`` to ``skimage.graph``. This affects ``cut_threshold``, ``cut_normalized``, ``merge_hierarchical``, ``rag_mean_color``, ``RAG``, ``show_rag``, and ``rag_boundary``
(`#6674 <https://github.com/scikit-image/scikit-image/pull/6674>`_).
- Return ``False`` in ``skimage.measure.LineModelND.estimate`` instead of raising an error if the model is under-determined
(`#6453 <https://github.com/scikit-image/scikit-image/pull/6453>`_).
- Return ``False`` in ``skimage.measure.CircleModel.estimate`` instead of warning if the model is under-determined
(`#6453 <https://github.com/scikit-image/scikit-image/pull/6453>`_).
- Rename ``skimage.filters.inverse`` to ``skimage.filters.inverse_filter``.
``skimage.filters.inverse`` is deprecated and will be removed in the next release
(`#6418 <https://github.com/scikit-image/scikit-image/pull/6418>`_, `#6701 <https://github.com/scikit-image/scikit-image/pull/6701>`_).
- Update minimal supported dependencies to ``numpy>=1.20``
(`#6565 <https://github.com/scikit-image/scikit-image/pull/6565>`_).
- Update minimal supported dependencies to ``scipy>=1.8``
(`#6564 <https://github.com/scikit-image/scikit-image/pull/6564>`_).
- Update minimal supported dependencies to ``networkx>=2.8``
(`#6564 <https://github.com/scikit-image/scikit-image/pull/6564>`_).
- Update minimal supported dependency to ``pillow>=9.0.1``
(`#6402 <https://github.com/scikit-image/scikit-image/pull/6402>`_).
- Update minimal supported dependency to ``setuptools 67``
(`#6754 <https://github.com/scikit-image/scikit-image/pull/6754>`_).
- Update optional, minimal supported dependency to ``matplotlib>=3.3``
(`#6383 <https://github.com/scikit-image/scikit-image/pull/6383>`_).
- Warn for non-integer image inputs to ``skimage.feature.local_binary_pattern``.
Applying the function to floating-point images may give unexpected results when small numerical differences between adjacent pixels are present
(`#6272 <https://github.com/scikit-image/scikit-image/pull/6272>`_).
- Warn if ``skimage.registration.phase_cross_correlation`` returns only the shift vector.
Starting with the next release this function will always return a tuple of three (shift vector, error, phase difference).
Use ``return_error="always"`` to silence this warning and switch to this new behavior
(`#6543 <https://github.com/scikit-image/scikit-image/pull/6543>`_).
- Warn in ``skimage.metrics.structural_similarity``, if ``data_range`` is not specified in case of floating point data
(`#6612 <https://github.com/scikit-image/scikit-image/pull/6612>`_).
- Automatic detection of the color channel is deprecated in ``skimage.filters.gaussian`` and a warning is emitted if the parameter ``channel_axis`` is not set explicitly
(`#6583 <https://github.com/scikit-image/scikit-image/pull/6583>`_).
Completed deprecations
----------------------
- Remove ``skimage.viewer`` which was scheduled for removal in the postponed version 1.0
(`#6160 <https://github.com/scikit-image/scikit-image/pull/6160>`_).
- Remove deprecated parameter ``indices`` from ``skimage.feature.peak_local_max``
(`#6161 <https://github.com/scikit-image/scikit-image/pull/6161>`_).
- Remove ``skimage.feature.structure_tensor_eigvals`` (it was replaced by ``skimage.feature.structure_tensor_eigenvalues``) and change the default parameter value in ``skimage.feature.structure_tensor`` to ``order="rc"``
(`#6162 <https://github.com/scikit-image/scikit-image/pull/6162>`_).
- Remove deprecated parameter ``array`` in favor of ``image`` from ``skimage.measure.find_contours``
(`#6163 <https://github.com/scikit-image/scikit-image/pull/6163>`_).
- Remove deprecated Qt IO plugin and the ``skivi`` console script
(`#6164 <https://github.com/scikit-image/scikit-image/pull/6164>`_).
- Remove deprecated parameter value ``method='_lorensen'`` in ``skimage.measure.marching_cubes``
(`#6230 <https://github.com/scikit-image/scikit-image/pull/6230>`_).
- Remove deprecated parameter ``multichannel``; use ``channel_axis`` instead.
This affects ``skimage.draw.random_shapes``, ``skimage.exposure.match_histograms``, ``skimage.feature.multiscale_basic_features``, ``skimage.feature.hog``, ``skimage.feature.difference_of_gaussians``, ``skimage.filters.unsharp_mask``, and ``skimage.metrics.structural_similarity``.
In ``skimage.restoration``, this affects ``cycle_spin``, ``denoise_bilateral``, ``denoise_tv_bregman``, ``denoise_tv_chambolle``, ``denoise_wavelet``, ``estimate_sigma``, ``inpaint_biharmonic``, and ``denoise_nl_means``.
In ``skimage.segmentation``, this affects ``felzenszwalb``, ``random_walker``, and ``slic``.
In ``skimage.transform``, this affects ``rescale``, ``warp_polar``, ``pyramid_reduce``, ``pyramid_expand``, ``pyramid_gaussian``, and ``pyramid_laplacian``.
In ``skimage.util``, this affects ``montage`` and ``apply_parallel``
(`#6583 <https://github.com/scikit-image/scikit-image/pull/6583>`_).
- Remove deprecated parameter ``selem``; use ``footprint`` instead.
In ``skimage.filters``, this affects ``median``, ``autolevel_percentile``, ``gradient_percentile``, ``mean_percentile``, ``subtract_mean_percentile``, ``enhance_contrast_percentile``, ``percentile``, ``pop_percentile``, ``sum_percentile``, ``threshold_percentile``, ``mean_bilateral``, ``pop_bilateral``, ``sum_bilateral``, ``autolevel``, ``equalize``, ``gradient``, ``maximum``, ``mean``, ``geometric_mean``, ``subtract_mean``, ``median``, ``minimum``, ``modal``, ``enhance_contrast``, ``pop``, ``sum``, ``threshold``, ``noise_filter``, ``entropy``, ``otsu``, ``windowed_histogram``, and ``majority``.
In ``skimage.morphology``, this affects ``flood_fill``, ``flood``, ``binary_erosion``, ``binary_dilation``, ``binary_opening``, ``binary_closing``, ``h_maxima``, ``h_minima``, ``local_maxima``, ``local_minima``, ``erosion``, ``dilation``, ``opening``, ``closing``, ``white_tophat``, ``black_tophat``, and ``reconstruction``
(`#6583 <https://github.com/scikit-image/scikit-image/pull/6583>`_).
- Remove deprecated parameter ``max_iter`` from ``skimage.filters.threshold_minimum``, ``skimage.morphology.thin``, and ``skimage.segmentation.chan_vese``;
use ``max_num_iter`` instead
(`#6583 <https://github.com/scikit-image/scikit-image/pull/6583>`_).
- Remove deprecated parameter ``max_iterations`` from ``skimage.segmentation.active_contour``;
use ``max_num_iter`` instead
(`#6583 <https://github.com/scikit-image/scikit-image/pull/6583>`_).
- Remove deprecated parameter ``input`` from ``skimage.measure.label``;
use ``label_image`` instead
(`#6583 <https://github.com/scikit-image/scikit-image/pull/6583>`_).
- Remove deprecated parameter ``coordinates`` from ``skimage.measure.regionprops`` and ``skimage.segmentation.active_contour``
(`#6583 <https://github.com/scikit-image/scikit-image/pull/6583>`_).
- Remove deprecated parameter ``neighbourhood`` from ``skimage.measure.perimeter``;
use ``neighborhood`` instead
(`#6583 <https://github.com/scikit-image/scikit-image/pull/6583>`_).
- Remove deprecated parameters ``height`` and ``width`` from ``skimage.morphology.rectangle``;
use ``ncols`` and ``nrows`` instead
(`#6583 <https://github.com/scikit-image/scikit-image/pull/6583>`_).
- Remove deprecated parameter ``in_place`` from ``skimage.morphology.remove_small_objects``, ``skimage.morphology.remove_small_holes``, and ``skimage.segmentation.clear_border``; use ``out`` instead
(`#6583 <https://github.com/scikit-image/scikit-image/pull/6583>`_).
- Remove deprecated parameter ``iterations`` from ``skimage.restoration.richardson_lucy``, ``skimage.segmentation.morphological_chan_vese``, and ``skimage.segmentation.morphological_geodesic_active_contour``; use ``num_iter`` instead
(`#6583 <https://github.com/scikit-image/scikit-image/pull/6583>`_).
- Remove support for deprecated keys ``"min_iter"`` and ``"max_iter"`` in ``skimage.restoration.unsupervised_wiener``'s parameter ``user_params``; use ``"min_num_iter"`` and ``"max_num_iter"`` instead
(`#6583 <https://github.com/scikit-image/scikit-image/pull/6583>`_).
- Remove deprecated functions ``greycomatrix`` and ``greycoprops`` from ``skimage.feature``
(`#6583 <https://github.com/scikit-image/scikit-image/pull/6583>`_).
- Remove deprecated submodules ``skimage.morphology.grey`` and ``skimage.morphology.greyreconstruct``; use ``skimage.morphology`` instead
(`#6583 <https://github.com/scikit-image/scikit-image/pull/6583>`_).
- Remove deprecated submodule ``skimage.morphology.selem``; use ``skimage.morphology.footprints`` instead
(`#6583 <https://github.com/scikit-image/scikit-image/pull/6583>`_).
- Remove deprecated ``skimage.future.graph.ncut`` (it was replaced by ``skimage.graph.cut_normalized``)
(`#6685 <https://github.com/scikit-image/scikit-image/pull/6685>`_).
Bug fixes
---------
- Fix round-off error in ``skimage.exposure.adjust_gamma``
(`#6285 <https://github.com/scikit-image/scikit-image/pull/6285>`_).
- Round and convert output coordinates of ``skimage.draw.rectangle`` to ``int`` even if the input coordinates use ``float``.
This fix ensures that the output can be used for indexing similar to other draw functions
(`#6501 <https://github.com/scikit-image/scikit-image/pull/6501>`_).
- Avoid unexpected exclusion of peaks near the image border in ``skimage.feature.peak_local_max`` if the peak value is smaller 0
(`#6502 <https://github.com/scikit-image/scikit-image/pull/6502>`_).
- Avoid anti-aliasing in ``skimage.transform.resize`` by default when using nearest neighbor interpolation (``order == 0``) with an integer input data type
(`#6503 <https://github.com/scikit-image/scikit-image/pull/6503>`_).
- Use mask during rescaling in ``skimage.segmentation.slic``.
Previously, the mask was ignored when rescaling the image to make choice of compactness insensitive to the image values.
The new behavior makes it possible to mask values such as `numpy.nan` or `numpy.infinity`.
Additionally, raise an error if the input ``image`` has two dimensions and a ``channel_axis`` is specified - indicating that the image is multi-channel
(`#6525 <https://github.com/scikit-image/scikit-image/pull/6525>`_).
- Fix unexpected error when passing a tuple to the parameter ``exclude_border`` in ``skimage.feature.blog_dog`` and ``skimage.feature.blob_log``
(`#6533 <https://github.com/scikit-image/scikit-image/pull/6533>`_).
- Raise a specific error message in ``skimage.segmentation.random_walker`` if no seeds are provided as positive values in the parameter ``labels``
(`#6562 <https://github.com/scikit-image/scikit-image/pull/6562>`_).
- Raise a specific error message when accessing region properties from ``skimage.measure.regionprops`` when the required ``intensity_image`` is unavailable
(`#6584 <https://github.com/scikit-image/scikit-image/pull/6584>`_).
- Avoid errors in ``skimage.feature.ORB.detect_and_extract`` by breaking early if the octave image is too small
(`#6590 <https://github.com/scikit-image/scikit-image/pull/6590>`_).
- Fix ``skimage.restoration.inpaint_biharmonic`` for images with Fortran-ordered memory layout
(`#6263 <https://github.com/scikit-image/scikit-image/pull/6263>`_).
- Fix automatic detection of the color channel in ``skimage.filters.gaussian`` (this behavior is deprecated, see new deprecations)
(`#6583 <https://github.com/scikit-image/scikit-image/pull/6583>`_).
- Fix stacklevel of warning in ``skimage.color.lab2rgb``
(`#6616 <https://github.com/scikit-image/scikit-image/pull/6616>`_).
- Fix the order of return values for ``skimage.feature.hessian_matrix`` and raise an error if ``order='xy'`` is requested for images with more than 2 dimensions
(`#6624 <https://github.com/scikit-image/scikit-image/pull/6624>`_).
- Fix misleading exception in functions in ``skimage.filters.rank`` that did
not mention that 2D images are also supported
(`#6666 <https://github.com/scikit-image/scikit-image/pull/6666>`_).
- Fix in-place merging of wheights in ``skimage.graph.RAG.merge_nodes``
(`#6692 <https://github.com/scikit-image/scikit-image/pull/6692>`_).
- Fix growing memory error and silence compiler warning in internal ``heappush`` function
(`#6727 <https://github.com/scikit-image/scikit-image/pull/6727>`_).
- Fix compiliation warning about struct initialization in `Cascade.detect_multi_scale`
(`#6728 <https://github.com/scikit-image/scikit-image/pull/6728>`_).
Documentation
-------------
New
^^^
- Add gallery example "Decompose flat footprints (structuring elements)"
(`#6151 <https://github.com/scikit-image/scikit-image/pull/6151>`_).
- Add gallery example "Butterworth Filters" and improve docstring of ``skimage.filters.butterworth``
(`#6251 <https://github.com/scikit-image/scikit-image/pull/6251>`_).
- Add gallery example "Render text onto an image"
(`#6431 <https://github.com/scikit-image/scikit-image/pull/6431>`_).
- Add gallery example "Track solidification of a metallic alloy"
(`#6469 <https://github.com/scikit-image/scikit-image/pull/6469>`_).
- Add gallery example "Colocalization metrics"
(`#6189 <https://github.com/scikit-image/scikit-image/pull/6189>`_).
- Add support page (``.github/SUPPORT.md``) to help users from GitHub find appropriate support resources
(`#6171 <https://github.com/scikit-image/scikit-image/pull/6171>`_, `#6575 <https://github.com/scikit-image/scikit-image/pull/6575>`_).
- Add ``CITATION.bib`` to repository to help with citing scikit-image
(`#6195 <https://github.com/scikit-image/scikit-image/pull/6195>`_).
- Add usage instructions for new Meson-based build system with ``dev.py``
(`#6600 <https://github.com/scikit-image/scikit-image/pull/6600>`_).
Improved & updated
^^^^^^^^^^^^^^^^^^
- Improve gallery example "Measure perimeters with different estimators"
(`#6200 <https://github.com/scikit-image/scikit-image/pull/6200>`_, `#6121 <https://github.com/scikit-image/scikit-image/pull/6121>`_).
- Adapt gallery example "Build image pyramids" to more diversified shaped images and downsample factors
(`#6293 <https://github.com/scikit-image/scikit-image/pull/6293>`_).
- Adapt gallery example "Explore 3D images (of cells)" with interactive slice explorer using plotly
(`#4953 <https://github.com/scikit-image/scikit-image/pull/4953>`_).
- Clarify meaning of the ``weights`` term and rewrite docstrings of ``skimage.restoration.denoise_tv_bregman`` and ``skimage.restoration.denoise_tv_chambolle``
(`#6544 <https://github.com/scikit-image/scikit-image/pull/6544>`_).
- Describe the behavior of ``skimage.io.MultiImage`` more precisely in its docstring
(`#6290 <https://github.com/scikit-image/scikit-image/pull/6290>`_, `#6292 <https://github.com/scikit-image/scikit-image/pull/6292>`_).
- Clarify that the enabled ``watershed_line`` parameter will not catch borders between adjacent marker regions in ``skimage.segmentation.watershed``
(`#6280 <https://github.com/scikit-image/scikit-image/pull/6280>`_).
- Clarify that ``skimage.morphology.skeletonize`` accepts an ``image`` of any input type
(`#6322 <https://github.com/scikit-image/scikit-image/pull/6322>`_).
- Use gridded thumbnails in our gallery to demonstrate the different images and datasets available in ``skimage.data``
(`#6298 <https://github.com/scikit-image/scikit-image/pull/6298>`_, `#6300 <https://github.com/scikit-image/scikit-image/pull/6300>`_, `#6301 <https://github.com/scikit-image/scikit-image/pull/6301>`_).
- Tweak ``balance`` in the docstring example of ``skimage.restoration.wiener`` for a less blurry result
(`#6265 <https://github.com/scikit-image/scikit-image/pull/6265>`_).
- Document support for Path objects in ``skimage.io.imread`` and ``skimage.io.imsave``
(`#6361 <https://github.com/scikit-image/scikit-image/pull/6361>`_).
- Improve error message in ``skimage.filters.threshold_multiotsu`` if the discretized image cannot be thresholded
(`#6375 <https://github.com/scikit-image/scikit-image/pull/6375>`_).
- Show original unlabeled image as well in the gallery example "Expand segmentation labels without overlap"
(`#6396 <https://github.com/scikit-image/scikit-image/pull/6396>`_).
- Document refactoring of ``grey*`` to ``skimage.feature.graymatrix`` and ``skimage.feature.graycoprops`` in the release 0.19
(`#6420 <https://github.com/scikit-image/scikit-image/pull/6420>`_).
- Document inclusion criteria for new functionality in core developer guide
(`#6488 <https://github.com/scikit-image/scikit-image/pull/6488>`_).
- Print the number of segments after applying the Watershed in the gallery example "Comparison of segmentation and superpixel algorithms"
(`#6535 <https://github.com/scikit-image/scikit-image/pull/6535>`_).
- Replace issue templates with issue forms
(`#6554 <https://github.com/scikit-image/scikit-image/pull/6554>`_, `#6576 <https://github.com/scikit-image/scikit-image/pull/6576>`_).
- Expand reviewer guidelines in pull request template
(`#6208 <https://github.com/scikit-image/scikit-image/pull/6208>`_).
- Provide pre-commit PR instructions in pull request template
(`#6578 <https://github.com/scikit-image/scikit-image/pull/6578>`_).
- Warn about and explain the handling of floating-point data in the docstring of ``skimage.metricts.structural_similarity``
(`#6595 <https://github.com/scikit-image/scikit-image/pull/6595>`_).
- Fix intensity autoscaling in animated ``imshow`` in gallery example "Measure fluorescence intensity at the nuclear envelope"
(`#6599 <https://github.com/scikit-image/scikit-image/pull/6599>`_).
- Clarify dependency on ``scikit-image[data]`` and pooch in ``INSTALL.rst``
(`#6619 <https://github.com/scikit-image/scikit-image/pull/6619>`_).
- Don't use confusing loop in installation instructions for conda
(`#6672 <https://github.com/scikit-image/scikit-image/pull/6672>`_).
- Document value ranges of L*a*b* and L*Ch in ``lab2xyz``, ``rgb2lab``, ``lab2lch``, and ``lch2lab`` in ``skimage.color``
(`#6688 <https://github.com/scikit-image/scikit-image/pull/6688>`_, `#6697 <https://github.com/scikit-image/scikit-image/pull/6697>`_, `#6719 <https://github.com/scikit-image/scikit-image/pull/6719>`_).
- Use more consistent style in docstring of ``skimage.feature.local_binary_pattern``
(`#6736 <https://github.com/scikit-image/scikit-image/pull/6736>`_).
Fixes, spelling & minor tweaks
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
- Remove deprecated reference and use ``skimage.measure.marching_cubes`` in gallery example "Marching Cubes"
(`#6377 <https://github.com/scikit-image/scikit-image/pull/6377>`_).
- List only the two primary OS-independent methods of installing scikit-image
(`#6557 <https://github.com/scikit-image/scikit-image/pull/6557>`_, `#6560 <https://github.com/scikit-image/scikit-image/pull/6560>`_).
- Fix description of ``connectivity`` parameter in the docstring of ``skimage.morphology.flood``
(`#6534 <https://github.com/scikit-image/scikit-image/pull/6534>`_).
- Fix formatting in the docstring of ``skimage.metrics.hausdorff_distance``
(`#6203 <https://github.com/scikit-image/scikit-image/pull/6203>`_).
- Fix typo in docstring of ``skimage.measure.moments_hu``
(`#6016 <https://github.com/scikit-image/scikit-image/pull/6016>`_).
- Fix formatting of mode parameter in ``skimage.util.random_noise``
(`#6532 <https://github.com/scikit-image/scikit-image/pull/6532>`_).
- Fix broken links in SKIP 3
(`#6445 <https://github.com/scikit-image/scikit-image/pull/6445>`_).
- Fix broken link in docstring of ``skimage.filters.sobel``
(`#6474 <https://github.com/scikit-image/scikit-image/pull/6474>`_).
- Change "neighbour" to EN-US spelling "neighbor"
(`#6204 <https://github.com/scikit-image/scikit-image/pull/6204>`_).
- Add missing copyrights to LICENSE.txt and use formatting according to SPDX identifiers
(`#6419 <https://github.com/scikit-image/scikit-image/pull/6419>`_).
- Include ``skimage.morphology.footprint_from_sequence`` in the public API documentation
(`#6555 <https://github.com/scikit-image/scikit-image/pull/6555>`_).
- Correct note about return type in the docstring of ``skimage.exposure.rescale_intensity``
(`#6582 <https://github.com/scikit-image/scikit-image/pull/6582>`_).
- Stop using the ``git://`` connection protocol and remove references to it
(`#6201 <https://github.com/scikit-image/scikit-image/pull/6201>`_, `#6283 <https://github.com/scikit-image/scikit-image/pull/6283>`_).
- Update scikit-image's mailing addresses to the new domain discuss.scientific-python.org
(`#6255 <https://github.com/scikit-image/scikit-image/pull/6255>`_).
- Remove references to deprecated mailing list in ``doc/source/user_guide/getting_help.rst``
(`#6575 <https://github.com/scikit-image/scikit-image/pull/6575>`_).
- Use "center" in favor of "centre", and "color" in favor of "colour" gallery examples
(`#6421 <https://github.com/scikit-image/scikit-image/pull/6421>`_, `#6422 <https://github.com/scikit-image/scikit-image/pull/6422>`_).
- Replace reference to ``api_changes.rst`` with ``release_dev.rst``
(`#6495 <https://github.com/scikit-image/scikit-image/pull/6495>`_).
- Clarify header pointing to notes for latest version released
(`#6508 <https://github.com/scikit-image/scikit-image/pull/6508>`_).
- Add missing spaces to error message in ``skimage.measure.regionprops``
(`#6545 <https://github.com/scikit-image/scikit-image/pull/6545>`_).
- Apply codespell to fix common spelling mistakes
(`#6537 <https://github.com/scikit-image/scikit-image/pull/6537>`_).
- Add missing space in math directive in normalized_mutual_information's docstring
(`#6549 <https://github.com/scikit-image/scikit-image/pull/6549>`_).
- Fix lengths of docstring heading underline in ``skimage.morphology.isotropic_`` functions
(`#6628 <https://github.com/scikit-image/scikit-image/pull/6628>`_).
- Fix plot order due to duplicate examples with the file name ``plot_thresholding.py``
(`#6644 <https://github.com/scikit-image/scikit-image/pull/6644>`_).
- Get rid of numpy deprecation warning in gallery example ``plot_equalize``
(`#6650 <https://github.com/scikit-image/scikit-image/pull/6650>`_).
- Fix swapping of opening and closing in gallery example ``plot_rank_filters``
(`#6652 <https://github.com/scikit-image/scikit-image/pull/6652>`_).
- Get rid of numpy deprecation warning in gallery example ``in plot_log_gamma.py``
(`#6655 <https://github.com/scikit-image/scikit-image/pull/6655>`_).
- Remove warnings and unnecessary messages in gallery example "Tinting gray-scale images"
(`#6656 <https://github.com/scikit-image/scikit-image/pull/6656>`_).
- Update the contribution guide to recommend creating the virtualenv outside the source tree
(`#6675 <https://github.com/scikit-image/scikit-image/pull/6675>`_).
- Fix typo in docstring of ``skimage.data.coffee``
(`#6740 <https://github.com/scikit-image/scikit-image/pull/6740>`_).
- Add missing backtick in docstring of ``skimage.graph.merge_nodes``
(`#6741 <https://github.com/scikit-image/scikit-image/pull/6741>`_).
- Fix typo in ``skimage.metrics.variation_of_information``
(`#6768 <https://github.com/scikit-image/scikit-image/pull/6768>`_).
Other and development related updates
-------------------------------------
Governance & planning
^^^^^^^^^^^^^^^^^^^^^
- Add draft of SKIP 4 "Transitioning to scikit-image 2.0"
(`#6339 <https://github.com/scikit-image/scikit-image/pull/6339>`_, `#6353 <https://github.com/scikit-image/scikit-image/pull/6353>`_).
Maintenance
^^^^^^^^^^^
- Prepare release notes for v0.20.0
(`#6556 <https://github.com/scikit-image/scikit-image/pull/6556>`_, `#6766 <https://github.com/scikit-image/scikit-image/pull/6766>`_).
- Add and test alternative build system based on Meson as an alternative to the deprecated distutils system
(`#6536 <https://github.com/scikit-image/scikit-image/pull/6536>`_).
- Use ``cnp.float32_t`` and ``cnp.float64_t`` over ``float`` and ``double`` in Cython code
(`#6303 <https://github.com/scikit-image/scikit-image/pull/6303>`_).
- Move ``skimage/measure/mc_meta`` folder into ``tools/precompute/`` folder to avoid its unnecessary distribution to users
(`#6294 <https://github.com/scikit-image/scikit-image/pull/6294>`_).
- Remove unused function ``getLutNames`` in ``tools/precompute/mc_meta/createluts.py``
(`#6294 <https://github.com/scikit-image/scikit-image/pull/6294>`_).
- Point urls for data files to a specific commit
(`#6297 <https://github.com/scikit-image/scikit-image/pull/6297>`_).
- Drop Codecov badge from project README
(`#6302 <https://github.com/scikit-image/scikit-image/pull/6302>`_).
- Remove undefined reference to ``'python_to_notebook'`` in ``doc/ext/notebook_doc.py``
(`#6307 <https://github.com/scikit-image/scikit-image/pull/6307>`_).
- Parameterize tests in ``skimage.measure.tests.test_moments``
(`#6323 <https://github.com/scikit-image/scikit-image/pull/6323>`_).
- Avoid unnecessary copying in ``skimage.morphology.skeletonize`` and update code style and tests
(`#6327 <https://github.com/scikit-image/scikit-image/pull/6327>`_).
- Fix typo in ``_probabilistic_hough_line``
(`#6373 <https://github.com/scikit-image/scikit-image/pull/6373>`_).
- Derive OBJECT_COLUMNS from COL_DTYPES in ``skimage.measure._regionprops``
(`#6389 <https://github.com/scikit-image/scikit-image/pull/6389>`_).
- Support ``loadtxt`` of NumPy 1.23 with ``skimage/feature/orb_descriptor_positions.txt``
(`#6400 <https://github.com/scikit-image/scikit-image/pull/6400>`_).
- Exclude pillow 9.1.1 from supported requirements
(`#6384 <https://github.com/scikit-image/scikit-image/pull/6384>`_).
- Use the same numpy version dependencies for building as used by default
(`#6409 <https://github.com/scikit-image/scikit-image/pull/6409>`_).
- Forward-port v0.19.1 and v0.19.2 release notes
(`#6253 <https://github.com/scikit-image/scikit-image/pull/6253>`_).
- Forward-port v0.19.3 release notes
(`#6416 <https://github.com/scikit-image/scikit-image/pull/6416>`_).
- Exclude submodules of ``doc.*`` from package install
(`#6428 <https://github.com/scikit-image/scikit-image/pull/6428>`_).
- Substitute deprecated ``vertices`` with ``simplices`` in ``skimage.transform._geometric``
(`#6430 <https://github.com/scikit-image/scikit-image/pull/6430>`_).
- Fix minor typo in ``skimage.filters.sato``
(`#6434 <https://github.com/scikit-image/scikit-image/pull/6434>`_).
- Simplify sort-by-absolute-value in ridge filters
(`#6440 <https://github.com/scikit-image/scikit-image/pull/6440>`_).
- Removed completed items in ``TODO.txt``
(`#6442 <https://github.com/scikit-image/scikit-image/pull/6442>`_).
- Remove duplicate import in ``skimage.feature._canny``
(`#6457 <https://github.com/scikit-image/scikit-image/pull/6457>`_).
- Use ``with open(...) as f`` instead of ``f = open(...)``
(`#6458 <https://github.com/scikit-image/scikit-image/pull/6458>`_).
- Use context manager when possible
(`#6484 <https://github.com/scikit-image/scikit-image/pull/6484>`_).
- Use ``broadcast_to`` instead of ``as_strided`` to generate broadcasted arrays
(`#6476 <https://github.com/scikit-image/scikit-image/pull/6476>`_).
- Use ``moving_image`` in docstring of ``skimage.registration._optical_flow._tvl1``
(`#6480 <https://github.com/scikit-image/scikit-image/pull/6480>`_).
- Use ``pyplot.get_cmap`` instead of deprecated ``cm.get_cmap`` in ``skimage.future.graph.show_rag`` for compatibility with matplotlib 3.3 to 3.6
(`#6483 <https://github.com/scikit-image/scikit-image/pull/6483>`_, `#6490 <https://github.com/scikit-image/scikit-image/pull/6490>`_).
- Update ``plot_euler_number.py`` for maplotlib 3.6 compatibility
(`#6522 <https://github.com/scikit-image/scikit-image/pull/6522>`_).
- Make non-functional change to build.txt to fix cache issue on CircleCI
(`#6528 <https://github.com/scikit-image/scikit-image/pull/6528>`_).
- Update deprecated field ``license_file`` to ``license_files`` in ``setup.cfg``
(`#6529 <https://github.com/scikit-image/scikit-image/pull/6529>`_).
- Ignore codespell fixes with git blame
(`#6539 <https://github.com/scikit-image/scikit-image/pull/6539>`_).
- Remove ``FUNDING.yml`` in preference of org version
(`#6553 <https://github.com/scikit-image/scikit-image/pull/6553>`_).
- Handle pending changes to ``tifffile.imwrite`` defaults and avoid test warnings
(`#6460 <https://github.com/scikit-image/scikit-image/pull/6460>`_).
- Handle deprecation by updating to ``networkx.to_scipy_sparse_array``
(`#6564 <https://github.com/scikit-image/scikit-image/pull/6564>`_).
- Update minimum supported numpy, scipy, and networkx
(`#6385 <https://github.com/scikit-image/scikit-image/pull/6385>`_).
- Apply linting results after enabling pre-commit in CI
(`#6568 <https://github.com/scikit-image/scikit-image/pull/6568>`_).
- Refactor lazy loading to use stubs & lazy_loader package
(`#6577 <https://github.com/scikit-image/scikit-image/pull/6577>`_).
- Update sphinx configuration
(`#6579 <https://github.com/scikit-image/scikit-image/pull/6579>`_).
- Update ``pyproject.toml`` to support Python 3.11 and to fix 32-bit pinned packages on Windows
(`#6519 <https://github.com/scikit-image/scikit-image/pull/6519>`_).
- Update primary email address in mailmap entry for grlee77
(`#6639 <https://github.com/scikit-image/scikit-image/pull/6639>`_).
- Handle new warnings introduced in NumPy 1.24
(`#6637 <https://github.com/scikit-image/scikit-image/pull/6637>`_).
- Remove unnecessary dependency on ninja in ``pyproject.toml``
(`#6634 <https://github.com/scikit-image/scikit-image/pull/6634>`_).
- Pin to latest meson-python ``>=0.11.0``
(`#6627 <https://github.com/scikit-image/scikit-image/pull/6627>`_).
- Increase warning stacklevel by 1 in ``skimage.color.lab2xyz``
(`#6613 <https://github.com/scikit-image/scikit-image/pull/6613>`_).
- Update OpenBLAS to v0.3.17
(`#6607 <https://github.com/scikit-image/scikit-image/pull/6607>`_, `#6610 <https://github.com/scikit-image/scikit-image/pull/6610>`_).
- Fix Meson build on windows in sync with SciPy
(`#6609 <https://github.com/scikit-image/scikit-image/pull/6609>`_).
- Set ``check: true`` for ``run_command`` in ``skimage/meson.build``
(`#6606 <https://github.com/scikit-image/scikit-image/pull/6606>`_).
- Add ``dev.py`` and setup commands
(`#6600 <https://github.com/scikit-image/scikit-image/pull/6600>`_).
- Organize ``dev.py`` commands into sections
(`#6629 <https://github.com/scikit-image/scikit-image/pull/6629>`_).
- Remove thumbnail_size in config since sphinx-gallery>=0.9.0
(`#6647 <https://github.com/scikit-image/scikit-image/pull/6647>`_).
- Add new test cases for ``skimage.transform.resize``
(`#6669 <https://github.com/scikit-image/scikit-image/pull/6669>`_).
- Use meson-python main branch
(`#6671 <https://github.com/scikit-image/scikit-image/pull/6671>`_).
- Simplify QhullError import
(`#6677 <https://github.com/scikit-image/scikit-image/pull/6677>`_).
- Remove old SciPy cruft
(`#6678 <https://github.com/scikit-image/scikit-image/pull/6678>`_, `#6681 <https://github.com/scikit-image/scikit-image/pull/6681>`_).
- Remove old references to imread package
(`#6680 <https://github.com/scikit-image/scikit-image/pull/6680>`_).
- Remove pillow cruft (and a few other cleanups)
(`#6683 <https://github.com/scikit-image/scikit-image/pull/6683>`_).
- Remove leftover ``gtk_plugin.ini``
(`#6686 <https://github.com/scikit-image/scikit-image/pull/6686>`_).
- Prepare v0.20.0rc0
(`#6706 <https://github.com/scikit-image/scikit-image/pull/6706>`_).
- Remove pre-release suffix for for Python 3.11
(`#6709 <https://github.com/scikit-image/scikit-image/pull/6709>`_).
- Loosen tests for SciPy 1.10
(`#6715 <https://github.com/scikit-image/scikit-image/pull/6715>`_).
- Specify C flag only if supported by compiler
(`#6716 <https://github.com/scikit-image/scikit-image/pull/6716>`_).
- Extract version info from ``skimage/__init__.py`` in ``skimage/meson.build``
(`#6723 <https://github.com/scikit-image/scikit-image/pull/6723>`_).
- Fix Cython errors/warnings
(`#6725 <https://github.com/scikit-image/scikit-image/pull/6725>`_).
- Generate pyproject deps from requirements
(`#6726 <https://github.com/scikit-image/scikit-image/pull/6726>`_).
- MAINT: Use ``uintptr_t`` to calculate new heap ptr positions
(`#6734 <https://github.com/scikit-image/scikit-image/pull/6734>`_).
- Bite the bullet: remove distutils and setup.py
(`#6738 <https://github.com/scikit-image/scikit-image/pull/6738>`_).
- Use meson-python developer version
(`#6753 <https://github.com/scikit-image/scikit-image/pull/6753>`_).
- Require ``setuptools`` 65.6+
(`#6751 <https://github.com/scikit-image/scikit-image/pull/6751>`_).
- Remove ``setup.cfg``, use ``pyproject.toml`` instead
(`#6758 <https://github.com/scikit-image/scikit-image/pull/6758>`_).
- Update ``pyproject.toml`` to use ``meson-python>=0.13.0rc0``
(`#6759 <https://github.com/scikit-image/scikit-image/pull/6759>`_).
Benchmarks
^^^^^^^^^^
- Add benchmarks for ``morphology.local_maxima``
(`#3255 <https://github.com/scikit-image/scikit-image/pull/3255>`_).
- Add benchmarks for ``skimage.morphology.reconstruction``
(`#6342 <https://github.com/scikit-image/scikit-image/pull/6342>`_).
- Update benchmark environment to Python 3.10 and NumPy 1.23
(`#6511 <https://github.com/scikit-image/scikit-image/pull/6511>`_).
CI & automation
^^^^^^^^^^^^^^^
- Add Github ``actions/stale`` to label "dormant" issues and PRs
(`#6506 <https://github.com/scikit-image/scikit-image/pull/6506>`_, `#6546 <https://github.com/scikit-image/scikit-image/pull/6546>`_, `#6552 <https://github.com/scikit-image/scikit-image/pull/6552>`_).
- Fix the autogeneration of API docs for lazy loaded subpackages
(`#6075 <https://github.com/scikit-image/scikit-image/pull/6075>`_).
- Checkout gh-pages with a shallow clone
(`#6085 <https://github.com/scikit-image/scikit-image/pull/6085>`_).
- Fix dev doc build
(`#6091 <https://github.com/scikit-image/scikit-image/pull/6091>`_).
- Fix CI by excluding Pillow 9.1.0
(`#6315 <https://github.com/scikit-image/scikit-image/pull/6315>`_).
- Pin pip pip to <22.1 in ``tools/github/before_install.sh``
(`#6379 <https://github.com/scikit-image/scikit-image/pull/6379>`_).
- Update GH actions from v2 to v3
(`#6382 <https://github.com/scikit-image/scikit-image/pull/6382>`_).
- Update to supported CircleCI images
(`#6401 <https://github.com/scikit-image/scikit-image/pull/6401>`_).
- Use artifact-redirector
(`#6407 <https://github.com/scikit-image/scikit-image/pull/6407>`_).
- Forward-port gh-6369: Fix windows wheels: use vsdevcmd.bat to make sure rc.exe is on the path
(`#6417 <https://github.com/scikit-image/scikit-image/pull/6417>`_).
- Restrict GitHub Actions permissions to required ones
(`#6426 <https://github.com/scikit-image/scikit-image/pull/6426>`_, `#6504 <https://github.com/scikit-image/scikit-image/pull/6504>`_).
- Update to Ubuntu LTS version on Actions workflows
(`#6478 <https://github.com/scikit-image/scikit-image/pull/6478>`_).
- Relax label name comparison in ``benchmarks.yaml`` workflow
(`#6520 <https://github.com/scikit-image/scikit-image/pull/6520>`_).
- Add linting via pre-commit
(`#6563 <https://github.com/scikit-image/scikit-image/pull/6563>`_).
- Add CI tests for Python 3.11
(`#6566 <https://github.com/scikit-image/scikit-image/pull/6566>`_).
- Fix CI for Scipy 1.9.2
(`#6567 <https://github.com/scikit-image/scikit-image/pull/6567>`_).
- Test optional Py 3.10 dependencies on MacOS
(`#6580 <https://github.com/scikit-image/scikit-image/pull/6580>`_).
- Pin setuptools in GHA MacOS workflow and ``azure-pipelines.yml``
(`#6626 <https://github.com/scikit-image/scikit-image/pull/6626>`_).
- Build Python 3.11 wheels
(`#6581 <https://github.com/scikit-image/scikit-image/pull/6581>`_).
- Fix doc build on CircleCI and add ccache
(`#6646 <https://github.com/scikit-image/scikit-image/pull/6646>`_).
- Build wheels on CI via branch rather than tag
(`#6668 <https://github.com/scikit-image/scikit-image/pull/6668>`_).
- Do not build wheels on pushes to main
(`#6673 <https://github.com/scikit-image/scikit-image/pull/6673>`_).
- Use ``tools/github/before_install.sh`` wheels workflow
(`#6718 <https://github.com/scikit-image/scikit-image/pull/6718>`_).
- Use Ruff for linting
(`#6729 <https://github.com/scikit-image/scikit-image/pull/6729>`_).
- Use test that can fail for sdist
(`#6731 <https://github.com/scikit-image/scikit-image/pull/6731>`_).
- Fix fstring in ``skimage._shared._warnings.expected_warnings``
(`#6733 <https://github.com/scikit-image/scikit-image/pull/6733>`_).
- Build macosx/py38 wheel natively
(`#6743 <https://github.com/scikit-image/scikit-image/pull/6743>`_).
- Remove CircleCI URL check
(`#6749 <https://github.com/scikit-image/scikit-image/pull/6749>`_).
- CI Set MACOSX_DEPLOYMENT_TARGET=10.9 for Wheels
(`#6750 <https://github.com/scikit-image/scikit-image/pull/6750>`_).
- Add temporary workaround until new meson-python release
(`#6757 <https://github.com/scikit-image/scikit-image/pull/6757>`_).
- Update action to use new environment file
(`#6762 <https://github.com/scikit-image/scikit-image/pull/6762>`_).
- Autogenerate pyproject.toml
(`#6763 <https://github.com/scikit-image/scikit-image/pull/6763>`_).
71 authors contributed to this release [alphabetical by first name or login]
----------------------------------------------------------------------------
- <NAME>
- <NAME>
- AleixBP (AleixBP)
- Alex (sashashura)
- <NAME>
- <NAME>
- Amin (MOAMSA)
- <NAME>
- <NAME>
- <NAME>
- bsmietanka (bsmietanka)
- <NAME>
- <NAME>
- Daria
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- forgeRW (forgeRW)
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- Jan-<NAME>
- Jan-<NAME>
- <NAME>
- <NAME>
- johnthagen (johnthagen)
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- lihaitao (li1127217ye)
- <NAME>
- Malinda (maldil)
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- Naveen
- OBgoneSouth (OBgoneSouth)
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- samtygier (samtygier)
- <NAME>
- Sanghyeok Hyun
- <NAME>
- <NAME>
- Simon-<NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- Tim-<NAME>
- <NAME>
42 reviewers contributed to this release [alphabetical by first name or login]
------------------------------------------------------------------------------
- <NAME>
- <NAME>
- Alex (sashashura)
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- Daria
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- Malinda (maldil)
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- Sanghyeok Hyun
- <NAME>
- <NAME>
- Simon-<NAME>
- <NAME>
- <NAME>
- <NAME>
- Tim-<NAME>
<file_sep>/skimage/segmentation/tests/test_quickshift.py
import numpy as np
import pytest
from skimage.segmentation import quickshift
from skimage._shared import testing
from skimage._shared.testing import (assert_greater, run_in_parallel,
assert_equal, assert_array_equal)
@run_in_parallel()
@testing.parametrize('dtype', [np.float32, np.float64])
def test_grey(dtype):
rng = np.random.default_rng(0)
img = np.zeros((20, 21))
img[:10, 10:] = 0.2
img[10:, :10] = 0.4
img[10:, 10:] = 0.6
img += 0.05 * rng.normal(size=img.shape)
img = img.astype(dtype, copy=False)
seg = quickshift(img, kernel_size=2, max_dist=3, rng=0,
convert2lab=False, sigma=0)
with testing.expected_warnings(['`random_seed` is a deprecated argument']):
quickshift(img, kernel_size=2, max_dist=3, random_seed=0,
convert2lab=False, sigma=0)
# we expect 4 segments:
assert_equal(len(np.unique(seg)), 4)
# that mostly respect the 4 regions:
for i in range(4):
hist = np.histogram(img[seg == i], bins=[0, 0.1, 0.3, 0.5, 1])[0]
assert_greater(hist[i], 20)
@testing.parametrize('dtype', [np.float32, np.float64])
@testing.parametrize('channel_axis', [-3, -2, -1, 0, 1, 2])
def test_color(dtype, channel_axis):
rng = np.random.default_rng(583428449)
img = np.zeros((20, 21, 3))
img[:10, :10, 0] = 1
img[10:, :10, 1] = 1
img[10:, 10:, 2] = 1
img += 0.01 * rng.normal(size=img.shape)
img[img > 1] = 1
img[img < 0] = 0
img = img.astype(dtype, copy=False)
img = np.moveaxis(img, source=-1, destination=channel_axis)
seg = quickshift(img, rng=0, max_dist=30, kernel_size=10, sigma=0,
channel_axis=channel_axis)
# we expect 4 segments:
assert_equal(len(np.unique(seg)), 4)
assert_array_equal(seg[:10, :10], 1)
assert_array_equal(seg[10:, :10], 3)
assert_array_equal(seg[:10, 10:], 0)
assert_array_equal(seg[10:, 10:], 2)
seg2 = quickshift(img, kernel_size=1, max_dist=2, rng=0,
convert2lab=False, sigma=0,
channel_axis=channel_axis)
# very oversegmented:
assert len(np.unique(seg2)) > 10
# still don't cross lines
assert (seg2[9, :] != seg2[10, :]).all()
assert (seg2[:, 9] != seg2[:, 10]).all()
def test_convert2lab_not_rgb():
img = np.zeros((20, 21, 2))
with pytest.raises(
ValueError, match="Only RGB images can be converted to Lab space"
):
quickshift(img, convert2lab=True)
<file_sep>/doc/examples/edges/plot_canny.py
"""
===================
Canny edge detector
===================
The Canny filter is a multi-stage edge detector. It uses a filter based on the
derivative of a Gaussian in order to compute the intensity of the gradients.The
Gaussian reduces the effect of noise present in the image. Then, potential
edges are thinned down to 1-pixel curves by removing non-maximum pixels of the
gradient magnitude. Finally, edge pixels are kept or removed using hysteresis
thresholding on the gradient magnitude.
The Canny has three adjustable parameters: the width of the Gaussian (the
noisier the image, the greater the width), and the low and high threshold for
the hysteresis thresholding.
"""
import numpy as np
import matplotlib.pyplot as plt
from scipy import ndimage as ndi
from skimage.util import random_noise
from skimage import feature
# Generate noisy image of a square
image = np.zeros((128, 128), dtype=float)
image[32:-32, 32:-32] = 1
image = ndi.rotate(image, 15, mode='constant')
image = ndi.gaussian_filter(image, 4)
image = random_noise(image, mode='speckle', mean=0.1)
# Compute the Canny filter for two values of sigma
edges1 = feature.canny(image)
edges2 = feature.canny(image, sigma=3)
# display results
fig, ax = plt.subplots(nrows=1, ncols=3, figsize=(8, 3))
ax[0].imshow(image, cmap='gray')
ax[0].set_title('noisy image', fontsize=20)
ax[1].imshow(edges1, cmap='gray')
ax[1].set_title(r'Canny filter, $\sigma=1$', fontsize=20)
ax[2].imshow(edges2, cmap='gray')
ax[2].set_title(r'Canny filter, $\sigma=3$', fontsize=20)
for a in ax:
a.axis('off')
fig.tight_layout()
plt.show()
<file_sep>/doc/source/skips/4-transition-to-v2.rst
.. _skip_4_transition_v2:
==========================================
SKIP 4 — Transitioning to scikit-image 2.0
==========================================
:Author: <NAME> <<EMAIL>>
:Author: <NAME>
:Status: Draft
:Type: Standards Track
:Created: 2022-04-08
:Resolved: <null>
:Resolution: <null>
:Version effective: None
Abstract
--------
scikit-image is preparing to release version 1.0. This :ref:`was seen
<skip_3_transition_v1>` as an opportunity to clean up the API, including
backwards incompatible changes. Some of these changes involve changing return
values without changing function signatures, which can ordinarily only be done
by adding an otherwise useless keyword argument (such as
``new_return_style=True``) whose default value changes over several releases.
The result is *still* a backwards incompatible change, but made over a longer
time period.
Despite being in beta and in a 0.x series of releases, scikit-image is used
extremely broadly, and any backwards incompatible changes are likely to be
disruptive. Given the rejection of :ref:`SKIP-3 <skip_3_transition_v1>`, this
document proposes an alternative pathway to create a new API. The new pathway
involves the following steps:
- Any pending deprecations that were scheduled for v0.20 and v0.21 are
finalised (the new API suggested by deprecation messages in v0.19 becomes
the only API).
- This is released as 1.0.
- At this point, the branch ``main`` changes the package and import names to
``skimage2``, and the API is free to evolve.
Further motivation for the API changes is explained below, and largely
duplicated from :ref:`SKIP-3 <skip_3_transition_v1>`.
Motivation and Scope
--------------------
scikit-image has grown organically over the past 12+ years, with functionality
being added by a broad community of contributors from different backgrounds.
This has resulted in various parts of the API being inconsistent: for example,
``skimage.transform.warp`` inverts the order of coordinates, so that a
translation of (45, 32) actually moves the values in a NumPy array by 32 along
the 0th axis, and 45 along the 1st, *but only in 2D*. In 3D, a translation of
(45, 32, 77) moves the values in each axis by the number in the corresponding
position.
Additionally, as our user base has grown, it has become apparent that certain
early API choices turned out to be more confusing than helpful. For example,
scikit-image will automatically convert images to various data types,
*rescaling them in the process*. A uint8 image in the range [0, 255] will
automatically be converted to a float64 image in [0, 1]. This might initially
seem reasonable, but, for consistency, uint16 images in [0, 65535] are rescaled
to [0, 1] floats, and uint16 images with 12-bit range in [0, 4095], which are
common in microscopy, are rescaled to [0, 0.0625]. These silent conversions
have resulted in much user confusion.
Changing this convention would require adding a ``preserve_range=`` keyword
argument to almost *all* scikit-image functions, whose default value would
change from False to True over 4 versions. Eventually, the change would be
backwards-incompatible, no matter how gentle we made the deprecation curve.
Other major functions, such as ``skimage.measure.regionprops``, could use an
API tweak, for example by returning a dictionary mapping labels to properties,
rather than a list.
Given the accumulation of potential API changes that have turned out to be too
burdensome and noisy to fix with a standard deprecation cycle, principally
because they involve changing function outputs for the same inputs, it makes
sense to make all those changes in a transition to version 2.0.
Although semantic versioning [6]_ technically allows API changes with major
version bumps, we must acknowledge that (1) an enormous number of projects
depend on scikit-image and would thus be affected by backwards incompatible
changes, and (2) it is not yet common practice in the scientific Python
community to put upper version bounds on dependencies, so it is very unlikely
that anyone used ``scikit-image<1.*`` or ``scikit-image<2.*`` in their
dependency list. This implies that releasing a version 2.0 of scikit-image with
breaking API changes would disrupt a large number of users. Additionally, such
wide-sweeping changes would invalidate a large number of StackOverflow and
other user guides. Finally, releasing a new version with a large number of
changes prevents users from gradually migrating to the new API: an old code
base must be migrated wholesale because it is impossible to depend on both
versions of the API. This would represent an enormous barrier of entry for many
users.
Given the above, this SKIP proposes that we release a new package where we can
apply everything we have learned from over a decade of development, without
disrupting our existing user base.
Detailed description
--------------------
It is beyond the scope of this document to list all of the proposed API changes
for skimage2, many of which have yet to be decided upon. Indeed, the
scope and ambition of the 2.0 transition could grow if this SKIP is accepted.
This SKIP instead proposes a mechanism for managing the transition without
breaking users' code. A meta-issue tracking the proposed changes can be found
on GitHub, scikit-image/scikit-image#5439 [7]_. Some examples are briefly
included below for illustrative purposes:
- Stop rescaling input arrays when the dtype must be coerced to float.
- Stop swapping coordinate axis order in different contexts, such as drawing or
warping.
- Allow automatic return of non-NumPy types, so long as they are coercible to
NumPy with ``numpy.asarray``.
- Harmonizing similar parameters in different functions to have the same name;
for example, we currently have ``random_seed``, ``random_state``, ``seed``,
or ``sample_seed`` in different functions, all to mean the same thing.
- Changing ``measure.regionprops`` to return a dictionary instead of a list.
- Combine functions that have the same purpose, such as ``watershed``,
``slic``, or ``felzenschwalb``, into a common namespace. This would make it
easier for new users to find out which functions they should try out for a
specific task. It would also help the community grow around common APIs,
where now scikit-image APIs are essentially unique for each function.
To make this transition with a minimum amount of user disruption, this SKIP
proposes releasing a new library, skimage2, that would replace the existing
library, *but only if users explicitly opt-in*. Additionally, by releasing a
new library, users could depend *both* on scikit-image (1.0) and on skimage2,
allowing users to migrate their code progressively.
Related Work
------------
`pandas` released 1.0.0 in January 2020, including many backwards-incompatible
API changes [3]_. `scipy` released version 1.0 in 2017, but, given its stage of
maturity and position at the base of the scientific Python ecosystem, opted not
to make major breaking changes [4]_. However, SciPy has adopted a policy of
adding upper-bounds on dependencies [5]_, acknowledging that the ecosystem as a
whole makes backwards incompatible changes on a 2 version deprecation cycle.
Several libraries have successfully migrated their user community to a new
namespace with a version number on it, such as OpenCV (imported as ``cv2``) and
BeautifulSoup (imported as ``bs4``), Jinja (``jinja2``) and psycopg (currently
imported as ``psycopg2``). Further afield, R's ggplot is used as ``ggplot2``.
Implementation
--------------
The details of the proposal are as follows:
- scikit-image 0.19 will be followed by scikit-image 1.0. Every deprecation
message will be removed from 1.0, and the API will be considered the
scikit-image 1.0 API.
- After 1.0, the main branch will be changed to (a) change the import name to
skimage2, (b) change the package name to skimage2, and (c) change the version
number to 2.0-dev.
- There will be *no* "scikit-image" package on PyPI with version 2.0. Users who
``pip install scikit-image`` will always get the 1.x version of the package.
To install scikit-image 2.0, users will need to ``pip install skimage2``,
``conda install skimage2``, or similar.
- After consensus has been reached on the new API, skimage2 will be released.
- Following the release of skimage2, a release of scikit-image 1.1 is made. This
release is identical to 1.0 (including bugfixes) but will advise users to
either (a) upgrade to skimage2 or (b) pin the package to ``scikit-image<1.1``
to avoid the warning.
- scikit-image 1.0.x and 1.1.x will receive critical bug fixes for an
unspecified period of time, depending on the severity of the bug and the
amount of effort involved.
Backward compatibility
----------------------
This proposal breaks backward compatibility in numerous places in the library.
However, it does so in a new namespace, so that this proposal does not raise
backward compatibility concerns for our users. That said, the authors will
attempt to limit the number of backward incompatible changes to those likely to
substantially improve the overall user experience. It is anticipated that
porting `skimage` code to `skimage2` will be a straightforward process
and we will publish a user guide for making the transition by the time of
the `skimage2` release. Users will be notified about these resources - among
other things - by a warning in scikit-image 1.1.
Alternatives
------------
Releasing the new API in the same package using semantic versioning
...................................................................
This is :ref:`SKIP-3 <skip_3_transition_v1>`, which was rejected after discussion
with the community.
Continuous deprecation over multiple versions
.............................................
This transition could occur gradually over many versions. For example, for
functions automatically converting and rescaling float inputs, we could add a
``preserve_range`` keyword argument that would initially default to False, but
the default value of False would be deprecated, with users getting a warning to
switch to True. After the switch, we could (optionally) deprecate the
argument, arriving, after a further two releases, at the same place:
scikit-image no longer rescales data automatically, there are no
unnecessary keyword arguments lingering all over the API.
Of course, this kind of operation would have to be done simultaneously over all
of the above proposed changes.
Ultimately, the core team felt that this approach generates more work for both
the scikit-image developers and the developers of downstream libraries, for
dubious benefit: ultimately, later versions of scikit-image will still be
incompatible with prior versions, although over a longer time scale.
A single package containing both versions
.........................................
Since the import name is changing, it would be possible to make a single
package with both the ``skimage`` and ``skimage2`` namespaces shipping
together, at least for some time. This option is attractive but it implies
longer-term maintenance of the 1.0 namespace, for which we might lack
maintainer time, or a long deprecation cycle for the 1.0 namespace, which would
ultimately result in a lot of unhappy users getting deprecation messages from
their scikit-image use.
Not making the proposed API changes
...................................
Another possibility is to reject backwards incompatible API changes outright,
except in extreme cases. The core team feels that this is essentially
equivalent to pinning the library at 0.19.
"scikit-image2" as the new package name
.......................................
The authors acknowledge that the new names should be chosen with care to keep
the disruption to scikit-image's user base and community as small as possible.
However, to protect users without upper version constraints from accidentally
upgrading to the new API, the package name ``scikit-image`` must be changed.
Changing the import name ``skimage`` is similarly advantageous because it allows
using both APIs in the same environment.
This document suggests just ``skimage2`` as the single new name for
scikit-image's API version 2.0, both for the import name and the name on PyPI,
conda-forge and elsewhere. The following arguments were given in favor of this:
- Only one new name is introduced with the project thereby keeping the number of
associated names as low as possible.
- With this change, the import and package name match.
- Users might be confused whether they should install ``scikit-image2`` or
``scikit-image-2``. It was felt that ``skimage2`` avoids this confusion.
- Users who know what ``skimage`` is and see ``skimage2`` in an install
instruction somewhere, will likely be able to infer that it is a newer version
of the package.
- It is unlikely that users will be aware of the new API 2.0 but not of the new
package name. A proposed release of scikit-image 1.1 might point users to
``skimage2`` during the installation and update process and thereby clearly
communicate the successors name.
The following arguments were made against naming the package ``skimage2``:
- According to the "Principle of least astonishment", ``scikit-image2`` might be
considered the least surprising evolution of the package name.
- It breaks with the convention that is followed by other scikits including
scikit-image. (It was pointed out that this convention has not been true for
some time and introducing a version number in the name is a precedent anyway.)
The earlier section "Related Work" describes how other projects dealt with
similar problems.
Discussion
----------
This SKIP is the result of discussion of :ref:`SKIP-3 <skip_3_transition_v1>`. See
the "Resolution" section of that document for further background on the
motivation for this SKIP.
Resolution
----------
References and Footnotes
------------------------
All SKIPs should be declared as dedicated to the public domain with the CC0
license [1]_, as in `Copyright`, below, with attribution encouraged with CC0+BY
[2]_.
.. [1] CC0 1.0 Universal (CC0 1.0) Public Domain Dedication,
https://creativecommons.org/publicdomain/zero/1.0/
.. [2] https://dancohen.org/2013/11/26/cc0-by/
.. [3] https://pandas.pydata.org/pandas-docs/stable/whatsnew/v1.0.0.html#backwards-incompatible-api-changes
.. [4] https://docs.scipy.org/doc/scipy/reference/release.1.0.0.html
.. [5] https://github.com/scipy/scipy/pull/12862
.. [6] https://semver.org/
.. [7] https://github.com/scikit-image/scikit-image/issues/5439
Copyright
---------
This document is dedicated to the public domain with the Creative Commons CC0
license [1]_. Attribution to this source is encouraged where appropriate, as per
CC0+BY [2]_.
<file_sep>/doc/examples/applications/plot_text.py
"""
=========================
Render text onto an image
=========================
Scikit-image currently doesn't feature a function that allows you to
write text onto an image. However, there is a fairly easy workaround
using scikit-image's optional dependency `matplotlib
<https://matplotlib.org/>`_.
"""
import matplotlib.pyplot as plt
import numpy as np
from skimage import data
img = data.cat()
fig = plt.figure()
fig.figimage(img, resize=True)
fig.text(0, 0.99, "I am stefan's cat.", fontsize=32, va="top")
fig.canvas.draw()
annotated_img = np.asarray(fig.canvas.renderer.buffer_rgba())
plt.close(fig)
###############################################################################
# For the purpose of this example, we can also show the image; however, if one
# just wants to write onto the image, this step is not necessary.
fig, ax = plt.subplots()
ax.imshow(annotated_img)
ax.set_axis_off()
ax.set_position([0, 0, 1, 1])
plt.show()
<file_sep>/skimage/feature/tests/test_sift.py
import numpy as np
import pytest
from numpy.testing import assert_almost_equal, assert_equal
from skimage import data
from skimage._shared.testing import run_in_parallel
from skimage.feature import SIFT
from skimage.util.dtype import _convert
img = data.coins()
@run_in_parallel()
@pytest.mark.parametrize(
'dtype', ['float32', 'float64', 'uint8', 'uint16', 'int64']
)
def test_keypoints_sift(dtype):
_img = _convert(img, dtype)
detector_extractor = SIFT()
detector_extractor.detect_and_extract(_img)
exp_keypoint_rows = np.array([18, 18, 19, 22, 26, 26, 30, 31, 31, 32])
exp_keypoint_cols = np.array([331, 331, 325, 330, 310, 330, 205, 323, 149,
338])
exp_octaves = np.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
exp_position_rows = np.array([17.81909936, 17.81909936, 19.05454661,
21.85933727, 25.54800708, 26.25710504,
29.90826307, 30.78713806, 30.87953572,
31.72557969])
exp_position_cols = np.array([331.49693187, 331.49693187, 325.24476016,
330.44616424, 310.33932904, 330.46155224,
204.74535177, 322.84100812, 149.43192282,
337.89643013])
exp_orientations = np.array([0.26391655, 0.26391655, 0.39134262,
1.77063053, 0.98637565, 1.37997279, 0.4919992,
1.48615988, 0.33753212, 1.64859617])
exp_scales = np.array([2, 2, 1, 3, 3, 1, 2, 1, 1, 1])
exp_sigmas = np.array([1.35160379, 1.35160379, 0.94551567, 1.52377498,
1.55173233, 0.93973722, 1.37594124, 1.06663786,
1.04827034, 1.0378916])
exp_scalespace_sigmas = np.array([[0.8, 1.00793684, 1.26992084, 1.6,
2.01587368, 2.53984168],
[1.6, 2.01587368, 2.53984168, 3.2,
4.03174736, 5.07968337],
[3.2, 4.03174736, 5.07968337, 6.4,
8.06349472, 10.15936673],
[6.4, 8.06349472, 10.15936673, 12.8,
16.12698944, 20.31873347],
[12.8, 16.12698944, 20.31873347, 25.6,
32.25397888, 40.63746693],
[25.6, 32.25397888, 40.63746693, 51.2,
64.50795775, 81.27493386]])
assert_almost_equal(exp_keypoint_rows,
detector_extractor.keypoints[:10, 0])
assert_almost_equal(exp_keypoint_cols,
detector_extractor.keypoints[:10, 1])
assert_almost_equal(exp_octaves,
detector_extractor.octaves[:10])
assert_almost_equal(exp_position_rows,
detector_extractor.positions[:10, 0], decimal=4)
assert_almost_equal(exp_position_cols,
detector_extractor.positions[:10, 1], decimal=4)
assert_almost_equal(exp_orientations,
detector_extractor.orientations[:10], decimal=4)
assert_almost_equal(exp_scales,
detector_extractor.scales[:10])
assert_almost_equal(exp_sigmas,
detector_extractor.sigmas[:10], decimal=4)
assert_almost_equal(exp_scalespace_sigmas,
detector_extractor.scalespace_sigmas, decimal=4)
detector_extractor2 = SIFT()
detector_extractor2.detect(img)
detector_extractor2.extract(img)
assert_almost_equal(detector_extractor.keypoints[:10, 0],
detector_extractor2.keypoints[:10, 0])
assert_almost_equal(detector_extractor.keypoints[:10, 0],
detector_extractor2.keypoints[:10, 0])
def test_descriptor_sift():
detector_extractor = SIFT(n_hist=2, n_ori=4)
exp_descriptors = np.array([[173, 30, 55, 32, 173, 16, 45, 82, 173, 154,
170, 173, 173, 169, 65, 110],
[173, 30, 55, 32, 173, 16, 45, 82, 173, 154,
170, 173, 173, 169, 65, 110],
[189, 52, 18, 18, 189, 11, 21, 55, 189, 75,
173, 91, 189, 65, 189, 162],
[172, 156, 185, 66, 92, 76, 78, 185, 185, 87,
88, 82, 98, 56, 96, 185],
[216, 19, 40, 9, 196, 7, 57, 36, 216, 56, 158,
29, 216, 42, 144, 154],
[169, 120, 169, 91, 129, 108, 169, 67, 169,
142, 111, 95, 169, 120, 69, 41],
[199, 10, 138, 44, 178, 11, 161, 34, 199, 113,
73, 64, 199, 82, 31, 178],
[154, 56, 154, 49, 144, 154, 154, 78, 154, 51,
154, 83, 154, 154, 154, 72],
[230, 46, 47, 21, 230, 15, 65, 95, 230, 52, 72,
51, 230, 19, 59, 130],
[155, 117, 154, 102, 155, 155, 90, 110, 145,
127, 155, 50, 57, 155, 155, 70]],
dtype=np.uint8
)
detector_extractor.detect_and_extract(img)
assert_equal(exp_descriptors, detector_extractor.descriptors[:10])
keypoints_count = detector_extractor.keypoints.shape[0]
assert keypoints_count == detector_extractor.descriptors.shape[0]
assert keypoints_count == detector_extractor.orientations.shape[0]
assert keypoints_count == detector_extractor.octaves.shape[0]
assert keypoints_count == detector_extractor.positions.shape[0]
assert keypoints_count == detector_extractor.scales.shape[0]
assert keypoints_count == detector_extractor.scales.shape[0]
def test_no_descriptors_extracted_sift():
img = np.ones((128, 128))
detector_extractor = SIFT()
with pytest.raises(RuntimeError):
detector_extractor.detect_and_extract(img)
<file_sep>/CODE_OF_CONDUCT.md
[scikit-image Code of Conduct](doc/source/about/code_of_conduct.md)
<file_sep>/skimage/measure/_colocalization.py
import numpy as np
from scipy.stats import pearsonr
from .._shared.utils import check_shape_equality, as_binary_ndarray
__all__ = ['pearson_corr_coeff',
'manders_coloc_coeff',
'manders_overlap_coeff',
'intersection_coeff',
]
def pearson_corr_coeff(image0, image1, mask=None):
r"""Calculate Pearson's Correlation Coefficient between pixel intensities
in channels.
Parameters
----------
image0 : (M, N) ndarray
Image of channel A.
image1 : (M, N) ndarray
Image of channel 2 to be correlated with channel B.
Must have same dimensions as `image0`.
mask : (M, N) ndarray of dtype bool, optional
Only `image0` and `image1` pixels within this region of interest mask
are included in the calculation. Must have same dimensions as `image0`.
Returns
-------
pcc : float
Pearson's correlation coefficient of the pixel intensities between
the two images, within the mask if provided.
p-value : float
Two-tailed p-value.
Notes
-----
Pearson's Correlation Coefficient (PCC) measures the linear correlation
between the pixel intensities of the two images. Its value ranges from -1
for perfect linear anti-correlation to +1 for perfect linear correlation.
The calculation of the p-value assumes that the intensities of pixels in
each input image are normally distributed.
Scipy's implementation of Pearson's correlation coefficient is used. Please
refer to it for further information and caveats [1]_.
.. math::
r = \frac{\sum (A_i - m_A_i) (B_i - m_B_i)}
{\sqrt{\sum (A_i - m_A_i)^2 \sum (B_i - m_B_i)^2}}
where
:math:`A_i` is the value of the :math:`i^{th}` pixel in `image0`
:math:`B_i` is the value of the :math:`i^{th}` pixel in `image1`,
:math:`m_A_i` is the mean of the pixel values in `image0`
:math:`m_B_i` is the mean of the pixel values in `image1`
A low PCC value does not necessarily mean that there is no correlation
between the two channel intensities, just that there is no linear
correlation. You may wish to plot the pixel intensities of each of the two
channels in a 2D scatterplot and use Spearman's rank correlation if a
non-linear correlation is visually identified [2]_. Also consider if you
are interested in correlation or co-occurence, in which case a method
involving segmentation masks (e.g. MCC or intersection coefficient) may be
more suitable [3]_ [4]_.
Providing the mask of only relevant sections of the image (e.g., cells, or
particular cellular compartments) and removing noise is important as the
PCC is sensitive to these measures [3]_ [4]_.
References
----------
.. [1] https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.pearsonr.html # noqa
.. [2] https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.spearmanr.html # noqa
.. [3] <NAME>., <NAME>., & <NAME>. (2011). A practical
guide to evaluating colocalization in biological microscopy.
American journal of physiology. Cell physiology, 300(4), C723–C742.
https://doi.org/10.1152/ajpcell.00462.2010
.. [4] <NAME>. and <NAME>. (2006), A guided tour into
subcellular colocalization analysis in light microscopy. Journal of
Microscopy, 224: 213-232.
https://doi.org/10.1111/j.1365-2818.2006.01706.x
"""
image0 = np.asarray(image0)
image1 = np.asarray(image1)
if mask is not None:
mask = as_binary_ndarray(mask, variable_name="mask")
check_shape_equality(image0, image1, mask)
image0 = image0[mask]
image1 = image1[mask]
else:
check_shape_equality(image0, image1)
# scipy pearsonr function only takes flattened arrays
image0 = image0.reshape(-1)
image1 = image1.reshape(-1)
return pearsonr(image0, image1)
def manders_coloc_coeff(image0, image1_mask, mask=None):
r"""Manders' colocalization coefficient between two channels.
Parameters
----------
image0 : (M, N) ndarray
Image of channel A. All pixel values should be non-negative.
image1_mask : (M, N) ndarray of dtype bool
Binary mask with segmented regions of interest in channel B.
Must have same dimensions as `image0`.
mask : (M, N) ndarray of dtype bool, optional
Only `image0` pixel values within this region of interest mask are
included in the calculation.
Must have same dimensions as `image0`.
Returns
-------
mcc : float
Manders' colocalization coefficient.
Notes
-----
Manders' Colocalization Coefficient (MCC) is the fraction of total
intensity of a certain channel (channel A) that is within the segmented
region of a second channel (channel B) [1]_. It ranges from 0 for no
colocalisation to 1 for complete colocalization. It is also referred to
as M1 and M2.
MCC is commonly used to measure the colocalization of a particular protein
in a subceullar compartment. Typically a segmentation mask for channel B
is generated by setting a threshold that the pixel values must be above
to be included in the MCC calculation. In this implementation,
the channel B mask is provided as the argument `image1_mask`, allowing
the exact segmentation method to be decided by the user beforehand.
The implemented equation is:
.. math::
r = \frac{\sum A_{i,coloc}}{\sum A_i}
where
:math:`A_i` is the value of the :math:`i^{th}` pixel in `image0`
:math:`A_{i,coloc} = A_i` if :math:`Bmask_i > 0`
:math:`Bmask_i` is the value of the :math:`i^{th}` pixel in
`mask`
MCC is sensitive to noise, with diffuse signal in the first channel
inflating its value. Images should be processed to remove out of focus and
background light before the MCC is calculated [2]_.
References
----------
.. [1] <NAME>., <NAME>. and <NAME>. (1993), Measurement of
co-localization of objects in dual-colour confocal images. Journal
of Microscopy, 169: 375-382.
https://doi.org/10.1111/j.1365-2818.1993.tb03313.x
https://imagej.net/media/manders.pdf
.. [2] <NAME>., <NAME>., & <NAME>. (2011). A practical
guide to evaluating colocalization in biological microscopy.
American journal of physiology. Cell physiology, 300(4), C723–C742.
https://doi.org/10.1152/ajpcell.00462.2010
"""
image0 = np.asarray(image0)
image1_mask = as_binary_ndarray(image1_mask, variable_name="image1_mask")
if mask is not None:
mask = as_binary_ndarray(mask, variable_name="mask")
check_shape_equality(image0, image1_mask, mask)
image0 = image0[mask]
image1_mask = image1_mask[mask]
else:
check_shape_equality(image0, image1_mask)
# check non-negative image
if image0.min() < 0:
raise ValueError("image contains negative values")
sum = np.sum(image0)
if (sum == 0):
return 0
return np.sum(image0 * image1_mask) / sum
def manders_overlap_coeff(image0, image1, mask=None):
r"""Manders' overlap coefficient
Parameters
----------
image0 : (M, N) ndarray
Image of channel A. All pixel values should be non-negative.
image1 : (M, N) ndarray
Image of channel B. All pixel values should be non-negative.
Must have same dimensions as `image0`
mask : (M, N) ndarray of dtype bool, optional
Only `image0` and `image1` pixel values within this region of interest
mask are included in the calculation.
Must have ♣same dimensions as `image0`.
Returns
-------
moc: float
Manders' Overlap Coefficient of pixel intensities between the two
images.
Notes
-----
Manders' Overlap Coefficient (MOC) is given by the equation [1]_:
.. math::
r = \frac{\sum A_i B_i}{\sqrt{\sum A_i^2 \sum B_i^2}}
where
:math:`A_i` is the value of the :math:`i^{th}` pixel in `image0`
:math:`B_i` is the value of the :math:`i^{th}` pixel in `image1`
It ranges between 0 for no colocalization and 1 for complete colocalization
of all pixels.
MOC does not take into account pixel intensities, just the fraction of
pixels that have positive values for both channels[2]_ [3]_. Its usefulness
has been criticized as it changes in response to differences in both
co-occurence and correlation and so a particular MOC value could indicate
a wide range of colocalization patterns [4]_ [5]_.
References
----------
.. [1] <NAME>., <NAME>. and <NAME>. (1993), Measurement of
co-localization of objects in dual-colour confocal images. Journal
of Microscopy, 169: 375-382.
https://doi.org/10.1111/j.1365-2818.1993.tb03313.x
https://imagej.net/media/manders.pdf
.. [2] <NAME>., <NAME>., & <NAME>. (2011). A practical
guide to evaluating colocalization in biological microscopy.
American journal of physiology. Cell physiology, 300(4), C723–C742.
https://doi.org/10.1152/ajpcell.00462.2010
.. [3] <NAME>. and <NAME>. (2006), A guided tour into
subcellular colocalization analysis in light microscopy. Journal of
Microscopy, 224: 213-232.
https://doi.org/10.1111/j.1365-2818.2006.01
.. [4] <NAME>, <NAME>. (2010), Quantifying colocalization by
correlation: the Pearson correlation coefficient is
superior to the Mander's overlap coefficient. Cytometry A.
Aug;77(8):733-42.https://doi.org/10.1002/cyto.a.20896
.. [5] <NAME>, <NAME>. Quantifying colocalization: The case for
discarding the Manders overlap coefficient. Cytometry. 2021; 99:
910– 920. https://doi.org/10.1002/cyto.a.24336
"""
image0 = np.asarray(image0)
image1 = np.asarray(image1)
if mask is not None:
mask = as_binary_ndarray(mask, variable_name="mask")
check_shape_equality(image0, image1, mask)
image0 = image0[mask]
image1 = image1[mask]
else:
check_shape_equality(image0, image1)
# check non-negative image
if image0.min() < 0:
raise ValueError("image0 contains negative values")
if image1.min() < 0:
raise ValueError("image1 contains negative values")
denom = (np.sum(np.square(image0)) * (np.sum(np.square(image1)))) ** 0.5
return np.sum(np.multiply(image0, image1)) / denom
def intersection_coeff(image0_mask, image1_mask, mask=None):
r"""Fraction of a channel's segmented binary mask that overlaps with a
second channel's segmented binary mask.
Parameters
----------
image0_mask : (M, N) ndarray of dtype bool
Image mask of channel A.
image1_mask : (M, N) ndarray of dtype bool
Image mask of channel B.
Must have same dimensions as `image0_mask`.
mask : (M, N) ndarray of dtype bool, optional
Only `image0_mask` and `image1_mask` pixels within this region of
interest
mask are included in the calculation.
Must have same dimensions as `image0_mask`.
Returns
-------
Intersection coefficient, float
Fraction of `image0_mask` that overlaps with `image1_mask`.
"""
image0_mask = as_binary_ndarray(image0_mask, variable_name="image0_mask")
image1_mask = as_binary_ndarray(image1_mask, variable_name="image1_mask")
if mask is not None:
mask = as_binary_ndarray(mask, variable_name="mask")
check_shape_equality(image0_mask, image1_mask, mask)
image0_mask = image0_mask[mask]
image1_mask = image1_mask[mask]
else:
check_shape_equality(image0_mask, image1_mask)
nonzero_image0 = np.count_nonzero(image0_mask)
if nonzero_image0 == 0:
return 0
nonzero_joint = np.count_nonzero(np.logical_and(image0_mask, image1_mask))
return nonzero_joint / nonzero_image0
<file_sep>/skimage/future/__init__.pyi
# Explicitly setting `__all__` is necessary for type inference engines
# to know which symbols are exported. See
# https://peps.python.org/pep-0484/#stub-files
__all__ = [
"manual_lasso_segmentation",
"manual_polygon_segmentation",
"fit_segmenter",
"predict_segmenter",
"TrainableSegmenter",
]
from .manual_segmentation import manual_lasso_segmentation, manual_polygon_segmentation
from .trainable_segmentation import fit_segmenter, predict_segmenter, TrainableSegmenter
<file_sep>/doc/examples/segmentation/plot_perimeters.py
"""
============================================
Measure perimeters with different estimators
============================================
In this example, we show the error on measuring perimeters, comparing classic
approximations and Crofton ones. For that, we estimate the perimeter of an
object (either a square or a disk) and its rotated version, as we increase the
rotation angle.
"""
import matplotlib.pyplot as plt
import numpy as np
from skimage.measure import perimeter, perimeter_crofton
from skimage.transform import rotate
# scale parameter can be used to increase the grid size. The resulting curves
# should be smoothed with higher scales
scale = 10
# Construct two objects, a square and a disk
square = np.zeros((100*scale, 100*scale))
square[40*scale:60*scale, 40*scale:60*scale] = 1
[X, Y] = np.meshgrid(np.linspace(0, 100*scale), np.linspace(0, 100*scale))
R = 20 * scale
disk = (X-50*scale)**2+(Y-50*scale)**2 <= R**2
fig, axes = plt.subplots(1, 2, figsize=(8, 5))
ax = axes.flatten()
dX = X[0, 1] - X[0, 0]
true_perimeters = [80 * scale, 2 * np.pi * R / dX]
# For each type of object, estimate its perimeter as the object is rotated,
# according to different approximations
for index, obj in enumerate([square, disk]):
# `neighborhood` value can be 4 or 8 for the classic perimeter estimator
for n in [4, 8]:
p = []
angles = range(90)
for i in angles:
rotated = rotate(obj, i, order=0)
p.append(perimeter(rotated, n))
ax[index].plot(angles, p)
# `directions` value can be 2 or 4 for the Crofton estimator
for d in [2, 4]:
p = []
angles = np.arange(0, 90, 2)
for i in angles:
rotated = rotate(obj, i, order=0)
p.append(perimeter_crofton(rotated, d))
ax[index].plot(angles, p)
ax[index].axhline(true_perimeters[index], linestyle='--', color='k')
ax[index].set_xlabel('Rotation angle')
ax[index].legend(['N4 perimeter', 'N8 perimeter',
'Crofton 2 directions', 'Crofton 4 directions',
'Ground truth'],
loc='best')
ax[index].set_ylabel('Perimeter of the rotated object')
ax[0].set_title('Square')
ax[1].set_title('Disk')
plt.tight_layout()
plt.show()
<file_sep>/doc/source/development/index.rst
Development
===========
Below you will find resources about the development of scikit-image.
.. toctree::
:maxdepth: 1
contribute
../gitwash/index
core_developer
../skips/index
<file_sep>/skimage/data/__init__.pyi
__all__ = [
'astronaut',
'binary_blobs',
'brain',
'brick',
'camera',
'cat',
'cell',
'cells3d',
'checkerboard',
'chelsea',
'clock',
'coffee',
'coins',
'colorwheel',
'data_dir',
'download_all',
'eagle',
'file_hash',
'grass',
'gravel',
'horse',
'hubble_deep_field',
'human_mitosis',
'immunohistochemistry',
'kidney',
'lbp_frontal_face_cascade_filename',
'lfw_subset',
'lily',
'logo',
'microaneurysms',
'moon',
'nickel_solidification',
'page',
'protein_transport',
'retina',
'rocket',
'shepp_logan_phantom',
'skin',
'stereo_motorcycle',
'text',
'vortex',
]
from ._binary_blobs import binary_blobs
from ._fetchers import (
astronaut,
brain,
brick,
camera,
cat,
cell,
cells3d,
checkerboard,
chelsea,
clock,
coffee,
coins,
colorwheel,
data_dir,
download_all,
eagle,
file_hash,
grass,
gravel,
horse,
hubble_deep_field,
human_mitosis,
immunohistochemistry,
kidney,
lbp_frontal_face_cascade_filename,
lfw_subset,
lily,
logo,
microaneurysms,
moon,
nickel_solidification,
page,
palisades_of_vogt,
protein_transport,
retina,
rocket,
shepp_logan_phantom,
skin,
stereo_motorcycle,
text,
vortex,
)
<file_sep>/doc/examples/data/plot_general.py
"""
======================
General-purpose images
======================
The title of each image indicates the name of the function.
"""
import matplotlib.pyplot as plt
import matplotlib
import numpy as np
from skimage import data
matplotlib.rcParams['font.size'] = 18
images = ('astronaut',
'binary_blobs',
'brick',
'colorwheel',
'camera',
'cat',
'checkerboard',
'clock',
'coffee',
'coins',
'eagle',
'grass',
'gravel',
'horse',
'logo',
'page',
'text',
'rocket',
)
for name in images:
caller = getattr(data, name)
image = caller()
plt.figure()
plt.title(name)
if image.ndim == 2:
plt.imshow(image, cmap=plt.cm.gray)
else:
plt.imshow(image)
plt.show()
############################################################################
# Thumbnail image for the gallery
# sphinx_gallery_thumbnail_number = -1
fig, axs = plt.subplots(nrows=3, ncols=3)
for ax in axs.flat:
ax.axis("off")
axs[0, 0].imshow(data.astronaut())
axs[0, 1].imshow(data.binary_blobs(), cmap=plt.cm.gray)
axs[0, 2].imshow(data.brick(), cmap=plt.cm.gray)
axs[1, 0].imshow(data.colorwheel())
axs[1, 1].imshow(data.camera(), cmap=plt.cm.gray)
axs[1, 2].imshow(data.cat())
axs[2, 0].imshow(data.checkerboard(), cmap=plt.cm.gray)
axs[2, 1].imshow(data.clock(), cmap=plt.cm.gray)
further_img = np.full((300, 300), 255)
for xpos in [100, 150, 200]:
further_img[150 - 10 : 150 + 10, xpos - 10 : xpos + 10] = 0
axs[2, 2].imshow(further_img, cmap=plt.cm.gray)
plt.subplots_adjust(wspace=0.1, hspace=0.1)
<file_sep>/skimage/util/__init__.py
"""General utility functions.
This module contains a number of utility functions to work with images in general.
"""
import functools
import warnings
import numpy as np
# keep .dtype imports first to avoid circular imports
from .dtype import (dtype_limits, img_as_float, img_as_float32, img_as_float64,
img_as_bool, img_as_int, img_as_ubyte, img_as_uint)
from ._slice_along_axes import slice_along_axes
from ._invert import invert
from ._label import label_points
from ._montage import montage
from ._map_array import map_array
from ._regular_grid import regular_grid, regular_seeds
from .apply_parallel import apply_parallel
from .arraycrop import crop
from .compare import compare_images
from .noise import random_noise
from .shape import view_as_blocks, view_as_windows
from .unique import unique_rows
__all__ = [
'img_as_float32',
'img_as_float64',
'img_as_float',
'img_as_int',
'img_as_uint',
'img_as_ubyte',
'img_as_bool',
'dtype_limits',
'view_as_blocks',
'view_as_windows',
'slice_along_axes',
'crop',
'compare_images',
'map_array',
'montage',
'random_noise',
'regular_grid',
'regular_seeds',
'apply_parallel',
'invert',
'unique_rows',
'label_points',
]
<file_sep>/README.md
# scikit-image: Image processing in Python
[](https://forum.image.sc/tags/scikit-image)
[](https://stackoverflow.com/questions/tagged/scikit-image)
[](https://skimage.zulipchat.com)
- **Website (including documentation):** [https://scikit-image.org/](https://scikit-image.org)
- **Documentation:** [https://scikit-image.org/docs/stable/](https://scikit-image.org/docs/stable/)
- **User forum:** [https://forum.image.sc/tag/scikit-image](https://forum.image.sc/tag/scikit-image)
- **Developer forum:** [https://discuss.scientific-python.org/c/contributor/skimage](https://discuss.scientific-python.org/c/contributor/skimage)
- **Source:** [https://github.com/scikit-image/scikit-image](https://github.com/scikit-image/scikit-image)
## Installation
- **pip:** `pip install scikit-image`
- **conda:** `conda install -c conda-forge scikit-image`
Also see [installing `scikit-image`](https://github.com/scikit-image/scikit-image/blob/main/INSTALL.rst).
## License
See [LICENSE.txt](https://github.com/scikit-image/scikit-image/blob/main/LICENSE.txt).
## Citation
If you find this project useful, please cite:
> <NAME>, <NAME>, <NAME>,
> <NAME>, <NAME>, <NAME>, Emmanuelle
> Gouillart, <NAME>, and the scikit-image contributors.
> _scikit-image: Image processing in Python_. PeerJ 2:e453 (2014)
> https://doi.org/10.7717/peerj.453
<file_sep>/skimage/filters/ridges.py
"""
Ridge filters.
Ridge filters can be used to detect continuous edges, such as vessels,
neurites, wrinkles, rivers, and other tube-like structures. The present
class of ridge filters relies on the eigenvalues of the Hessian matrix of
image intensities to detect tube-like structures where the intensity changes
perpendicular but not along the structure.
"""
from warnings import warn
import numpy as np
from scipy import linalg
from .._shared.utils import _supported_float_type, check_nD, deprecate_func
from ..feature.corner import hessian_matrix, hessian_matrix_eigvals
from ..util import img_as_float
@deprecate_func(
deprecated_version="0.20",
removed_version="0.22",
hint="Use `skimage.feature.hessian_matrix_eigvals` on the results of "
"`skimage.feature.hessian_matrix` instead."
)
def compute_hessian_eigenvalues(image, sigma, sorting='none',
mode='constant', cval=0,
use_gaussian_derivatives=False):
"""
Compute Hessian eigenvalues of nD images.
For 2D images, the computation uses a more efficient, skimage-based
algorithm.
Parameters
----------
image : (N, ..., M) ndarray
Array with input image data.
sigma : float
Smoothing factor of image for detection of structures at different
(sigma) scales.
sorting : {'val', 'abs', 'none'}, optional
Sorting of eigenvalues by values ('val') or absolute values ('abs'),
or without sorting ('none'). Default is 'none'.
mode : {'constant', 'reflect', 'wrap', 'nearest', 'mirror'}, optional
How to handle values outside the image borders.
cval : float, optional
Used in conjunction with mode 'constant', the value outside
the image boundaries.
use_gaussian_derivatives : boolean, optional
Indicates whether the Hessian is computed by convolving with Gaussian
derivatives, or by a simple finite-difference operation.
Returns
-------
eigenvalues : (D, N, ..., M) ndarray
Array with (sorted) eigenvalues of Hessian eigenvalues for each pixel
of the input image.
"""
# Convert image to float
float_dtype = _supported_float_type(image.dtype)
# rescales integer images to [-1, 1]
image = img_as_float(image)
# make sure float16 gets promoted to float32
image = image.astype(float_dtype, copy=False)
# Make nD hessian
hessian_matrix_kwargs = dict(
sigma=sigma, order='rc', mode=mode, cval=cval,
use_gaussian_derivatives=use_gaussian_derivatives
)
hessian_elements = hessian_matrix(image, **hessian_matrix_kwargs)
if not use_gaussian_derivatives:
# Kept to preserve legacy behavior
hessian_elements = [(sigma ** 2) * e for e in hessian_elements]
# Compute Hessian eigenvalues
hessian_eigenvalues = hessian_matrix_eigvals(hessian_elements)
if sorting == 'abs':
# Sort eigenvalues by absolute values in ascending order
hessian_eigenvalues = np.take_along_axis(
hessian_eigenvalues, abs(hessian_eigenvalues).argsort(0), 0)
elif sorting == 'val':
# Sort eigenvalues by values in ascending order
hessian_eigenvalues = np.sort(hessian_eigenvalues, axis=0)
# Return Hessian eigenvalues
return hessian_eigenvalues
def meijering(image, sigmas=range(1, 10, 2), alpha=None,
black_ridges=True, mode='reflect', cval=0):
"""
Filter an image with the Meijering neuriteness filter.
This filter can be used to detect continuous ridges, e.g. neurites,
wrinkles, rivers. It can be used to calculate the fraction of the
whole image containing such objects.
Calculates the eigenvalues of the Hessian to compute the similarity of
an image region to neurites, according to the method described in [1]_.
Parameters
----------
image : (N, M[, ..., P]) ndarray
Array with input image data.
sigmas : iterable of floats, optional
Sigmas used as scales of filter
alpha : float, optional
Shaping filter constant, that selects maximally flat elongated
features. The default, None, selects the optimal value -1/(ndim+1).
black_ridges : boolean, optional
When True (the default), the filter detects black ridges; when
False, it detects white ridges.
mode : {'constant', 'reflect', 'wrap', 'nearest', 'mirror'}, optional
How to handle values outside the image borders.
cval : float, optional
Used in conjunction with mode 'constant', the value outside
the image boundaries.
Returns
-------
out : (N, M[, ..., P]) ndarray
Filtered image (maximum of pixels across all scales).
See also
--------
sato
frangi
hessian
References
----------
.. [1] <NAME>., <NAME>., <NAME>., <NAME>., <NAME>.,
<NAME>. (2004). Design and validation of a tool for neurite tracing
and analysis in fluorescence microscopy images. Cytometry Part A,
58(2), 167-176.
:DOI:`10.1002/cyto.a.20022`
"""
image = image.astype(_supported_float_type(image.dtype), copy=False)
if not black_ridges: # Normalize to black ridges.
image = -image
if alpha is None:
alpha = 1 / (image.ndim + 1)
mtx = linalg.circulant(
[1, *[alpha] * (image.ndim - 1)]).astype(image.dtype)
# Generate empty array for storing maximum value
# from different (sigma) scales
filtered_max = np.zeros_like(image)
for sigma in sigmas: # Filter for all sigmas.
eigvals = hessian_matrix_eigvals(hessian_matrix(
image, sigma, mode=mode, cval=cval, use_gaussian_derivatives=True))
# Compute normalized eigenvalues l_i = e_i + sum_{j!=i} alpha * e_j.
vals = np.tensordot(mtx, eigvals, 1)
# Get largest normalized eigenvalue (by magnitude) at each pixel.
vals = np.take_along_axis(
vals, abs(vals).argmax(0)[None], 0).squeeze(0)
# Remove negative values.
vals = np.maximum(vals, 0)
# Normalize to max = 1 (unless everything is already zero).
max_val = vals.max()
if max_val > 0:
vals /= max_val
filtered_max = np.maximum(filtered_max, vals)
return filtered_max # Return pixel-wise max over all sigmas.
def sato(image, sigmas=range(1, 10, 2), black_ridges=True,
mode='reflect', cval=0):
"""
Filter an image with the Sato tubeness filter.
This filter can be used to detect continuous ridges, e.g. tubes,
wrinkles, rivers. It can be used to calculate the fraction of the
whole image containing such objects.
Defined only for 2-D and 3-D images. Calculates the eigenvalues of the
Hessian to compute the similarity of an image region to tubes, according to
the method described in [1]_.
Parameters
----------
image : (N, M[, P]) ndarray
Array with input image data.
sigmas : iterable of floats, optional
Sigmas used as scales of filter.
black_ridges : boolean, optional
When True (the default), the filter detects black ridges; when
False, it detects white ridges.
mode : {'constant', 'reflect', 'wrap', 'nearest', 'mirror'}, optional
How to handle values outside the image borders.
cval : float, optional
Used in conjunction with mode 'constant', the value outside
the image boundaries.
Returns
-------
out : (N, M[, P]) ndarray
Filtered image (maximum of pixels across all scales).
See also
--------
meijering
frangi
hessian
References
----------
.. [1] <NAME>., <NAME>., <NAME>., <NAME>., <NAME>.,
<NAME>., ..., <NAME>. (1998). Three-dimensional multi-scale line
filter for segmentation and visualization of curvilinear structures in
medical images. Medical image analysis, 2(2), 143-168.
:DOI:`10.1016/S1361-8415(98)80009-1`
"""
check_nD(image, [2, 3]) # Check image dimensions.
image = image.astype(_supported_float_type(image.dtype), copy=False)
if not black_ridges: # Normalize to black ridges.
image = -image
# Generate empty array for storing maximum value
# from different (sigma) scales
filtered_max = np.zeros_like(image)
for sigma in sigmas: # Filter for all sigmas.
eigvals = hessian_matrix_eigvals(hessian_matrix(
image, sigma, mode=mode, cval=cval, use_gaussian_derivatives=True))
# Compute normalized tubeness (eqs. (9) and (22), ref. [1]_) as the
# geometric mean of eigvals other than the lowest one
# (hessian_matrix_eigvals returns eigvals in decreasing order), clipped
# to 0, multiplied by sigma^2.
eigvals = eigvals[:-1]
vals = (sigma ** 2
* np.prod(np.maximum(eigvals, 0), 0) ** (1 / len(eigvals)))
filtered_max = np.maximum(filtered_max, vals)
return filtered_max # Return pixel-wise max over all sigmas.
def frangi(image, sigmas=range(1, 10, 2), scale_range=None,
scale_step=None, alpha=0.5, beta=0.5, gamma=None,
black_ridges=True, mode='reflect', cval=0):
"""
Filter an image with the Frangi vesselness filter.
This filter can be used to detect continuous ridges, e.g. vessels,
wrinkles, rivers. It can be used to calculate the fraction of the
whole image containing such objects.
Defined only for 2-D and 3-D images. Calculates the eigenvalues of the
Hessian to compute the similarity of an image region to vessels, according
to the method described in [1]_.
Parameters
----------
image : (N, M[, P]) ndarray
Array with input image data.
sigmas : iterable of floats, optional
Sigmas used as scales of filter, i.e.,
np.arange(scale_range[0], scale_range[1], scale_step)
scale_range : 2-tuple of floats, optional
The range of sigmas used.
scale_step : float, optional
Step size between sigmas.
alpha : float, optional
Frangi correction constant that adjusts the filter's
sensitivity to deviation from a plate-like structure.
beta : float, optional
Frangi correction constant that adjusts the filter's
sensitivity to deviation from a blob-like structure.
gamma : float, optional
Frangi correction constant that adjusts the filter's
sensitivity to areas of high variance/texture/structure.
The default, None, uses half of the maximum Hessian norm.
black_ridges : boolean, optional
When True (the default), the filter detects black ridges; when
False, it detects white ridges.
mode : {'constant', 'reflect', 'wrap', 'nearest', 'mirror'}, optional
How to handle values outside the image borders.
cval : float, optional
Used in conjunction with mode 'constant', the value outside
the image boundaries.
Returns
-------
out : (N, M[, P]) ndarray
Filtered image (maximum of pixels across all scales).
Notes
-----
Earlier versions of this filter were implemented by <NAME>,
(November 2001), <NAME>, University of Twente (May 2009) [2]_, and
<NAME> (January 2017) [3]_.
See also
--------
meijering
sato
hessian
References
----------
.. [1] <NAME>., <NAME>., <NAME>., & <NAME>.
(1998,). Multiscale vessel enhancement filtering. In International
Conference on Medical Image Computing and Computer-Assisted
Intervention (pp. 130-137). Springer Berlin Heidelberg.
:DOI:`10.1007/BFb0056195`
.. [2] <NAME>.: Hessian based Frangi vesselness filter.
.. [3] <NAME>.: https://github.com/ellisdg/frangi3d/tree/master/frangi
"""
if scale_range is not None and scale_step is not None:
warn('Use keyword parameter `sigmas` instead of `scale_range` and '
'`scale_range` which will be removed in version 0.17.',
stacklevel=2)
sigmas = np.arange(scale_range[0], scale_range[1], scale_step)
check_nD(image, [2, 3]) # Check image dimensions.
image = image.astype(_supported_float_type(image.dtype), copy=False)
if not black_ridges: # Normalize to black ridges.
image = -image
# Generate empty array for storing maximum value
# from different (sigma) scales
filtered_max = np.zeros_like(image)
for sigma in sigmas: # Filter for all sigmas.
eigvals = hessian_matrix_eigvals(hessian_matrix(
image, sigma, mode=mode, cval=cval, use_gaussian_derivatives=True))
# Sort eigenvalues by magnitude.
eigvals = np.take_along_axis(eigvals, abs(eigvals).argsort(0), 0)
lambda1 = eigvals[0]
if image.ndim == 2:
lambda2, = np.maximum(eigvals[1:], 1e-10)
r_a = np.inf # implied by eq. (15).
r_b = abs(lambda1) / lambda2 # eq. (15).
else: # ndim == 3
lambda2, lambda3 = np.maximum(eigvals[1:], 1e-10)
r_a = lambda2 / lambda3 # eq. (11).
r_b = abs(lambda1) / np.sqrt(lambda2 * lambda3) # eq. (10).
s = np.sqrt((eigvals ** 2).sum(0)) # eq. (12).
if gamma is None:
gamma = s.max() / 2
if gamma == 0:
gamma = 1 # If s == 0 everywhere, gamma doesn't matter.
# Filtered image, eq. (13) and (15). Our implementation relies on the
# blobness exponential factor underflowing to zero whenever the second
# or third eigenvalues are negative (we clip them to 1e-10, to make r_b
# very large).
vals = 1.0 - np.exp(-r_a**2 / (2 * alpha**2)) # plate sensitivity
vals *= np.exp(-r_b**2 / (2 * beta**2)) # blobness
vals *= 1.0 - np.exp(-s**2 / (2 * gamma**2)) # structuredness
filtered_max = np.maximum(filtered_max, vals)
return filtered_max # Return pixel-wise max over all sigmas.
def hessian(image, sigmas=range(1, 10, 2), scale_range=None, scale_step=None,
alpha=0.5, beta=0.5, gamma=15, black_ridges=True, mode='reflect',
cval=0):
"""Filter an image with the Hybrid Hessian filter.
This filter can be used to detect continuous edges, e.g. vessels,
wrinkles, rivers. It can be used to calculate the fraction of the whole
image containing such objects.
Defined only for 2-D and 3-D images. Almost equal to Frangi filter, but
uses alternative method of smoothing. Refer to [1]_ to find the differences
between Frangi and Hessian filters.
Parameters
----------
image : (N, M[, P]) ndarray
Array with input image data.
sigmas : iterable of floats, optional
Sigmas used as scales of filter, i.e.,
np.arange(scale_range[0], scale_range[1], scale_step)
scale_range : 2-tuple of floats, optional
The range of sigmas used.
scale_step : float, optional
Step size between sigmas.
beta : float, optional
Frangi correction constant that adjusts the filter's
sensitivity to deviation from a blob-like structure.
gamma : float, optional
Frangi correction constant that adjusts the filter's
sensitivity to areas of high variance/texture/structure.
black_ridges : boolean, optional
When True (the default), the filter detects black ridges; when
False, it detects white ridges.
mode : {'constant', 'reflect', 'wrap', 'nearest', 'mirror'}, optional
How to handle values outside the image borders.
cval : float, optional
Used in conjunction with mode 'constant', the value outside
the image boundaries.
Returns
-------
out : (N, M[, P]) ndarray
Filtered image (maximum of pixels across all scales).
Notes
-----
Written by <NAME> (November 2001)
Re-Written by <NAME>on University of Twente (May 2009) [2]_
See also
--------
meijering
sato
frangi
References
----------
.. [1] <NAME>., <NAME>., <NAME>., & <NAME>. (2014,). Automatic
wrinkle detection using hybrid Hessian filter. In Asian Conference on
Computer Vision (pp. 609-622). Springer International Publishing.
:DOI:`10.1007/978-3-319-16811-1_40`
.. [2] <NAME>.: Hessian based Frangi vesselness filter.
"""
filtered = frangi(image, sigmas=sigmas, scale_range=scale_range,
scale_step=scale_step, alpha=alpha, beta=beta,
gamma=gamma, black_ridges=black_ridges, mode=mode,
cval=cval)
filtered[filtered <= 0] = 1
return filtered
<file_sep>/TODO.txt
Remember to list any API changes below in `doc/release/release_dev.rst`.
Version 0.17
------------
* Finalize ``skimage.future.manual_segmentation`` API.
Version 0.22
------------
* In ``skimage/filters/lpi_filter.py``, remove the deprecated function
inverse().
* Set `channel_axis=None` in `skimage._shared.filters.gaussian` and remove
`skimage._shared.filters._PatchClassRepr`,
`skimage/_shared/filters.ChannelAxisNotSet`, and
`skimage.filters.tests.test_gaussian.test_deprecated_automatic_channel_detection`.
Also remove the associated warning in `skimage._shared.filters.gaussian`'s
docstring.
* Deprecate ``return_error`` argument in
``skimage.registration.phase_cross_correlation``. The function should always
return a tuple of (shift, error, phasediff).
Update ``test_phase_cross_correlation_deprecation``, too.
* Remove ``skimage/future/graph`` and ``skimage/future/tests/test_graph`.
Remove the ``future/graph`` entry in ``skimage/conftest.py::collect_ignore``.
Remove the ``r'\.future.graph$'`` entry added to
``docwriter.package_skip_patterns`` in
``doc/tools/build_modref_templates.py``.
* Remove deprecated function ``skimage.filters.ridges.compute_hessian_eigenvalues``.
Version 0.23
------------
* Remove deprecated `random_seed`, `random_state`, and `sample_seed`
arguments in favor of `rng`.
* Remove deprecated function ``skimage.color.colorconv.get_xyz_coords()``.
Other (2022)
------------
* Remove custom code for ignored warning in `skimage/_shared/testing.py` relating
to (sparse) matricies (instead of arrays).
* Remove warningsfilter for imageio and Pillow once
https://github.com/python-pillow/Pillow/pull/7125 is shipped in the minimal required
version of pillow (probably the release after Pillow 9.5.0).
* NumPy 1.25.0 is minimal required version:
* Remove optional test for a NaN-related deprecation warning from numpy.clip in
skimage/exposure/tests/test_exposure.py::test_rescale_nan_warning
<file_sep>/doc/examples/README.txt
.. _examples_gallery:
Examples
========
A gallery of examples and that showcase how scikit-image can be used. Some
examples demonstrate the use of the API in general and some demonstrate specific
applications in tutorial form.
.. hint::
Check out our :ref:`user_guide` for a narrative
introduction to key library conventions and basic image manipulation.
<file_sep>/doc/examples/filters/plot_blur_effect.py
"""
=========================
Estimate strength of blur
=========================
This example shows how the metric implemented in ``measure.blur_effect``
behaves, both as a function of the strength of blur and of the size of the
re-blurring filter. This no-reference perceptual blur metric is described in
[1]_.
.. [1] <NAME>, <NAME>, <NAME>, and <NAME> "The blur effect: perception and estimation with a new
no-reference perceptual blur metric" Proc. SPIE 6492, Human Vision and
Electronic Imaging XII, 64920I (2007)
https://hal.archives-ouvertes.fr/hal-00232709
:DOI:`10.1117/12.702790`
"""
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import scipy.ndimage as ndi
import plotly
import plotly.express as px
from skimage import (
color, data, measure
)
#####################################################################
# Generate series of increasingly blurred images
# ==============================================
# Let us load an image available through scikit-image’s data registry. The
# blur metric applies to single-channel images.
image = data.astronaut()
image = color.rgb2gray(image)
#####################################################################
# Let us blur this image with a series of uniform filters of increasing size.
blurred_images = [ndi.uniform_filter(image, size=k) for k in range(2, 32, 2)]
img_stack = np.stack(blurred_images)
fig = px.imshow(
img_stack,
animation_frame=0,
binary_string=True,
labels={'animation_frame': 'blur strength ~'}
)
plotly.io.show(fig)
#####################################################################
# Plot blur metric
# ================
# Let us compute the blur metric for all blurred images: We expect it to
# increase towards 1 with increasing blur strength. We compute it for three
# different values of re-blurring filter: 3, 11 (default), and 30.
B = pd.DataFrame(
data=np.zeros((len(blurred_images), 3)),
columns=['h_size = 3', 'h_size = 11', 'h_size = 30']
)
for ind, im in enumerate(blurred_images):
B.loc[ind, 'h_size = 3'] = measure.blur_effect(im, h_size=3)
B.loc[ind, 'h_size = 11'] = measure.blur_effect(im, h_size=11)
B.loc[ind, 'h_size = 30'] = measure.blur_effect(im, h_size=30)
B.plot().set(xlabel='blur strength (half the size of uniform filter)',
ylabel='blur metric')
plt.show()
#####################################################################
# We can see that as soon as the blur is stronger than (reaches the scale of)
# the size of the uniform filter, the metric gets close to 1 and, hence, tends
# asymptotically to 1 with increasing blur strength.
# The value of 11 pixels gives a blur metric which correlates best with human
# perception. That's why it's the default value in the implementation of the
# perceptual blur metric ``measure.blur_effect``.
<file_sep>/skimage/metrics/_adapted_rand_error.py
from .._shared.utils import check_shape_equality
from ._contingency_table import contingency_table
__all__ = ['adapted_rand_error']
def adapted_rand_error(image_true=None, image_test=None, *, table=None,
ignore_labels=(0,), alpha=0.5):
r"""Compute Adapted Rand error as defined by the SNEMI3D contest. [1]_
Parameters
----------
image_true : ndarray of int
Ground-truth label image, same shape as im_test.
image_test : ndarray of int
Test image.
table : scipy.sparse array in crs format, optional
A contingency table built with skimage.evaluate.contingency_table.
If None, it will be computed on the fly.
ignore_labels : sequence of int, optional
Labels to ignore. Any part of the true image labeled with any of these
values will not be counted in the score.
alpha : float, optional
Relative weight given to precision and recall in the adapted Rand error
calculation.
Returns
-------
are : float
The adapted Rand error.
prec : float
The adapted Rand precision: this is the number of pairs of pixels that
have the same label in the test label image *and* in the true image,
divided by the number in the test image.
rec : float
The adapted Rand recall: this is the number of pairs of pixels that
have the same label in the test label image *and* in the true image,
divided by the number in the true image.
Notes
-----
Pixels with label 0 in the true segmentation are ignored in the score.
The adapted Rand error is calculated as follows:
:math:`1 - \frac{\sum_{ij} p_{ij}^{2}}{\alpha \sum_{k} s_{k}^{2} +
(1-\alpha)\sum_{k} t_{k}^{2}}`,
where :math:`p_{ij}` is the probability that a pixel has the same label
in the test image *and* in the true image, :math:`t_{k}` is the
probability that a pixel has label :math:`k` in the true image,
and :math:`s_{k}` is the probability that a pixel has label :math:`k`
in the test image.
Default behavior is to weight precision and recall equally in the
adapted Rand error calculation.
When alpha = 0, adapted Rand error = recall.
When alpha = 1, adapted Rand error = precision.
References
----------
.. [1] <NAME>, <NAME>, <NAME>, et al. (2015)
Crowdsourcing the creation of image segmentation algorithms
for connectomics. Front. Neuroanat. 9:142.
:DOI:`10.3389/fnana.2015.00142`
"""
if image_test is not None and image_true is not None:
check_shape_equality(image_true, image_test)
if table is None:
p_ij = contingency_table(image_true, image_test,
ignore_labels=ignore_labels, normalize=False)
else:
p_ij = table
if alpha < 0.0 or alpha > 1.0:
raise ValueError('alpha must be between 0 and 1')
# Sum of the joint distribution squared
sum_p_ij2 = p_ij.data @ p_ij.data - p_ij.sum()
a_i = p_ij.sum(axis=1).A.ravel()
b_i = p_ij.sum(axis=0).A.ravel()
# Sum of squares of the test segment sizes (this is 2x the number of pairs
# of pixels with the same label in im_test)
sum_a2 = a_i @ a_i - a_i.sum()
# Same for im_true
sum_b2 = b_i @ b_i - b_i.sum()
precision = sum_p_ij2 / sum_a2
recall = sum_p_ij2 / sum_b2
fscore = sum_p_ij2 / (alpha * sum_a2 + (1 - alpha) * sum_b2)
are = 1. - fscore
return are, precision, recall
<file_sep>/skimage/util/tests/test_apply_parallel.py
import numpy as np
from skimage._shared.testing import (assert_array_almost_equal, assert_equal)
from skimage import color, data, img_as_float
from skimage.filters import threshold_local, gaussian
from skimage.util.apply_parallel import apply_parallel
import pytest
da = pytest.importorskip('dask.array')
def test_apply_parallel():
# data
a = np.arange(144).reshape(12, 12).astype(float)
# apply the filter
expected1 = threshold_local(a, 3)
result1 = apply_parallel(threshold_local, a, chunks=(6, 6), depth=5,
extra_arguments=(3,),
extra_keywords={'mode': 'reflect'})
assert_array_almost_equal(result1, expected1)
def wrapped_gauss(arr):
return gaussian(arr, 1, mode='reflect')
expected2 = gaussian(a, 1, mode='reflect')
result2 = apply_parallel(wrapped_gauss, a, chunks=(6, 6), depth=5)
assert_array_almost_equal(result2, expected2)
expected3 = gaussian(a, 1, mode='reflect')
result3 = apply_parallel(
wrapped_gauss, da.from_array(a, chunks=(6, 6)), depth=5, compute=True
)
assert isinstance(result3, np.ndarray)
assert_array_almost_equal(result3, expected3)
def test_apply_parallel_lazy():
# data
a = np.arange(144).reshape(12, 12).astype(float)
d = da.from_array(a, chunks=(6, 6))
# apply the filter
expected1 = threshold_local(a, 3)
result1 = apply_parallel(threshold_local, a, chunks=(6, 6), depth=5,
extra_arguments=(3,),
extra_keywords={'mode': 'reflect'},
compute=False)
# apply the filter on a Dask Array
result2 = apply_parallel(threshold_local, d, depth=5,
extra_arguments=(3,),
extra_keywords={'mode': 'reflect'})
assert isinstance(result1, da.Array)
assert_array_almost_equal(result1.compute(), expected1)
assert isinstance(result2, da.Array)
assert_array_almost_equal(result2.compute(), expected1)
def test_no_chunks():
a = np.ones(1 * 4 * 8 * 9).reshape(1, 4, 8, 9)
def add_42(arr):
return arr + 42
expected = add_42(a)
result = apply_parallel(add_42, a)
assert_array_almost_equal(result, expected)
def test_apply_parallel_wrap():
def wrapped(arr):
return gaussian(arr, 1, mode='wrap')
a = np.arange(144).reshape(12, 12).astype(float)
expected = gaussian(a, 1, mode='wrap')
result = apply_parallel(wrapped, a, chunks=(6, 6), depth=5, mode='wrap')
assert_array_almost_equal(result, expected)
def test_apply_parallel_nearest():
def wrapped(arr):
return gaussian(arr, 1, mode='nearest')
a = np.arange(144).reshape(12, 12).astype(float)
expected = gaussian(a, 1, mode='nearest')
result = apply_parallel(wrapped, a, chunks=(6, 6), depth={0: 5, 1: 5},
mode='nearest')
assert_array_almost_equal(result, expected)
@pytest.mark.parametrize('dtype', (np.float32, np.float64))
@pytest.mark.parametrize('chunks', (None, (128, 128, 3)))
@pytest.mark.parametrize('depth', (0, 8, (8, 8, 0)))
def test_apply_parallel_rgb(depth, chunks, dtype):
cat = data.chelsea().astype(dtype) / 255.
func = color.rgb2ycbcr
cat_ycbcr_expected = func(cat)
cat_ycbcr = apply_parallel(func, cat, chunks=chunks, depth=depth,
dtype=dtype, channel_axis=-1)
assert_equal(cat_ycbcr.dtype, cat.dtype)
assert_array_almost_equal(cat_ycbcr_expected, cat_ycbcr)
@pytest.mark.parametrize('chunks', (None, (128, 256), 'ndim'))
@pytest.mark.parametrize('depth', (0, 8, (8, 16), 'ndim'))
@pytest.mark.parametrize('channel_axis', (0, 1, 2, -1, -2, -3))
def test_apply_parallel_rgb_channel_axis(depth, chunks, channel_axis):
"""Test channel_axis combinations.
For depth and chunks, test in three ways:
1.) scalar (to be applied over all axes)
2.) tuple of length ``image.ndim - 1`` corresponding to spatial axes
3.) tuple of length ``image.ndim`` corresponding to all axes
"""
cat = img_as_float(data.chelsea())
func = color.rgb2ycbcr
cat_ycbcr_expected = func(cat, channel_axis=-1)
# move channel axis to another position
cat = np.moveaxis(cat, -1, channel_axis)
if chunks == 'ndim':
# explicitly specify the chunksize for the channel axis
chunks = [128, 128]
chunks.insert(channel_axis % cat.ndim, cat.shape[channel_axis])
if depth == 'ndim':
# explicitly specify the depth for the channel axis
depth = [8, 8]
depth.insert(channel_axis % cat.ndim, 0)
cat_ycbcr = apply_parallel(func, cat, chunks=chunks, depth=depth,
dtype=cat.dtype, channel_axis=channel_axis,
extra_keywords=dict(channel_axis=channel_axis))
# move channels of output back to the last dimension
cat_ycbcr = np.moveaxis(cat_ycbcr, channel_axis, -1)
assert_array_almost_equal(cat_ycbcr_expected, cat_ycbcr)
<file_sep>/benchmarks/benchmark_morphology.py
"""Benchmarks for `skimage.morphology`.
See "Writing benchmarks" in the asv docs for more information.
"""
import numpy as np
from numpy.lib import NumpyVersion as Version
import skimage
from skimage import data, morphology, util
class Skeletonize3d:
def setup(self, *args):
try:
# use a separate skeletonize_3d function on older scikit-image
if Version(skimage.__version__) < Version('0.16.0'):
self.skeletonize = morphology.skeletonize_3d
else:
self.skeletonize = morphology.skeletonize
except AttributeError:
raise NotImplementedError("3d skeletonize unavailable")
# we stack the horse data 5 times to get an example volume
self.image = np.stack(5 * [util.invert(data.horse())])
def time_skeletonize_3d(self):
self.skeletonize(self.image)
def peakmem_reference(self, *args):
"""Provide reference for memory measurement with empty benchmark.
Peakmem benchmarks measure the maximum amount of RAM used by a
function. However, this maximum also includes the memory used
during the setup routine (as of asv 0.2.1; see [1]_).
Measuring an empty peakmem function might allow us to disambiguate
between the memory used by setup and the memory used by target (see
other ``peakmem_`` functions below).
References
----------
.. [1]: https://asv.readthedocs.io/en/stable/writing_benchmarks.html#peak-memory
"""
pass
def peakmem_skeletonize_3d(self):
self.skeletonize(self.image)
# For binary morphology all functions ultimately are based on a single erosion
# function in the scipy.ndimage C code, so only benchmark binary_erosion here.
class BinaryMorphology2D:
# skip rectangle as roughly equivalent to square
param_names = ["shape", "footprint", "radius", "decomposition"]
params = [
((512, 512),),
("square", "diamond", "octagon", "disk", "ellipse", "star"),
(1, 3, 5, 15, 25, 40),
(None, "sequence", "separable", "crosses"),
]
def setup(self, shape, footprint, radius, decomposition):
rng = np.random.default_rng(123)
# Make an image that is mostly True, with random isolated False areas
# (so it will not become fully False for any of the footprints).
self.image = rng.standard_normal(shape) < 3.5
fp_func = getattr(morphology, footprint)
allow_sequence = ("rectangle", "square", "diamond", "octagon", "disk")
allow_separable = ("rectangle", "square")
allow_crosses = ("disk", "ellipse")
allow_decomp = tuple(
set(allow_sequence) | set(allow_separable) | set(allow_crosses)
)
footprint_kwargs = {}
if decomposition == "sequence" and footprint not in allow_sequence:
raise NotImplementedError("decomposition unimplemented")
elif decomposition == "separable" and footprint not in allow_separable:
raise NotImplementedError("separable decomposition unavailable")
elif decomposition == "crosses" and footprint not in allow_crosses:
raise NotImplementedError("separable decomposition unavailable")
if footprint in allow_decomp:
footprint_kwargs["decomposition"] = decomposition
if footprint in ["rectangle", "square"]:
size = 2 * radius + 1
self.footprint = fp_func(size, **footprint_kwargs)
elif footprint in ["diamond", "disk"]:
self.footprint = fp_func(radius, **footprint_kwargs)
elif footprint == "star":
# set a so bounding box size is approximately 2*radius + 1
# size will be 2*a + 1 + 2*floor(a / 2)
a = max((2 * radius) // 3, 1)
self.footprint = fp_func(a, **footprint_kwargs)
elif footprint == "octagon":
# overall size is m + 2 * n
# so choose m = n so that overall size is ~ 2*radius + 1
m = n = max((2 * radius) // 3, 1)
self.footprint = fp_func(m, n, **footprint_kwargs)
elif footprint == "ellipse":
if radius > 1:
# make somewhat elliptical
self.footprint = fp_func(radius - 1, radius + 1,
**footprint_kwargs)
else:
self.footprint = fp_func(radius, radius, **footprint_kwargs)
def time_erosion(
self, shape, footprint, radius, *args
):
morphology.binary_erosion(self.image, self.footprint)
class BinaryMorphology3D:
# skip rectangle as roughly equivalent to square
param_names = ["shape", "footprint", "radius", "decomposition"]
params = [
((128, 128, 128),),
("ball", "cube", "octahedron"),
(1, 3, 5, 10),
(None, "sequence", "separable"),
]
def setup(self, shape, footprint, radius, decomposition):
rng = np.random.default_rng(123)
# make an image that is mostly True, with a few isolated False areas
self.image = rng.standard_normal(shape) > -3
fp_func = getattr(morphology, footprint)
allow_decomp = ("cube", "octahedron", "ball")
allow_separable = ("cube",)
if decomposition == "separable" and footprint != "cube":
raise NotImplementedError("separable unavailable")
footprint_kwargs = {}
if decomposition is not None and footprint not in allow_decomp:
raise NotImplementedError("decomposition unimplemented")
elif decomposition == "separable" and footprint not in allow_separable:
raise NotImplementedError("separable decomposition unavailable")
if footprint in allow_decomp:
footprint_kwargs["decomposition"] = decomposition
if footprint == "cube":
size = 2 * radius + 1
self.footprint = fp_func(size, **footprint_kwargs)
elif footprint in ["ball", "octahedron"]:
self.footprint = fp_func(radius, **footprint_kwargs)
def time_erosion(
self, shape, footprint, radius, *args
):
morphology.binary_erosion(self.image, self.footprint)
class IsotropicMorphology2D:
# skip rectangle as roughly equivalent to square
param_names = ["shape", "radius"]
params = [
((512, 512),),
(1, 3, 5, 15, 25, 40),
]
def setup(self, shape, radius):
rng = np.random.default_rng(123)
# Make an image that is mostly True, with random isolated False areas
# (so it will not become fully False for any of the footprints).
self.image = rng.standard_normal(shape) < 3.5
def time_erosion(
self, shape, radius, *args
):
morphology.isotropic_erosion(self.image, radius)
# Repeat the same footprint tests for grayscale morphology
# just need to call morphology.erosion instead of morphology.binary_erosion
class GrayMorphology2D(BinaryMorphology2D):
def time_erosion(
self, shape, footprint, radius, *args
):
morphology.erosion(self.image, self.footprint)
class GrayMorphology3D(BinaryMorphology3D):
def time_erosion(
self, shape, footprint, radius, *args
):
morphology.erosion(self.image, self.footprint)
class GrayReconstruction:
# skip rectangle as roughly equivalent to square
param_names = ["shape", "dtype"]
params = [
((10, 10), (64, 64), (1200, 1200), (96, 96, 96)),
(np.uint8, np.float32, np.float64),
]
def setup(self, shape, dtype):
rng = np.random.default_rng(123)
# make an image that is mostly True, with a few isolated False areas
rvals = rng.integers(1, 255, size=shape).astype(dtype=dtype)
roi1 = tuple(slice(s // 4, s // 2) for s in rvals.shape)
roi2 = tuple(slice(s // 2 + 1, (3 * s) // 4) for s in rvals.shape)
seed = np.full(rvals.shape, 1, dtype=dtype)
seed[roi1] = rvals[roi1]
seed[roi2] = rvals[roi2]
# create a mask with a couple of square regions set to seed maximum
mask = np.full(seed.shape, 1, dtype=dtype)
mask[roi1] = 255
mask[roi2] = 255
self.seed = seed
self.mask = mask
def time_reconstruction(self, shape, dtype):
morphology.reconstruction(self.seed, self.mask)
def peakmem_reference(self, *args):
"""Provide reference for memory measurement with empty benchmark.
Peakmem benchmarks measure the maximum amount of RAM used by a
function. However, this maximum also includes the memory used
during the setup routine (as of asv 0.2.1; see [1]_).
Measuring an empty peakmem function might allow us to disambiguate
between the memory used by setup and the memory used by target (see
other ``peakmem_`` functions below).
References
----------
.. [1]: https://asv.readthedocs.io/en/stable/writing_benchmarks.html#peak-memory # noqa
"""
pass
def peakmem_reconstruction(self, shape, dtype):
morphology.reconstruction(self.seed, self.mask)
class LocalMaxima:
param_names = ["connectivity", "allow_borders"]
params = [(1, 2), (False, True)]
def setup(self, *args):
# Natural image with small extrema
self.image = data.moon()
def time_2d(self, connectivity, allow_borders):
morphology.local_maxima(
self.image, connectivity=connectivity,
allow_borders=allow_borders
)
def peakmem_reference(self, *args):
"""Provide reference for memory measurement with empty benchmark.
.. [1] https://asv.readthedocs.io/en/stable/writing_benchmarks.html#peak-memory
"""
pass
def peakmem_2d(self,connectivity, allow_borders):
morphology.local_maxima(
self.image, connectivity=connectivity,
allow_borders=allow_borders
)
<file_sep>/CONTRIBUTING.rst
.. _howto_contribute:
How to contribute to scikit-image
=================================
Developing Open Source is great fun! Join us on the `scikit-image
developer forum <https://discuss.scientific-python.org/c/contributor/skimage>`_.
If you're looking for something to implement or to fix, you can browse the
`open issues on GitHub <https://github.com/scikit-image/scikit-image/issues?q=is%3Aopen>`__.
.. warning::
Given the uncertainty around licensing of AI-generated code, we
require that you **not** make use of these tools during the development
of any contributions to scikit-image.
.. contents::
:local:
Development process
-------------------
The following is a brief overview about how changes to source code and documentation
can be contributed to scikit-image.
1. If you are a first-time contributor:
* Go to `https://github.com/scikit-image/scikit-image
<https://github.com/scikit-image/scikit-image>`_ and click the
"fork" button to create your own copy of the project.
* Clone (download) the repository with the project source on your local computer::
git clone https://github.com/your-username/scikit-image.git
* Change into the root directory of the cloned repository::
cd scikit-image
* Add the upstream repository::
git remote add upstream https://github.com/scikit-image/scikit-image.git
* Now, you have remote repositories named:
- ``upstream``, which refers to the ``scikit-image`` repository, and
- ``origin``, which refers to your personal fork.
* Next, :ref:`set up your build environment <build-env-setup>`.
* Finally, we recommend that you use a pre-commit hook, which runs code
checkers and formatters each time you do a ``git commit``::
pip install pre-commit
pre-commit install
2. Develop your contribution:
* Pull the latest changes from upstream::
git checkout main
git pull upstream main
* Create a branch for the feature you want to work on. Use a sensible name,
such as 'transform-speedups'::
git checkout -b transform-speedups
* Commit locally as you progress (with ``git add`` and ``git commit``).
Please write `good commit messages
<https://vxlabs.com/software-development-handbook/#good-commit-messages>`_.
3. To submit your contribution:
* Push your changes back to your fork on GitHub::
git push origin transform-speedups
* Enter your GitHub username and password (repeat contributors or advanced
users can remove this step by `connecting to GitHub with SSH
<https://help.github.com/en/github/authenticating-to-github/connecting-to-github-with-ssh>`_).
* Go to GitHub. The new branch will show up with a green "pull request"
button -- click it.
* If you want, post on the `developer forum
<https://discuss.scientific-python.org/c/contributor/skimage>`_ to explain your changes or
to ask for review.
For a more detailed discussion, read these :doc:`detailed documents
<../gitwash/index>` on how to use Git with ``scikit-image`` (:ref:`using-git`).
4. Review process:
* Reviewers (the other developers and interested community members) will
write inline and/or general comments on your pull request (PR) to help
you improve its implementation, documentation, and style. Every single
developer working on the project has their code reviewed, and we've come
to see it as a friendly conversation from which we all learn and the
overall code quality benefits. Therefore, please don't let the review
discourage you from contributing: its only aim is to improve the quality
of the project, not to criticize (we are, after all, very grateful for the
time you're donating!).
* To update your pull request, make your changes on your local repository
and commit. As soon as those changes are pushed up (to the same branch as
before) the pull request will update automatically.
* Continuous integration (CI) services are triggered after each pull request
submission to build the package, run unit tests, measure code coverage,
and check the coding style (PEP8) of your branch. The tests must pass
before your PR can be merged. If CI fails, you can find out why by
clicking on the "failed" icon (red cross) and inspecting the build and
test logs.
* A pull request must be approved by two core team members before merging.
5. Document changes
If your change introduces any API modifications, please update
``doc/release/release_dev.rst``.
If your change introduces a deprecation, add a reminder to ``TODO.txt``
for the team to remove the deprecated functionality in the future.
.. note::
To reviewers: if it is not obvious from the PR description, add a short
explanation of what a branch did to the merge message and, if closing a
bug, also add "Closes #123" where 123 is the issue number.
Divergence between ``upstream main`` and your feature branch
------------------------------------------------------------
If GitHub indicates that the branch of your PR can no longer
be merged automatically, merge the main branch into yours::
git fetch upstream main
git merge upstream/main
If any conflicts occur, they need to be fixed before continuing. See
which files are in conflict using::
git status
Which displays a message like::
Unmerged paths:
(use "git add <file>..." to mark resolution)
both modified: file_with_conflict.txt
Inside the conflicted file, you'll find sections like these::
The way the text looks in your branch
Choose one version of the text that should be kept, and delete the
rest::
The way the text looks in your branch
Now, add the fixed file::
git add file_with_conflict.txt
Once you've fixed all merge conflicts, do::
git commit
.. note::
Advanced Git users are encouraged to `rebase instead of merge
<https://scikit-image.org/docs/dev/gitwash/development_workflow.html#rebasing-on-trunk>`__,
but we squash and merge most PRs either way.
Guidelines
----------
* All code should have tests (see `test coverage`_ below for more details).
* All code should be documented, to the same
`standard <https://numpydoc.readthedocs.io/en/latest/format.html#docstring-standard>`_ as NumPy and SciPy.
* For new functionality, always add an example to the gallery (see
`Gallery`_ below for more details).
* No changes are ever merged without review and approval by two core team members.
There are two exceptions to this rule. First, pull requests which affect
only the documentation require review and approval by only one core team
member in most cases. If the maintainer feels the changes are large or
likely to be controversial, two reviews should still be encouraged. The
second case is that of minor fixes which restore CI to a working state,
because these should be merged fairly quickly. Reach out on the
`developer forum <https://discuss.scientific-python.org/c/contributor/skimage>`_ if
you get no response to your pull request.
**Never merge your own pull request.**
Stylistic Guidelines
--------------------
* Set up your editor to remove trailing whitespace. Follow `PEP08
<https://www.python.org/dev/peps/pep-0008/>`__.
* Use numpy data types instead of strings (``np.uint8`` instead of
``"uint8"``).
* Use the following import conventions::
import numpy as np
import matplotlib.pyplot as plt
import scipy as sp
import skimage as ski
sp.ndimage.label(...)
ski.measure.label(...)
# only in Cython code
cimport numpy as cnp
cnp.import_array()
* When documenting array parameters, use ``image : (M, N) ndarray``
and then refer to ``M`` and ``N`` in the docstring, if necessary.
* Refer to array dimensions as (plane), row, column, not as x, y, z. See
:ref:`Coordinate conventions <numpy-images-coordinate-conventions>`
in the user guide for more information.
* Functions should support all input image dtypes. Use utility functions such
as ``img_as_float`` to help convert to an appropriate type. The output
format can be whatever is most efficient. This allows us to string together
several functions into a pipeline, e.g.::
hough(canny(my_image))
* Use ``Py_ssize_t`` as data type for all indexing, shape and size variables
in C/C++ and Cython code.
* Use relative module imports, i.e. ``from .._shared import xyz`` rather than
``from skimage._shared import xyz``.
* Wrap Cython code in a pure Python function, which defines the API. This
improves compatibility with code introspection tools, which are often not
aware of Cython code.
* For Cython functions, release the GIL whenever possible, using
``with nogil:``.
Testing
-------
The test suite must pass before a pull request can be merged, and
tests should be added to cover all modifications in behavior.
We use the `pytest <https://docs.pytest.org/en/latest/>`__ testing
framework, with tests located in the various
``skimage/submodule/tests`` folders.
Testing requirements are listed in `requirements/test.txt`.
Run:
- **All tests**: ``spin test``
- Tests for a **submodule**: ``spin test skimage/morphology``
- Run tests from a **specific file**: ``spin test skimage/morphology/tests/test_gray.py``
- Run **a test inside a file**:
``spin test skimage/morphology/tests/test_gray.py::test_3d_fallback_black_tophat``
- Run tests with **arbitrary ``pytest`` options**:
``spin test -- any pytest args you want``.
- Run all tests and **doctests**:
``spin test -- --doctest-modules skimage``
Warnings during testing phase
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
By default, warnings raised by the test suite result in errors.
You can switch that behavior off by setting the environment variable
``SKIMAGE_TEST_STRICT_WARNINGS`` to `0`.
Test coverage
-------------
Tests for a module should ideally cover all code in that module,
i.e., statement coverage should be at 100%.
To measure test coverage run::
$ spin coverage
This will print a report with one line for each file in `skimage`,
detailing the test coverage::
Name Stmts Exec Cover Missing
------------------------------------------------------------------------------
skimage/color/colorconv 77 77 100%
skimage/filter/__init__ 1 1 100%
...
Building docs
-------------
To build the HTML documentation, run:
.. code:: sh
spin docs
Output is in ``scikit-image/doc/build/html/``. Add the ``--clean``
flag to build from scratch, deleting any cached output.
Gallery
^^^^^^^
The example gallery is built using
`Sphinx-Gallery <https://sphinx-gallery.github.io>`_.
Refer to their documentation for complete usage instructions, and also
to existing examples in ``doc/examples``.
Gallery examples should have a maximum figure width of 8 inches.
You can also `change a gallery entry's thumbnail
<https://sphinx-gallery.github.io/stable/configuration.html#choosing-thumbnail>`_.
Fixing Warnings
^^^^^^^^^^^^^^^
- "citation not found: R###" There is probably an underscore after a
reference in the first line of a docstring (e.g. [1]\_). Use this
method to find the source file: $ cd doc/build; grep -rin R####
- "Duplicate citation R###, other instance in..."" There is probably a
[2] without a [1] in one of the docstrings
- Make sure to use pre-sphinxification paths to images (not the
\_images directory)
Deprecation cycle
-----------------
If the way a function is called has to be changed, a deprecation cycle
must be followed to warn users.
A deprecation cycle is *not* necessary when:
* adding a new function, or
* adding a new keyword argument to the *end* of a function signature, or
* fixing unexpected or incorrect behavior.
A deprecation cycle is necessary when:
* renaming keyword arguments, or
* changing the order of arguments or keywords, or
* adding arguments to a function, or
* changing a function's name or location, or
* changing the default value of function arguments or keywords.
Typically, deprecation warnings are in place for two releases, before
a change is made.
For example, consider the modification of a default value in
a function signature. In version N, we have:
.. code-block:: python
def some_function(image, rescale=True):
"""Do something.
Parameters
----------
image : ndarray
Input image.
rescale : bool, optional
Rescale the image unless ``False`` is given.
Returns
-------
out : ndarray
The resulting image.
"""
out = do_something(image, rescale=rescale)
return out
In version N+1, we will change this to:
.. code-block:: python
def some_function(image, rescale=None):
"""Do something.
Parameters
----------
image : ndarray
Input image.
rescale : bool, optional
Rescale the image unless ``False`` is given.
.. warning:: The default value will change from ``True`` to
``False`` in skimage N+3.
Returns
-------
out : ndarray
The resulting image.
"""
if rescale is None:
warn('The default value of rescale will change '
'to `False` in version N+3.', stacklevel=2)
rescale = True
out = do_something(image, rescale=rescale)
return out
And, in version N+3:
.. code-block:: python
def some_function(image, rescale=False):
"""Do something.
Parameters
----------
image : ndarray
Input image.
rescale : bool, optional
Rescale the image if ``True`` is given.
Returns
-------
out : ndarray
The resulting image.
"""
out = do_something(image, rescale=rescale)
return out
Here is the process for a 3-release deprecation cycle:
- Set the default to `None`, and modify the
docstring to specify that the default is `True`.
- In the function, _if_ rescale is `None`, set it to `True` and warn that the
default will change to `False` in version N+3.
- In ``doc/release/release_dev.rst``, under deprecations, add "In
`some_function`, the `rescale` argument will default to `False` in N+3."
- In ``TODO.txt``, create an item in the section related to version
N+3 and write "change rescale default to False in some_function".
Note that the 3-release deprecation cycle is not a strict rule and, in some
cases, developers can agree on a different procedure.
Raising Warnings
^^^^^^^^^^^^^^^^
``skimage`` raises ``FutureWarning``\ s to highlight changes in its
API, e.g.:
.. code-block:: python
from warnings import warn
warn(
"Automatic detection of the color channel was deprecated in "
"v0.19, and `channel_axis=None` will be the new default in "
"v0.22. Set `channel_axis=-1` explicitly to silence this "
"warning.",
FutureWarning,
stacklevel=2,
)
The `stacklevel
<https://docs.python.org/3/library/warnings.html#warnings.warn>`_ is
a bit of a technicality, but ensures that the warning points to the
user-called function, and not to a utility function within.
In most cases, set the ``stacklevel`` to ``2``.
When warnings originate from helper routines internal to the
scikit-image library, set it to ``3``.
To test if your warning is being emitted correctly, try calling the function
from an IPython console. It should point you to the console input itself
instead of being emitted by files in the scikit-image library:
* **Good**: ``ipython:1: UserWarning: ...``
* **Bad**: ``scikit-image/skimage/measure/_structural_similarity.py:155: UserWarning:``
Deprecating Keywords and Functions
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
When removing keywords or entire functions, the
``skimage._shared.utils.deprecate_kwarg`` and
``skimage._shared.utils.deprecate_func`` utility functions can be used
to perform the above procedure.
Adding Data
-----------
While code is hosted on `github <https://github.com/scikit-image/>`_,
example datasets are on `gitlab <https://gitlab.com/scikit-image/data>`_.
These are fetched with `pooch <https://github.com/fatiando/pooch>`_
when accessing `skimage.data.*`.
New datasets are submitted on gitlab and, once merged, the data
registry ``skimage/data/_registry.py`` in the main GitHub repository
can be updated.
Benchmarks
----------
While not mandatory for most pull requests, we ask that performance related
PRs include a benchmark in order to clearly depict the use-case that is being
optimized for. A historical view of our snapshots can be found on
at the following `website <https://pandas.pydata.org/speed/scikit-image/>`_.
In this section we will review how to setup the benchmarks,
and three commands ``spin asv -- dev``, ``spin asv -- run`` and
``spin asv -- continuous``.
Prerequisites
^^^^^^^^^^^^^
Begin by installing `airspeed velocity <https://asv.readthedocs.io/en/stable/>`_
in your development environment. Prior to installation, be sure to activate your
development environment, then if using ``venv`` you may install the requirement with::
source skimage-dev/bin/activate
pip install asv
If you are using conda, then the command::
conda activate skimage-dev
conda install asv
is more appropriate. Once installed, it is useful to run the command::
spin asv -- machine
To let airspeed velocity know more information about your machine.
Writing a benchmark
^^^^^^^^^^^^^^^^^^^
To write benchmark, add a file in the ``benchmarks`` directory which contains a
a class with one ``setup`` method and at least one method prefixed with ``time_``.
The ``time_`` method should only contain code you wish to benchmark.
Therefore it is useful to move everything that prepares the benchmark scenario
into the ``setup`` method. This function is called before calling a ``time_``
method and its execution time is not factored into the benchmarks.
Take for example the ``TransformSuite`` benchmark:
.. code-block:: python
import numpy as np
from skimage import transform
class TransformSuite:
"""Benchmark for transform routines in scikit-image."""
def setup(self):
self.image = np.zeros((2000, 2000))
idx = np.arange(500, 1500)
self.image[idx[::-1], idx] = 255
self.image[idx, idx] = 255
def time_hough_line(self):
result1, result2, result3 = transform.hough_line(self.image)
Here, the creation of the image is completed in the ``setup`` method, and not
included in the reported time of the benchmark.
It is also possible to benchmark features such as peak memory usage. To learn
more about the features of `asv`, please refer to the official
`airpseed velocity documentation <https://asv.readthedocs.io/en/latest/writing_benchmarks.html>`_.
Also, the benchmark files need to be importable when benchmarking old versions
of scikit-image. So if anything from scikit-image is imported at the top level,
it should be done as:
.. code-block:: python
try:
from skimage import metrics
except ImportError:
pass
The benchmarks themselves don't need any guarding against missing features,
only the top-level imports.
To allow tests of newer functions to be marked as "n/a" (not available)
rather than "failed" for older versions, the setup method itself can raise a
NotImplemented error. See the following example for the registration module:
.. code-block:: python
try:
from skimage import registration
except ImportError:
raise NotImplementedError("registration module not available")
Testing the benchmarks locally
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Prior to running the true benchmark, it is often worthwhile to test that the
code is free of typos. To do so, you may use the command::
spin asv -- dev -b TransformSuite
Where the ``TransformSuite`` above will be run once in your current environment
to test that everything is in order.
Running your benchmark
^^^^^^^^^^^^^^^^^^^^^^
The command above is fast, but doesn't test the performance of the code
adequately. To do that you may want to run the benchmark in your current
environment to see the performance of your change as you are developing new
features. The command ``asv run -E existing`` will specify that you wish to run
the benchmark in your existing environment. This will save a significant amount
of time since building scikit-image can be a time consuming task::
spin asv -- run -E existing -b TransformSuite
Comparing results to main
^^^^^^^^^^^^^^^^^^^^^^^^^
Often, the goal of a PR is to compare the results of the modifications in terms
speed to a snapshot of the code that is in the main branch of the
``scikit-image`` repository. The command ``asv continuous`` is of help here::
spin asv -- continuous main -b TransformSuite
This call will build out the environments specified in the ``asv.conf.json``
file and compare the performance of the benchmark between your current commit
and the code in the main branch.
The output may look something like::
$ spin asv -- continuous main -b TransformSuite
· Creating environments
· Discovering benchmarks
·· Uninstalling from conda-py3.7-cython-numpy1.15-scipy
·· Installing 544c0fe3 <benchmark_docs> into conda-py3.7-cython-numpy1.15-scipy.
· Running 4 total benchmarks (2 commits * 2 environments * 1 benchmarks)
[ 0.00%] · For scikit-image commit 37c764cb <benchmark_docs~1> (round 1/2):
[...]
[100.00%] ··· ...ansform.TransformSuite.time_hough_line 33.2±2ms
BENCHMARKS NOT SIGNIFICANTLY CHANGED.
In this case, the differences between HEAD and main are not significant
enough for airspeed velocity to report.
It is also possible to get a comparison of results for two specific revisions
for which benchmark results have previously been run via the `asv compare`
command::
spin asv -- compare v0.14.5 v0.17.2
Finally, one can also run ASV benchmarks only for a specific commit hash or
release tag by appending ``^!`` to the commit or tag name. For example to run
the skimage.filter module benchmarks on release v0.17.2::
spin asv -- run -b Filter v0.17.2^!
<file_sep>/doc/examples/transform/plot_pyramid.py
"""
====================
Build image pyramids
====================
The ``pyramid_gaussian`` function takes an image and yields successive images
shrunk by a constant scale factor. Image pyramids are often used, e.g., to
implement algorithms for denoising, texture discrimination, and scale-invariant
detection.
"""
import numpy as np
import matplotlib.pyplot as plt
from skimage import data
from skimage.transform import pyramid_gaussian
image = data.astronaut()
rows, cols, dim = image.shape
pyramid = tuple(pyramid_gaussian(image, downscale=2, channel_axis=-1))
#####################################################################
# Generate a composite image for visualization
# ============================================
#
# For visualization, we generate a composite image with the same number of rows
# as the source image but with ``cols + pyramid[1].shape[1]`` columns. We then
# have space to stack all of the dowsampled images to the right of the
# original.
#
# Note: The sum of the number of rows in all dowsampled images in the pyramid
# may sometimes exceed the original image size in cases when image.shape[0] is
# not a power of two. We expand the number of rows in the composite slightly as
# necessary to account for this. Expansion beyond the number of rows in the
# original will also be necessary to cover cases where downscale < 2.
# determine the total number of rows and columns for the composite
composite_rows = max(rows, sum(p.shape[0] for p in pyramid[1:]))
composite_cols = cols + pyramid[1].shape[1]
composite_image = np.zeros((composite_rows, composite_cols, 3),
dtype=np.double)
# store the original to the left
composite_image[:rows, :cols, :] = pyramid[0]
# stack all downsampled images in a column to the right of the original
i_row = 0
for p in pyramid[1:]:
n_rows, n_cols = p.shape[:2]
composite_image[i_row:i_row + n_rows, cols:cols + n_cols] = p
i_row += n_rows
fig, ax = plt.subplots()
ax.imshow(composite_image)
plt.show()
<file_sep>/doc/examples/applications/plot_colocalization_metrics.py
"""
======================
Colocalization metrics
======================
In this example, we demonstrate the use of different metrics to assess the
colocalization of two different image channels.
Colocalization can be split into two different concepts:
1. Co-occurence: What proportion of a substance is localized to a particular
area?
2. Correlation: What is the relationship in intensity between two substances?
"""
#####################################################################
# Co-occurence: subcellular localization
# ======================================
#
# Imagine that we are trying to determine the subcellular localization of a
# protein - is it located more in the nucleus or cytoplasm compared to a
# control?
#
# We begin by segmenting the nucleus of a sample image as described in another
# `example <https://scikit-image.org/docs/stable/auto_examples/applications/plot_fluorescence_nuclear_envelope.html>`_
# and assume that whatever is not in the nucleus is in the cytoplasm.
# The protein, "protein A", will be simulated as blobs and segmented.
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import LinearSegmentedColormap
from scipy import ndimage as ndi
from skimage import data, filters, measure, segmentation
rng = np.random.default_rng()
# segment nucleus
nucleus = data.protein_transport()[0, 0, :, :180]
smooth = filters.gaussian(nucleus, sigma=1.5)
thresh = smooth > filters.threshold_otsu(smooth)
fill = ndi.binary_fill_holes(thresh)
nucleus_seg = segmentation.clear_border(fill)
# protein blobs of varying intensity
proteinA = np.zeros_like(nucleus, dtype="float64")
proteinA_seg = np.zeros_like(nucleus, dtype="float64")
for blob_seed in range(10):
blobs = data.binary_blobs(180,
blob_size_fraction=0.5,
volume_fraction=(50/(180**2)),
rng=blob_seed)
blobs_image = filters.gaussian(blobs, sigma=1.5) * rng.integers(50, 256)
proteinA += blobs_image
proteinA_seg += blobs
# plot data
fig, ax = plt.subplots(3, 2, figsize=(8, 12), sharey=True)
ax[0, 0].imshow(nucleus, cmap=plt.cm.gray)
ax[0, 0].set_title('Nucleus')
ax[0, 1].imshow(nucleus_seg, cmap=plt.cm.gray)
ax[0, 1].set_title('Nucleus segmentation')
black_magenta = LinearSegmentedColormap.from_list("", ["black", "magenta"])
ax[1, 0].imshow(proteinA, cmap=black_magenta)
ax[1, 0].set_title('Protein A')
ax[1, 1].imshow(proteinA_seg, cmap=black_magenta)
ax[1, 1].set_title('Protein A segmentation')
ax[2, 0].imshow(proteinA, cmap=black_magenta)
ax[2, 0].imshow(nucleus_seg, cmap=plt.cm.gray, alpha=0.2)
ax[2, 0].set_title('Protein A\nwith nucleus overlaid')
ax[2, 1].imshow(proteinA_seg, cmap=black_magenta)
ax[2, 1].imshow(nucleus_seg, cmap=plt.cm.gray, alpha=0.2)
ax[2, 1].set_title('Protein A segmentation\nwith nucleus overlaid')
for a in ax.ravel():
a.set_axis_off()
#####################################################################
# Intersection coefficient
# ========================
#
# After segmenting both the nucleus and the protein of interest, we can
# determine what fraction of the protein A segmentation overlaps with the
# nucleus segmentation.
measure.intersection_coeff(proteinA_seg, nucleus_seg)
#####################################################################
# Manders' Colocalization Coefficient (MCC)
# =========================================
#
# The overlap coefficient assumes that the area of protein segmentation
# corresponds to the concentration of that protein - with larger areas
# indicating more protein. As the resolution of images are usually too small to
# make out individual proteins, they can clump together within one pixel,
# making the intensity of that pixel brighter. So, to better capture the
# protein concentration, we may choose to determine what proportion of the
# *intensity* of the protein channel is inside the nucleus. This metric is
# known as Manders' Colocalization Coefficient.
#
# In this image, while there are a lot of protein A spots within the nucleus
# they are dim compared to some of the spots outside the nucleus, so the MCC is
# much lower than the overlap coefficient.
measure.manders_coloc_coeff(proteinA, nucleus_seg)
#####################################################################
# After choosing a co-occurence metric, we can apply the same process to
# control images. If no control images are available, the Costes method could
# be used to compare the MCC value of the original image with that of the
# randomly scrambled image. Information about this method is given in [1]_.
#
# .. [1] <NAME>, <NAME> and <NAME>, Image co-localization –
# co-occurrence versus correlation. J Cell Sci 1 February 2018
# 131 (3): jcs211847. doi: https://doi.org/10.1242/jcs.211847
#####################################################################
# Correlation: association of two proteins
# ========================================
#
# Now, imagine that we want to know how closely related two proteins are.
#
# First, we will generate protein B and plot intensities of the two proteins in
# every pixel to see the relationship between them.
# generating protein B data that is correlated to protein A for demo
proteinB = proteinA + rng.normal(loc=100, scale=10, size=proteinA.shape)
# plot images
fig, ax = plt.subplots(1, 2, figsize=(8, 8), sharey=True)
ax[0].imshow(proteinA, cmap=black_magenta)
ax[0].set_title('Protein A')
black_cyan = LinearSegmentedColormap.from_list("", ["black", "cyan"])
ax[1].imshow(proteinB, cmap=black_cyan)
ax[1].set_title('Protein B')
for a in ax.ravel():
a.set_axis_off()
# plot pixel intensity scatter
plt.figure()
plt.scatter(proteinA, proteinB)
plt.title('Pixel intensity')
plt.xlabel('Protein A intensity')
plt.ylabel('Protein B intensity')
#####################################################################
# The intensities look linearly correlated so Pearson's Correlation Coefficient
# would give us a good measure of how strong the association is.
pcc, pval = measure.pearson_corr_coeff(proteinA, proteinB)
print(f"PCC: {pcc:0.3g}, p-val: {pval:0.3g}")
#####################################################################
# Sometimes the intensities are correlated but not in a linear way. A rank-based
# correlation coefficient like `Spearman's
# <https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.spearmanr.html>`_
# might give a more accurate measure of the non-linear relationship in that
# case.
plt.show()
<file_sep>/doc/source/about/index.rst
About
=====
Get to know the project and the community. Learn where we are going and how we work
together.
.. toctree::
:maxdepth: 1
values
code_of_conduct
Governance and decision-making <../skips/1-governance>
<file_sep>/skimage/feature/brief_pythran.py
#pythran export _brief_loop(float32[:,:] or float64[:,:], uint8[:,:], int64[:,2], int32[:,2], int32[:,2])
def _brief_loop(image, descriptors, keypoints, pos0, pos1):
for p in range(pos0.shape[0]):
pr0, pc0 = pos0[p]
pr1, pc1 = pos1[p]
for k in range(keypoints.shape[0]):
kr, kc = keypoints[k]
if image[kr + pr0, kc + pc0] < image[kr + pr1, kc + pc1]:
descriptors[k, p] = True
<file_sep>/skimage/util/_slice_along_axes.py
__all__ = ['slice_along_axes']
def slice_along_axes(image, slices, axes=None, copy=False):
"""Slice an image along given axes.
Parameters
----------
image : ndarray
Input image.
slices : list of 2-tuple (a, b) where a < b.
For each axis in `axes`, a corresponding 2-tuple
``(min_val, max_val)`` to slice with (as with Python slices,
``max_val`` is non-inclusive).
axes : int or tuple, optional
Axes corresponding to the limits given in `slices`. If None,
axes are in ascending order, up to the length of `slices`.
copy : bool, optional
If True, ensure that the output is not a view of `image`.
Returns
-------
out : ndarray
The region of `image` corresponding to the given slices and axes.
Examples
--------
>>> from skimage import data
>>> img = data.camera()
>>> img.shape
(512, 512)
>>> cropped_img = slice_along_axes(img, [(0, 100)])
>>> cropped_img.shape
(100, 512)
>>> cropped_img = slice_along_axes(img, [(0, 100), (0, 100)])
>>> cropped_img.shape
(100, 100)
>>> cropped_img = slice_along_axes(img, [(0, 100), (0, 75)], axes=[1, 0])
>>> cropped_img.shape
(75, 100)
"""
# empty length of bounding box detected on None
if not slices:
return image
if axes is None:
axes = list(range(image.ndim))
if len(axes) < len(slices):
raise ValueError("More `slices` than available axes")
elif len(axes) != len(slices):
raise ValueError("`axes` and `slices` must have equal length")
if len(axes) != len(set(axes)):
raise ValueError("`axes` must be unique")
if not all(a >= 0 and a < image.ndim for a in axes):
raise ValueError(f"axes {axes} out of range; image has only "
f"{image.ndim} dimensions")
_slices = [slice(None),] * image.ndim
for (a, b), ax in zip(slices, axes):
if a < 0:
a %= image.shape[ax]
if b < 0:
b %= image.shape[ax]
if a > b:
raise ValueError(
f"Invalid slice ({a}, {b}): must be ordered `(min_val, max_val)`"
)
if a < 0 or b > image.shape[ax]:
raise ValueError(f"Invalid slice ({a}, {b}) for image with dimensions {image.shape}")
_slices[ax] = slice(a, b)
image_slice = image[tuple(_slices)]
if copy and image_slice.base is not None:
image_slice = image_slice.copy()
return image_slice
<file_sep>/skimage/morphology/__init__.py
from .binary import (binary_closing, binary_dilation, binary_erosion,
binary_opening)
from .gray import (black_tophat, closing, dilation, erosion, opening,
white_tophat)
from .isotropic import (isotropic_erosion, isotropic_dilation,
isotropic_opening, isotropic_closing)
from .footprints import (ball, cube, diamond, disk, ellipse,
footprint_from_sequence, octagon, octahedron,
rectangle, square, star)
from ..measure._label import label
from ._skeletonize import medial_axis, skeletonize, skeletonize_3d, thin
from .convex_hull import convex_hull_image, convex_hull_object
from .grayreconstruct import reconstruction
from .misc import remove_small_holes, remove_small_objects
from .extrema import h_maxima, h_minima, local_minima, local_maxima
from ._flood_fill import flood, flood_fill
from .max_tree import (area_opening, area_closing, diameter_closing,
diameter_opening, max_tree,
max_tree_local_maxima)
__all__ = ['area_closing',
'area_opening',
'ball',
'binary_closing',
'binary_dilation',
'binary_erosion',
'binary_opening',
'black_tophat',
'closing',
'convex_hull_image',
'convex_hull_object',
'cube',
'diameter_closing',
'diameter_opening',
'diamond',
'dilation',
'disk',
'ellipse',
'erosion',
'flood',
'flood_fill',
'footprint_from_sequence',
'h_maxima',
'h_minima',
'isotropic_closing',
'isotropic_dilation',
'isotropic_erosion',
'isotropic_opening',
'label',
'local_maxima',
'local_minima',
'max_tree',
'max_tree_local_maxima',
'medial_axis',
'octagon',
'octahedron',
'opening',
'reconstruction',
'rectangle',
'remove_small_holes',
'remove_small_objects',
'skeletonize',
'skeletonize_3d',
'square',
'star',
'thin',
'white_tophat'
]
<file_sep>/doc/source/gitwash/this_project.inc
.. scikit-image
.. _`scikit-image`: https://scikit-image.org
.. _`scikit-image github`: https://github.com/scikit-image/scikit-image
.. _`scikit-image developer forum`: https://discuss.scientific-python.org/c/contributor/skimage
<file_sep>/doc/examples/data/plot_3d.py
"""
==========================================
Datasets with 3 or more spatial dimensions
==========================================
Most scikit-image functions are compatible with 3D datasets, i.e., images with
3 spatial dimensions (to be distinguished from 2D multichannel images, which
are also arrays with
three axes). :func:`skimage.data.cells3d` returns a 3D fluorescence microscopy
image of cells. The returned dataset is a 3D multichannel image with dimensions
provided in ``(z, c, y, x)`` order. Channel 0 contains cell membranes, while channel
1 contains nuclei.
The example below shows how to explore this dataset. This 3D image can be used
to test the various functions of scikit-image.
"""
from skimage import data
import plotly
import plotly.express as px
import numpy as np
img = data.cells3d()[20:]
# omit some slices that are partially empty
img = img[5:26]
upper_limit = 1.5 * np.percentile(img, q=99)
img = np.clip(img, 0, upper_limit)
fig = px.imshow(
img,
facet_col=1,
animation_frame=0,
binary_string=True,
binary_format="jpg",
)
fig.layout.annotations[0]["text"] = "Cell membranes"
fig.layout.annotations[1]["text"] = "Nuclei"
plotly.io.show(fig)
<file_sep>/.github/PULL_REQUEST_TEMPLATE.md
## Description
<!--
- Reference relevant issues or related pull requests with their URL / #<number>.
- Do not use AI to help write your contribution.
- Use `pre-commit` to check and format code.
-->
## Checklist
<!-- Before pull requests can be merged, they should provide: -->
- A descriptive but concise pull request title
- [Docstrings for all functions](https://github.com/numpy/numpy/blob/master/doc/example.py)
- [Unit tests](https://scikit-image.org/docs/dev/development/contribute.html#testing)
- A gallery example in `./doc/examples` for new features
- [Contribution guide](https://scikit-image.org/docs/dev/development/contribute.html) is followed
## Release note
Summarize the introduced changes in the code block below in one or a few sentences. The
summary will be included in the next release notes automatically:
```release-note
...
```
<file_sep>/skimage/morphology/isotropic.py
"""
Binary morphological operations
"""
import numpy as np
from scipy import ndimage as ndi
def isotropic_erosion(image, radius, out=None, spacing=None):
"""Return binary morphological erosion of an image.
This function returns the same result as :func:`skimage.morphology.binary_erosion`
but performs faster for large circular structuring elements.
This works by applying a threshold to the exact Euclidean distance map
of the image [1]_, [2]_.
The implementation is based on: func:`scipy.ndimage.distance_transform_edt`.
Parameters
----------
image : ndarray
Binary input image.
radius : float
The radius by which regions should be eroded.
out : ndarray of bool, optional
The array to store the result of the morphology. If None,
a new array will be allocated.
spacing : float, or sequence of float, optional
Spacing of elements along each dimension.
If a sequence, must be of length equal to the input's dimension (number of axes).
If a single number, this value is used for all axes.
If not specified, a grid spacing of unity is implied.
Returns
-------
eroded : ndarray of bool
The result of the morphological erosion taking values in
``[False, True]``.
References
----------
.. [1] <NAME>. and <NAME>., "Fast Euclidean morphological operators
using local distance transformation by propagation, and applications,"
Image Processing And Its Applications, 1999. Seventh International
Conference on (Conf. Publ. No. 465), 1999, pp. 856-860 vol.2.
:DOI:`10.1049/cp:19990446`
.. [2] <NAME>, Fast erosion and dilation by contour processing
and thresholding of distance maps, Pattern Recognition Letters,
Volume 13, Issue 3, 1992, Pages 161-166.
:DOI:`10.1016/0167-8655(92)90055-5`
"""
dist = ndi.distance_transform_edt(image, sampling=spacing)
return np.greater(dist, radius, out=out)
def isotropic_dilation(image, radius, out=None, spacing=None):
"""Return binary morphological dilation of an image.
This function returns the same result as :func:`skimage.morphology.binary_dilation`
but performs faster for large circular structuring elements.
This works by applying a threshold to the exact Euclidean distance map
of the inverted image [1]_, [2]_.
The implementation is based on: func:`scipy.ndimage.distance_transform_edt`.
Parameters
----------
image : ndarray
Binary input image.
radius : float
The radius by which regions should be dilated.
out : ndarray of bool, optional
The array to store the result of the morphology. If None is
passed, a new array will be allocated.
spacing : float, or sequence of float, optional
Spacing of elements along each dimension.
If a sequence, must be of length equal to the input's dimension (number of axes).
If a single number, this value is used for all axes.
If not specified, a grid spacing of unity is implied.
Returns
-------
dilated : ndarray of bool
The result of the morphological dilation with values in
``[False, True]``.
References
----------
.. [1] <NAME>. and <NAME>., "Fast Euclidean morphological operators
using local distance transformation by propagation, and applications,"
Image Processing And Its Applications, 1999. Seventh International
Conference on (Conf. Publ. No. 465), 1999, pp. 856-860 vol.2.
:DOI:`10.1049/cp:19990446`
.. [2] <NAME>, Fast erosion and dilation by contour processing
and thresholding of distance maps, Pattern Recognition Letters,
Volume 13, Issue 3, 1992, Pages 161-166.
:DOI:`10.1016/0167-8655(92)90055-5`
"""
dist = ndi.distance_transform_edt(np.logical_not(image), sampling=spacing)
return np.less_equal(dist, radius, out=out)
def isotropic_opening(image, radius, out=None, spacing=None):
"""Return binary morphological opening of an image.
This function returns the same result as :func:`skimage.morphology.binary_opening`
but performs faster for large circular structuring elements.
This works by thresholding the exact Euclidean distance map [1]_, [2]_.
The implementation is based on: func:`scipy.ndimage.distance_transform_edt`.
Parameters
----------
image : ndarray
Binary input image.
radius : float
The radius with which the regions should be opened.
out : ndarray of bool, optional
The array to store the result of the morphology. If None
is passed, a new array will be allocated.
spacing : float, or sequence of float, optional
Spacing of elements along each dimension.
If a sequence, must be of length equal to the input's dimension (number of axes).
If a single number, this value is used for all axes.
If not specified, a grid spacing of unity is implied.
Returns
-------
opened : ndarray of bool
The result of the morphological opening.
References
----------
.. [1] <NAME>. and <NAME>., "Fast Euclidean morphological operators
using local distance transformation by propagation, and applications,"
Image Processing And Its Applications, 1999. Seventh International
Conference on (Conf. Publ. No. 465), 1999, pp. 856-860 vol.2.
:DOI:`10.1049/cp:19990446`
.. [2] <NAME>, Fast erosion and dilation by contour processing
and thresholding of distance maps, Pattern Recognition Letters,
Volume 13, Issue 3, 1992, Pages 161-166.
:DOI:`10.1016/0167-8655(92)90055-5`
"""
eroded = isotropic_erosion(image, radius, out=out, spacing=spacing)
return isotropic_dilation(eroded, radius, out=out, spacing=spacing)
def isotropic_closing(image, radius, out=None, spacing=None):
"""Return binary morphological closing of an image.
This function returns the same result as binary :func:`skimage.morphology.binary_closing`
but performs faster for large circular structuring elements.
This works by thresholding the exact Euclidean distance map [1]_, [2]_.
The implementation is based on: func:`scipy.ndimage.distance_transform_edt`.
Parameters
----------
image : ndarray
Binary input image.
radius : float
The radius with which the regions should be closed.
out : ndarray of bool, optional
The array to store the result of the morphology. If None,
is passed, a new array will be allocated.
spacing : float, or sequence of float, optional
Spacing of elements along each dimension.
If a sequence, must be of length equal to the input's dimension (number of axes).
If a single number, this value is used for all axes.
If not specified, a grid spacing of unity is implied.
Returns
-------
closed : ndarray of bool
The result of the morphological closing.
References
----------
.. [1] <NAME>. and <NAME>., "Fast Euclidean morphological operators
using local distance transformation by propagation, and applications,"
Image Processing And Its Applications, 1999. Seventh International
Conference on (Conf. Publ. No. 465), 1999, pp. 856-860 vol.2.
:DOI:`10.1049/cp:19990446`
.. [2] <NAME>, Fast erosion and dilation by contour processing
and thresholding of distance maps, Pattern Recognition Letters,
Volume 13, Issue 3, 1992, Pages 161-166.
:DOI:`10.1016/0167-8655(92)90055-5`
"""
dilated = isotropic_dilation(image, radius, out=out, spacing=spacing)
return isotropic_erosion(dilated, radius, out=out, spacing=spacing)
<file_sep>/requirements/README.md
# pip requirements files
## Index
These files are generated by `tools/generate_requirements.py` from `pyproject.toml`.
- [default.txt](default.txt)
Default project dependencies.
- [build.txt](build.txt)
Requirements for building from the source repository.
- [data.txt](data.txt)
Data requirements.
- [developer.txt](developer.txt)
Developer requirements.
- [docs.txt](docs.txt)
Documentation requirements.
- [optional.txt](optional.txt)
Optional requirements. All of these are installable without a compiler through pypi.
- [test.txt](test.txt)
Requirements for running test suite.
## Examples
### Installing requirements
```bash
$ pip install -U -r requirements/default.txt
```
### Running the tests
```bash
$ pip install -U -r requirements/default.txt
$ pip install -U -r requirements/test.txt
```
<file_sep>/doc/source/development/core_developer.md
(core_dev)=
# Core Developer Guide
Welcome, new core developer! The core team appreciate the quality of
your work, and enjoy working with you; we have therefore invited you
to join us. Thank you for your numerous contributions to the project
so far.
This document offers guidelines for your new role. First and
foremost, you should familiarize yourself with the project's
{doc}`mission, vision, and values <../about/values>`. When in
doubt, always refer back here.
As a core team member, you gain the responsibility of shepherding
other contributors through the review process; here are some
guidelines.
## All Contributors Are Treated The Same
You now have the ability to push changes directly to the main
branch, but should never do so; instead, continue making pull requests
as before and in accordance with the
{doc}`general contributor guide <contribute>`.
As a core contributor, you gain the ability to merge or approve
other contributors' pull requests. Much like nuclear launch keys, it
is a shared power: you must merge _only after_ another core has
approved the pull request, _and_ after you yourself have carefully
reviewed it. (See {ref}`sec:reviewing` and especially
{ref}`sec:understand` below.) To ensure a clean git history,
use GitHub's [Squash and Merge][gh_sqmrg]
feature to merge, unless you have a good reason not to do so.
[gh_sqmrg]: https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/merging-a-pull-request#merging-a-pull-request-on-github
(sec:reviewing)=
## Reviewing
### How to Conduct A Good Review
_Always_ be kind to contributors. Nearly all of `scikit-image` is
volunteer work, for which we are tremendously grateful. Provide
constructive criticism on ideas and implementations, and remind
yourself of how it felt when your own work was being evaluated as a
novice.
`scikit-image` strongly values mentorship in code review. New users
often need more handholding, having little to no git
experience. Repeat yourself liberally, and, if you don’t recognize a
contributor, point them to our development guide, or other GitHub
workflow tutorials around the web. Do not assume that they know how
GitHub works (e.g., many don't realize that adding a commit
automatically updates a pull request). Gentle, polite, kind
encouragement can make the difference between a new core developer and
an abandoned pull request.
When reviewing, focus on the following:
1. **API:** The API is what users see when they first use
`scikit-image`. APIs are difficult to change once released, so
should be simple, [functional][wiki_functional] (i.e. not
carry state), consistent with other parts of the library, and
should avoid modifying input variables. Please familiarize
yourself with the project's [deprecation policy][dep_pol]
2. **Documentation:** Any new feature should have a gallery
example, that not only illustrates but explains it.
3. **The algorithm:** You should understand the code being modified or
added before approving it. (See {ref}`sec:understand`
below.) Implementations should do what they claim,
and be simple, readable, and efficient.
4. **Tests:** All contributions to the library _must_ be tested, and
each added line of code should be covered by at least one test. Good
tests not only execute the code, but explores corner cases. It is tempting
not to review tests, but please do so.
5. **Licensing:** New contributions should be available under the same license
as or be compatible with {doc}`scikit-image's license <../license>`.
Examples of BSD-compatible licenses are the [MIT License][mit_license] and
[Apache License 2.0][apache_2-2]. When in doubt, ask the team for help.
If you, the contributor, are not the copyright holder of the submitted
code, please ask the original authors for approval and include their names
in `LICENSE.txt`. You can use the other entries in that file as templates.
6. **Established methods:** In general, we are looking to include algorithms
and methods which are established, well documented in the literature and
widely used by the imaging community. While this is not a hard requirement,
new contributions should be consistent with {doc}`our mission <../about/values>`.
[wiki_functional]: https://en.wikipedia.org/wiki/Functional_programming
[dep_pol]: https://scikit-image.org/docs/dev/development/contribute.html#deprecation-cycle
[mit_license]: https://spdx.org/licenses/MIT.html
[apache_2-2]: https://spdx.org/licenses/Apache-2.0.html
Other changes may be _nitpicky_: spelling mistakes, formatting,
etc. Do not ask contributors to make these changes, and instead
make the changes by [pushing to their branch][gh_push]
or using GitHub’s [suggestion][gh_suggest] [feature][gh_feedback].
(The latter is preferred because it gives the contributor a choice in
whether to accept the changes.)
[gh_push]: https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/committing-changes-to-a-pull-request-branch-created-from-a-fork
[gh_suggest]: https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/commenting-on-a-pull-request
[gh_feedback]: https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/incorporating-feedback-in-your-pull-request
Our default merge policy is to squash all PR commits into a single
commit. Users who wish to bring the latest changes from `main`
into their branch should be advised to merge, not to rebase. Even
when merge conflicts arise, don’t ask for a rebase unless you know
that a contributor is experienced with git. Instead, rebase the branch
yourself, force-push to their branch, and advise the contributor on
how to force-pull. If the contributor is no longer active, you may
take over their branch by submitting a new pull request and closing
the original. In doing so, ensure you communicate that you are not
throwing the contributor's work away!
Please add a note to a pull request after you push new changes; GitHub
does not send out notifications for these.
(sec:understand)=
### Merge Only Changes You Understand
_Long-term maintainability_ is an important concern. Code doesn't
merely have to _work_, but should be _understood_ by multiple core
developers. Changes will have to be made in the future, and the
original contributor may have moved on.
Therefore, _do not merge a code change unless you understand it_. Ask
for help freely: we have a long history of consulting community
members, or even external developers, for added insight where needed,
and see this as a great learning opportunity.
While we collectively "own" any patches (and bugs!) that become part
of the code base, you are vouching for changes you merge. Please take
that responsibility seriously.
In practice, if you are the second core developer reviewing and approving a
given pull request, you typically merge it (again, using GitHub's Squash and
Merge feature) in the wake of your approval. What are the exceptions to this
process? If the pull request has been particularly controversial or the
subject of much debate (e.g., involving API changes), then you would want to
wait a few days before merging. This waiting time gives others a chance to
speak up in case they are not fine with the current state of the pull request.
Another exceptional situation is one where the first approving review happened
a long time ago and many changes have taken place in the meantime.
When squashing commits GitHub concatenates all commit messages.
Please edit the resulting message so that it gives a concise, tidy
overview of changes. For example, you may want to grab the
description from the PR itself, and delete lines such as "pep8 fix",
"apply review comments", etc. Please retain all Co-authored-by
entries.
## Closing issues and pull requests
Sometimes, an issue must be closed that was not fully resolved. This can be
for a number of reasons:
- the person behind the original post has not responded to calls for
clarification, and none of the core developers have been able to reproduce
their issue;
- fixing the issue is difficult, and it is deemed too niche a use case to
devote sustained effort or prioritize over other issues; or
- the use case or feature request is something that core developers feel
does not belong in scikit-image,
among others. Similarly, pull requests sometimes need to be closed without
merging, because:
- the pull request implements a niche feature that we consider not worth the
added maintenance burden;
- the pull request implements a useful feature, but requires significant
effort to bring up to scikit-image's standards, and the original
contributor has moved on, and no other developer can be found to make the
necessary changes; or
- the pull request makes changes that do not align with our values, such as
increasing the code complexity of a function significantly to implement a
marginal speedup,
among others.
All these may be valid reasons for closing, but we must be wary not to alienate
contributors by closing an issue or pull request without an explanation. When
closing, your message should:
- explain clearly how the decision was made to close. This is particularly
important when the decision was made in a community meeting, which does not
have as visible a record as the comments thread on the issue itself;
- thank the contributor(s) for their work; and
- provide a clear path for the contributor or anyone else to appeal the
decision.
These points help ensure that all contributors feel welcome and empowered to
keep contributing, regardless of the outcome of past contributions.
## Further resources
As a core member, you should be familiar with community and developer
resources such as:
- Our {doc}`contributor guide <contribute>`
- Our [community guidelines](https://scikit-image.org/community_guidelines.html)
- [PEP8](https://www.python.org/dev/peps/pep-0008/) for Python style
- [PEP257](https://www.python.org/dev/peps/pep-0257/) and the
[NumPy documentation guide][numpydoc]
for docstrings. (NumPy docstrings are a superset of PEP257. You
should read both.)
- The scikit-image [tag on StackOverflow][so_tag]
- The scikit-image [tag on forum.image.sc](https://forum.image.sc/tags/scikit-image)
- Our [developer forum][ml]
- Our [chat room](https://skimage.zulipchat.com/)
[numpydoc]: https://docs.scipy.org/doc/numpy/docs/howto_document.html
[so_tag]: https://stackoverflow.com/questions/tagged/scikit-image
[ml]: https://discuss.scientific-python.org/c/contributor/skimage
You are not required to monitor all of the social resources.
## Inviting New Core Members
Any core member may nominate other contributors to join the core team.
Nominations happen on a private email list,
<<EMAIL>>. As of this writing, there is no hard-and-fast
rule about who can be nominated; at a minimum, they should have: been
part of the project for at least six months, contributed
significant changes of their own, contributed to the discussion and
review of others' work, and collaborated in a way befitting our
community values.
## Contribute To This Guide!
This guide reflects the experience of the current core developers. We
may well have missed things that, by now, have become second
nature—things that you, as a new team member, will spot more easily.
Please ask the other core developers if you have any questions, and
submit a pull request with insights gained.
## Conclusion
We are excited to have you on board! We look forward to your
contributions to the code base and the community. Thank you in
advance!
<file_sep>/skimage/transform/tests/test_finite_radon_transform.py
import numpy as np
from skimage.transform import frt2, ifrt2
def test_frt():
SIZE = 59 # must be prime to ensure that f inverse is unique
# Generate a test image
L = np.tri(SIZE, dtype=np.int32) + np.tri(SIZE, dtype=np.int32)[::-1]
f = frt2(L)
fi = ifrt2(f)
assert np.array_equal(L, fi)
<file_sep>/tools/github/script.sh
#!/usr/bin/env bash
# Fail on non-zero exit and echo the commands
set -evx
python -m pip install $PIP_FLAGS -r requirements/test.txt
export MPL_DIR=`python -c 'import matplotlib; print(matplotlib.get_configdir())'`
mkdir -p $MPL_DIR
touch $MPL_DIR/matplotlibrc
TEST_ARGS="--doctest-modules --cov=skimage --showlocals"
if [[ ${WITHOUT_POOCH} == "1" ]]; then
# remove pooch (previously installed via requirements/test.txt)
python -m pip uninstall pooch -y
fi
if [[ "${OPTIONAL_DEPS}" == "1" ]]; then
python -m pip install $PIP_FLAGS -r ./requirements/optional.txt
fi
python -m pip list
(cd .. && pytest $TEST_ARGS --pyargs skimage)
if [[ "${BUILD_DOCS}" == "1" ]] || [[ "${TEST_EXAMPLES}" == "1" ]]; then
echo Build or run examples
python -m pip install $PIP_FLAGS -r ./requirements/docs.txt
python -m pip list
echo 'backend : Template' > $MPL_DIR/matplotlibrc
fi
if [[ "${BUILD_DOCS}" == "1" ]]; then
echo Build docs
export SPHINXCACHE=${HOME}/.cache/sphinx; make -C doc html
elif [[ "${TEST_EXAMPLES}" == "1" ]]; then
echo Test examples
for f in doc/examples/*/*.py; do
python "${f}"
if [ $? -ne 0 ]; then
exit 1
fi
done
fi
set +ev
<file_sep>/meson.md
# Building with Meson
We are assuming that you have a default Python environment already configured on
your computer and that you intend to install `scikit-image` inside of it.
### Developer build
Install the required dependencies:
```
pip install -r requirements.txt
pip install -r requirements/build.txt
```
Then build `skimage`:
```
spin build
spin test
```
To run a specific test:
```
spin test -- skimage/io/tests/test_imageio.py
```
Or to try the new version in IPython:
```
pip install ipython
spin ipython
```
Run `spin --help` for more commands.
### Developer build (explicit)
**Install build tools:** `pip install -r requirements/build.txt`
**Generate ninja make files:** `meson build --prefix=$PWD/build`
**Compile:** `ninja -C build`
**Install:** `meson install -C build`
The installation step copies the necessary Python files into the build dir to form a
complete package.
Do not skip this step, or the package won't work.
To use the package, add it to your PYTHONPATH:
```
export PYTHONPATH=${PWD}/build/lib64/python3.10/site-packages
pytest --pyargs skimage
```
### pip install
The standard installation procedure via pip still works:
```
pip install --no-build-isolation .
```
Note, however, that `pip install -e .` (in-place developer install) does not!
See "Developer build" above.
### sdist and wheel
The Python `build` module calls Meson and ninja as necessary to
produce an sdist and a wheel:
```
python -m build --no-isolation
```
## Notes
### Templated Cython files
The `skimage/morphology/skeletonize_3d.pyx.in` is converted into a pyx
file using Tempita. That pyx file appears in the _build_
directory, and can be compiled from there.
If that file had to import local `*.pyx` files (it does not) then the
build dependencies would need be set to ensure that the relevant pyx
files are copied into the build directory prior to compilation (see
`_cython_tree` in the SciPy Meson build files).
<file_sep>/benchmarks/benchmark_measure.py
import numpy as np
from skimage import data, filters, measure
try:
from skimage.measure._regionprops import PROP_VALS
except ImportError:
PROP_VALS = []
def init_regionprops_data():
image = filters.gaussian(data.coins().astype(float), 3)
# increase size to (2048, 2048) by tiling
image = np.tile(image, (4, 4))
label_image = measure.label(image > 130, connectivity=image.ndim)
intensity_image = image
return label_image, intensity_image
class RegionpropsTableIndividual:
param_names = ['prop']
params = sorted(list(PROP_VALS))
def setup(self, prop):
try:
from skimage.measure import regionprops_table # noqa
except ImportError:
# regionprops_table was introduced in scikit-image v0.16.0
raise NotImplementedError("regionprops_table unavailable")
self.label_image, self.intensity_image = init_regionprops_data()
def time_single_region_property(self, prop):
measure.regionprops_table(self.label_image, self.intensity_image,
properties=[prop], cache=True)
# omit peakmem tests to save time (memory usage was minimal)
class RegionpropsTableAll:
param_names = ['cache']
params = (False, True)
def setup(self, cache):
try:
from skimage.measure import regionprops_table # noqa
except ImportError:
# regionprops_table was introduced in scikit-image v0.16.0
raise NotImplementedError("regionprops_table unavailable")
self.label_image, self.intensity_image = init_regionprops_data()
def time_regionprops_table_all(self, cache):
measure.regionprops_table(self.label_image, self.intensity_image,
properties=PROP_VALS, cache=cache)
# omit peakmem tests to save time (memory usage was minimal)
class MomentsSuite:
params = ([(64, 64), (4096, 2048), (32, 32, 32), (256, 256, 192)],
[np.uint8, np.float32, np.float64],
[1, 2, 3])
param_names = ['shape', 'dtype', 'order']
"""Benchmark for filter routines in scikit-image."""
def setup(self, shape, dtype, *args):
rng = np.random.default_rng(1234)
if np.dtype(dtype).kind in 'iu':
self.image = rng.integers(0, 256, shape, dtype=dtype)
else:
self.image = rng.standard_normal(shape, dtype=dtype)
def time_moments_raw(self, shape, dtype, order):
measure.moments(self.image)
def time_moments_central(self, shape, dtype, order):
measure.moments_central(self.image)
def peakmem_reference(self, shape, dtype, order):
pass
def peakmem_moments_central(self, shape, dtype, order):
measure.moments_central(self.image)
<file_sep>/skimage/graph/__init__.pyi
# Explicitly setting `__all__` is necessary for type inference engines
# to know which symbols are exported. See
# https://peps.python.org/pep-0484/#stub-files
__all__ = [
'pixel_graph',
'central_pixel',
'shortest_path',
'MCP',
'MCP_Geometric',
'MCP_Connect',
'MCP_Flexible',
'route_through_array',
'rag_mean_color',
'rag_boundary',
'cut_threshold',
'cut_normalized',
'merge_hierarchical',
'RAG',
]
from ._graph import pixel_graph, central_pixel
from ._graph_cut import cut_threshold, cut_normalized
from ._graph_merge import merge_hierarchical
from ._rag import rag_mean_color, RAG, show_rag, rag_boundary
from .spath import shortest_path
from .mcp import (
MCP, MCP_Geometric,
MCP_Connect,
MCP_Flexible,
route_through_array
)
<file_sep>/skimage/morphology/tests/test_isotropic.py
import numpy as np
from numpy.testing import assert_array_equal
from skimage import color, data, morphology
from skimage.morphology import binary, isotropic
from skimage.util import img_as_bool
img = color.rgb2gray(data.astronaut())
bw_img = img > 100 / 255.
def test_non_square_image():
isotropic_res = isotropic.isotropic_erosion(bw_img[:100, :200], 3)
binary_res = img_as_bool(binary.binary_erosion(
bw_img[:100, :200], morphology.disk(3)))
assert_array_equal(isotropic_res, binary_res)
def test_isotropic_erosion():
isotropic_res = isotropic.isotropic_erosion(bw_img, 3)
binary_res = img_as_bool(binary.binary_erosion(bw_img, morphology.disk(3)))
assert_array_equal(isotropic_res, binary_res)
def _disk_with_spacing(radius, dtype=np.uint8, *, strict_radius=True, spacing=None):
# Identical to morphology.disk, but with a spacing parameter and without decomposition.
# This is different from morphology.ellipse which produces a slightly different footprint.
L = np.arange(-radius, radius + 1)
X, Y = np.meshgrid(L, L)
if spacing is not None:
X *= spacing[1]
Y *= spacing[0]
if not strict_radius:
radius += 0.5
return np.array((X ** 2 + Y ** 2) <= radius ** 2, dtype=dtype)
def test_isotropic_erosion_spacing():
isotropic_res = isotropic.isotropic_dilation(bw_img, 6, spacing=(1,2))
binary_res = img_as_bool(binary.binary_dilation(bw_img, _disk_with_spacing(6, spacing=(1,2))))
assert_array_equal(isotropic_res, binary_res)
def test_isotropic_dilation():
isotropic_res = isotropic.isotropic_dilation(bw_img, 3)
binary_res = img_as_bool(
binary.binary_dilation(
bw_img, morphology.disk(3)))
assert_array_equal(isotropic_res, binary_res)
def test_isotropic_closing():
isotropic_res = isotropic.isotropic_closing(bw_img, 3)
binary_res = img_as_bool(binary.binary_closing(bw_img, morphology.disk(3)))
assert_array_equal(isotropic_res, binary_res)
def test_isotropic_opening():
isotropic_res = isotropic.isotropic_opening(bw_img, 3)
binary_res = img_as_bool(binary.binary_opening(bw_img, morphology.disk(3)))
assert_array_equal(isotropic_res, binary_res)
def test_footprint_overflow():
img = np.zeros((20, 20), dtype=bool)
img[2:19, 2:19] = True
isotropic_res = isotropic.isotropic_erosion(img, 9)
binary_res = img_as_bool(binary.binary_erosion(img, morphology.disk(9)))
assert_array_equal(isotropic_res, binary_res)
def test_out_argument():
for func in (isotropic.isotropic_erosion, isotropic.isotropic_dilation):
radius = 3
img = np.ones((10, 10))
out = np.zeros_like(img)
out_saved = out.copy()
func(img, radius, out=out)
assert np.any(out != out_saved)
assert_array_equal(out, func(img, radius))
<file_sep>/skimage/filters/tests/test_median.py
import numpy as np
import pytest
from numpy.testing import assert_allclose
from scipy import ndimage
from skimage.filters import median, rank
@pytest.fixture
def image():
return np.array([[1, 2, 3, 2, 1],
[1, 1, 2, 2, 3],
[3, 2, 1, 2, 1],
[3, 2, 1, 1, 1],
[1, 2, 1, 2, 3]],
dtype=np.uint8)
@pytest.mark.parametrize(
"mode, cval, behavior, warning_type",
[('nearest', 0.0, 'ndimage', None),
('constant', 0.0, 'rank', UserWarning),
('nearest', 0.0, 'rank', None),
('nearest', 0.0, 'ndimage', None)]
)
def test_median_warning(image, mode, cval, behavior, warning_type):
if warning_type:
with pytest.warns(warning_type):
median(image, mode=mode, behavior=behavior)
else:
median(image, mode=mode, behavior=behavior)
@pytest.mark.parametrize(
"behavior, func, params",
[('ndimage', ndimage.median_filter, {'size': (3, 3)}),
('rank', rank.median, {'footprint': np.ones((3, 3), dtype=np.uint8)})]
)
def test_median_behavior(image, behavior, func, params):
assert_allclose(median(image, behavior=behavior), func(image, **params))
@pytest.mark.parametrize(
"dtype", [np.uint8, np.uint16, np.float32, np.float64]
)
def test_median_preserve_dtype(image, dtype):
median_image = median(image.astype(dtype), behavior='ndimage')
assert median_image.dtype == dtype
def test_median_error_ndim():
img = np.random.randint(0, 10, size=(5, 5, 5, 5), dtype=np.uint8)
with pytest.raises(ValueError):
median(img, behavior='rank')
@pytest.mark.parametrize(
"img, behavior",
[(np.random.randint(0, 10, size=(3, 3), dtype=np.uint8), 'rank'),
(np.random.randint(0, 10, size=(3, 3), dtype=np.uint8), 'ndimage'),
(np.random.randint(0, 10, size=(3, 3, 3), dtype=np.uint8), 'ndimage')]
)
def test_median(img, behavior):
median(img, behavior=behavior)
<file_sep>/skimage/exposure/__init__.pyi
# Explicitly setting `__all__` is necessary for type inference engines
# to know which symbols are exported. See
# https://peps.python.org/pep-0484/#stub-files
__all__ = [
'histogram',
'equalize_hist',
'equalize_adapthist',
'rescale_intensity',
'cumulative_distribution',
'adjust_gamma',
'adjust_sigmoid',
'adjust_log',
'is_low_contrast',
'match_histograms'
]
from ._adapthist import equalize_adapthist
from .histogram_matching import match_histograms
from .exposure import (
histogram,
equalize_hist,
rescale_intensity,
cumulative_distribution,
adjust_gamma,
adjust_sigmoid,
adjust_log,
is_low_contrast
)
<file_sep>/skimage/measure/pnpoly.py
from ._pnpoly import _grid_points_in_poly, _points_in_poly
def grid_points_in_poly(shape, verts, binarize=True):
"""Test whether points on a specified grid are inside a polygon.
For each ``(r, c)`` coordinate on a grid, i.e. ``(0, 0)``, ``(0, 1)`` etc.,
test whether that point lies inside a polygon.
You can control the output type with the `binarize` flag. Please refer to its
documentation for further details.
Parameters
----------
shape : tuple (M, N)
Shape of the grid.
verts : (V, 2) array
Specify the V vertices of the polygon, sorted either clockwise
or anti-clockwise. The first point may (but does not need to be)
duplicated.
binarize: bool
If `True`, the output of the function is a boolean mask.
Otherwise, it is a labeled array. The labels are:
O - outside, 1 - inside, 2 - vertex, 3 - edge.
See Also
--------
points_in_poly
Returns
-------
mask : (M, N) ndarray
If `binarize` is True, the output is a boolean mask. True means the
corresponding pixel falls inside the polygon.
If `binarize` is False, the output is a labeled array, with pixels
having a label between 0 and 3. The meaning of the values is:
O - outside, 1 - inside, 2 - vertex, 3 - edge.
"""
output = _grid_points_in_poly(shape, verts)
if binarize:
output = output.astype(bool)
return output
def points_in_poly(points, verts):
"""Test whether points lie inside a polygon.
Parameters
----------
points : (N, 2) array
Input points, ``(x, y)``.
verts : (M, 2) array
Vertices of the polygon, sorted either clockwise or anti-clockwise.
The first point may (but does not need to be) duplicated.
See Also
--------
grid_points_in_poly
Returns
-------
mask : (N,) array of bool
True if corresponding point is inside the polygon.
"""
return _points_in_poly(points, verts)
<file_sep>/skimage/draw/_polygon2mask.py
import numpy as np
from . import draw
def polygon2mask(image_shape, polygon):
"""Create a binary mask from a polygon.
Parameters
----------
image_shape : tuple of size 2
The shape of the mask.
polygon : (N, 2) array_like
The polygon coordinates of shape (N, 2) where N is
the number of points.
Returns
-------
mask : 2-D ndarray of type 'bool'
The binary mask that corresponds to the input polygon.
See Also
--------
polygon:
Generate coordinates of pixels inside a polygon.
Notes
-----
This function does not do any border checking. Parts of the polygon that
are outside the coordinate space defined by `image_shape` are not drawn.
Examples
--------
>>> import skimage as ski
>>> image_shape = (10, 10)
>>> polygon = np.array([[1, 1], [2, 7], [8, 4]])
>>> mask = ski.draw.polygon2mask(image_shape, polygon)
>>> mask.astype(int)
array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 1, 1, 1, 1, 1, 0, 0],
[0, 0, 1, 1, 1, 1, 1, 0, 0, 0],
[0, 0, 0, 1, 1, 1, 1, 0, 0, 0],
[0, 0, 0, 1, 1, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])
If vertices / points of the `polygon` are outside the coordinate space
defined by `image_shape`, only a part (or none at all) of the polygon is
drawn in the mask.
>>> offset = np.array([[2, -4]])
>>> ski.draw.polygon2mask(image_shape, polygon - offset).astype(int)
array([[0, 0, 0, 0, 0, 0, 1, 1, 1, 1],
[0, 0, 0, 0, 0, 0, 1, 1, 1, 1],
[0, 0, 0, 0, 0, 0, 0, 1, 1, 1],
[0, 0, 0, 0, 0, 0, 0, 1, 1, 1],
[0, 0, 0, 0, 0, 0, 0, 0, 1, 1],
[0, 0, 0, 0, 0, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 1, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])
"""
polygon = np.asarray(polygon)
vertex_row_coords, vertex_col_coords = polygon.T
fill_row_coords, fill_col_coords = draw.polygon(
vertex_row_coords, vertex_col_coords, image_shape)
mask = np.zeros(image_shape, dtype=bool)
mask[fill_row_coords, fill_col_coords] = True
return mask
<file_sep>/skimage/_build_utils/version.py
#!/usr/bin/env python
""" Extract version number from __init__.py
"""
import os
ski_init = os.path.join(os.path.dirname(__file__), '../__init__.py')
data = open(ski_init).readlines()
version_line = next(line for line in data if line.startswith('__version__'))
version = version_line.strip().split(' = ')[1].replace('"', '').replace("'", '')
print(version)
<file_sep>/skimage/morphology/tests/test_footprints.py
"""
Tests for Morphological footprints
(skimage.morphology.footprint)
Author: <NAME>
"""
import numpy as np
import pytest
from numpy.testing import assert_equal
from skimage._shared.testing import fetch
from skimage.morphology import footprints
class TestFootprints:
def test_square_footprint(self):
"""Test square footprints"""
for k in range(0, 5):
actual_mask = footprints.square(k)
expected_mask = np.ones((k, k), dtype='uint8')
assert_equal(expected_mask, actual_mask)
def test_rectangle_footprint(self):
"""Test rectangle footprints"""
for i in range(0, 5):
for j in range(0, 5):
actual_mask = footprints.rectangle(i, j)
expected_mask = np.ones((i, j), dtype='uint8')
assert_equal(expected_mask, actual_mask)
def test_cube_footprint(self):
"""Test cube footprints"""
for k in range(0, 5):
actual_mask = footprints.cube(k)
expected_mask = np.ones((k, k, k), dtype='uint8')
assert_equal(expected_mask, actual_mask)
def strel_worker(self, fn, func):
matlab_masks = np.load(fetch(fn))
k = 0
for arrname in sorted(matlab_masks):
expected_mask = matlab_masks[arrname]
actual_mask = func(k)
if expected_mask.shape == (1,):
expected_mask = expected_mask[:, np.newaxis]
assert_equal(expected_mask, actual_mask)
k = k + 1
def strel_worker_3d(self, fn, func):
matlab_masks = np.load(fetch(fn))
k = 0
for arrname in sorted(matlab_masks):
expected_mask = matlab_masks[arrname]
actual_mask = func(k)
if expected_mask.shape == (1,):
expected_mask = expected_mask[:, np.newaxis]
# Test center slice for each dimension. This gives a good
# indication of validity without the need for a 3D reference
# mask.
c = int(expected_mask.shape[0]/2)
assert_equal(expected_mask, actual_mask[c, :, :])
assert_equal(expected_mask, actual_mask[:, c, :])
assert_equal(expected_mask, actual_mask[:, :, c])
k = k + 1
def test_footprint_disk(self):
"""Test disk footprints"""
self.strel_worker("data/disk-matlab-output.npz", footprints.disk)
def test_footprint_diamond(self):
"""Test diamond footprints"""
self.strel_worker("data/diamond-matlab-output.npz", footprints.diamond)
def test_footprint_ball(self):
"""Test ball footprints"""
self.strel_worker_3d("data/disk-matlab-output.npz", footprints.ball)
def test_footprint_octahedron(self):
"""Test octahedron footprints"""
self.strel_worker_3d("data/diamond-matlab-output.npz",
footprints.octahedron)
def test_footprint_octagon(self):
"""Test octagon footprints"""
expected_mask1 = np.array([[0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0],
[0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0],
[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0],
[0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0],
[0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0]],
dtype=np.uint8)
actual_mask1 = footprints.octagon(5, 3)
expected_mask2 = np.array([[0, 1, 0],
[1, 1, 1],
[0, 1, 0]], dtype=np.uint8)
actual_mask2 = footprints.octagon(1, 1)
assert_equal(expected_mask1, actual_mask1)
assert_equal(expected_mask2, actual_mask2)
def test_footprint_ellipse(self):
"""Test ellipse footprints"""
expected_mask1 = np.array([[0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0]],
dtype=np.uint8)
actual_mask1 = footprints.ellipse(5, 3)
expected_mask2 = np.array([[1, 1, 1],
[1, 1, 1],
[1, 1, 1]], dtype=np.uint8)
actual_mask2 = footprints.ellipse(1, 1)
assert_equal(expected_mask1, actual_mask1)
assert_equal(expected_mask2, actual_mask2)
assert_equal(expected_mask1, footprints.ellipse(3, 5).T)
assert_equal(expected_mask2, footprints.ellipse(1, 1).T)
def test_footprint_star(self):
"""Test star footprints"""
expected_mask1 = np.array([[0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0],
[0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0],
[0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0],
[0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0],
[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0],
[0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0],
[0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0],
[0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0],
[0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0]],
dtype=np.uint8)
actual_mask1 = footprints.star(4)
expected_mask2 = np.array([[1, 1, 1],
[1, 1, 1],
[1, 1, 1]], dtype=np.uint8)
actual_mask2 = footprints.star(1)
assert_equal(expected_mask1, actual_mask1)
assert_equal(expected_mask2, actual_mask2)
@pytest.mark.parametrize(
'function, args, supports_sequence_decomposition',
[
(footprints.disk, (3,), True),
(footprints.ball, (3,), True),
(footprints.square, (3,), True),
(footprints.cube, (3,), True),
(footprints.diamond, (3,), True),
(footprints.octahedron, (3,), True),
(footprints.rectangle, (3, 4), True),
(footprints.ellipse, (3, 4), False),
(footprints.octagon, (3, 4), True),
(footprints.star, (3,), False),
]
)
@pytest.mark.parametrize("dtype", [np.uint8, np.float64])
def test_footprint_dtype(function, args, supports_sequence_decomposition,
dtype):
# make sure footprint dtype matches what was requested
footprint = function(*args, dtype=dtype)
assert footprint.dtype == dtype
if supports_sequence_decomposition:
sequence = function(*args, dtype=dtype, decomposition='sequence')
assert all([fp_tuple[0].dtype == dtype for fp_tuple in sequence])
@pytest.mark.parametrize("function", ["disk", "ball"])
@pytest.mark.parametrize("radius", [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 50, 75,
100])
def test_nsphere_series_approximation(function, radius):
fp_func = getattr(footprints, function)
expected = fp_func(radius, strict_radius=False, decomposition=None)
footprint_sequence = fp_func(radius, strict_radius=False,
decomposition="sequence")
approximate = footprints.footprint_from_sequence(footprint_sequence)
assert approximate.shape == expected.shape
# verify that maximum error does not exceed some fraction of the size
error = np.sum(np.abs(expected.astype(int) - approximate.astype(int)))
if radius == 1:
assert error == 0
else:
max_error = 0.1 if function == "disk" else 0.15
assert error / expected.size <= max_error
@pytest.mark.parametrize("radius", [1, 2, 3, 4, 5, 10, 20, 50, 75])
@pytest.mark.parametrize("strict_radius", [False, True])
def test_disk_crosses_approximation(radius, strict_radius):
fp_func = footprints.disk
expected = fp_func(radius, strict_radius=strict_radius, decomposition=None)
footprint_sequence = fp_func(radius, strict_radius=strict_radius,
decomposition="crosses")
approximate = footprints.footprint_from_sequence(footprint_sequence)
assert approximate.shape == expected.shape
# verify that maximum error does not exceed some fraction of the size
error = np.sum(np.abs(expected.astype(int) - approximate.astype(int)))
max_error = 0.05
assert error / expected.size <= max_error
@pytest.mark.parametrize("width", [3, 8, 20, 50])
@pytest.mark.parametrize("height", [3, 8, 20, 50])
def test_ellipse_crosses_approximation(width, height):
fp_func = footprints.ellipse
expected = fp_func(width, height, decomposition=None)
footprint_sequence = fp_func(width, height, decomposition="crosses")
approximate = footprints.footprint_from_sequence(footprint_sequence)
assert approximate.shape == expected.shape
# verify that maximum error does not exceed some fraction of the size
error = np.sum(np.abs(expected.astype(int) - approximate.astype(int)))
max_error = 0.05
assert error / expected.size <= max_error
def test_disk_series_approximation_unavailable():
# ValueError if radius is too large (only precomputed up to radius=250)
with pytest.raises(ValueError):
footprints.disk(radius=10000, decomposition="sequence")
def test_ball_series_approximation_unavailable():
# ValueError if radius is too large (only precomputed up to radius=100)
with pytest.raises(ValueError):
footprints.ball(radius=10000, decomposition="sequence")
<file_sep>/pyproject.toml
[project]
name = 'scikit-image'
description = 'Image processing in Python'
requires-python = '>=3.9'
readme = 'README.md'
classifiers = [
'Development Status :: 4 - Beta',
'Environment :: Console',
'Intended Audience :: Developers',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: BSD License',
'Programming Language :: C',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.9',
'Programming Language :: Python :: 3.10',
'Programming Language :: Python :: 3.11',
'Programming Language :: Python :: 3 :: Only',
'Topic :: Software Development :: Libraries',
'Topic :: Scientific/Engineering',
'Operating System :: Microsoft :: Windows',
'Operating System :: POSIX',
'Operating System :: Unix',
'Operating System :: MacOS',
]
dynamic = ['version']
dependencies = [
'numpy>=1.22',
'scipy>=1.8',
'networkx>=2.8',
'pillow>=9.0.1',
'imageio>=2.27',
'tifffile>=2022.8.12',
'PyWavelets>=1.1.1',
'packaging>=21',
'lazy_loader>=0.3',
]
[[project.maintainers]]
name = 'scikit-image developers'
email = '<EMAIL>'
[project.license]
file = 'LICENSE.txt'
[project.optional-dependencies]
build = [
# Also update [build-system] -> requires
'meson-python>=0.13',
'wheel',
'setuptools>=67',
'packaging>=21',
'ninja',
'Cython>=0.29.32',
'pythran',
'numpy>=1.22',
# Developer UI
'spin==0.5',
'build',
]
data = ['pooch>=1.6.0']
developer = [
'pre-commit',
"tomli; python_version < '3.11'",
]
docs = [
'sphinx>=5.0',
'sphinx-gallery>=0.11',
'numpydoc>=1.5',
'sphinx-copybutton',
'pytest-runner',
'matplotlib>=3.5',
'dask[array]>=2022.9.2',
'pandas>=1.5',
'seaborn>=0.11',
'pooch>=1.6',
'tifffile>=2022.8.12',
'myst-parser',
'ipywidgets',
'ipykernel', # needed until https://github.com/jupyter-widgets/ipywidgets/issues/3731 is resolved
'plotly>=5.10',
'kaleido',
'scikit-learn>=0.24.0',
'sphinx_design>=0.3',
'pydata-sphinx-theme>=0.13',
]
optional = [
'SimpleITK',
'astropy>=5.0',
'cloudpickle>=0.2.1', # necessary to provide the 'processes' scheduler for dask
'dask[array]>=2021.1.0',
'matplotlib>=3.5',
'pooch>=1.6.0',
'pyamg',
'scikit-learn>=1.0',
]
test = [
'asv',
'matplotlib>=3.5',
'numpydoc>=1.5',
'pooch>=1.6.0',
'pytest>=7.0',
'pytest-cov>=2.11.0',
'pytest-localserver',
'pytest-faulthandler',
]
[project.urls]
homepage = 'https://scikit-image.org'
documentation = 'https://scikit-image.org/docs/stable'
source = 'https://github.com/scikit-image/scikit-image'
download = 'https://pypi.org/project/scikit-image/#files'
tracker = 'https://github.com/scikit-image/scikit-image/issues'
[build-system]
build-backend = 'mesonpy'
requires = [
'meson-python>=0.13',
'wheel',
'setuptools>=67',
'packaging>=21',
'Cython>=0.29.32',
'pythran',
'lazy_loader>=0.2',
"numpy==1.22.4; python_version=='3.9' and platform_python_implementation != 'PyPy'",
"numpy==1.22.4; python_version=='3.10' and platform_system=='Windows' and platform_python_implementation != 'PyPy'",
"numpy==1.22.4; python_version=='3.10' and platform_system != 'Windows' and platform_python_implementation != 'PyPy'",
"numpy==1.23.3; python_version=='3.11' and platform_python_implementation != 'PyPy'",
"numpy; python_version>='3.12'",
"numpy; python_version>='3.9' and platform_python_implementation=='PyPy'",
]
[tool.spin]
package = 'skimage'
[tool.spin.commands]
Build = [
'spin.build',
'spin.test',
'.spin/cmds.py:sdist',
]
Environments = [
'spin.shell',
'spin.ipython',
'spin.python',
]
Documentation = ['.spin/cmds.py:docs']
Metrics = [
'.spin/cmds.py:asv',
'.spin/cmds.py:coverage',
]
[tool.ruff]
line-length = 88
target-version = 'py39'
select = [
'F',
'E',
'W',
'UP',
]
ignore = [
'E501',
'E741',
'E712',
]
exclude = [
'.git',
'.ruff_cache',
'build',
'build-install',
'dist',
'doc/source/auto_examples',
]
[tool.ruff.per-file-ignores]
"**/__init__.py" = [
'E402',
'F401',
'F403',
'F405',
]
"**/__init__.pyi" = [
'E402',
'F401',
'F403',
'F405',
]
"skimage/_shared/testing.py" = ['F401']
"doc/examples/**/*.py" = ['E402']
[tool.ruff.pydocstyle]
convention = 'numpy'
[tool.pytest]
python_files = [
'benchmark_*.py',
'test_*.py',
]
python_classes = [
'Test*',
'*Suite',
]
python_functions = [
'time_*',
'test_*',
'peakmem_*',
]
[tool.coverage.run]
omit = ['*/tests/*']
<file_sep>/doc/ext/skimage_extensions.py
"""Custom Sphinx extensions for scikit-image's docs.
Have a look at the `setup` function to see what kind of functionality is added.
"""
import re
from pathlib import Path
from sphinx.util import logging
from sphinx.directives.other import TocTree
logger = logging.getLogger(__name__)
def natural_sort_key(item):
"""Transform entries into tuples that can be sorted in natural order [1]_.
This can be passed to the "key" argument of Python's `sorted` function.
Parameters
----------
item :
Item to generate the key from. `str` is called on this item before generating
the key.
Returns
-------
key : tuple[str or int]
Key to sort by.
Examples
--------
>>> natural_sort_key("release_notes_2.rst")
('release_notes_', 2, '.rst')
>>> natural_sort_key("release_notes_10.rst")
('release_notes_', 10, '.rst')
>>> sorted(["10.b", "2.c", "100.a"], key=natural_sort_key)
['2.c', '10.b', '100.a']
References
----------
.. [1] https://en.wikipedia.org/wiki/Natural_sort_order
"""
splitted = re.split(r"(\d+)", str(item))
key = tuple(int(x) if x.isdigit() else x for x in splitted)
return key
class NaturalSortedTocTree(TocTree):
"""Directive that sorts all TOC entries in natural order by their file names.
Behaves similar to Sphinx's default ``toctree`` directive. The ``reversed`` option
is respected, though the given order of entries (or globbed entries) is ignored.
"""
def parse_content(self, toctree):
ret = super().parse_content(toctree)
reverse = 'reversed' in self.options
toctree['entries'] = sorted(
toctree['entries'], key=natural_sort_key, reverse=reverse
)
return ret
RANDOM_JS_TEMPLATE = '''\
function insert_gallery() {
var images = {{IMAGES}};
var links = {{LINKS}};
ix = Math.floor(Math.random() * images.length);
document.write(
'{{GALLERY_DIV}}'.replace('IMG', images[ix]).replace('URL', links[ix])
);
console.log('{{GALLERY_DIV}}'.replace('IMG', images[ix]).replace('URL', links[ix]));
};
'''
GALLERY_DIV = '''\
<div class="gallery_image">
<a href="URL"><img src="IMG"/></a>
</div>\
'''
def write_random_js(app, exception):
"""Generate a javascript snippet that links to a random gallery example."""
if app.builder.format != "html":
logger.debug(
"[skimage_extensions] skipping generation of random.js for non-html build"
)
return
build_dir = Path(app.outdir)
random_js_path = Path(app.outdir) / "_static/random.js"
image_urls = []
tutorial_urls = []
url_root = "https://scikit-image.org/docs/dev/"
examples = build_dir.rglob("auto_examples/**/plot_*.html")
for example in examples:
image_name = f"sphx_glr_{example.stem}_001.png"
if not (build_dir / "_images" / image_name).exists():
continue
image_url = f'{url_root}_images/{image_name}'
tutorial_url = f'{url_root}{example.relative_to(build_dir)}'
image_urls.append(image_url)
tutorial_urls.append(tutorial_url)
if tutorial_urls == 0:
logger.error(
"[skimage_extensions] did not find any gallery examples while creating %s",
random_js_path
)
return
content = RANDOM_JS_TEMPLATE.replace('{{IMAGES}}', str(image_urls))
content = content.replace('{{LINKS}}', str(tutorial_urls))
content = content.replace('{{GALLERY_DIV}}', ''.join(GALLERY_DIV.split('\n')))
random_js_path.parent.mkdir(parents=True, exist_ok=True)
with open(random_js_path, 'w') as file:
file.write(content)
logger.info(
"[skimage_extensions] created %s with %i possible targets",
random_js_path,
len(tutorial_urls),
)
def setup(app):
app.add_directive('naturalsortedtoctree', NaturalSortedTocTree)
app.connect('build-finished', write_random_js)
<file_sep>/skimage/filters/_fft_based.py
import functools
import numpy as np
import scipy.fft as fft
from .._shared.utils import _supported_float_type
def _get_nd_butterworth_filter(shape, factor, order, high_pass, real,
dtype=np.float64, squared_butterworth=True):
"""Create a N-dimensional Butterworth mask for an FFT
Parameters
----------
shape : tuple of int
Shape of the n-dimensional FFT and mask.
factor : float
Fraction of mask dimensions where the cutoff should be.
order : float
Controls the slope in the cutoff region.
high_pass : bool
Whether the filter is high pass (low frequencies attenuated) or
low pass (high frequencies are attenuated).
real : bool
Whether the FFT is of a real (True) or complex (False) image
squared_butterworth : bool, optional
When True, the square of the Butterworth filter is used.
Returns
-------
wfilt : ndarray
The FFT mask.
"""
ranges = []
for i, d in enumerate(shape):
# start and stop ensures center of mask aligns with center of FFT
axis = np.arange(-(d - 1) // 2, (d - 1) // 2 + 1) / (d * factor)
ranges.append(fft.ifftshift(axis ** 2))
# for real image FFT, halve the last axis
if real:
limit = d // 2 + 1
ranges[-1] = ranges[-1][:limit]
# q2 = squared Euclidean distance grid
q2 = functools.reduce(
np.add, np.meshgrid(*ranges, indexing="ij", sparse=True)
)
q2 = q2.astype(dtype)
q2 = np.power(q2, order)
wfilt = 1 / (1 + q2)
if high_pass:
wfilt *= q2
if not squared_butterworth:
np.sqrt(wfilt, out=wfilt)
return wfilt
def butterworth(
image,
cutoff_frequency_ratio=0.005,
high_pass=True,
order=2.0,
channel_axis=None,
*,
squared_butterworth=True,
npad=0,
):
"""Apply a Butterworth filter to enhance high or low frequency features.
This filter is defined in the Fourier domain.
Parameters
----------
image : (M[, N[, ..., P]][, C]) ndarray
Input image.
cutoff_frequency_ratio : float, optional
Determines the position of the cut-off relative to the shape of the
FFT. Receives a value between [0, 0.5].
high_pass : bool, optional
Whether to perform a high pass filter. If False, a low pass filter is
performed.
order : float, optional
Order of the filter which affects the slope near the cut-off. Higher
order means steeper slope in frequency space.
channel_axis : int, optional
If there is a channel dimension, provide the index here. If None
(default) then all axes are assumed to be spatial dimensions.
squared_butterworth : bool, optional
When True, the square of a Butterworth filter is used. See notes below
for more details.
npad : int, optional
Pad each edge of the image by `npad` pixels using `numpy.pad`'s
``mode='edge'`` extension.
Returns
-------
result : ndarray
The Butterworth-filtered image.
Notes
-----
A band-pass filter can be achieved by combining a high-pass and low-pass
filter. The user can increase `npad` if boundary artifacts are apparent.
The "Butterworth filter" used in image processing textbooks (e.g. [1]_,
[2]_) is often the square of the traditional Butterworth filters as
described by [3]_, [4]_. The squared version will be used here if
`squared_butterworth` is set to ``True``. The lowpass, squared Butterworth
filter is given by the following expression for the lowpass case:
.. math::
H_{low}(f) = \\frac{1}{1 + \\left(\\frac{f}{c f_s}\\right)^{2n}}
with the highpass case given by
.. math::
H_{hi}(f) = 1 - H_{low}(f)
where :math:`f=\\sqrt{\\sum_{d=0}^{\\mathrm{ndim}} f_{d}^{2}}` is the
absolute value of the spatial frequency, :math:`f_s` is the sampling
frequency, :math:`c` the ``cutoff_frequency_ratio``, and :math:`n` is the
filter `order` [1]_. When ``squared_butterworth=False``, the square root of
the above expressions are used instead.
Note that ``cutoff_frequency_ratio`` is defined in terms of the sampling
frequency, :math:`f_s`. The FFT spectrum covers the Nyquist range
(:math:`[-f_s/2, f_s/2]`) so ``cutoff_frequency_ratio`` should have a value
between 0 and 0.5. The frequency response (gain) at the cutoff is 0.5 when
``squared_butterworth`` is true and :math:`1/\\sqrt{2}` when it is false.
Examples
--------
Apply a high-pass and low-pass Butterworth filter to a grayscale and
color image respectively:
>>> from skimage.data import camera, astronaut
>>> from skimage.filters import butterworth
>>> high_pass = butterworth(camera(), 0.07, True, 8)
>>> low_pass = butterworth(astronaut(), 0.01, False, 4, channel_axis=-1)
References
----------
.. [1] <NAME>., et al. The Image Processing Handbook, 3rd. Ed.
1999, CRC Press, LLC.
.. [2] <NAME>. Image Processing and Analysis. 2018. Cengage
Learning.
.. [3] <NAME>. "On the theory of filter amplifiers."
Wireless Engineer 7.6 (1930): 536-541.
.. [4] https://en.wikipedia.org/wiki/Butterworth_filter
"""
if npad < 0:
raise ValueError("npad must be >= 0")
elif npad > 0:
center_slice = tuple(slice(npad, s + npad) for s in image.shape)
image = np.pad(image, npad, mode='edge')
fft_shape = (image.shape if channel_axis is None
else np.delete(image.shape, channel_axis))
is_real = np.isrealobj(image)
float_dtype = _supported_float_type(image.dtype, allow_complex=True)
if cutoff_frequency_ratio < 0 or cutoff_frequency_ratio > 0.5:
raise ValueError(
"cutoff_frequency_ratio should be in the range [0, 0.5]"
)
wfilt = _get_nd_butterworth_filter(
fft_shape, cutoff_frequency_ratio, order, high_pass, is_real,
float_dtype, squared_butterworth
)
axes = np.arange(image.ndim)
if channel_axis is not None:
axes = np.delete(axes, channel_axis)
abs_channel = channel_axis % image.ndim
post = image.ndim - abs_channel - 1
sl = ((slice(None),) * abs_channel + (np.newaxis,) +
(slice(None),) * post)
wfilt = wfilt[sl]
if is_real:
butterfilt = fft.irfftn(wfilt * fft.rfftn(image, axes=axes),
s=fft_shape, axes=axes)
else:
butterfilt = fft.ifftn(wfilt * fft.fftn(image, axes=axes),
s=fft_shape, axes=axes)
if npad > 0:
butterfilt = butterfilt[center_slice]
return butterfilt
<file_sep>/doc/source/user_guide/index.rst
.. _user_guide:
User guide
==========
Here you can find our narrative documentation, learn about scikit-image's key concepts
and more advanced topics.
.. toctree::
:maxdepth: 1
:numbered:
install
getting_started
numpy_images
data_types
plugins
video
visualization
transforming_image_data
geometrical_transform
tutorials
getting_help
.. toctree::
:maxdepth: 1
:caption: Other resources
glossary
<file_sep>/skimage/filters/tests/test_gaussian.py
import numpy as np
import pytest
from numpy.testing import assert_array_equal
from skimage._shared.utils import _supported_float_type
from skimage._shared._warnings import expected_warnings
from skimage.filters import difference_of_gaussians, gaussian
def test_negative_sigma():
a = np.zeros((3, 3))
a[1, 1] = 1
with pytest.raises(ValueError):
gaussian(a, sigma=-1.0)
with pytest.raises(ValueError):
gaussian(a, sigma=[-1.0, 1.0])
with pytest.raises(ValueError):
gaussian(a, sigma=np.asarray([-1.0, 1.0]))
def test_null_sigma():
a = np.zeros((3, 3))
a[1, 1] = 1.
assert np.all(gaussian(a, 0, preserve_range=True) == a)
def test_default_sigma():
a = np.zeros((3, 3))
a[1, 1] = 1.
assert_array_equal(
gaussian(a, preserve_range=True),
gaussian(a, preserve_range=True, sigma=1)
)
@pytest.mark.parametrize(
'dtype', [np.uint8, np.int32, np.float16, np.float32, np.float64]
)
def test_image_dtype(dtype):
a = np.zeros((3, 3), dtype=dtype)
assert gaussian(a).dtype == _supported_float_type(a.dtype)
def test_energy_decrease():
a = np.zeros((3, 3))
a[1, 1] = 1.
gaussian_a = gaussian(a, preserve_range=True, sigma=1, mode='reflect')
assert gaussian_a.std() < a.std()
@pytest.mark.parametrize('channel_axis', [0, 1, -1])
def test_multichannel(channel_axis):
a = np.zeros((5, 5, 3))
a[1, 1] = np.arange(1, 4)
a = np.moveaxis(a, -1, channel_axis)
gaussian_rgb_a = gaussian(a, sigma=1, mode='reflect', preserve_range=True,
channel_axis=channel_axis)
# Check that the mean value is conserved in each channel
# (color channels are not mixed together)
spatial_axes = tuple(
[ax for ax in range(a.ndim) if ax != channel_axis % a.ndim]
)
assert np.allclose(a.mean(axis=spatial_axes),
gaussian_rgb_a.mean(axis=spatial_axes))
if channel_axis % a.ndim == 2:
with expected_warnings(
["Automatic detection of the color channel was deprecated"]
):
# Test legacy behavior equivalent to old (channel_axis=-1)
gaussian_rgb_a = gaussian(a, sigma=1, mode='reflect',
preserve_range=True)
# Check that the mean value is conserved in each channel
# (color channels are not mixed together)
assert np.allclose(a.mean(axis=spatial_axes),
gaussian_rgb_a.mean(axis=spatial_axes))
# Iterable sigma
gaussian_rgb_a = gaussian(a, sigma=[1, 2], mode='reflect',
channel_axis=channel_axis,
preserve_range=True)
assert np.allclose(a.mean(axis=spatial_axes),
gaussian_rgb_a.mean(axis=spatial_axes))
def test_preserve_range():
"""Test preserve_range parameter."""
ones = np.ones((2, 2), dtype=np.int64)
filtered_ones = gaussian(ones, preserve_range=False)
assert np.all(filtered_ones == filtered_ones[0, 0])
assert filtered_ones[0, 0] < 1e-10
filtered_preserved = gaussian(ones, preserve_range=True)
assert np.all(filtered_preserved == 1.)
img = np.array([[10.0, -10.0], [-4, 3]], dtype=np.float32)
gaussian(img, 1)
def test_1d_ok():
"""Testing Gaussian Filter for 1D array.
With any array consisting of positive integers and only one zero - it
should filter all values to be greater than 0.1
"""
nums = np.arange(7)
filtered = gaussian(nums, preserve_range=True)
assert np.all(filtered > 0.1)
def test_4d_ok():
img = np.zeros((5,) * 4)
img[2, 2, 2, 2] = 1
res = gaussian(img, 1, mode='reflect', preserve_range=True)
assert np.allclose(res.sum(), 1)
@pytest.mark.parametrize(
"dtype", [np.float32, np.float64]
)
def test_preserve_output(dtype):
image = np.arange(9, dtype=dtype).reshape((3, 3))
output = np.zeros_like(image, dtype=dtype)
gaussian_image = gaussian(image, sigma=1, output=output,
preserve_range=True)
assert gaussian_image is output
def test_output_error():
image = np.arange(9, dtype=np.float32).reshape((3, 3))
output = np.zeros_like(image, dtype=np.uint8)
with pytest.raises(ValueError):
gaussian(image, sigma=1, output=output,
preserve_range=True)
@pytest.mark.parametrize("s", [1, (2, 3)])
@pytest.mark.parametrize("s2", [4, (5, 6)])
@pytest.mark.parametrize("channel_axis", [None, 0, 1, -1])
def test_difference_of_gaussians(s, s2, channel_axis):
image = np.random.rand(10, 10)
if channel_axis is not None:
n_channels = 5
image = np.stack((image,) * n_channels, channel_axis)
im1 = gaussian(image, s, preserve_range=True, channel_axis=channel_axis)
im2 = gaussian(image, s2, preserve_range=True, channel_axis=channel_axis)
dog = im1 - im2
dog2 = difference_of_gaussians(image, s, s2, channel_axis=channel_axis)
assert np.allclose(dog, dog2)
@pytest.mark.parametrize("s", [1, (1, 2)])
def test_auto_sigma2(s):
image = np.random.rand(10, 10)
im1 = gaussian(image, s, preserve_range=True)
s2 = 1.6 * np.array(s)
im2 = gaussian(image, s2, preserve_range=True)
dog = im1 - im2
dog2 = difference_of_gaussians(image, s, s2)
assert np.allclose(dog, dog2)
def test_dog_invalid_sigma_dims():
image = np.ones((5, 5, 3))
with pytest.raises(ValueError):
difference_of_gaussians(image, (1, 2))
with pytest.raises(ValueError):
difference_of_gaussians(image, 1, (3, 4))
with pytest.raises(ValueError):
difference_of_gaussians(image, (1, 2, 3), channel_axis=-1)
def test_dog_invalid_sigma2():
image = np.ones((3, 3))
with pytest.raises(ValueError):
difference_of_gaussians(image, 3, 2)
with pytest.raises(ValueError):
difference_of_gaussians(image, (1, 5), (2, 4))
def test_deprecated_automatic_channel_detection():
rgb = np.zeros((5, 5, 3))
rgb[1, 1] = np.arange(1, 4)
gray = np.pad(rgb, pad_width=((0, 0), (0, 0), (1, 0)))
# Warning is raised if channel_axis is not set and shape is (M, N, 3)
with pytest.warns(
FutureWarning,
match="Automatic detection .* was deprecated .* Set `channel_axis=-1`"
):
filtered_rgb = gaussian(rgb, sigma=1, mode="reflect")
# Check that the mean value is conserved in each channel
# (color channels are not mixed together)
assert np.allclose(filtered_rgb.mean(axis=(0, 1)), rgb.mean(axis=(0, 1)))
# No warning if channel_axis is not set and shape is not (M, N, 3)
filtered_gray = gaussian(gray, sigma=1, mode="reflect")
# No warning is raised if channel_axis is explicitly set
filtered_rgb2 = gaussian(rgb, sigma=1, mode="reflect", channel_axis=-1)
assert np.array_equal(filtered_rgb, filtered_rgb2)
filtered_gray2 = gaussian(gray, sigma=1, mode="reflect", channel_axis=None)
assert np.array_equal(filtered_gray, filtered_gray2)
assert not np.array_equal(filtered_rgb, filtered_gray)
# Check how the proxy value shows up in the rendered function signature
from skimage._shared.filters import ChannelAxisNotSet
assert repr(ChannelAxisNotSet) == "<ChannelAxisNotSet>"
<file_sep>/skimage/registration/__init__.pyi
# Explicitly setting `__all__` is necessary for type inference engines
# to know which symbols are exported. See
# https://peps.python.org/pep-0484/#stub-files
__all__ = [
'optical_flow_ilk',
'optical_flow_tvl1',
'phase_cross_correlation'
]
from ._optical_flow import optical_flow_tvl1, optical_flow_ilk
from ._phase_cross_correlation import phase_cross_correlation
<file_sep>/skimage/restoration/__init__.py
"""Image restoration module.
"""
import lazy_loader as lazy
__getattr__, __dir__, __all__ = lazy.attach_stub(__name__, __file__)
<file_sep>/.binder/postBuild
#!/bin/bash
set -e
# Taken from https://github.com/scikit-learn/scikit-learn/blob/72b3041ed57e42817e4c5c9853b3a2597cab3654/.binder/postBuild
# under BSD3 license, copyright the scikit-learn contributors
python -m pip install .
# This script is called in a binder context. When this script is called, we are
# inside a git checkout of the scikit-image/scikit-image repo. This script
# generates notebooks from the scikit-image python examples.
if [[ ! -f /.dockerenv ]]; then
echo "This script was written for repo2docker and is supposed to run inside a docker container."
echo "Exiting because this script can delete data if run outside of a docker container."
exit 1
fi
# Copy content we need from the scikit-image repo
TMP_CONTENT_DIR=/tmp/scikit-image
mkdir -p $TMP_CONTENT_DIR
cp -r doc/examples .binder $TMP_CONTENT_DIR
# delete everything in current directory including dot files and dot folders
# to create a "clean" experience for readers
find . -delete
# Generate notebooks and remove other files from examples folder
GENERATED_NOTEBOOKS_DIR=auto_examples
cp -r $TMP_CONTENT_DIR/examples $GENERATED_NOTEBOOKS_DIR
find $GENERATED_NOTEBOOKS_DIR -name '*.py' -exec sphx_glr_python_to_jupyter.py '{}' +
NON_NOTEBOOKS=$(find $GENERATED_NOTEBOOKS_DIR -type f | grep -v '\.ipynb')
rm -f $NON_NOTEBOOKS
# Modify path to be consistent by the path given by sphinx-gallery
mkdir notebooks
mv $GENERATED_NOTEBOOKS_DIR notebooks/
# Put the .binder folder back (may be useful for debugging purposes)
mv $TMP_CONTENT_DIR/.binder .
# Final clean up
rm -rf $TMP_CONTENT_DIR
<file_sep>/skimage/feature/_fisher_vector.py
"""
fisher_vector.py - Implementation of the Fisher vector encoding algorithm
This module contains the source code for Fisher vector computation. The
computation is separated into two distinct steps, which are called separately
by the user, namely:
learn_gmm: Used to estimate the GMM for all vectors/descriptors computed for
all examples in the dataset (e.g. estimated using all the SIFT
vectors computed for all images in the dataset, or at least a subset
of this).
fisher_vector: Used to compute the Fisher vector representation for a
single set of descriptors/vector (e.g. the SIFT
descriptors for a single image in your dataset, or
perhaps a test image).
Reference: <NAME>. and <NAME>. Fisher kernels on Visual Vocabularies
for Image Categorization, IEEE Conference on Computer Vision and
Pattern Recognition, 2007
Origin Author: <NAME> (Author of the original implementation for the Fisher
vector computation using scikit-learn and NumPy. Subsequently ported to
scikit-image (here) by other authors.)
"""
import numpy as np
class FisherVectorException(Exception):
pass
class DescriptorException(FisherVectorException):
pass
def learn_gmm(descriptors, *, n_modes=32, gm_args=None):
"""Estimate a Gaussian mixture model (GMM) given a set of descriptors and
number of modes (i.e. Gaussians). This function is essentially a wrapper
around the scikit-learn implementation of GMM, namely the
:func:`sklearn.mixture.GaussianMixture` class.
Due to the nature of the Fisher vector, the only enforced parameter of the
underlying scikit-learn class is the covariance_type, which must be 'diag'.
There is no simple way to know what value to use for `n_modes` a-priori.
Typically, the value is usually one of ``{16, 32, 64, 128}``. One may train
a few GMMs and choose the one that maximises the log probability of the
GMM, or choose `n_modes` such that the downstream classifier trained on
the resultant Fisher vectors has maximal performance.
Parameters
----------
descriptors : np.ndarray (N, M) or list [(N1, M), (N2, M), ...]
List of NumPy arrays, or a single NumPy array, of the descriptors
used to estimate the GMM. The reason a list of NumPy arrays is
permissible is because often when using a Fisher vector encoding,
descriptors/vectors are computed separately for each sample/image in
the dataset, such as SIFT vectors for each image. If a list if passed
in, then each element must be a NumPy array in which the number of
rows may differ (e.g. different number of SIFT vector for each image),
but the number of columns for each must be the same (i.e. the
dimensionality must be the same).
n_modes : int
The number of modes/Gaussians to estimate during the GMM estimate.
gm_args : dict
Keyword arguments that can be passed into the underlying scikit-learn
:func:`sklearn.mixture.GaussianMixture` class.
Returns
-------
gmm : :func:`sklearn.mixture.GaussianMixture`
The estimated GMM object, which contains the necessary parameters
needed to compute the Fisher vector.
References
----------
.. [1] https://scikit-learn.org/stable/modules/generated/sklearn.mixture.GaussianMixture.html
Examples
--------
>>> import pytest
>>> _ = pytest.importorskip('sklearn')
>>> from skimage.feature import fisher_vector
>>> rng = np.random.Generator(np.random.PCG64())
>>> sift_for_images = [rng.standard_normal((10, 128)) for _ in range(10)]
>>> num_modes = 16
>>> # Estimate 16-mode GMM with these synthetic SIFT vectors
>>> gmm = learn_gmm(sift_for_images, n_modes=num_modes)
"""
try:
from sklearn.mixture import GaussianMixture
except ImportError:
raise ImportError(
'scikit-learn is not installed. Please ensure it is installed in '
'order to use the Fisher vector functionality.'
)
if not isinstance(descriptors, (list, np.ndarray)):
raise DescriptorException(
'Please ensure descriptors are either a NumPY array, '
'or a list of NumPy arrays.'
)
d_mat_1 = descriptors[0]
if isinstance(descriptors, list) and not isinstance(d_mat_1, np.ndarray):
raise DescriptorException(
'Please ensure descriptors are a list of NumPy arrays.'
)
if isinstance(descriptors, list):
expected_shape = descriptors[0].shape
ranks = [len(e.shape) == len(expected_shape) for e in descriptors]
if not all(ranks):
raise DescriptorException(
'Please ensure all elements of your descriptor list '
'are of rank 2.'
)
dims = [e.shape[1] == descriptors[0].shape[1] for e in descriptors]
if not all(dims):
raise DescriptorException(
'Please ensure all descriptors are of the same dimensionality.'
)
if not isinstance(n_modes, int) or n_modes <= 0:
raise FisherVectorException(
'Please ensure n_modes is a positive integer.'
)
if gm_args:
has_cov_type = 'covariance_type' in gm_args
cov_type_not_diag = gm_args['covariance_type'] != 'diag'
if has_cov_type and cov_type_not_diag:
raise FisherVectorException('Covariance type must be "diag".')
if isinstance(descriptors, list):
descriptors = np.vstack(descriptors)
if gm_args:
has_cov_type = 'covariance_type' in gm_args
if has_cov_type:
gmm = GaussianMixture(
n_components=n_modes, **gm_args
)
else:
gmm = GaussianMixture(
n_components=n_modes, covariance_type='diag', **gm_args
)
else:
gmm = GaussianMixture(n_components=n_modes, covariance_type='diag')
gmm.fit(descriptors)
return gmm
def fisher_vector(descriptors, gmm, *, improved=False, alpha=0.5):
"""Compute the Fisher vector given some descriptors/vectors,
and an associated estimated GMM.
Parameters
----------
descriptors : np.ndarray, shape=(n_descriptors, descriptor_length)
NumPy array of the descriptors for which the Fisher vector
representation is to be computed.
gmm : sklearn.mixture.GaussianMixture
An estimated GMM object, which contains the necessary parameters needed
to compute the Fisher vector.
improved : bool, default=False
Flag denoting whether to compute improved Fisher vectors or not.
Improved Fisher vectors are L2 and power normalized. Power
normalization is simply f(z) = sign(z) pow(abs(z), alpha) for some
0 <= alpha <= 1.
alpha : float, default=0.5
The parameter for the power normalization step. Ignored if
improved=False.
Returns
-------
fisher_vector : np.ndarray
The computation Fisher vector, which is given by a concatenation of the
gradients of a GMM with respect to its parameters (mixture weights,
means, and covariance matrices). For D-dimensional input descriptors or
vectors, and a K-mode GMM, the Fisher vector dimensionality will be
2KD + K. Thus, its dimensionality is invariant to the number of
descriptors/vectors.
References
----------
.. [1] <NAME>. and <NAME>. Fisher kernels on Visual Vocabularies
for Image Categorization, IEEE Conference on Computer Vision and
Pattern Recognition, 2007
.. [2] <NAME>. and <NAME>. and <NAME>. Improving the Fisher
Kernel for Large-Scale Image Classification, ECCV, 2010
Examples
--------
>>> import pytest
>>> _ = pytest.importorskip('sklearn')
>>> from skimage.feature import fisher_vector, learn_gmm
>>> sift_for_images = [np.random.random((10, 128)) for _ in range(10)]
>>> num_modes = 16
>>> # Estimate 16-mode GMM with these synthetic SIFT vectors
>>> gmm = learn_gmm(sift_for_images, n_modes=num_modes)
>>> test_image_descriptors = np.random.random((25, 128))
>>> # Compute the Fisher vector
>>> fv = fisher_vector(test_image_descriptors, gmm)
"""
try:
from sklearn.mixture import GaussianMixture
except ImportError:
raise ImportError(
'scikit-learn is not installed. Please ensure it is installed in '
'order to use the Fisher vector functionality.'
)
if not isinstance(descriptors, np.ndarray):
raise DescriptorException(
'Please ensure descriptors is a NumPy array.'
)
if not isinstance(gmm, GaussianMixture):
raise FisherVectorException(
'Please ensure gmm is a sklearn.mixture.GaussianMixture object.'
)
if improved and not isinstance(alpha, float):
raise FisherVectorException(
'Please ensure that the alpha parameter is a float.'
)
num_descriptors = len(descriptors)
mixture_weights = gmm.weights_
means = gmm.means_
covariances = gmm.covariances_
posterior_probabilities = gmm.predict_proba(descriptors)
# Statistics necessary to compute GMM gradients wrt its parameters
pp_sum = posterior_probabilities.mean(axis=0, keepdims=True).T
pp_x = posterior_probabilities.T.dot(descriptors) / num_descriptors
pp_x_2 = posterior_probabilities.T.dot(
np.power(descriptors, 2)
) / num_descriptors
# Compute GMM gradients wrt its parameters
d_pi = pp_sum.squeeze() - mixture_weights
d_mu = pp_x - pp_sum * means
d_sigma_t1 = pp_sum * np.power(means, 2)
d_sigma_t2 = pp_sum * covariances
d_sigma_t3 = 2 * pp_x * means
d_sigma = -pp_x_2 - d_sigma_t1 + d_sigma_t2 + d_sigma_t3
# Apply analytical diagonal normalization
sqrt_mixture_weights = np.sqrt(mixture_weights)
d_pi /= sqrt_mixture_weights
d_mu /= sqrt_mixture_weights[:, np.newaxis] * np.sqrt(covariances)
d_sigma /= np.sqrt(2) * sqrt_mixture_weights[:, np.newaxis] * covariances
# Concatenate GMM gradients to form Fisher vector representation
fisher_vector = np.hstack((d_pi, d_mu.ravel(), d_sigma.ravel()))
if improved:
fisher_vector = \
np.sign(fisher_vector) * np.power(np.abs(fisher_vector), alpha)
fisher_vector = fisher_vector / np.linalg.norm(fisher_vector)
return fisher_vector
<file_sep>/doc/examples/applications/plot_cornea_spot_inpainting.py
"""
============================================
Restore spotted cornea image with inpainting
============================================
Optical coherence tomography (OCT) is a non-invasive imaging technique used by
ophthalmologists to take pictures of the back of a patient's eye [1]_.
When performing OCT,
dust may stick to the reference mirror of the equipment, causing dark spots to
appear on the images. The problem is that these dirt spots cover areas of
in-vivo tissue, hence hiding data of interest. Our goal here is to restore
(reconstruct) the hidden areas based on the pixels near their boundaries.
This tutorial is adapted from an application shared by Jules Scholler [2]_.
The images were acquired by <NAME> (see
:func:`skimage.data.palisades_of_vogt`).
.. [1] <NAME>, reviewed by <NAME>, MD (2023)
`What Is Optical Coherence Tomography?
<https://www.aao.org/eye-health/treatments/what-is-optical-coherence-tomography>`_,
American Academy of Ophthalmology.
.. [2] <NAME> (2019) "Image denoising using inpainting"
https://www.jscholler.com/2019-02-28-remove-dots/
"""
import matplotlib.pyplot as plt
import numpy as np
import plotly.io
import plotly.express as px
import skimage as ski
#####################################################################
# The dataset we are using here is an image sequence (a movie!) of
# human in-vivo tissue. Specifically, it shows the *palisades of Vogt* of a
# given cornea sample.
#####################################################################
# Load image data
# ===============
image_seq = ski.data.palisades_of_vogt()
print(f'number of dimensions: {image_seq.ndim}')
print(f'shape: {image_seq.shape}')
print(f'dtype: {image_seq.dtype}')
#####################################################################
# The dataset is an image stack with 60 frames (time points) and 2 spatial
# dimensions. Let us visualize 10 frames by sampling every six time points:
# We can see some changes in illumination.
# We take advantage of the ``animation_frame`` parameter in
# Plotly's ``imshow`` function. As a side note, when the
# ``binary_string`` parameter is set to ``True``, the image is
# represented as grayscale.
fig = px.imshow(
image_seq[::6, :, :],
animation_frame=0,
binary_string=True,
labels={'animation_frame': '6-step time point'},
title='Sample of in-vivo human cornea'
)
fig.update_layout(
autosize=False,
minreducedwidth=250,
minreducedheight=250
)
plotly.io.show(fig)
#####################################################################
# Aggregate over time
# ===================
# First, we want to detect those dirt spots where the data are lost. In
# technical terms, we want to *segment* the dirt spots (for
# all frames in the sequence). Unlike the actual data (signal), the dirt spots
# do not move from one frame to the next; they are still. Therefore, we begin
# by computing a time aggregate of the image sequence. We shall use the median
# image to segment the dirt spots, the latter then standing out
# with respect to the background (blurred signal).
# Complementarily, to get a feel for the (moving) data, let us compute the
# variance.
image_med = np.median(image_seq, axis=0)
image_var = np.var(image_seq, axis=0)
assert image_var.shape == image_med.shape
print(f'shape: {image_med.shape}')
fig, ax = plt.subplots(ncols=2, figsize=(12, 6))
ax[0].imshow(image_med, cmap='gray')
ax[0].set_title('Image median over time')
ax[1].imshow(image_var, cmap='gray')
ax[1].set_title('Image variance over time')
fig.tight_layout()
#####################################################################
# Use local thresholding
# ======================
# To segment the dirt spots, we use thresholding. The images we are working
# with are unevenly illuminated, which causes spatial variations in the
# (absolute) intensities of the foreground and the background. For example,
# the average background intensity in one region may be different in another
# (distant) one. It is therefore more fitting to compute different threshold
# values across the image, one for each region. This is called adaptive (or
# local) thresholding, as opposed to the usual thresholding procedure which
# employs a single (global) threshold for all pixels in the image.
#
# When calling the ``threshold_local`` function from the ``filters`` module,
# we may change the default neighborhood size (``block_size``), i.e., the
# typical size (number of pixels) over which illumination varies,
# as well as the ``offset`` (shifting the neighborhood's weighted mean).
# Let us try two different values for ``block_size``:
thresh_1 = ski.filters.threshold_local(image_med, block_size=21, offset=15)
thresh_2 = ski.filters.threshold_local(image_med, block_size=43, offset=15)
mask_1 = image_med < thresh_1
mask_2 = image_med < thresh_2
#####################################################################
# Let us define a convenience function to display two plots side by side, so
# it is easier for us to compare them:
def plot_comparison(plot1, plot2, title1, title2):
fig, (ax1, ax2) = plt.subplots(
ncols=2,
figsize=(12, 6),
sharex=True,
sharey=True
)
ax1.imshow(plot1, cmap='gray')
ax1.set_title(title1)
ax2.imshow(plot2, cmap='gray')
ax2.set_title(title2)
plot_comparison(mask_1, mask_2, "block_size = 21", "block_size = 43")
#####################################################################
# The "dirt spots" appear to be more distinct in the second mask, i.e., the
# one resulting from using the larger ``block_size`` value.
# We noticed that increasing the value of the offset parameter from
# its default zero value would yield a more uniform background,
# letting the objects of interest stand out more visibly. Note that
# toggling parameter values can give us a deeper
# understanding of the method being used, which can typically move us
# closer to the desired results.
thresh_0 = ski.filters.threshold_local(image_med, block_size=43)
mask_0 = image_med < thresh_0
plot_comparison(mask_0, mask_2, "No offset", "offset = 15")
#####################################################################
# Remove fine-grained features
# ============================
# We use morphological filters to sharpen the mask and focus on the dirt
# spots. The two fundamental morphological operators are *dilation* and
# *erosion*, where dilation (resp. erosion) sets the pixel to the brightest
# (resp. darkest) value of the neighborhood defined by a structuring element
# (footprint).
#
# Here, we use the ``diamond`` function from the ``morphology`` module to
# create a diamond-shaped footprint.
# An erosion followed by a dilation is called an *opening*.
# First, we apply an opening filter, in order to remove small objects and thin
# lines, while preserving the shape and size of larger objects.
footprint = ski.morphology.diamond(3)
mask_open = ski.morphology.opening(mask_2, footprint)
plot_comparison(mask_2, mask_open, "mask before", "after opening")
#####################################################################
# Since "opening" an image starts with an erosion operation, bright regions
# which are smaller than the structuring element have been removed.
# When applying an opening filter, tweaking the footprint parameter lets us
# control how fine-grained the removed features are. For example, if we used
# ``footprint = ski.morphology.diamond(1)`` in the above, we could see that
# only smaller features would be filtered out, hence retaining more spots in
# the mask. Conversely, if we used a disk-shaped footprint of same radius,
# i.e., ``footprint = ski.morphology.disk(3)``, more of the fine-grained
# features would be filtered out, since the disk's area is larger than the
# diamond's.
#####################################################################
# Next, we can make the detected areas wider by applying a dilation filter:
mask_dilate = ski.morphology.dilation(mask_open, footprint)
plot_comparison(mask_open, mask_dilate, "before", "after dilation")
#####################################################################
# Dilation enlarges bright regions and shrinks dark regions.
# Notice how, indeed, the white spots have thickened.
#####################################################################
# Inpaint each frame separately
# =============================
# We are now ready to apply inpainting to each frame. For this we use function
# ``inpaint_biharmonic`` from the ``restoration`` module. It implements an
# algorithm based on biharmonic equations.
# This function takes two arrays as inputs:
# The image to restore and a mask (with same shape) corresponding to the
# regions we want to inpaint.
image_seq_inpainted = np.zeros(image_seq.shape)
for i in range(image_seq.shape[0]):
image_seq_inpainted[i] = ski.restoration.inpaint_biharmonic(
image_seq[i],
mask_dilate
)
#####################################################################
# Let us visualize one restored image, where the dirt spots have been
# inpainted. First, we find the contours of the dirt spots (well, of the mask)
# so we can draw them on top of the restored image:
contours = ski.measure.find_contours(mask_dilate)
# Gather all (row, column) coordinates of the contours
x = []
y = []
for contour in contours:
x.append(contour[:, 0])
y.append(contour[:, 1])
# Note that the following one-liner is equivalent to the above:
# x, y = zip(*((contour[:, 0], contour[:, 1]) for contour in contours))
# Flatten the coordinates
x_flat = np.concatenate(x).ravel().round().astype(int)
y_flat = np.concatenate(y).ravel().round().astype(int)
# Create mask of these contours
contour_mask = np.zeros(mask_dilate.shape, dtype=bool)
contour_mask[x_flat, y_flat] = 1
# Pick one frame
sample_result = image_seq_inpainted[12]
# Normalize it (so intensity values range [0, 1])
sample_result /= sample_result.max()
#####################################################################
# We use function ``label2rgb`` from the ``color`` module to overlay the
# restored image with the segmented spots, using transparency (alpha
# parameter).
color_contours = ski.color.label2rgb(
contour_mask,
image=sample_result,
alpha=0.4,
bg_color=(1, 1, 1)
)
fig, ax = plt.subplots(figsize=(6, 6))
ax.imshow(color_contours)
ax.set_title('Segmented spots over restored image')
fig.tight_layout()
#####################################################################
# Note that the dirt spot located at (x, y) ~ (719, 1237) stands out; ideally,
# it should have been segmented and inpainted. We can see that we 'lost' it to
# the opening processing step, when removing fine-grained features.
plt.show()
<file_sep>/doc/source/user_guide/getting_help.rst
=================================
Getting help on using ``skimage``
=================================
API Reference
-------------
Keep the `reference guide <https://scikit-image.org/docs/stable/>`__
handy while programming with scikit-image.
Select the docs that match the version of skimage you are using.
Examples gallery
----------------
The :ref:`examples_gallery` gallery provides graphical examples and
code snippets of typical image processing tasks. There, you may find
an example that is close to your use case.
Feel free to suggest new gallery examples on our `developer forum
<https://discuss.scientific-python.org/c/contributor/skimage>`__.
Search field
------------
Use the ``quick search`` field in the navigation bar of the online
documentation to find mentions of keywords (segmentation,
rescaling, denoising, etc.) in the documentation.
API Discovery
-------------
We provide a ``lookfor`` function to search API functions::
import skimage as ski
ski.lookfor('eigenvector')
Also see NumPy's ``lookfor``.
Ask for help
------------
Still stuck? We are here to help! Reach out through:
- our `user forum <https://forum.image.sc/tags/scikit-image>`_ for
image processing and usage questions;
- our `developer forum
<https://discuss.scientific-python.org/c/contributor/skimage>`_
for technical questions and suggestions;
- our `chat channel <https://skimage.zulipchat.com/>`_ for real-time
interaction; or
- `Stack Overflow
<https://stackoverflow.com/questions/tagged/scikit-image>`_ for
coding questions.
<file_sep>/skimage/transform/__init__.pyi
# Explicitly setting `__all__` is necessary for type inference engines
# to know which symbols are exported. See
# https://peps.python.org/pep-0484/#stub-files
__all__ = [
'hough_circle',
'hough_ellipse',
'hough_line',
'probabilistic_hough_line',
'hough_circle_peaks',
'hough_line_peaks',
'radon',
'iradon',
'iradon_sart',
'order_angles_golden_ratio',
'frt2',
'ifrt2',
'integral_image',
'integrate',
'warp',
'warp_coords',
'warp_polar',
'estimate_transform',
'matrix_transform',
'EuclideanTransform',
'SimilarityTransform',
'AffineTransform',
'ProjectiveTransform',
'EssentialMatrixTransform',
'FundamentalMatrixTransform',
'PolynomialTransform',
'PiecewiseAffineTransform',
'swirl',
'resize',
'resize_local_mean',
'rotate',
'rescale',
'downscale_local_mean',
'pyramid_reduce',
'pyramid_expand',
'pyramid_gaussian',
'pyramid_laplacian',
]
from .hough_transform import (
hough_line,
hough_line_peaks,
probabilistic_hough_line,
hough_circle,
hough_circle_peaks,
hough_ellipse
)
from .radon_transform import (
radon, iradon, iradon_sart,
order_angles_golden_ratio
)
from .finite_radon_transform import frt2, ifrt2
from .integral import integral_image, integrate
from ._geometric import (
estimate_transform,
matrix_transform,
EuclideanTransform,
SimilarityTransform,
AffineTransform,
ProjectiveTransform,
FundamentalMatrixTransform,
EssentialMatrixTransform,
PolynomialTransform,
PiecewiseAffineTransform
)
from ._warps import (
swirl, resize,
rotate, rescale,
downscale_local_mean,
warp, warp_coords,
warp_polar, resize_local_mean
)
from .pyramids import (
pyramid_reduce,
pyramid_expand,
pyramid_gaussian,
pyramid_laplacian
)
<file_sep>/skimage/_shared/filters.py
"""Filters used across multiple skimage submodules.
These are defined here to avoid circular imports.
The unit tests remain under skimage/filters/tests/
"""
from collections.abc import Iterable
import numpy as np
from scipy import ndimage as ndi
from .._shared.utils import _supported_float_type, convert_to_float, warn
class _PatchClassRepr(type):
"""Control class representations in rendered signatures."""
def __repr__(cls):
return f"<{cls.__name__}>"
class ChannelAxisNotSet(metaclass=_PatchClassRepr):
"""Signal that the `channel_axis` parameter is not set.
This is a proxy object, used to signal to `skimage.filters.gaussian` that
the `channel_axis` parameter has not been set, in which case the function
will determine whether a color channel is present. We cannot use ``None``
for this purpose as it has its own meaning which indicates that the given
image is grayscale.
This automatic behavior was broken in v0.19, recovered but deprecated in
v0.20 and will be removed in v0.22.
"""
def gaussian(image, sigma=1, output=None, mode='nearest', cval=0,
preserve_range=False, truncate=4.0, *,
channel_axis=ChannelAxisNotSet):
"""Multi-dimensional Gaussian filter.
Parameters
----------
image : array-like
Input image (grayscale or color) to filter.
sigma : scalar or sequence of scalars, optional
Standard deviation for Gaussian kernel. The standard
deviations of the Gaussian filter are given for each axis as a
sequence, or as a single number, in which case it is equal for
all axes.
output : array, optional
The ``output`` parameter passes an array in which to store the
filter output.
mode : {'reflect', 'constant', 'nearest', 'mirror', 'wrap'}, optional
The ``mode`` parameter determines how the array borders are
handled, where ``cval`` is the value when mode is equal to
'constant'. Default is 'nearest'.
cval : scalar, optional
Value to fill past edges of input if ``mode`` is 'constant'. Default
is 0.0
preserve_range : bool, optional
If True, keep the original range of values. Otherwise, the input
``image`` is converted according to the conventions of ``img_as_float``
(Normalized first to values [-1.0 ; 1.0] or [0 ; 1.0] depending on
dtype of input)
For more information, see:
https://scikit-image.org/docs/dev/user_guide/data_types.html
truncate : float, optional
Truncate the filter at this many standard deviations.
channel_axis : int or None, optional
If None, the image is assumed to be a grayscale (single channel) image.
Otherwise, this parameter indicates which axis of the array corresponds
to channels.
.. versionadded:: 0.19
``channel_axis`` was added in 0.19.
.. warning::
Automatic detection of the color channel based on the old deprecated
`multichannel=None` was broken in version 0.19. In 0.20 this
behavior is fixed. The last axis of an `image` with dimensions
(M, N, 3) is interpreted as a color channel if `channel_axis` is not
set by the user (signaled by the default proxy value
`ChannelAxisNotSet`). Starting with 0.22, `channel_axis=None` will
be used as the new default value.
Returns
-------
filtered_image : ndarray
the filtered array
Notes
-----
This function is a wrapper around :func:`scipy.ndi.gaussian_filter`.
Integer arrays are converted to float.
The ``output`` should be floating point data type since gaussian converts
to float provided ``image``. If ``output`` is not provided, another array
will be allocated and returned as the result.
The multi-dimensional filter is implemented as a sequence of
one-dimensional convolution filters. The intermediate arrays are
stored in the same data type as the output. Therefore, for output
types with a limited precision, the results may be imprecise
because intermediate results may be stored with insufficient
precision.
Examples
--------
>>> a = np.zeros((3, 3))
>>> a[1, 1] = 1
>>> a
array([[0., 0., 0.],
[0., 1., 0.],
[0., 0., 0.]])
>>> gaussian(a, sigma=0.4) # mild smoothing
array([[0.00163116, 0.03712502, 0.00163116],
[0.03712502, 0.84496158, 0.03712502],
[0.00163116, 0.03712502, 0.00163116]])
>>> gaussian(a, sigma=1) # more smoothing
array([[0.05855018, 0.09653293, 0.05855018],
[0.09653293, 0.15915589, 0.09653293],
[0.05855018, 0.09653293, 0.05855018]])
>>> # Several modes are possible for handling boundaries
>>> gaussian(a, sigma=1, mode='reflect')
array([[0.08767308, 0.12075024, 0.08767308],
[0.12075024, 0.16630671, 0.12075024],
[0.08767308, 0.12075024, 0.08767308]])
>>> # For RGB images, each is filtered separately
>>> from skimage.data import astronaut
>>> image = astronaut()
>>> filtered_img = gaussian(image, sigma=1, channel_axis=-1)
"""
if channel_axis is ChannelAxisNotSet:
if image.ndim == 3 and image.shape[-1] == 3:
warn(
"Automatic detection of the color channel was deprecated in "
"v0.19, and `channel_axis=None` will be the new default in "
"v0.22. Set `channel_axis=-1` explicitly to silence this "
"warning.",
FutureWarning,
stacklevel=2,
)
channel_axis = -1
else:
channel_axis = None
if np.any(np.asarray(sigma) < 0.0):
raise ValueError("Sigma values less than zero are not valid")
if channel_axis is not None:
# do not filter across channels
if not isinstance(sigma, Iterable):
sigma = [sigma] * (image.ndim - 1)
if len(sigma) == image.ndim - 1:
sigma = list(sigma)
sigma.insert(channel_axis % image.ndim, 0)
image = convert_to_float(image, preserve_range)
float_dtype = _supported_float_type(image.dtype)
image = image.astype(float_dtype, copy=False)
if (output is not None) and (not np.issubdtype(output.dtype, np.floating)):
raise ValueError("Provided output data type is not float")
return ndi.gaussian_filter(image, sigma, output=output,
mode=mode, cval=cval, truncate=truncate)
<file_sep>/skimage/feature/tests/test_fisher_vector.py
import pytest
import numpy as np
pytest.importorskip('sklearn')
from skimage.feature._fisher_vector import ( # noqa: E402
learn_gmm, fisher_vector, FisherVectorException,
DescriptorException
)
def test_gmm_wrong_descriptor_format_1():
"""Test that DescriptorException is raised when wrong type for descriptions
is passed.
"""
with pytest.raises(DescriptorException):
learn_gmm('completely wrong test', n_modes=1)
def test_gmm_wrong_descriptor_format_2():
"""Test that DescriptorException is raised when descriptors are of
different dimensionality.
"""
with pytest.raises(DescriptorException):
learn_gmm([np.zeros((5, 11)), np.zeros((4, 10))], n_modes=1)
def test_gmm_wrong_descriptor_format_3():
"""Test that DescriptorException is raised when not all descriptors are of
rank 2.
"""
with pytest.raises(DescriptorException):
learn_gmm([np.zeros((5, 10)), np.zeros((4, 10, 1))], n_modes=1)
def test_gmm_wrong_descriptor_format_4():
"""Test that DescriptorException is raised when elements of descriptor list
are of the incorrect type (i.e. not a NumPy ndarray).
"""
with pytest.raises(DescriptorException):
learn_gmm([[1, 2, 3], [1, 2, 3]], n_modes=1)
def test_gmm_wrong_num_modes_format_1():
"""Test that FisherVectorException is raised when incorrect type for
n_modes is passed into the learn_gmm function.
"""
with pytest.raises(FisherVectorException):
learn_gmm([np.zeros((5, 10)), np.zeros((4, 10))], n_modes='not_valid')
def test_gmm_wrong_num_modes_format_2():
"""Test that FisherVectorException is raised when a number that is not a
positive integer is passed into the n_modes argument of learn_gmm.
"""
with pytest.raises(FisherVectorException):
learn_gmm([np.zeros((5, 10)), np.zeros((4, 10))], n_modes=-1)
def test_gmm_wrong_covariance_type():
"""Test that FisherVectorException is raised when wrong covariance type is
passed in as a keyword argument.
"""
with pytest.raises(FisherVectorException):
learn_gmm(
np.random.random((10, 10)), n_modes=2,
gm_args={'covariance_type': 'full'}
)
def test_gmm_correct_covariance_type():
"""Test that GMM estimation is successful when the correct covariance type
is passed in as a keyword argument.
"""
gmm = learn_gmm(
np.random.random((10, 10)), n_modes=2,
gm_args={'covariance_type': 'diag'}
)
assert gmm.means_ is not None
assert gmm.covariances_ is not None
assert gmm.weights_ is not None
def test_gmm_e2e():
"""
Test the GMM estimation. Since this is essentially a wrapper for the
scikit-learn GaussianMixture class, the testing of the actual inner
workings of the GMM estimation is left to scikit-learn and its
dependencies.
We instead simply assert that the estimation was successful based on the
fact that the GMM object will have associated mixture weights, means, and
variances after estimation is successful/complete.
"""
gmm = learn_gmm(np.random.random((100, 64)), n_modes=5)
assert gmm.means_ is not None
assert gmm.covariances_ is not None
assert gmm.weights_ is not None
def test_fv_wrong_descriptor_types():
"""
Test that DescriptorException is raised when the incorrect type for the
descriptors is passed into the fisher_vector function.
"""
try:
from sklearn.mixture import GaussianMixture
except ImportError:
print(
'scikit-learn is not installed. Please ensure it is installed in '
'order to use the Fisher vector functionality.'
)
with pytest.raises(DescriptorException):
fisher_vector([[1, 2, 3, 4]], GaussianMixture())
def test_fv_wrong_gmm_type():
"""
Test that FisherVectorException is raised when a GMM not of type
sklearn.mixture.GaussianMixture is passed into the fisher_vector
function.
"""
class MyDifferentGaussianMixture:
pass
with pytest.raises(FisherVectorException):
fisher_vector(np.zeros((10, 10)), MyDifferentGaussianMixture())
def test_fv_e2e():
"""
Test the Fisher vector computation given a GMM returned from the learn_gmm
function. We simply assert that the dimensionality of the resulting Fisher
vector is correct.
The dimensionality of a Fisher vector is given by 2KD + K, where K is the
number of Gaussians specified in the associated GMM, and D is the
dimensionality of the descriptors using to estimate the GMM.
"""
dim = 128
num_modes = 8
expected_dim = 2 * num_modes * dim + num_modes
descriptors = [
np.random.random((np.random.randint(5, 30), dim))
for _ in range(10)
]
gmm = learn_gmm(descriptors, n_modes=num_modes)
fisher_vec = fisher_vector(descriptors[0], gmm)
assert len(fisher_vec) == expected_dim
def test_fv_e2e_improved():
"""
Test the improved Fisher vector computation given a GMM returned from the
learn_gmm function. We simply assert that the dimensionality of the
resulting Fisher vector is correct.
The dimensionality of a Fisher vector is given by 2KD + K, where K is the
number of Gaussians specified in the associated GMM, and D is the
dimensionality of the descriptors using to estimate the GMM.
"""
dim = 128
num_modes = 8
expected_dim = 2 * num_modes * dim + num_modes
descriptors = [
np.random.random((np.random.randint(5, 30), dim))
for _ in range(10)
]
gmm = learn_gmm(descriptors, n_modes=num_modes)
fisher_vec = fisher_vector(descriptors[0], gmm, improved=True)
assert len(fisher_vec) == expected_dim
<file_sep>/tools/precompute/moments_sympy.py
"""
This script uses SymPy to generate the analytical equations used to transform
raw moments into central moments in ``skimage/measure/_moments_analytical.py``
"""
from sympy import symbols, binomial, Sum
from sympy import IndexedBase, Idx
from sympy.printing.pycode import pycode
# from sympy import init_printing, pprint
# init_printing(use_unicode=True)
# Define a moments matrix, M
M = IndexedBase('M')
ndim = 3
order = 3
if ndim == 2:
# symbols for the centroid components
c_x, c_y = symbols('c_x c_y')
# indices into the moments matrix, M
i, j = symbols('i j', cls=Idx)
# centroid
cx = M[1, 0] / M[0, 0]
cy = M[0, 1] / M[0, 0]
# Loop over all moments of order <= `order`.
print(f"Generating expressions for {ndim}D moments of order <= {order}")
for p in range(0, order + 1):
for q in range(0, order + 1):
if p + q > order:
continue
# print(f"order={p + q}: p={p}, q={q}")
# This expression is given at
# https://en.wikipedia.org/wiki/Image_moment#Central_moments
expr = Sum(
(
binomial(p, i) * binomial(q, j)
* (-cx)**(p - i) * (-cy)**(q - j)
* M[i, j]
),
(i, 0, p), (j, 0, q)
).doit()
# substitute back in the c_x and c_y symbols
expr = expr.subs(M[1, 0]/M[0, 0], c_x)
expr = expr.subs(M[0, 1]/M[0, 0], c_y)
# print python code for generation of the central moment
python_code = f"moments_central[{p}, {q}] = {pycode(expr)}\n"
# replace symbol names with corresponding python variable names
python_code = python_code.replace('c_', 'c')
python_code = python_code.replace('M[', 'm[')
print(python_code)
elif ndim == 3:
# symbols for the centroid components
c_x, c_y, c_z = symbols('c_x c_y c_z')
# indices into the moments matrix, M
i, j, k = symbols('i j k', cls=Idx)
# centroid
cx = M[1, 0, 0] / M[0, 0, 0]
cy = M[0, 1, 0] / M[0, 0, 0]
cz = M[0, 0, 1] / M[0, 0, 0]
# Loop over all moments of order <= `order`.
print(f"Generating expressions for {ndim}D moments of order <= {order}")
for p in range(0, order + 1):
for q in range(0, order + 1):
for r in range(0, order + 1):
if p + q + r > order:
continue
# print(f"order={p + q + r}: p={p}, q={q}, r={r}")
# This expression is a 3D extension of the 2D equation given at
# https://en.wikipedia.org/wiki/Image_moment#Central_moments
expr = Sum(
(
binomial(p, i) * binomial(q, j) * binomial(r, k)
* (-cx)**(p - i) * (-cy)**(q - j) * (-cz)**(r - k)
* M[i, j, k]
),
(i, 0, p), (j, 0, q), (k, 0, r)
).doit()
# substitute back in c_x, c_y, c_z
expr = expr.subs(M[1, 0, 0]/M[0, 0, 0], c_x)
expr = expr.subs(M[0, 1, 0]/M[0, 0, 0], c_y)
expr = expr.subs(M[0, 0, 1]/M[0, 0, 0], c_z)
# print python code for generation of the central moment
python_code = f"moments_central[{p}, {q}, {r}] = {pycode(expr)}\n"
# replace symbol names with corresponding python variable names
python_code = python_code.replace('c_', 'c')
python_code = python_code.replace('M[', 'm[')
print(python_code)
<file_sep>/benchmarks/benchmark_graph.py
# See "Writing benchmarks" in the asv docs for more information.
# https://asv.readthedocs.io/en/latest/writing_benchmarks.html
import numpy as np
from scipy import ndimage as ndi
from skimage import color, data, filters, graph, morphology
class GraphSuite:
"""Benchmark for pixel graph routines in scikit-image."""
def setup(self):
retina = color.rgb2gray(data.retina())
t0, _ = filters.threshold_multiotsu(retina, classes=3)
mask = (retina > t0)
vessels = filters.sato(retina, sigmas=range(1, 10)) * mask
thresholded = filters.apply_hysteresis_threshold(vessels, 0.01, 0.03)
labeled = ndi.label(thresholded)[0]
largest_nonzero_label = np.argmax(np.bincount(labeled[labeled > 0]))
binary = (labeled == largest_nonzero_label)
self.skeleton = morphology.skeletonize(binary)
labeled2 = ndi.label(thresholded[::2, ::2])[0]
largest_nonzero_label2 = np.argmax(np.bincount(labeled2[labeled2 > 0]))
binary2 = (labeled2 == largest_nonzero_label2)
small_skeleton = morphology.skeletonize(binary2)
self.g, self.n = graph.pixel_graph(small_skeleton, connectivity=2)
def time_build_pixel_graph(self):
graph.pixel_graph(self.skeleton, connectivity=2)
def time_central_pixel(self):
graph.central_pixel(self.g, self.n)
<file_sep>/skimage/morphology/tests/test_reconstruction.py
import math
import numpy as np
import pytest
from numpy.testing import assert_array_almost_equal
from skimage._shared.utils import _supported_float_type
from skimage.morphology.grayreconstruct import reconstruction
def test_zeros():
"""Test reconstruction with image and mask of zeros"""
assert_array_almost_equal(
reconstruction(np.zeros((5, 7)), np.zeros((5, 7))), 0)
def test_image_equals_mask():
"""Test reconstruction where the image and mask are the same"""
assert_array_almost_equal(
reconstruction(np.ones((7, 5)), np.ones((7, 5))), 1)
def test_image_less_than_mask():
"""Test reconstruction where the image is uniform and less than mask"""
image = np.ones((5, 5))
mask = np.ones((5, 5)) * 2
assert_array_almost_equal(reconstruction(image, mask), 1)
def test_one_image_peak():
"""Test reconstruction with one peak pixel"""
image = np.ones((5, 5))
image[2, 2] = 2
mask = np.ones((5, 5)) * 3
assert_array_almost_equal(reconstruction(image, mask), 2)
# minsize chosen to test sizes covering use of 8, 16 and 32-bit integers
# internally
@pytest.mark.parametrize('minsize', [None, 200, 20000, 40000, 80000])
@pytest.mark.parametrize('dtype', [np.uint8, np.float32])
def test_two_image_peaks(minsize, dtype):
"""Test reconstruction with two peak pixels isolated by the mask"""
image = np.array([[1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 2, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 3, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1]], dtype=dtype)
mask = np.array([[4, 4, 4, 1, 1, 1, 1, 1, 1],
[4, 4, 4, 1, 1, 1, 1, 1, 1],
[4, 4, 4, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 4, 4, 4, 1],
[1, 1, 1, 1, 1, 4, 4, 4, 1],
[1, 1, 1, 1, 1, 4, 4, 4, 1]], dtype=dtype)
expected = np.array([[2, 2, 2, 1, 1, 1, 1, 1, 1],
[2, 2, 2, 1, 1, 1, 1, 1, 1],
[2, 2, 2, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 3, 3, 3, 1],
[1, 1, 1, 1, 1, 3, 3, 3, 1],
[1, 1, 1, 1, 1, 3, 3, 3, 1]], dtype=dtype)
if minsize is not None:
# increase data size by tiling (done to test various int types)
nrow = math.ceil(math.sqrt(minsize / image.size))
ncol = math.ceil(minsize / (image.size * nrow))
image = np.tile(image, (nrow, ncol))
mask = np.tile(mask, (nrow, ncol))
expected = np.tile(expected, (nrow, ncol))
out = reconstruction(image, mask)
assert out.dtype == _supported_float_type(mask.dtype)
assert_array_almost_equal(out, expected)
def test_zero_image_one_mask():
"""Test reconstruction with an image of all zeros and a mask that's not"""
result = reconstruction(np.zeros((10, 10)), np.ones((10, 10)))
assert_array_almost_equal(result, 0)
@pytest.mark.parametrize('dtype', [np.int8, np.uint8, np.int16, np.uint16,
np.int32, np.uint32, np.int64, np.uint64,
np.float16, np.float32, np.float64])
def test_fill_hole(dtype):
"""Test reconstruction by erosion, which should fill holes in mask."""
seed = np.array([0, 8, 8, 8, 8, 8, 8, 8, 8, 0], dtype=dtype)
mask = np.array([0, 3, 6, 2, 1, 1, 1, 4, 2, 0], dtype=dtype)
result = reconstruction(seed, mask, method='erosion')
assert result.dtype == _supported_float_type(mask.dtype)
expected = np.array([0, 3, 6, 4, 4, 4, 4, 4, 2, 0], dtype=dtype)
assert_array_almost_equal(result, expected)
def test_invalid_seed():
seed = np.ones((5, 5))
mask = np.ones((5, 5))
with pytest.raises(ValueError):
reconstruction(seed * 2, mask,
method='dilation')
with pytest.raises(ValueError):
reconstruction(seed * 0.5, mask,
method='erosion')
def test_invalid_footprint():
seed = np.ones((5, 5))
mask = np.ones((5, 5))
with pytest.raises(ValueError):
reconstruction(seed, mask,
footprint=np.ones((4, 4)))
with pytest.raises(ValueError):
reconstruction(seed, mask,
footprint=np.ones((3, 4)))
reconstruction(seed, mask, footprint=np.ones((3, 3)))
def test_invalid_method():
seed = np.array([0, 8, 8, 8, 8, 8, 8, 8, 8, 0])
mask = np.array([0, 3, 6, 2, 1, 1, 1, 4, 2, 0])
with pytest.raises(ValueError):
reconstruction(seed, mask, method='foo')
def test_invalid_offset_not_none():
"""Test reconstruction with invalid not None offset parameter"""
image = np.array([[1, 1, 1, 1, 1, 1, 1, 1],
[1, 2, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 3, 1],
[1, 1, 1, 1, 1, 1, 1, 1]])
mask = np.array([[4, 4, 4, 1, 1, 1, 1, 1],
[4, 4, 4, 1, 1, 1, 1, 1],
[4, 4, 4, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 4, 4, 4],
[1, 1, 1, 1, 1, 4, 4, 4],
[1, 1, 1, 1, 1, 4, 4, 4]])
with pytest.raises(ValueError):
reconstruction(image, mask, method='dilation',
footprint=np.ones((3, 3)), offset=np.array([3, 0]))
def test_offset_not_none():
"""Test reconstruction with valid offset parameter"""
seed = np.array([0, 3, 6, 2, 1, 1, 1, 4, 2, 0])
mask = np.array([0, 8, 6, 8, 8, 8, 8, 4, 4, 0])
expected = np.array([0, 3, 6, 6, 6, 6, 6, 4, 4, 0])
assert_array_almost_equal(
reconstruction(seed, mask, method='dilation',
footprint=np.ones(3), offset=np.array([0])), expected)
<file_sep>/doc/source/release_notes/release_0.11.rst
scikit-image 0.11.0 release notes
=================================
We're happy to announce the release of scikit-image v0.11.0!
scikit-image is an image processing toolbox for SciPy that includes algorithms
for segmentation, geometric transformations, color space manipulation,
analysis, filtering, morphology, feature detection, and more.
For more information, examples, and documentation, please visit our website:
http://scikit-image.org
Highlights
----------
For this release, we merged over 200 pull requests with bug fixes,
cleanups, improved documentation and new features. Highlights
include:
- Region Adjacency Graphs
- Color distance RAGs (#1031)
- Threshold Cut on RAGs (#1031)
- Similarity RAGs (#1080)
- Normalized Cut on RAGs (#1080)
- RAG drawing (#1087)
- Hierarchical merging (#1100)
- Sub-pixel shift registration (#1066)
- Non-local means denoising (#874)
- Sliding window histogram (#1127)
- More illuminants in color conversion (#1130)
- Handling of CMYK images (#1360)
- `stop_probability` for RANSAC (#1176)
- Li thresholding (#1376)
- Signed edge operators (#1240)
- Full ndarray support for `peak_local_max` (#1355)
- Improve conditioning of geometric transformations (#1319)
- Standardize handling of multi-image files (#1200)
- Ellipse structuring element (#1298)
- Multi-line drawing tool (#1065), line handle style (#1179)
- Point in polygon testing (#1123)
- Rotation around a specified center (#1168)
- Add `shape` option to drawing functions (#1222)
- Faster regionprops (#1351)
- `skimage.future` package (#1365)
- More robust I/O module (#1189)
API Changes
-----------
- The ``skimage.filter`` subpackage has been renamed to ``skimage.filters``.
- Some edge detectors returned values greater than 1--their results are now
appropriately scaled with a factor of ``sqrt(2)``.
Contributors to this release
----------------------------
(Listed alphabetically by last name)
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
<file_sep>/doc/examples/numpy_operations/plot_footprint_decompositions.py
"""
================================================
Decompose flat footprints (structuring elements)
================================================
Many footprints (structuring elements) can be decomposed into an equivalent
series of smaller structuring elements. The term "flat" refers to footprints
that only contain values of 0 or 1 (i.e., all methods in
``skimage.morphology.footprints``). Binary dilation operations have an
associative and distributive property that often allows decomposition into
an equivalent series of smaller footprints. Most often this is done to provide
a performance benefit.
As a concrete example, dilation with a square footprint of shape (15, 15) is
equivalent to dilation with a rectangle of shape (15, 1) followed by another
dilation with a rectangle of shape (1, 15). It is also equivalent to 7
consecutive dilations with a square footprint of shape (3, 3).
There are many possible decompositions and which one performs best may be
architecture-dependent.
scikit-image currently provides two forms of automated decomposition. For the
cases of ``square``, ``rectangle`` and ``cube`` footprints, there is an option
for a "separable" decomposition (size > 1 along only one axis at a time).
There is no separable decomposition into 1D operations for some other symmetric
convex shapes, e.g., ``diamond``, ``octahedron`` and ``octagon``. However, it
is possible to provide a "sequence" decomposition based on a series of small
footprints of shape ``(3,) * ndim``.
For simplicity of implementation, all decompositions shown below use only
odd-sized footprints with their origin located at the center of the footprint.
"""
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import colors
from mpl_toolkits.mplot3d import Axes3D
from skimage.morphology import (ball, cube, diamond, disk, ellipse, octagon,
octahedron, rectangle, square)
from skimage.morphology.footprints import footprint_from_sequence
# Generate 2D and 3D structuring elements.
footprint_dict = {
"square(11) (separable)": (square(11, decomposition=None),
square(11, decomposition="separable")),
"square(11) (sequence)": (square(11, decomposition=None),
square(11, decomposition="sequence")),
"rectangle(7, 11) (separable)": (rectangle(7, 11, decomposition=None),
rectangle(7, 11,
decomposition="separable")),
"rectangle(7, 11) (sequence)": (rectangle(7, 11, decomposition=None),
rectangle(7, 11,
decomposition="sequence")),
"diamond(5) (sequence)": (diamond(5, decomposition=None),
diamond(5, decomposition="sequence")),
"disk(7, strict_radius=False) (sequence)": (
disk(7, strict_radius=False, decomposition=None),
disk(7, strict_radius=False, decomposition="sequence")
),
"disk(7, strict_radius=True) (crosses)": (
disk(7, strict_radius=True, decomposition=None),
disk(7, strict_radius=True, decomposition="crosses")
),
"ellipse(4, 9) (crosses)": (
ellipse(4, 9, decomposition=None),
ellipse(4, 9, decomposition="crosses")
),
"disk(20) (sequence)": (disk(20, strict_radius=False, decomposition=None),
disk(20, strict_radius=False,
decomposition="sequence")),
"octagon(7, 4) (sequence)": (octagon(7, 4, decomposition=None),
octagon(7, 4, decomposition="sequence")),
"cube(11) (separable)": (cube(11, decomposition=None),
cube(11, decomposition="separable")),
"cube(11) (sequence)": (cube(11, decomposition=None),
cube(11, decomposition="sequence")),
"octahedron(7) (sequence)": (octahedron(7, decomposition=None),
octahedron(7, decomposition="sequence")),
"ball(9) (sequence)": (ball(9, strict_radius=False, decomposition=None),
ball(9, strict_radius=False,
decomposition="sequence")),
}
# Visualize the elements
# binary white / blue colormap
cmap = colors.ListedColormap(['white', (0.1216, 0.4706, 0.70588)])
fontdict = dict(fontsize=16, fontweight='bold')
for title, (footprint, footprint_sequence) in footprint_dict.items():
ndim = footprint.ndim
num_seq = len(footprint_sequence)
approximate_decomposition = (
'ball' in title or 'disk' in title or 'ellipse' in title
)
if approximate_decomposition:
# Two extra plot in approximate cases to show both:
# 1.) decomposition=None idea footprint
# 2.) actual composite footprint corresponding to the sequence
num_subplots = num_seq + 2
else:
# composite and decomposition=None are identical so only 1 extra plot
num_subplots = num_seq + 1
fig = plt.figure(figsize=(4 * num_subplots, 5))
if ndim == 2:
ax = fig.add_subplot(1, num_subplots, num_subplots)
ax.imshow(footprint, cmap=cmap, vmin=0, vmax=1)
if approximate_decomposition:
ax2 = fig.add_subplot(1, num_subplots, num_subplots - 1)
footprint_composite = footprint_from_sequence(footprint_sequence)
ax2.imshow(footprint_composite, cmap=cmap, vmin=0, vmax=1)
else:
ax = fig.add_subplot(1, num_subplots, num_subplots,
projection=Axes3D.name)
ax.voxels(footprint, cmap=cmap)
if approximate_decomposition:
ax2 = fig.add_subplot(1, num_subplots, num_subplots - 1,
projection=Axes3D.name)
footprint_composite = footprint_from_sequence(footprint_sequence)
ax2.voxels(footprint_composite, cmap=cmap)
title1 = title.split(' (')[0]
if approximate_decomposition:
# plot decomposition=None on a separate axis from the composite
title = title1 + '\n(decomposition=None)'
else:
# for exact cases composite and decomposition=None are identical
title = title1 + '\n(composite)'
ax.set_title(title, fontdict=fontdict)
ax.set_axis_off()
if approximate_decomposition:
ax2.set_title(title1 + '\n(composite)', fontdict=fontdict)
ax2.set_axis_off()
for n, (fp, num_reps) in enumerate(footprint_sequence):
npad = [((footprint.shape[d] - fp.shape[d]) // 2, ) * 2
for d in range(ndim)]
fp = np.pad(fp, npad, mode='constant')
if ndim == 2:
ax = fig.add_subplot(1, num_subplots, n + 1)
ax.imshow(fp, cmap=cmap, vmin=0, vmax=1)
else:
ax = fig.add_subplot(1, num_subplots, n + 1,
projection=Axes3D.name)
ax.voxels(fp, cmap=cmap)
title = f"element {n + 1} of {num_seq}\n({num_reps} iteration"
title += "s)" if num_reps > 1 else ")"
ax.set_title(title, fontdict=fontdict)
ax.set_axis_off()
ax.set_xlabel(f'num_reps = {num_reps}')
fig.tight_layout()
# draw a line separating the sequence elements from the composite
line_pos = num_seq / num_subplots
line = plt.Line2D([line_pos, line_pos], [0, 1], color="black")
fig.add_artist(line)
plt.show()
<file_sep>/skimage/conftest.py
from skimage._shared.testing import setup_test, teardown_test
# List of files that pytest should ignore
collect_ignore = [
"io/_plugins",
]
def pytest_runtest_setup(item):
setup_test()
def pytest_runtest_teardown(item):
teardown_test()
<file_sep>/requirements.txt
-r requirements/default.txt
-r requirements/test.txt
-r requirements/developer.txt
<file_sep>/skimage/draw/__init__.pyi
# Explicitly setting `__all__` is necessary for type inference engines
# to know which symbols are exported. See
# https://peps.python.org/pep-0484/#stub-files
__all__ = [
'line',
'line_aa',
'line_nd',
'bezier_curve',
'polygon',
'polygon_perimeter',
'ellipse',
'ellipse_perimeter',
'ellipsoid',
'ellipsoid_stats',
'circle_perimeter',
'circle_perimeter_aa',
'disk',
'set_color',
'random_shapes',
'rectangle',
'rectangle_perimeter',
'polygon2mask'
]
from .draw3d import ellipsoid, ellipsoid_stats
from ._draw import _bezier_segment
from ._random_shapes import random_shapes
from ._polygon2mask import polygon2mask
from .draw_nd import line_nd
from .draw import (
ellipse,
set_color,
polygon_perimeter,
line,
line_aa,
polygon,
ellipse_perimeter,
circle_perimeter,
circle_perimeter_aa,
disk, bezier_curve,
rectangle,
rectangle_perimeter
)
<file_sep>/tools/precompute/mc_meta/createluts.py
""" Create lookup tables for the marching cubes algorithm, by parsing
the file "LookUpTable.h". This prints a text to the stdout which
can then be copied to luts.py.
The luts are tuples of shape and base64 encoded bytes.
"""
import base64
def create_luts(fname):
# Get the lines in the C header file
text = open(fname,'rb').read().decode('utf-8')
lines1 = [line.rstrip() for line in text.splitlines()]
# Init lines for Python
lines2 = []
# Get classic table
more_lines, ii = get_table(lines1, 'static const char casesClassic', 0)
lines2.extend(more_lines)
# Get cases table
more_lines, ii = get_table(lines1, 'static const char cases', 0)
lines2.extend(more_lines)
# Get tiling tables
ii = 0
for casenr in range(99):
# Get table
more_lines, ii = get_table(lines1, 'static const char tiling', ii+1)
if ii < 0:
break
else:
lines2.extend(more_lines)
# Get test tables
ii = 0
for casenr in range(99):
# Get table
more_lines, ii = get_table(lines1, 'static const char test', ii+1)
if ii < 0:
break
else:
lines2.extend(more_lines)
# Get subconfig tables
ii = 0
for casenr in range(99):
# Get table
more_lines, ii = get_table(lines1, 'static const char subconfig', ii+1)
if ii < 0:
break
else:
lines2.extend(more_lines)
return '\n'.join(lines2)
def get_table(lines1, needle, i):
# Try to find the start
ii = search_line(lines1, needle, i)
if ii < 0:
return [], -1
# Init result
lines2 = []
# Get size and name
front, dummu, back = lines1[ii].partition('[')
name = front.split(' ')[-1].upper()
size = int(back.split(']',1)[0])
cdes = lines1[ii].rstrip(' {=')
# Write name
lines2.append(f'{name} = np.array([')
# Get elements
for i in range(ii+1, ii+1+9999999):
line1 = lines1[i]
front, dummy, back = line1.partition('*/')
if not back:
front, back = back, front
line2 = ' '
line2 += back.strip().replace('{', '[').replace('}',']').replace(';','')
line2 += front.replace('/*',' #').rstrip()
lines2.append(line2)
if line1.endswith('};'):
break
# Close and return
lines2.append(" , 'int8')")
lines2.append('')
#return lines2, ii+size
# Execute code and get array as base64 text
code = '\n'.join(lines2)
code = code.split('=',1)[1]
array = eval(code)
array64 = base64.encodebytes(array.tostring()).decode('utf-8')
# Reverse: bytes = base64.decodebytes(text.encode('utf-8'))
text = f'{name} = {array.shape}, """\n{array64}"""'
# Build actual lines
lines2 = []
lines2.append( '#' + cdes)
lines2.append(text)
lines2.append('')
return lines2, ii+size
def search_line(lines, refline, start=0):
for i, line in enumerate(lines[start:]):
if line.startswith(refline):
return i + start
return -1
if __name__ == '__main__':
import os
fname = os.path.join(os.getcwd(), 'LookUpTable.h')
with open(os.path.join(os.getcwd(), 'mcluts.py'), 'w') as f:
f.write('# -*- coding: utf-8 -*-\n')
f.write(
'# This file was auto-generated from `mc_meta/LookUpTable.h` by\n'
'# `mc_meta/createluts.py`. The `mc_meta` scripts are not\n'
'# distributed with scikit-image, but are available in the\n'
'# repository under tools/precompute/mc_meta.\n\n'
)
f.write(create_luts(fname))
<file_sep>/doc/source/index.rst
scikit-image's documentation
============================
**Date**: |today|, **Version**: |version|
Welcome! `scikit-image`_ is an image processing toolbox which builds on
`numpy`_, `scipy.ndimage`_ and other libraries to provide a versatile set of
image processing routines in `Python`_. Our project and community is guided by
the :doc:`about/code_of_conduct`.
.. _scikit-image: https://scikit-image.org
.. _numpy: https://numpy.org
.. _scipy.ndimage: https://docs.scipy.org/doc/scipy/reference/ndimage.html
.. _Python: https://www.python.org
Quick links
-----------
.. grid:: 2
:gutter: 3
.. grid-item-card:: :octicon:`rocket` Get started
:link: user_guide/install
:link-type: any
New to scikit-image? Start with our installation guide and scikit-image's key
concepts.
.. grid-item-card:: :octicon:`image` Examples
:link: auto_examples/index
:link-type: any
Browse our gallery of entry-level and domain-specific examples.
.. grid-item-card:: :octicon:`comment-discussion` Get help :octicon:`link-external`
:link: https://forum.image.sc/tag/scikit-image
Need help with a particular image analysis task? Ask us and a large
image analysis community on our user forum *image.sc*.
.. grid-item-card:: :octicon:`repo` API reference
:link: api/api
:link-type: any
A detailed description of scikit-image's public Python API. Assumes an
understanding of the key concepts.
.. grid-item-card:: :octicon:`tools` Contribute
:link: development/contribute
:link-type: any
Saw a typo? Found a bug? Want to improve a function? Learn how to
contribute to scikit-image!
.. grid-item-card:: :octicon:`history` Release notes
:link: release_notes/index
:link-type: any
Upgrading from a previous version? See what's new and changed between
each release of scikit-image.
.. grid-item-card:: :octicon:`people` About us
:link: about/index
:link-type: any
Get to know the project and the community. Learn where we are going and
how we work together.
.. grid-item-card:: :octicon:`milestone` SKIPs
:link: skips/index
:link-type: any
scikit-image proposals, documents describing major changes to the
library.
See also our site-wide :ref:`genindex` our
:ref:`search this documentation <search>`.
.. toctree::
:hidden:
user_guide/index
auto_examples/index
api/api
release_notes/index
development/index
about/index
<file_sep>/doc/source/release_notes/release_0.21.rst
scikit-image 0.21.0 release notes
=================================
We're happy to announce the release of scikit-image 0.21.0!
scikit-image is an image processing toolbox for SciPy that includes algorithms
for segmentation, geometric transformations, color space manipulation,
analysis, filtering, morphology, feature detection, and more.
For more information, examples, and documentation, please visit our website:
https://scikit-image.org
Highlights
----------
- Last release to support Python 3.8
- Unified API for PRNGs
New Features
------------
- Implement Fisher vectors in scikit-image
(`#5349 <https://github.com/scikit-image/scikit-image/pull/5349>`_).
- Add support for y-dimensional shear to the AffineTransform
(`#6752 <https://github.com/scikit-image/scikit-image/pull/6752>`_).
API Changes
-----------
In this release, we unify the way seeds are specified for algorithms that make use of
pseudo-random numbers. Before, various keyword arguments (``sample_seed``, ``seed``,
``random_seed``, and ``random_state``) served the same purpose in different places.
These have all been replaced with a single ``rng`` argument, that handles both integer
seeds and NumPy Generators. Please see the related `SciPy discussion`_, as well as
`Scientific Python SPEC 7`_ that attempts to summarize the argument.
.. _SciPy discussion: https://github.com/scipy/scipy/issues/14322
.. _Scientific Python SPEC 7: https://github.com/scientific-python/specs/pull/180
- Unify API on seed keyword for random seeds / generator
(`#6258 <https://github.com/scikit-image/scikit-image/pull/6258>`_).
- Refactor `_invariant_denoise` to `denoise_invariant`
(`#6660 <https://github.com/scikit-image/scikit-image/pull/6660>`_).
- Expose `color.get_xyz_coords` in public API
(`#6696 <https://github.com/scikit-image/scikit-image/pull/6696>`_).
- Make join_segmentations return array maps from output to input labels
(`#6786 <https://github.com/scikit-image/scikit-image/pull/6786>`_).
- Unify pseudo-random seeding interface
(`#6922 <https://github.com/scikit-image/scikit-image/pull/6922>`_).
- Change geometric transform inverse to property
(`#6926 <https://github.com/scikit-image/scikit-image/pull/6926>`_).
Enhancements
------------
- Bounding box crop
(`#5499 <https://github.com/scikit-image/scikit-image/pull/5499>`_).
- Add support for y-dimensional shear to the AffineTransform
(`#6752 <https://github.com/scikit-image/scikit-image/pull/6752>`_).
- Make join_segmentations return array maps from output to input labels
(`#6786 <https://github.com/scikit-image/scikit-image/pull/6786>`_).
- Check if `spacing` parameter is tuple in `regionprops`
(`#6907 <https://github.com/scikit-image/scikit-image/pull/6907>`_).
- Enable use of `rescale_intensity` with dask array
(`#6910 <https://github.com/scikit-image/scikit-image/pull/6910>`_).
Performance
-----------
- Add lazy loading to skimage.color submodule
(`#6967 <https://github.com/scikit-image/scikit-image/pull/6967>`_).
- Add Lazy loading to skimage.draw submodule
(`#6971 <https://github.com/scikit-image/scikit-image/pull/6971>`_).
- Add Lazy loader to skimage.exposure
(`#6978 <https://github.com/scikit-image/scikit-image/pull/6978>`_).
- Add lazy loading to skimage.future module
(`#6981 <https://github.com/scikit-image/scikit-image/pull/6981>`_).
Bug Fixes
---------
- Fix and refactor `deprecated` decorator to `deprecate_func`
(`#6594 <https://github.com/scikit-image/scikit-image/pull/6594>`_).
- Refactor `_invariant_denoise` to `denoise_invariant`
(`#6660 <https://github.com/scikit-image/scikit-image/pull/6660>`_).
- Expose `color.get_xyz_coords` in public API
(`#6696 <https://github.com/scikit-image/scikit-image/pull/6696>`_).
- shift and normalize data before fitting circle or ellipse
(`#6703 <https://github.com/scikit-image/scikit-image/pull/6703>`_).
- Showcase pydata-sphinx-theme
(`#6714 <https://github.com/scikit-image/scikit-image/pull/6714>`_).
- Fix matrix calculation for shear angle in `AffineTransform`
(`#6717 <https://github.com/scikit-image/scikit-image/pull/6717>`_).
- Fix threshold_li(): prevent log(0) on single-value background.
(`#6745 <https://github.com/scikit-image/scikit-image/pull/6745>`_).
- Fix copy-paste error in `footprints.diamond` test case
(`#6756 <https://github.com/scikit-image/scikit-image/pull/6756>`_).
- Update .devpy/cmds.py to match latest devpy
(`#6789 <https://github.com/scikit-image/scikit-image/pull/6789>`_).
- Avoid installation of rtoml via conda in installation guide
(`#6792 <https://github.com/scikit-image/scikit-image/pull/6792>`_).
- Raise error in skeletonize for invalid value to method param
(`#6805 <https://github.com/scikit-image/scikit-image/pull/6805>`_).
- Sign error fix in measure.regionprops for orientations of 45 degrees
(`#6836 <https://github.com/scikit-image/scikit-image/pull/6836>`_).
- Fix returned data type in `segmentation.watershed`
(`#6839 <https://github.com/scikit-image/scikit-image/pull/6839>`_).
- Handle NaNs when clipping in `transform.resize`
(`#6852 <https://github.com/scikit-image/scikit-image/pull/6852>`_).
- Fix failing regionprop_table for multichannel properties
(`#6861 <https://github.com/scikit-image/scikit-image/pull/6861>`_).
- Do not allow 64-bit integer inputs; add test to ensure masked and unmasked modes are aligned
(`#6875 <https://github.com/scikit-image/scikit-image/pull/6875>`_).
- Fix typo in apply_parallel introduced in #6876
(`#6881 <https://github.com/scikit-image/scikit-image/pull/6881>`_).
- Fix LPI filter for data with even dimensions
(`#6883 <https://github.com/scikit-image/scikit-image/pull/6883>`_).
- Use legacy datasets without creating a `data_dir`
(`#6886 <https://github.com/scikit-image/scikit-image/pull/6886>`_).
- Raise error when source_range is not correct
(`#6898 <https://github.com/scikit-image/scikit-image/pull/6898>`_).
- apply spacing rescaling when computing centroid_weighted
(`#6900 <https://github.com/scikit-image/scikit-image/pull/6900>`_).
- Corrected energy calculation in Chan Vese
(`#6902 <https://github.com/scikit-image/scikit-image/pull/6902>`_).
- Add missing backticks to DOI role in docstring of `area_opening`
(`#6913 <https://github.com/scikit-image/scikit-image/pull/6913>`_).
- Fix inclusion of `random.js` in HTML output
(`#6935 <https://github.com/scikit-image/scikit-image/pull/6935>`_).
- Fix URL of random gallery links
(`#6937 <https://github.com/scikit-image/scikit-image/pull/6937>`_).
- Use context manager to ensure urlopen buffer is closed
(`#6942 <https://github.com/scikit-image/scikit-image/pull/6942>`_).
- Fix sparse index type casting in skimage.graph._ncut
(`#6975 <https://github.com/scikit-image/scikit-image/pull/6975>`_).
Maintenance
-----------
- Fix and refactor `deprecated` decorator to `deprecate_func`
(`#6594 <https://github.com/scikit-image/scikit-image/pull/6594>`_).
- allow trivial ransac call
(`#6755 <https://github.com/scikit-image/scikit-image/pull/6755>`_).
- Fix copy-paste error in `footprints.diamond` test case
(`#6756 <https://github.com/scikit-image/scikit-image/pull/6756>`_).
- Use imageio v3 API
(`#6764 <https://github.com/scikit-image/scikit-image/pull/6764>`_).
- Unpin scipy dependency
(`#6773 <https://github.com/scikit-image/scikit-image/pull/6773>`_).
- Update .devpy/cmds.py to match latest devpy
(`#6789 <https://github.com/scikit-image/scikit-image/pull/6789>`_).
- Relicense CLAHE code under BSD-3-Clause
(`#6795 <https://github.com/scikit-image/scikit-image/pull/6795>`_).
- Relax reproduce section in bug issue template
(`#6825 <https://github.com/scikit-image/scikit-image/pull/6825>`_).
- Rename devpy to spin
(`#6842 <https://github.com/scikit-image/scikit-image/pull/6842>`_).
- Speed up threshold_local function by fixing call to _supported_float_type
(`#6847 <https://github.com/scikit-image/scikit-image/pull/6847>`_).
- Specify kernel for ipywidgets
(`#6849 <https://github.com/scikit-image/scikit-image/pull/6849>`_).
- Make `image_fetcher` and `create_image_fetcher` in `data` private
(`#6855 <https://github.com/scikit-image/scikit-image/pull/6855>`_).
- Update references to outdated dev.py with spin
(`#6856 <https://github.com/scikit-image/scikit-image/pull/6856>`_).
- Bump 0.21 removals to 0.22
(`#6868 <https://github.com/scikit-image/scikit-image/pull/6868>`_).
- Update dependencies
(`#6869 <https://github.com/scikit-image/scikit-image/pull/6869>`_).
- Update pre-commits
(`#6870 <https://github.com/scikit-image/scikit-image/pull/6870>`_).
- Add test for radon transform on circular phantom
(`#6873 <https://github.com/scikit-image/scikit-image/pull/6873>`_).
- Do not allow 64-bit integer inputs; add test to ensure masked and unmasked modes are aligned
(`#6875 <https://github.com/scikit-image/scikit-image/pull/6875>`_).
- Don't use mutable types as default values for arguments
(`#6876 <https://github.com/scikit-image/scikit-image/pull/6876>`_).
- Point `version_switcher.json` URL at dev docs
(`#6882 <https://github.com/scikit-image/scikit-image/pull/6882>`_).
- Add back parallel tests that were removed as part of Meson build
(`#6884 <https://github.com/scikit-image/scikit-image/pull/6884>`_).
- Use legacy datasets without creating a `data_dir`
(`#6886 <https://github.com/scikit-image/scikit-image/pull/6886>`_).
- Remove old doc cruft
(`#6901 <https://github.com/scikit-image/scikit-image/pull/6901>`_).
- Temporarily pin imageio to <2.28
(`#6909 <https://github.com/scikit-image/scikit-image/pull/6909>`_).
- Unify pseudo-random seeding interface follow-up
(`#6924 <https://github.com/scikit-image/scikit-image/pull/6924>`_).
- Use pytest.warn instead of custom context manager
(`#6931 <https://github.com/scikit-image/scikit-image/pull/6931>`_).
- Follow-up to move to pydata-sphinx-theme
(`#6933 <https://github.com/scikit-image/scikit-image/pull/6933>`_).
- Mark functions as `noexcept` to support Cython 3
(`#6936 <https://github.com/scikit-image/scikit-image/pull/6936>`_).
- Skip unstable test in `ransac`'s docstring
(`#6938 <https://github.com/scikit-image/scikit-image/pull/6938>`_).
- Stabilize EllipseModel fitting parameters
(`#6943 <https://github.com/scikit-image/scikit-image/pull/6943>`_).
- Point logo in generated HTML docs at scikit-image.org
(`#6947 <https://github.com/scikit-image/scikit-image/pull/6947>`_).
- If user provides RNG, spawn it before deepcopying
(`#6948 <https://github.com/scikit-image/scikit-image/pull/6948>`_).
- Skip ransac doctest
(`#6953 <https://github.com/scikit-image/scikit-image/pull/6953>`_).
- Expose `GeometricTransform.residuals` in HTML doc
(`#6968 <https://github.com/scikit-image/scikit-image/pull/6968>`_).
- Fix NumPy 1.25 deprecation warnings
(`#6969 <https://github.com/scikit-image/scikit-image/pull/6969>`_).
- Revert jupyterlite
(`#6972 <https://github.com/scikit-image/scikit-image/pull/6972>`_).
- Don't test numpy nightlies due to transcendental functions issue
(`#6973 <https://github.com/scikit-image/scikit-image/pull/6973>`_).
- Ignore tight layout warning from matplotlib pre-release
(`#6976 <https://github.com/scikit-image/scikit-image/pull/6976>`_).
- Remove temporary constraint <2.28 for imageio
(`#6980 <https://github.com/scikit-image/scikit-image/pull/6980>`_).
Documentation
-------------
- Document boundary behavior of `draw.polygon` and `draw.polygon2mask`
(`#6690 <https://github.com/scikit-image/scikit-image/pull/6690>`_).
- Showcase pydata-sphinx-theme
(`#6714 <https://github.com/scikit-image/scikit-image/pull/6714>`_).
- Merge duplicate instructions for setting up build environment.
(`#6770 <https://github.com/scikit-image/scikit-image/pull/6770>`_).
- Add docstring to `skimage.color` module
(`#6777 <https://github.com/scikit-image/scikit-image/pull/6777>`_).
- DOC: Fix underline length in `docstring_add_deprecated`
(`#6778 <https://github.com/scikit-image/scikit-image/pull/6778>`_).
- Link full license to README
(`#6779 <https://github.com/scikit-image/scikit-image/pull/6779>`_).
- Fix conda instructions for dev env setup.
(`#6781 <https://github.com/scikit-image/scikit-image/pull/6781>`_).
- Update docstring in skimage.future module
(`#6782 <https://github.com/scikit-image/scikit-image/pull/6782>`_).
- Remove outdated build instructions from README
(`#6788 <https://github.com/scikit-image/scikit-image/pull/6788>`_).
- Add docstring to the `transform` module
(`#6797 <https://github.com/scikit-image/scikit-image/pull/6797>`_).
- Handle pip-only dependencies when using conda.
(`#6806 <https://github.com/scikit-image/scikit-image/pull/6806>`_).
- Added examples to the EssentialMatrixTransform class and its estimation function
(`#6832 <https://github.com/scikit-image/scikit-image/pull/6832>`_).
- Fix returned data type in `segmentation.watershed`
(`#6839 <https://github.com/scikit-image/scikit-image/pull/6839>`_).
- Update references to outdated dev.py with spin
(`#6856 <https://github.com/scikit-image/scikit-image/pull/6856>`_).
- Added example to AffineTransform class
(`#6859 <https://github.com/scikit-image/scikit-image/pull/6859>`_).
- Update _warps_cy.pyx
(`#6867 <https://github.com/scikit-image/scikit-image/pull/6867>`_).
- Point `version_switcher.json` URL at dev docs
(`#6882 <https://github.com/scikit-image/scikit-image/pull/6882>`_).
- Fix docstring underline lengths
(`#6895 <https://github.com/scikit-image/scikit-image/pull/6895>`_).
- ENH Add JupyterLite button to gallery examples
(`#6911 <https://github.com/scikit-image/scikit-image/pull/6911>`_).
- Add missing backticks to DOI role in docstring of `area_opening`
(`#6913 <https://github.com/scikit-image/scikit-image/pull/6913>`_).
- Add 0.21 release notes
(`#6925 <https://github.com/scikit-image/scikit-image/pull/6925>`_).
- Simplify installation instruction document
(`#6927 <https://github.com/scikit-image/scikit-image/pull/6927>`_).
- Follow-up to move to pydata-sphinx-theme
(`#6933 <https://github.com/scikit-image/scikit-image/pull/6933>`_).
- Update release notes
(`#6944 <https://github.com/scikit-image/scikit-image/pull/6944>`_).
- MNT Fix typo in JupyterLite comment
(`#6945 <https://github.com/scikit-image/scikit-image/pull/6945>`_).
- Point logo in generated HTML docs at scikit-image.org
(`#6947 <https://github.com/scikit-image/scikit-image/pull/6947>`_).
- Add missing PRs to release notes
(`#6949 <https://github.com/scikit-image/scikit-image/pull/6949>`_).
- fix bad link in CODE_OF_CONDUCT.md
(`#6952 <https://github.com/scikit-image/scikit-image/pull/6952>`_).
- Expose `GeometricTransform.residuals` in HTML doc
(`#6968 <https://github.com/scikit-image/scikit-image/pull/6968>`_).
Infrastructure
--------------
- Showcase pydata-sphinx-theme
(`#6714 <https://github.com/scikit-image/scikit-image/pull/6714>`_).
- Prepare CI configuration for merge queue
(`#6771 <https://github.com/scikit-image/scikit-image/pull/6771>`_).
- Pin to devpy 0.1 tag
(`#6816 <https://github.com/scikit-image/scikit-image/pull/6816>`_).
- Relax reproduce section in bug issue template
(`#6825 <https://github.com/scikit-image/scikit-image/pull/6825>`_).
- Rename devpy to spin
(`#6842 <https://github.com/scikit-image/scikit-image/pull/6842>`_).
- Use lazy loader 0.2
(`#6844 <https://github.com/scikit-image/scikit-image/pull/6844>`_).
- Cleanup cruft in tools
(`#6846 <https://github.com/scikit-image/scikit-image/pull/6846>`_).
- Update pre-commits
(`#6870 <https://github.com/scikit-image/scikit-image/pull/6870>`_).
- Remove `codecov` dependency which disappeared from PyPI
(`#6887 <https://github.com/scikit-image/scikit-image/pull/6887>`_).
- Add CircleCI API token; fixes status link to built docs
(`#6894 <https://github.com/scikit-image/scikit-image/pull/6894>`_).
- Temporarily pin imageio to <2.28
(`#6909 <https://github.com/scikit-image/scikit-image/pull/6909>`_).
- Add PR links to release notes generating script
(`#6917 <https://github.com/scikit-image/scikit-image/pull/6917>`_).
- Use official meson-python release
(`#6928 <https://github.com/scikit-image/scikit-image/pull/6928>`_).
- Fix inclusion of `random.js` in HTML output
(`#6935 <https://github.com/scikit-image/scikit-image/pull/6935>`_).
- Fix URL of random gallery links
(`#6937 <https://github.com/scikit-image/scikit-image/pull/6937>`_).
- Respect SPHINXOPTS and add --install-deps flags to `spin docs`
(`#6940 <https://github.com/scikit-image/scikit-image/pull/6940>`_).
- Build skimage before generating docs
(`#6946 <https://github.com/scikit-image/scikit-image/pull/6946>`_).
- Enable testing against nightly upstream wheels
(`#6956 <https://github.com/scikit-image/scikit-image/pull/6956>`_).
- Add nightly wheel builder
(`#6957 <https://github.com/scikit-image/scikit-image/pull/6957>`_).
- Run weekly tests on nightly wheels
(`#6959 <https://github.com/scikit-image/scikit-image/pull/6959>`_).
- CI: ensure that a "type: " label is present on each PR
(`#6960 <https://github.com/scikit-image/scikit-image/pull/6960>`_).
- Add PR milestone labeler
(`#6977 <https://github.com/scikit-image/scikit-image/pull/6977>`_).
33 authors added to this release (alphabetical)
-----------------------------------------------
- `<NAME> (@adamjstewart) <https://github.com/scikit-image/scikit-image/commits?author=adamjstewart>`_
- `<NAME> (@decorouz) <https://github.com/scikit-image/scikit-image/commits?author=decorouz>`_
- `aeisenbarth (@aeisenbarth) <https://github.com/scikit-image/scikit-image/commits?author=aeisenbarth>`_
- `<NAME> (@ana42742) <https://github.com/scikit-image/scikit-image/commits?author=ana42742>`_
- `<NAME> (@bzamecnik) <https://github.com/scikit-image/scikit-image/commits?author=bzamecnik>`_
- `<NAME> (@carloshorn) <https://github.com/scikit-image/scikit-image/commits?author=carloshorn>`_
- `<NAME> (@23pointsNorth) <https://github.com/scikit-image/scikit-image/commits?author=23pointsNorth>`_
- `DavidTorpey (@DavidTorpey) <https://github.com/scikit-image/scikit-image/commits?author=DavidTorpey>`_
- `<NAME> (@immortal3) <https://github.com/scikit-image/scikit-image/commits?author=immortal3>`_
- `<NAME> (@enricotagliavini) <https://github.com/scikit-image/scikit-image/commits?author=enricotagliavini>`_
- `<NAME> (@ericpre) <https://github.com/scikit-image/scikit-image/commits?author=ericpre>`_
- `GGoussar (@GGoussar) <https://github.com/scikit-image/scikit-image/commits?author=GGoussar>`_
- `<NAME> (@grlee77) <https://github.com/scikit-image/scikit-image/commits?author=grlee77>`_
- `harshitha kolipaka (@harshithakolipaka) <https://github.com/scikit-image/scikit-image/commits?author=harshithakolipaka>`_
- `<NAME> (@hayatoikoma) <https://github.com/scikit-image/scikit-image/commits?author=hayatoikoma>`_
- `i-aki-y (@i-aki-y) <https://github.com/scikit-image/scikit-image/commits?author=i-aki-y>`_
- `<NAME> (@jakeMartin1234) <https://github.com/scikit-image/scikit-image/commits?author=jakeMartin1234>`_
- `<NAME> (@jarrodmillman) <https://github.com/scikit-image/scikit-image/commits?author=jarrodmillman>`_
- `<NAME> (@jni) <https://github.com/scikit-image/scikit-image/commits?author=jni>`_
- `<NAME> (@kevinmeetooa) <https://github.com/scikit-image/scikit-image/commits?author=kevinmeetooa>`_
- `<NAME> (@lagru) <https://github.com/scikit-image/scikit-image/commits?author=lagru>`_
- `<NAME> (@lesteve) <https://github.com/scikit-image/scikit-image/commits?author=lesteve>`_
- `mahamtariq58 (@mahamtariq58) <https://github.com/scikit-image/scikit-image/commits?author=mahamtariq58>`_
- `<NAME> (@mkcor) <https://github.com/scikit-image/scikit-image/commits?author=mkcor>`_
- `<NAME> (@hmaarrfk) <https://github.com/scikit-image/scikit-image/commits?author=hmaarrfk>`_
- `<NAME> (@Carreau) <https://github.com/scikit-image/scikit-image/commits?author=Carreau>`_
- `<NAME> (@matusvalo) <https://github.com/scikit-image/scikit-image/commits?author=matusvalo>`_
- `<NAME> (@v4hn) <https://github.com/scikit-image/scikit-image/commits?author=v4hn>`_
- `<NAME> (@rum1887) <https://github.com/scikit-image/scikit-image/commits?author=rum1887>`_
- `scott-vsi (@scott-vsi) <https://github.com/scikit-image/scikit-image/commits?author=scott-vsi>`_
- `<NAME> (@seanpquinn) <https://github.com/scikit-image/scikit-image/commits?author=seanpquinn>`_
- `<NAME> (@stefanv) <https://github.com/scikit-image/scikit-image/commits?author=stefanv>`_
- `<NAME> (@tonyreina) <https://github.com/scikit-image/scikit-image/commits?author=tonyreina>`_
27 reviewers added to this release (alphabetical)
-------------------------------------------------
- `<NAME> (@decorouz) <https://github.com/scikit-image/scikit-image/commits?author=decorouz>`_
- `aeisenbarth (@aeisenbarth) <https://github.com/scikit-image/scikit-image/commits?author=aeisenbarth>`_
- `<NAME> (@ana42742) <https://github.com/scikit-image/scikit-image/commits?author=ana42742>`_
- `<NAME> (@bsipocz) <https://github.com/scikit-image/scikit-image/commits?author=bsipocz>`_
- `<NAME> (@carloshorn) <https://github.com/scikit-image/scikit-image/commits?author=carloshorn>`_
- `<NAME> (@crisluengo) <https://github.com/scikit-image/scikit-image/commits?author=crisluengo>`_
- `DavidTorpey (@DavidTorpey) <https://github.com/scikit-image/scikit-image/commits?author=DavidTorpey>`_
- `<NAME> (@immortal3) <https://github.com/scikit-image/scikit-image/commits?author=immortal3>`_
- `<NAME> (@enricotagliavini) <https://github.com/scikit-image/scikit-image/commits?author=enricotagliavini>`_
- `<NAME> (@grlee77) <https://github.com/scikit-image/scikit-image/commits?author=grlee77>`_
- `<NAME> (@henrypinkard) <https://github.com/scikit-image/scikit-image/commits?author=henrypinkard>`_
- `i-aki-y (@i-aki-y) <https://github.com/scikit-image/scikit-image/commits?author=i-aki-y>`_
- `<NAME> (@jarrodmillman) <https://github.com/scikit-image/scikit-image/commits?author=jarrodmillman>`_
- `<NAME> (@jni) <https://github.com/scikit-image/scikit-image/commits?author=jni>`_
- `<NAME> (@kevinmeetooa) <https://github.com/scikit-image/scikit-image/commits?author=kevinmeetooa>`_
- `kzuiderveld (@kzuiderveld) <https://github.com/scikit-image/scikit-image/commits?author=kzuiderveld>`_
- `<NAME> (@lagru) <https://github.com/scikit-image/scikit-image/commits?author=lagru>`_
- `<NAME> (@mkcor) <https://github.com/scikit-image/scikit-image/commits?author=mkcor>`_
- `<NAME> (@hmaarrfk) <https://github.com/scikit-image/scikit-image/commits?author=hmaarrfk>`_
- `<NAME> (@rum1887) <https://github.com/scikit-image/scikit-image/commits?author=rum1887>`_
- `<NAME> (@rfezzani) <https://github.com/scikit-image/scikit-image/commits?author=rfezzani>`_
- `<NAME> (@seanpquinn) <https://github.com/scikit-image/scikit-image/commits?author=seanpquinn>`_
- `<NAME> (@seberg) <https://github.com/scikit-image/scikit-image/commits?author=seberg>`_
- `<NAME> (@FirefoxMetzger) <https://github.com/scikit-image/scikit-image/commits?author=FirefoxMetzger>`_
- `<NAME> (@stefanv) <https://github.com/scikit-image/scikit-image/commits?author=stefanv>`_
- `<NAME> (@tonyreina) <https://github.com/scikit-image/scikit-image/commits?author=tonyreina>`_
- `<NAME> (@tony-res) <https://github.com/scikit-image/scikit-image/commits?author=tony-res>`_
<file_sep>/.github/SUPPORT.md
## Technical support
Welcome to scikit-image! We use GitHub for tracking bugs and feature requests.
Before [creating a new
issue](https://github.com/scikit-image/scikit-image/issues/new/choose), please
check the [issue tracker](https://github.com/scikit-image/scikit-image/issues)
for existing similar issues.
Other development-related discussions take place on our [developer
forum](https://discuss.scientific-python.org/c/contributor/skimage).
## User support
### Forum
[image.sc forum](https://forum.image.sc/tag/scikit-image): Here, you may ask
how to perform a particular image analysis task.
The image.sc forum comprises a large image analysis community
across multiple software languages and packages.
### Real-time Chat
[skimage zulip](https://skimage.zulipchat.com): Our real-time chat forum.
Drop in to ask questions, say hello, or let us know how you are using
scikit-image!
<file_sep>/skimage/morphology/footprints.py
import os
from collections.abc import Sequence
from numbers import Integral
import numpy as np
from .. import draw
from skimage import morphology
# Precomputed ball and disk decompositions were saved as 2D arrays where the
# radius of the desired decomposition is used to index into the first axis of
# the array. The values at a given radius corresponds to the number of
# repetitions of 3 different types elementary of structuring elements.
#
# See _nsphere_series_decomposition for full details.
_nsphere_decompositions = {}
_nsphere_decompositions[2] = np.load(
os.path.join(os.path.dirname(__file__), 'disk_decompositions.npy'))
_nsphere_decompositions[3] = np.load(
os.path.join(os.path.dirname(__file__), 'ball_decompositions.npy'))
def _footprint_is_sequence(footprint):
if hasattr(footprint, '__array_interface__'):
return False
def _validate_sequence_element(t):
return (
isinstance(t, Sequence)
and len(t) == 2
and hasattr(t[0], '__array_interface__')
and isinstance(t[1], Integral)
)
if isinstance(footprint, Sequence):
if not all(_validate_sequence_element(t) for t in footprint):
raise ValueError(
"All elements of footprint sequence must be a 2-tuple where "
"the first element of the tuple is an ndarray and the second "
"is an integer indicating the number of iterations."
)
else:
raise ValueError("footprint must be either an ndarray or Sequence")
return True
def _shape_from_sequence(footprints, require_odd_size=False):
"""Determine the shape of composite footprint
In the future if we only want to support odd-sized square, we may want to
change this to require_odd_size
"""
if not _footprint_is_sequence(footprints):
raise ValueError("expected a sequence of footprints")
ndim = footprints[0][0].ndim
shape = [0] * ndim
def _odd_size(size, require_odd_size):
if require_odd_size and size % 2 == 0:
raise ValueError(
"expected all footprint elements to have odd size"
)
for d in range(ndim):
fp, nreps = footprints[0]
_odd_size(fp.shape[d], require_odd_size)
shape[d] = fp.shape[d] + (nreps - 1) * (fp.shape[d] - 1)
for fp, nreps in footprints[1:]:
_odd_size(fp.shape[d], require_odd_size)
shape[d] += nreps * (fp.shape[d] - 1)
return tuple(shape)
def footprint_from_sequence(footprints):
"""Convert a footprint sequence into an equivalent ndarray.
Parameters
----------
footprints : tuple of 2-tuples
A sequence of footprint tuples where the first element of each tuple
is an array corresponding to a footprint and the second element is the
number of times it is to be applied. Currently all footprints should
have odd size.
Returns
-------
footprint : ndarray
An single array equivalent to applying the sequence of `footprints`.
"""
# Create a single pixel image of sufficient size and apply binary dilation.
shape = _shape_from_sequence(footprints)
imag = np.zeros(shape, dtype=bool)
imag[tuple(s // 2 for s in shape)] = 1
return morphology.binary_dilation(imag, footprints)
def square(width, dtype=np.uint8, *, decomposition=None):
"""Generates a flat, square-shaped footprint.
Every pixel along the perimeter has a chessboard distance
no greater than radius (radius=floor(width/2)) pixels.
Parameters
----------
width : int
The width and height of the square.
Other Parameters
----------------
dtype : data-type, optional
The data type of the footprint.
decomposition : {None, 'separable', 'sequence'}, optional
If None, a single array is returned. For 'sequence', a tuple of smaller
footprints is returned. Applying this series of smaller footprints will
given an identical result to a single, larger footprint, but often with
better computational performance. See Notes for more details.
With 'separable', this function uses separable 1D footprints for each
axis. Whether 'seqeunce' or 'separable' is computationally faster may
be architecture-dependent.
Returns
-------
footprint : ndarray or tuple
The footprint where elements of the neighborhood are 1 and 0 otherwise.
When `decomposition` is None, this is just a numpy.ndarray. Otherwise,
this will be a tuple whose length is equal to the number of unique
structuring elements to apply (see Notes for more detail)
Notes
-----
When `decomposition` is not None, each element of the `footprint`
tuple is a 2-tuple of the form ``(ndarray, num_iter)`` that specifies a
footprint array and the number of iterations it is to be applied.
For binary morphology, using ``decomposition='sequence'`` or
``decomposition='separable'`` were observed to give better performance than
``decomposition=None``, with the magnitude of the performance increase
rapidly increasing with footprint size. For grayscale morphology with
square footprints, it is recommended to use ``decomposition=None`` since
the internal SciPy functions that are called already have a fast
implementation based on separable 1D sliding windows.
The 'sequence' decomposition mode only supports odd valued `width`. If
`width` is even, the sequence used will be identical to the 'separable'
mode.
"""
if decomposition is None:
return np.ones((width, width), dtype=dtype)
if decomposition == 'separable' or width % 2 == 0:
sequence = [(np.ones((width, 1), dtype=dtype), 1),
(np.ones((1, width), dtype=dtype), 1)]
elif decomposition == 'sequence':
# only handles odd widths
sequence = [(np.ones((3, 3), dtype=dtype), _decompose_size(width, 3))]
else:
raise ValueError(f"Unrecognized decomposition: {decomposition}")
return tuple(sequence)
def _decompose_size(size, kernel_size=3):
"""Determine number of repeated iterations for a `kernel_size` kernel.
Returns how many repeated morphology operations with an element of size
`kernel_size` is equivalent to a morphology with a single kernel of size
`n`.
"""
if kernel_size % 2 != 1:
raise ValueError("only odd length kernel_size is supported")
return 1 + (size - kernel_size) // (kernel_size - 1)
def rectangle(nrows, ncols, dtype=np.uint8, *, decomposition=None):
"""Generates a flat, rectangular-shaped footprint.
Every pixel in the rectangle generated for a given width and given height
belongs to the neighborhood.
Parameters
----------
nrows : int
The number of rows of the rectangle.
ncols : int
The number of columns of the rectangle.
Other Parameters
----------------
dtype : data-type, optional
The data type of the footprint.
decomposition : {None, 'separable', 'sequence'}, optional
If None, a single array is returned. For 'sequence', a tuple of smaller
footprints is returned. Applying this series of smaller footprints will
given an identical result to a single, larger footprint, but often with
better computational performance. See Notes for more details.
With 'separable', this function uses separable 1D footprints for each
axis. Whether 'sequence' or 'separable' is computationally faster may
be architecture-dependent.
Returns
-------
footprint : ndarray or tuple
A footprint consisting only of ones, i.e. every pixel belongs to the
neighborhood. When `decomposition` is None, this is just a
numpy.ndarray. Otherwise, this will be a tuple whose length is equal to
the number of unique structuring elements to apply (see Notes for more
detail)
Notes
-----
When `decomposition` is not None, each element of the `footprint`
tuple is a 2-tuple of the form ``(ndarray, num_iter)`` that specifies a
footprint array and the number of iterations it is to be applied.
For binary morphology, using ``decomposition='sequence'``
was observed to give better performance, with the magnitude of the
performance increase rapidly increasing with footprint size. For grayscale
morphology with rectangular footprints, it is recommended to use
``decomposition=None`` since the internal SciPy functions that are called
already have a fast implementation based on separable 1D sliding windows.
The `sequence` decomposition mode only supports odd valued `nrows` and
`ncols`. If either `nrows` or `ncols` is even, the sequence used will be
identical to ``decomposition='separable'``.
- The use of ``width`` and ``height`` has been deprecated in
version 0.18.0. Use ``nrows`` and ``ncols`` instead.
"""
if decomposition is None: # TODO: check optimal width setting here
return np.ones((nrows, ncols), dtype=dtype)
even_rows = nrows % 2 == 0
even_cols = ncols % 2 == 0
if decomposition == 'separable' or even_rows or even_cols:
sequence = [(np.ones((nrows, 1), dtype=dtype), 1),
(np.ones((1, ncols), dtype=dtype), 1)]
elif decomposition == 'sequence':
# this branch only support odd nrows, ncols
sq_size = 3
sq_reps = _decompose_size(min(nrows, ncols), sq_size)
sequence = [(np.ones((3, 3), dtype=dtype), sq_reps)]
if nrows > ncols:
nextra = nrows - ncols
sequence.append(
(np.ones((nextra + 1, 1), dtype=dtype), 1)
)
elif ncols > nrows:
nextra = ncols - nrows
sequence.append(
(np.ones((1, nextra + 1), dtype=dtype), 1)
)
else:
raise ValueError(f"Unrecognized decomposition: {decomposition}")
return tuple(sequence)
def diamond(radius, dtype=np.uint8, *, decomposition=None):
"""Generates a flat, diamond-shaped footprint.
A pixel is part of the neighborhood (i.e. labeled 1) if
the city block/Manhattan distance between it and the center of
the neighborhood is no greater than radius.
Parameters
----------
radius : int
The radius of the diamond-shaped footprint.
Other Parameters
----------------
dtype : data-type, optional
The data type of the footprint.
decomposition : {None, 'sequence'}, optional
If None, a single array is returned. For 'sequence', a tuple of smaller
footprints is returned. Applying this series of smaller footprints will
given an identical result to a single, larger footprint, but with
better computational performance. See Notes for more details.
Returns
-------
footprint : ndarray or tuple
The footprint where elements of the neighborhood are 1 and 0 otherwise.
When `decomposition` is None, this is just a numpy.ndarray. Otherwise,
this will be a tuple whose length is equal to the number of unique
structuring elements to apply (see Notes for more detail)
Notes
-----
When `decomposition` is not None, each element of the `footprint`
tuple is a 2-tuple of the form ``(ndarray, num_iter)`` that specifies a
footprint array and the number of iterations it is to be applied.
For either binary or grayscale morphology, using
``decomposition='sequence'`` was observed to have a performance benefit,
with the magnitude of the benefit increasing with increasing footprint
size.
"""
if decomposition is None:
L = np.arange(0, radius * 2 + 1)
I, J = np.meshgrid(L, L)
footprint = np.array(np.abs(I - radius) + np.abs(J - radius) <= radius,
dtype=dtype)
elif decomposition == 'sequence':
fp = diamond(1, dtype=dtype, decomposition=None)
nreps = _decompose_size(2 * radius + 1, fp.shape[0])
footprint = ((fp, nreps),)
else:
raise ValueError(f"Unrecognized decomposition: {decomposition}")
return footprint
def _nsphere_series_decomposition(radius, ndim, dtype=np.uint8):
"""Generate a sequence of footprints approximating an n-sphere.
Morphological operations with an n-sphere (hypersphere) footprint can be
approximated by applying a series of smaller footprints of extent 3 along
each axis. Specific solutions for this are given in [1]_ for the case of
2D disks with radius 2 through 10.
Here we used n-dimensional extensions of the "square", "diamond" and
"t-shaped" elements from that publication. All of these elementary elements
have size ``(3,) * ndim``. We numerically computed the number of
repetitions of each element that gives the closest match to the disk
(in 2D) or ball (in 3D) computed with ``decomposition=None``.
The approach can be extended to higher dimensions, but we have only stored
results for 2D and 3D at this point.
Empirically, the shapes at large radius approach a hexadecagon
(16-sides [2]_) in 2D and a rhombicuboctahedron (26-faces, [3]_) in 3D.
References
----------
.. [1] <NAME> and <NAME>. Decomposition of structuring elements for
optimal implementation of morphological operations. In Proceedings:
1997 IEEE Workshop on Nonlinear Signal and Image Processing, London,
UK.
https://www.iwaenc.org/proceedings/1997/nsip97/pdf/scan/ns970226.pdf
.. [2] https://en.wikipedia.org/wiki/Hexadecagon
.. [3] https://en.wikipedia.org/wiki/Rhombicuboctahedron
"""
if radius == 1:
# for radius 1 just use the exact shape (3,) * ndim solution
kwargs = dict(dtype=dtype, strict_radius=False, decomposition=None)
if ndim == 2:
return ((disk(1, **kwargs), 1),)
elif ndim == 3:
return ((ball(1, **kwargs), 1),)
# load precomputed decompositions
if ndim not in _nsphere_decompositions:
raise ValueError(
"sequence decompositions are only currently available for "
"2d disks or 3d balls"
)
precomputed_decompositions = _nsphere_decompositions[ndim]
max_radius = precomputed_decompositions.shape[0]
if radius > max_radius:
raise ValueError(
f"precomputed {ndim}D decomposition unavailable for "
f"radius > {max_radius}"
)
num_t_series, num_diamond, num_square = precomputed_decompositions[radius]
sequence = []
if num_t_series > 0:
# shape (3, ) * ndim "T-shaped" footprints
all_t = _t_shaped_element_series(ndim=ndim, dtype=dtype)
[sequence.append((t, num_t_series)) for t in all_t]
if num_diamond > 0:
d = np.zeros((3,) * ndim, dtype=dtype)
sl = [slice(1, 2)] * ndim
for ax in range(ndim):
sl[ax] = slice(None)
d[tuple(sl)] = 1
sl[ax] = slice(1, 2)
sequence.append((d, num_diamond))
if num_square > 0:
sq = np.ones((3, ) * ndim, dtype=dtype)
sequence.append((sq, num_square))
return tuple(sequence)
def _t_shaped_element_series(ndim=2, dtype=np.uint8):
"""A series of T-shaped structuring elements.
In the 2D case this is a T-shaped element and its rotation at multiples of
90 degrees. This series is used in efficient decompositions of disks of
various radius as published in [1]_.
The generalization to the n-dimensional case can be performed by having the
"top" of the T to extend in (ndim - 1) dimensions and then producing a
series of rotations such that the bottom end of the T points along each of
``2 * ndim`` orthogonal directions.
"""
if ndim == 2:
# The n-dimensional case produces the same set of footprints, but
# the 2D example is retained here for clarity.
t0 = np.array([[1, 1, 1],
[0, 1, 0],
[0, 1, 0]], dtype=dtype)
t90 = np.rot90(t0, 1)
t180 = np.rot90(t0, 2)
t270 = np.rot90(t0, 3)
return t0, t90, t180, t270
else:
# ndimensional generalization of the 2D case above
all_t = []
for ax in range(ndim):
for idx in [0, 2]:
t = np.zeros((3,) * ndim, dtype=dtype)
sl = [slice(None)] * ndim
sl[ax] = slice(idx, idx + 1)
t[tuple(sl)] = 1
sl = [slice(1, 2)] * ndim
sl[ax] = slice(None)
t[tuple(sl)] = 1
all_t.append(t)
return tuple(all_t)
def disk(radius, dtype=np.uint8, *, strict_radius=True, decomposition=None):
"""Generates a flat, disk-shaped footprint.
A pixel is within the neighborhood if the Euclidean distance between
it and the origin is no greater than radius (This is only approximately
True, when `decomposition == 'sequence'`).
Parameters
----------
radius : int
The radius of the disk-shaped footprint.
Other Parameters
----------------
dtype : data-type, optional
The data type of the footprint.
strict_radius : bool, optional
If False, extend the radius by 0.5. This allows the circle to expand
further within a cube that remains of size ``2 * radius + 1`` along
each axis. This parameter is ignored if decomposition is not None.
decomposition : {None, 'sequence', 'crosses'}, optional
If None, a single array is returned. For 'sequence', a tuple of smaller
footprints is returned. Applying this series of smaller footprints will
given a result equivalent to a single, larger footprint, but with
better computational performance. For disk footprints, the 'sequence'
or 'crosses' decompositions are not always exactly equivalent to
``decomposition=None``. See Notes for more details.
Returns
-------
footprint : ndarray
The footprint where elements of the neighborhood are 1 and 0 otherwise.
Notes
-----
When `decomposition` is not None, each element of the `footprint`
tuple is a 2-tuple of the form ``(ndarray, num_iter)`` that specifies a
footprint array and the number of iterations it is to be applied.
The disk produced by the ``decomposition='sequence'`` mode may not be
identical to that with ``decomposition=None``. A disk footprint can be
approximated by applying a series of smaller footprints of extent 3 along
each axis. Specific solutions for this are given in [1]_ for the case of
2D disks with radius 2 through 10. Here, we numerically computed the number
of repetitions of each element that gives the closest match to the disk
computed with kwargs ``strict_radius=False, decomposition=None``.
Empirically, the series decomposition at large radius approaches a
hexadecagon (a 16-sided polygon [2]_). In [3]_, the authors demonstrate
that a hexadecagon is the closest approximation to a disk that can be
achieved for decomposition with footprints of shape (3, 3).
The disk produced by the ``decomposition='crosses'`` is often but not
always identical to that with ``decomposition=None``. It tends to give a
closer approximation than ``decomposition='sequence'``, at a performance
that is fairly comparable. The individual cross-shaped elements are not
limited to extent (3, 3) in size. Unlike the 'seqeuence' decomposition, the
'crosses' decomposition can also accurately approximate the shape of disks
with ``strict_radius=True``. The method is based on an adaption of
algorithm 1 given in [4]_.
References
----------
.. [1] <NAME> and <NAME>. Decomposition of structuring elements for
optimal implementation of morphological operations. In Proceedings:
1997 IEEE Workshop on Nonlinear Signal and Image Processing, London,
UK.
https://www.iwaenc.org/proceedings/1997/nsip97/pdf/scan/ns970226.pdf
.. [2] https://en.wikipedia.org/wiki/Hexadecagon
.. [3] <NAME> and <NAME>. Optimal 3 × 3 decomposable disks for
morphological transformations. Image and Vision Computing, Vol. 15,
Issue 11, 1997.
:DOI:`10.1016/S0262-8856(97)00026-7`
.. [4] <NAME>. and <NAME>. Decomposition of Separable and Symmetric
Convex Templates. Proc. SPIE 1350, Image Algebra and Morphological
Image Processing, (1 November 1990).
:DOI:`10.1117/12.23608`
"""
if decomposition is None:
L = np.arange(-radius, radius + 1)
X, Y = np.meshgrid(L, L)
if not strict_radius:
radius += 0.5
return np.array((X ** 2 + Y ** 2) <= radius ** 2, dtype=dtype)
elif decomposition == 'sequence':
sequence = _nsphere_series_decomposition(radius, ndim=2, dtype=dtype)
elif decomposition == 'crosses':
fp = disk(radius, dtype, strict_radius=strict_radius,
decomposition=None)
sequence = _cross_decomposition(fp)
return sequence
def _cross(r0, r1, dtype=np.uint8):
"""Cross-shaped structuring element of shape (r0, r1).
Only the central row and column are ones.
"""
s0 = int(2 * r0 + 1)
s1 = int(2 * r1 + 1)
c = np.zeros((s0, s1), dtype=dtype)
if r1 != 0:
c[r0, :] = 1
if r0 != 0:
c[:, r1] = 1
return c
def _cross_decomposition(footprint, dtype=np.uint8):
""" Decompose a symmetric convex footprint into cross-shaped elements.
This is a decomposition of the footprint into a sequence of
(possibly asymmetric) cross-shaped elements. This technique was proposed in
[1]_ and corresponds roughly to algorithm 1 of that publication (some
details had to be modified to get reliable operation).
.. [1] <NAME>. and <NAME>. Decomposition of Separable and Symmetric
Convex Templates. Proc. SPIE 1350, Image Algebra and Morphological
Image Processing, (1 November 1990).
:DOI:`10.1117/12.23608`
"""
quadrant = footprint[footprint.shape[0] // 2:, footprint.shape[1] // 2:]
col_sums = quadrant.sum(0, dtype=int)
col_sums = np.concatenate((col_sums, np.asarray([0], dtype=int)))
i_prev = 0
idx = {}
sum0 = 0
for i in range(col_sums.size - 1):
if col_sums[i] > col_sums[i + 1]:
if i == 0:
continue
key = (col_sums[i_prev] - col_sums[i], i - i_prev)
sum0 += key[0]
if key not in idx:
idx[key] = 1
else:
idx[key] += 1
i_prev = i
n = quadrant.shape[0] - 1 - sum0
if n > 0:
key = (n, 0)
idx[key] = idx.get(key, 0) + 1
return tuple([(_cross(r0, r1, dtype), n) for (r0, r1), n in idx.items()])
def ellipse(width, height, dtype=np.uint8, *, decomposition=None):
"""Generates a flat, ellipse-shaped footprint.
Every pixel along the perimeter of ellipse satisfies
the equation ``(x/width+1)**2 + (y/height+1)**2 = 1``.
Parameters
----------
width : int
The width of the ellipse-shaped footprint.
height : int
The height of the ellipse-shaped footprint.
Other Parameters
----------------
dtype : data-type, optional
The data type of the footprint.
decomposition : {None, 'crosses'}, optional
If None, a single array is returned. For 'sequence', a tuple of smaller
footprints is returned. Applying this series of smaller footprints will
given an identical result to a single, larger footprint, but with
better computational performance. See Notes for more details.
Returns
-------
footprint : ndarray
The footprint where elements of the neighborhood are 1 and 0 otherwise.
The footprint will have shape ``(2 * height + 1, 2 * width + 1)``.
Notes
-----
When `decomposition` is not None, each element of the `footprint`
tuple is a 2-tuple of the form ``(ndarray, num_iter)`` that specifies a
footprint array and the number of iterations it is to be applied.
The ellipse produced by the ``decomposition='crosses'`` is often but not
always identical to that with ``decomposition=None``. The method is based
on an adaption of algorithm 1 given in [1]_.
References
----------
.. [1] <NAME> <NAME>. Decomposition of Separable and Symmetric
Convex Templates. Proc. SPIE 1350, Image Algebra and Morphological
Image Processing, (1 November 1990).
:DOI:`10.1117/12.23608`
Examples
--------
>>> from skimage.morphology import footprints
>>> footprints.ellipse(5, 3)
array([[0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0]], dtype=uint8)
"""
if decomposition is None:
footprint = np.zeros((2 * height + 1, 2 * width + 1), dtype=dtype)
rows, cols = draw.ellipse(height, width, height + 1, width + 1)
footprint[rows, cols] = 1
return footprint
elif decomposition == 'crosses':
fp = ellipse(width, height, dtype, decomposition=None)
sequence = _cross_decomposition(fp)
return sequence
def cube(width, dtype=np.uint8, *, decomposition=None):
""" Generates a cube-shaped footprint.
This is the 3D equivalent of a square.
Every pixel along the perimeter has a chessboard distance
no greater than radius (radius=floor(width/2)) pixels.
Parameters
----------
width : int
The width, height and depth of the cube.
Other Parameters
----------------
dtype : data-type, optional
The data type of the footprint.
decomposition : {None, 'separable', 'sequence'}, optional
If None, a single array is returned. For 'sequence', a tuple of smaller
footprints is returned. Applying this series of smaller footprints will
given an identical result to a single, larger footprint, but often with
better computational performance. See Notes for more details.
Returns
-------
footprint : ndarray or tuple
The footprint where elements of the neighborhood are 1 and 0 otherwise.
When `decomposition` is None, this is just a numpy.ndarray. Otherwise,
this will be a tuple whose length is equal to the number of unique
structuring elements to apply (see Notes for more detail)
Notes
-----
When `decomposition` is not None, each element of the `footprint`
tuple is a 2-tuple of the form ``(ndarray, num_iter)`` that specifies a
footprint array and the number of iterations it is to be applied.
For binary morphology, using ``decomposition='sequence'``
was observed to give better performance, with the magnitude of the
performance increase rapidly increasing with footprint size. For grayscale
morphology with square footprints, it is recommended to use
``decomposition=None`` since the internal SciPy functions that are called
already have a fast implementation based on separable 1D sliding windows.
The 'sequence' decomposition mode only supports odd valued `width`. If
`width` is even, the sequence used will be identical to the 'separable'
mode.
"""
if decomposition is None:
return np.ones((width, width, width), dtype=dtype)
if decomposition == 'separable' or width % 2 == 0:
sequence = [(np.ones((width, 1, 1), dtype=dtype), 1),
(np.ones((1, width, 1), dtype=dtype), 1),
(np.ones((1, 1, width), dtype=dtype), 1)]
elif decomposition == 'sequence':
# only handles odd widths
sequence = [
(np.ones((3, 3, 3), dtype=dtype), _decompose_size(width, 3))
]
else:
raise ValueError(f"Unrecognized decomposition: {decomposition}")
return tuple(sequence)
def octahedron(radius, dtype=np.uint8, *, decomposition=None):
"""Generates a octahedron-shaped footprint.
This is the 3D equivalent of a diamond.
A pixel is part of the neighborhood (i.e. labeled 1) if
the city block/Manhattan distance between it and the center of
the neighborhood is no greater than radius.
Parameters
----------
radius : int
The radius of the octahedron-shaped footprint.
Other Parameters
----------------
dtype : data-type, optional
The data type of the footprint.
decomposition : {None, 'sequence'}, optional
If None, a single array is returned. For 'sequence', a tuple of smaller
footprints is returned. Applying this series of smaller footprints will
given an identical result to a single, larger footprint, but with
better computational performance. See Notes for more details.
Returns
-------
footprint : ndarray or tuple
The footprint where elements of the neighborhood are 1 and 0 otherwise.
When `decomposition` is None, this is just a numpy.ndarray. Otherwise,
this will be a tuple whose length is equal to the number of unique
structuring elements to apply (see Notes for more detail)
Notes
-----
When `decomposition` is not None, each element of the `footprint`
tuple is a 2-tuple of the form ``(ndarray, num_iter)`` that specifies a
footprint array and the number of iterations it is to be applied.
For either binary or grayscale morphology, using
``decomposition='sequence'`` was observed to have a performance benefit,
with the magnitude of the benefit increasing with increasing footprint
size.
"""
# note that in contrast to diamond(), this method allows non-integer radii
if decomposition is None:
n = 2 * radius + 1
Z, Y, X = np.mgrid[-radius:radius:n * 1j,
-radius:radius:n * 1j,
-radius:radius:n * 1j]
s = np.abs(X) + np.abs(Y) + np.abs(Z)
footprint = np.array(s <= radius, dtype=dtype)
elif decomposition == 'sequence':
fp = octahedron(1, dtype=dtype, decomposition=None)
nreps = _decompose_size(2 * radius + 1, fp.shape[0])
footprint = ((fp, nreps),)
else:
raise ValueError(f"Unrecognized decomposition: {decomposition}")
return footprint
def ball(radius, dtype=np.uint8, *, strict_radius=True, decomposition=None):
"""Generates a ball-shaped footprint.
This is the 3D equivalent of a disk.
A pixel is within the neighborhood if the Euclidean distance between
it and the origin is no greater than radius.
Parameters
----------
radius : int
The radius of the ball-shaped footprint.
Other Parameters
----------------
dtype : data-type, optional
The data type of the footprint.
strict_radius : bool, optional
If False, extend the radius by 0.5. This allows the circle to expand
further within a cube that remains of size ``2 * radius + 1`` along
each axis. This parameter is ignored if decomposition is not None.
decomposition : {None, 'sequence'}, optional
If None, a single array is returned. For 'sequence', a tuple of smaller
footprints is returned. Applying this series of smaller footprints will
given a result equivalent to a single, larger footprint, but with
better computational performance. For ball footprints, the sequence
decomposition is not exactly equivalent to decomposition=None.
See Notes for more details.
Returns
-------
footprint : ndarray or tuple
The footprint where elements of the neighborhood are 1 and 0 otherwise.
Notes
-----
The disk produced by the decomposition='sequence' mode is not identical
to that with decomposition=None. Here we extend the approach taken in [1]_
for disks to the 3D case, using 3-dimensional extensions of the "square",
"diamond" and "t-shaped" elements from that publication. All of these
elementary elements have size ``(3,) * ndim``. We numerically computed the
number of repetitions of each element that gives the closest match to the
ball computed with kwargs ``strict_radius=False, decomposition=None``.
Empirically, the equivalent composite footprint to the sequence
decomposition approaches a rhombicuboctahedron (26-faces [2]_).
References
----------
.. [1] <NAME> and <NAME>. Decomposition of structuring elements for
optimal implementation of morphological operations. In Proceedings:
1997 IEEE Workshop on Nonlinear Signal and Image Processing, London,
UK.
https://www.iwaenc.org/proceedings/1997/nsip97/pdf/scan/ns970226.pdf
.. [2] https://en.wikipedia.org/wiki/Rhombicuboctahedron
"""
if decomposition is None:
n = 2 * radius + 1
Z, Y, X = np.mgrid[-radius:radius:n * 1j,
-radius:radius:n * 1j,
-radius:radius:n * 1j]
s = X ** 2 + Y ** 2 + Z ** 2
if not strict_radius:
radius += 0.5
return np.array(s <= radius * radius, dtype=dtype)
elif decomposition == 'sequence':
sequence = _nsphere_series_decomposition(radius, ndim=3, dtype=dtype)
else:
raise ValueError(f"Unrecognized decomposition: {decomposition}")
return sequence
def octagon(m, n, dtype=np.uint8, *, decomposition=None):
"""Generates an octagon shaped footprint.
For a given size of (m) horizontal and vertical sides
and a given (n) height or width of slanted sides octagon is generated.
The slanted sides are 45 or 135 degrees to the horizontal axis
and hence the widths and heights are equal. The overall size of the
footprint along a single axis will be ``m + 2 * n``.
Parameters
----------
m : int
The size of the horizontal and vertical sides.
n : int
The height or width of the slanted sides.
Other Parameters
----------------
dtype : data-type, optional
The data type of the footprint.
decomposition : {None, 'sequence'}, optional
If None, a single array is returned. For 'sequence', a tuple of smaller
footprints is returned. Applying this series of smaller footprints will
given an identical result to a single, larger footprint, but with
better computational performance. See Notes for more details.
Returns
-------
footprint : ndarray or tuple
The footprint where elements of the neighborhood are 1 and 0 otherwise.
When `decomposition` is None, this is just a numpy.ndarray. Otherwise,
this will be a tuple whose length is equal to the number of unique
structuring elements to apply (see Notes for more detail)
Notes
-----
When `decomposition` is not None, each element of the `footprint`
tuple is a 2-tuple of the form ``(ndarray, num_iter)`` that specifies a
footprint array and the number of iterations it is to be applied.
For either binary or grayscale morphology, using
``decomposition='sequence'`` was observed to have a performance benefit,
with the magnitude of the benefit increasing with increasing footprint
size.
"""
if m == n == 0:
raise ValueError("m and n cannot both be zero")
# TODO?: warn about even footprint size when m is even
if decomposition is None:
from . import convex_hull_image
footprint = np.zeros((m + 2 * n, m + 2 * n))
footprint[0, n] = 1
footprint[n, 0] = 1
footprint[0, m + n - 1] = 1
footprint[m + n - 1, 0] = 1
footprint[-1, n] = 1
footprint[n, -1] = 1
footprint[-1, m + n - 1] = 1
footprint[m + n - 1, -1] = 1
footprint = convex_hull_image(footprint).astype(dtype)
elif decomposition == 'sequence':
# special handling for edge cases with small m and/or n
if m <= 2 and n <= 2:
return ((octagon(m, n, dtype=dtype, decomposition=None), 1),)
# general approach for larger m and/or n
if m == 0:
m = 2
n -= 1
sequence = []
if m > 1:
sequence += list(square(m, dtype=dtype, decomposition='sequence'))
if n > 0:
sequence += [(diamond(1, dtype=dtype, decomposition=None), n)]
footprint = tuple(sequence)
else:
raise ValueError(f"Unrecognized decomposition: {decomposition}")
return footprint
def star(a, dtype=np.uint8):
"""Generates a star shaped footprint.
Start has 8 vertices and is an overlap of square of size `2*a + 1`
with its 45 degree rotated version.
The slanted sides are 45 or 135 degrees to the horizontal axis.
Parameters
----------
a : int
Parameter deciding the size of the star structural element. The side
of the square array returned is `2*a + 1 + 2*floor(a / 2)`.
Other Parameters
----------------
dtype : data-type, optional
The data type of the footprint.
Returns
-------
footprint : ndarray
The footprint where elements of the neighborhood are 1 and 0 otherwise.
"""
from . import convex_hull_image
if a == 1:
bfilter = np.zeros((3, 3), dtype)
bfilter[:] = 1
return bfilter
m = 2 * a + 1
n = a // 2
footprint_square = np.zeros((m + 2 * n, m + 2 * n))
footprint_square[n: m + n, n: m + n] = 1
c = (m + 2 * n - 1) // 2
footprint_rotated = np.zeros((m + 2 * n, m + 2 * n))
footprint_rotated[0, c] = footprint_rotated[-1, c] = 1
footprint_rotated[c, 0] = footprint_rotated[c, -1] = 1
footprint_rotated = convex_hull_image(footprint_rotated).astype(int)
footprint = footprint_square + footprint_rotated
footprint[footprint > 0] = 1
return footprint.astype(dtype)
<file_sep>/skimage/io/tests/test_imageio.py
from tempfile import NamedTemporaryFile
import numpy as np
from skimage.io import imread, imsave,plugin_order
from skimage._shared import testing
from skimage._shared.testing import fetch
import pytest
def test_prefered_plugin():
# Don't call use_plugin("imageio") before, this way we test that imageio is used
# by default
order = plugin_order()
assert order["imread"][0] == "imageio"
assert order["imsave"][0] == "imageio"
assert order["imread_collection"][0] == "imageio"
def test_imageio_as_gray():
img = imread(fetch('data/color.png'), as_gray=True)
assert img.ndim == 2
assert img.dtype == np.float64
img = imread(fetch('data/camera.png'), as_gray=True)
# check that conversion does not happen for a gray image
assert np.sctype2char(img.dtype) in np.typecodes['AllInteger']
def test_imageio_palette():
img = imread(fetch('data/palette_color.png'))
assert img.ndim == 3
def test_imageio_truncated_jpg():
# imageio>2.0 uses Pillow / PIL to try and load the file.
# Oddly, PIL explicitly raises a SyntaxError when the file read fails.
# The exception type changed from SyntaxError to OSError in PIL 8.2.0, so
# allow for either to be raised.
with testing.raises((OSError, SyntaxError)):
imread(fetch('data/truncated.jpg'))
class TestSave:
@pytest.mark.parametrize(
"shape,dtype", [
# float32, float64 can't be saved as PNG and raise
# uint32 is not roundtripping properly
((10, 10), np.uint8),
((10, 10), np.uint16),
((10, 10, 2), np.uint8),
((10, 10, 3), np.uint8),
((10, 10, 4), np.uint8),
]
)
def test_imsave_roundtrip(self, shape, dtype, tmp_path):
if np.issubdtype(dtype, np.floating):
min_ = 0
max_ = 1
else:
min_ = 0
max_ = np.iinfo(dtype).max
expected = np.linspace(
min_, max_,
endpoint=True,
num=np.prod(shape),
dtype=dtype
)
expected = expected.reshape(shape)
file_path = tmp_path / "roundtrip.png"
imsave(file_path, expected)
actual = imread(file_path)
np.testing.assert_array_almost_equal(actual, expected)
def test_bool_array_save(self):
with NamedTemporaryFile(suffix='.png') as f:
fname = f.name
with pytest.warns(UserWarning, match=r'.* is a boolean image'):
a = np.zeros((5, 5), bool)
a[2, 2] = True
imsave(fname, a)
def test_return_class():
testing.assert_equal(
type(imread(fetch('data/color.png'))),
np.ndarray
)
<file_sep>/skimage/restoration/__init__.pyi
# Explicitly setting `__all__` is necessary for type inference engines
# to know which symbols are exported. See
# https://peps.python.org/pep-0484/#stub-files
__all__ = ['wiener',
'unsupervised_wiener',
'richardson_lucy',
'unwrap_phase',
'denoise_tv_bregman',
'denoise_tv_chambolle',
'denoise_bilateral',
'denoise_wavelet',
'denoise_nl_means',
'denoise_invariant',
'estimate_sigma',
'inpaint_biharmonic',
'cycle_spin',
'calibrate_denoiser',
'rolling_ball',
'ellipsoid_kernel',
'ball_kernel',
]
from .deconvolution import wiener, unsupervised_wiener, richardson_lucy
from .unwrap import unwrap_phase
from ._denoise import (
denoise_tv_chambolle,
denoise_tv_bregman,
denoise_bilateral,
denoise_wavelet,
estimate_sigma
)
from ._cycle_spin import cycle_spin
from .non_local_means import denoise_nl_means
from .inpaint import inpaint_biharmonic
from .j_invariant import calibrate_denoiser, denoise_invariant
from ._rolling_ball import rolling_ball, ball_kernel, ellipsoid_kernel
<file_sep>/skimage/segmentation/tests/test_boundaries.py
import numpy as np
import pytest
from numpy.testing import assert_array_equal, assert_allclose
from skimage._shared.utils import _supported_float_type
from skimage.segmentation import find_boundaries, mark_boundaries
white = (1, 1, 1)
def test_find_boundaries():
image = np.zeros((10, 10), dtype=np.uint8)
image[2:7, 2:7] = 1
ref = np.array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 1, 1, 1, 1, 0, 0, 0],
[0, 1, 1, 1, 1, 1, 1, 1, 0, 0],
[0, 1, 1, 0, 0, 0, 1, 1, 0, 0],
[0, 1, 1, 0, 0, 0, 1, 1, 0, 0],
[0, 1, 1, 0, 0, 0, 1, 1, 0, 0],
[0, 1, 1, 1, 1, 1, 1, 1, 0, 0],
[0, 0, 1, 1, 1, 1, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])
result = find_boundaries(image)
assert_array_equal(result, ref)
def test_find_boundaries_bool():
image = np.zeros((5, 5), dtype=bool)
image[2:5, 2:5] = True
ref = np.array([[False, False, False, False, False],
[False, False, True, True, True],
[False, True, True, True, True],
[False, True, True, False, False],
[False, True, True, False, False]], dtype=bool)
result = find_boundaries(image)
assert_array_equal(result, ref)
@pytest.mark.parametrize(
'dtype', [np.uint8, np.float16, np.float32, np.float64]
)
def test_mark_boundaries(dtype):
image = np.zeros((10, 10), dtype=dtype)
label_image = np.zeros((10, 10), dtype=np.uint8)
label_image[2:7, 2:7] = 1
ref = np.array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 1, 1, 1, 1, 0, 0, 0],
[0, 1, 1, 1, 1, 1, 1, 1, 0, 0],
[0, 1, 1, 0, 0, 0, 1, 1, 0, 0],
[0, 1, 1, 0, 0, 0, 1, 1, 0, 0],
[0, 1, 1, 0, 0, 0, 1, 1, 0, 0],
[0, 1, 1, 1, 1, 1, 1, 1, 0, 0],
[0, 0, 1, 1, 1, 1, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])
marked = mark_boundaries(image, label_image, color=white, mode='thick')
assert marked.dtype == _supported_float_type(dtype)
result = np.mean(marked, axis=-1)
assert_array_equal(result, ref)
ref = np.array([[0, 2, 2, 2, 2, 2, 2, 2, 0, 0],
[2, 2, 1, 1, 1, 1, 1, 2, 2, 0],
[2, 1, 1, 1, 1, 1, 1, 1, 2, 0],
[2, 1, 1, 2, 2, 2, 1, 1, 2, 0],
[2, 1, 1, 2, 0, 2, 1, 1, 2, 0],
[2, 1, 1, 2, 2, 2, 1, 1, 2, 0],
[2, 1, 1, 1, 1, 1, 1, 1, 2, 0],
[2, 2, 1, 1, 1, 1, 1, 2, 2, 0],
[0, 2, 2, 2, 2, 2, 2, 2, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])
marked = mark_boundaries(image, label_image, color=white,
outline_color=(2, 2, 2), mode='thick')
result = np.mean(marked, axis=-1)
assert_array_equal(result, ref)
def test_mark_boundaries_bool():
image = np.zeros((10, 10), dtype=bool)
label_image = np.zeros((10, 10), dtype=np.uint8)
label_image[2:7, 2:7] = 1
ref = np.array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 1, 1, 1, 1, 0, 0, 0],
[0, 1, 1, 1, 1, 1, 1, 1, 0, 0],
[0, 1, 1, 0, 0, 0, 1, 1, 0, 0],
[0, 1, 1, 0, 0, 0, 1, 1, 0, 0],
[0, 1, 1, 0, 0, 0, 1, 1, 0, 0],
[0, 1, 1, 1, 1, 1, 1, 1, 0, 0],
[0, 0, 1, 1, 1, 1, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]])
marked = mark_boundaries(image, label_image, color=white, mode='thick')
result = np.mean(marked, axis=-1)
assert_array_equal(result, ref)
@pytest.mark.parametrize('dtype', [np.float16, np.float32, np.float64])
def test_mark_boundaries_subpixel(dtype):
labels = np.array([[0, 0, 0, 0],
[0, 0, 5, 0],
[0, 1, 5, 0],
[0, 0, 5, 0],
[0, 0, 0, 0]], dtype=np.uint8)
np.random.seed(0)
image = np.round(np.random.rand(*labels.shape), 2)
image = image.astype(dtype, copy=False)
marked = mark_boundaries(image, labels, color=white, mode='subpixel')
assert marked.dtype == _supported_float_type(dtype)
marked_proj = np.round(np.mean(marked, axis=-1), 2)
ref_result = np.array(
[[ 0.55, 0.63, 0.72, 0.69, 0.6 , 0.55, 0.54],
[ 0.45, 0.58, 0.72, 1. , 1. , 1. , 0.69],
[ 0.42, 0.54, 0.65, 1. , 0.44, 1. , 0.89],
[ 0.69, 1. , 1. , 1. , 0.69, 1. , 0.83],
[ 0.96, 1. , 0.38, 1. , 0.79, 1. , 0.53],
[ 0.89, 1. , 1. , 1. , 0.38, 1. , 0.16],
[ 0.57, 0.78, 0.93, 1. , 0.07, 1. , 0.09],
[ 0.2 , 0.52, 0.92, 1. , 1. , 1. , 0.54],
[ 0.02, 0.35, 0.83, 0.9 , 0.78, 0.81, 0.87]])
assert_allclose(marked_proj, ref_result, atol=0.01)
@pytest.mark.parametrize('mode', ['thick', 'inner', 'outer', 'subpixel'])
def test_boundaries_constant_image(mode):
"""A constant-valued image has not boundaries."""
ones = np.ones((8, 8), dtype=int)
b = find_boundaries(ones, mode=mode)
assert np.all(b == 0)
<file_sep>/doc/examples/features_detection/plot_fisher_vector.py
"""
===============================
Fisher vector feature encoding
===============================
A Fisher vector is an image feature encoding and quantization technique that
can be seen as a soft or probabilistic version of the popular
bag-of-visual-words or VLAD algorithms. Images are modelled using a visual
vocabulary which is estimated using a K-mode Gaussian mixture model trained on
low-level image features such as SIFT or ORB descriptors. The Fisher vector
itself is a concatenation of the gradients of the Gaussian mixture model (GMM)
with respect to its parameters - mixture weights, means, and covariance
matrices.
In this example, we compute Fisher vectors for the digits dataset in
scikit-learn, and train a classifier on these representations.
Please note that scikit-learn is required to run this example.
"""
from matplotlib import pyplot as plt
import numpy as np
from sklearn.datasets import load_digits
from sklearn.metrics import classification_report, ConfusionMatrixDisplay
from sklearn.model_selection import train_test_split
from sklearn.svm import LinearSVC
from skimage.transform import resize
from skimage.feature import fisher_vector, ORB, learn_gmm
data = load_digits()
images = data.images
targets = data.target
# Resize images so that ORB detects interest points for all images
images = np.array([resize(image, (80, 80)) for image in images])
# Compute ORB descriptors for each image
descriptors = []
for image in images:
detector_extractor = ORB(n_keypoints=5, harris_k=0.01)
detector_extractor.detect_and_extract(image)
descriptors.append(detector_extractor.descriptors.astype('float32'))
# Split the data into training and testing subsets
train_descriptors, test_descriptors, train_targets, test_targets = \
train_test_split(descriptors, targets)
# Train a K-mode GMM
k = 16
gmm = learn_gmm(train_descriptors, n_modes=k)
# Compute the Fisher vectors
training_fvs = np.array([
fisher_vector(descriptor_mat, gmm)
for descriptor_mat in train_descriptors
])
testing_fvs = np.array([
fisher_vector(descriptor_mat, gmm)
for descriptor_mat in test_descriptors
])
svm = LinearSVC().fit(training_fvs, train_targets)
predictions = svm.predict(testing_fvs)
print(classification_report(test_targets, predictions))
ConfusionMatrixDisplay.from_estimator(
svm,
testing_fvs,
test_targets,
cmap=plt.cm.Blues,
)
plt.show()
<file_sep>/skimage/_shared/_dependency_checks.py
from .version_requirements import is_installed
has_mpl = is_installed("matplotlib", ">=3.3")
<file_sep>/doc/examples/data/plot_scientific.py
"""
=================
Scientific images
=================
The title of each image indicates the name of the function.
"""
import matplotlib.pyplot as plt
import matplotlib
import numpy as np
from skimage import data
matplotlib.rcParams['font.size'] = 18
images = ('hubble_deep_field',
'immunohistochemistry',
'lily',
'microaneurysms',
'moon',
'retina',
'shepp_logan_phantom',
'skin',
'cell',
'human_mitosis',
)
for name in images:
caller = getattr(data, name)
image = caller()
plt.figure()
plt.title(name)
if image.ndim == 2:
plt.imshow(image, cmap=plt.cm.gray)
else:
plt.imshow(image)
plt.show()
############################################################################
# Thumbnail image for the gallery
# sphinx_gallery_thumbnail_number = -1
fig, axs = plt.subplots(nrows=3, ncols=3)
for ax in axs.flat:
ax.axis("off")
axs[0, 0].imshow(data.hubble_deep_field())
axs[0, 1].imshow(data.immunohistochemistry())
axs[0, 2].imshow(data.lily())
axs[1, 0].imshow(data.microaneurysms())
axs[1, 1].imshow(data.moon(), cmap=plt.cm.gray)
axs[1, 2].imshow(data.retina())
axs[2, 0].imshow(data.shepp_logan_phantom(), cmap=plt.cm.gray)
axs[2, 1].imshow(data.skin())
further_img = np.full((300, 300), 255)
for xpos in [100, 150, 200]:
further_img[150 - 10 : 150 + 10, xpos - 10 : xpos + 10] = 0
axs[2, 2].imshow(further_img, cmap=plt.cm.gray)
plt.subplots_adjust(wspace=-0.3, hspace=0.1)
<file_sep>/doc/examples/segmentation/plot_regionprops_table.py
"""
===================================================
Explore and visualize region properties with pandas
===================================================
This toy example shows how to compute the size of every labelled region in a
series of 10 images. We use 2D images and then 3D images. The blob-like
regions are generated synthetically. As the volume fraction (i.e., ratio of
pixels or voxels covered by the blobs) increases, the number of blobs
(regions) decreases, and the size (area or volume) of a single region can get
larger and larger. The area (size) values are available in a pandas-compatible
format, which makes for convenient data analysis and visualization.
Besides area, many other region properties are available.
"""
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
from skimage import data, measure
fractions = np.linspace(0.05, 0.5, 10)
#####################################################################
# 2D images
# =========
images = [data.binary_blobs(volume_fraction=f) for f in fractions]
labeled_images = [measure.label(image) for image in images]
properties = ['label', 'area']
tables = [measure.regionprops_table(image, properties=properties)
for image in labeled_images]
tables = [pd.DataFrame(table) for table in tables]
for fraction, table in zip(fractions, tables):
table['volume fraction'] = fraction
areas = pd.concat(tables, axis=0)
# Create custom grid of subplots
grid = plt.GridSpec(2, 2)
ax1 = plt.subplot(grid[0, 0])
ax2 = plt.subplot(grid[0, 1])
ax = plt.subplot(grid[1, :])
# Show image with lowest volume fraction
ax1.imshow(images[0], cmap='gray_r')
ax1.set_axis_off()
ax1.set_title(f'fraction {fractions[0]}')
# Show image with highest volume fraction
ax2.imshow(images[-1], cmap='gray_r')
ax2.set_axis_off()
ax2.set_title(f'fraction {fractions[-1]}')
# Plot area vs volume fraction
areas.plot(x='volume fraction', y='area', kind='scatter', ax=ax)
plt.show()
#####################################################################
# In the scatterplot, many points seem to be overlapping at low area values.
# To get a better sense of the distribution, we may want to add some 'jitter'
# to the visualization. To this end, we use `stripplot` (from `seaborn`, the
# Python library dedicated to statistical data visualization) with argument
# `jitter=True`.
fig, ax = plt.subplots()
sns.stripplot(x='volume fraction', y='area', data=areas, jitter=True,
ax=ax)
# Fix floating point rendering
ax.set_xticklabels([f'{frac:.2f}' for frac in fractions])
plt.show()
#####################################################################
# 3D images
# =========
# Doing the same analysis in 3D, we find a much more dramatic behaviour: blobs
# coalesce into a single, giant piece as the volume fraction crosses ~0.25.
# This corresponds to the `percolation threshold
# <https://en.wikipedia.org/wiki/Percolation_threshold>`_ in statistical
# physics and graph theory.
images = [data.binary_blobs(length=128, n_dim=3, volume_fraction=f)
for f in fractions]
labeled_images = [measure.label(image) for image in images]
properties = ['label', 'area']
tables = [measure.regionprops_table(image, properties=properties)
for image in labeled_images]
tables = [pd.DataFrame(table) for table in tables]
for fraction, table in zip(fractions, tables):
table['volume fraction'] = fraction
blob_volumes = pd.concat(tables, axis=0)
fig, ax = plt.subplots()
sns.stripplot(x='volume fraction', y='area', data=blob_volumes, jitter=True,
ax=ax)
ax.set_ylabel('blob size (3D)')
# Fix floating point rendering
ax.set_xticklabels([f'{frac:.2f}' for frac in fractions])
plt.show()
<file_sep>/skimage/measure/_moments_analytical.py
"""Analytical transformations from raw image moments to central moments.
The expressions for the 2D central moments of order <=2 are often given in
textbooks. Expressions for higher orders and dimensions were generated in SymPy
using ``tools/precompute/moments_sympy.py`` in the GitHub repository.
"""
import itertools
import math
import numpy as np
def _moments_raw_to_central_fast(moments_raw):
"""Analytical formulae for 2D and 3D central moments of order < 4.
`moments_raw_to_central` will automatically call this function when
ndim < 4 and order < 4.
Parameters
----------
moments_raw : ndarray
The raw moments.
Returns
-------
moments_central : ndarray
The central moments.
"""
ndim = moments_raw.ndim
order = moments_raw.shape[0] - 1
float_dtype = moments_raw.dtype
# convert to float64 during the computation for better accuracy
moments_raw = moments_raw.astype(np.float64, copy=False)
moments_central = np.zeros_like(moments_raw)
if order >= 4 or ndim not in [2, 3]:
raise ValueError(
"This function only supports 2D or 3D moments of order < 4."
)
m = moments_raw
if ndim == 2:
cx = m[1, 0] / m[0, 0]
cy = m[0, 1] / m[0, 0]
moments_central[0, 0] = m[0, 0]
# Note: 1st order moments are both 0
if order > 1:
# 2nd order moments
moments_central[1, 1] = m[1, 1] - cx*m[0, 1]
moments_central[2, 0] = m[2, 0] - cx*m[1, 0]
moments_central[0, 2] = m[0, 2] - cy*m[0, 1]
if order > 2:
# 3rd order moments
moments_central[2, 1] = (m[2, 1] - 2*cx*m[1, 1] - cy*m[2, 0]
+ cx**2*m[0, 1] + cy*cx*m[1, 0])
moments_central[1, 2] = (m[1, 2] - 2*cy*m[1, 1] - cx*m[0, 2]
+ 2*cy*cx*m[0, 1])
moments_central[3, 0] = m[3, 0] - 3*cx*m[2, 0] + 2*cx**2*m[1, 0]
moments_central[0, 3] = m[0, 3] - 3*cy*m[0, 2] + 2*cy**2*m[0, 1]
else:
# 3D case
cx = m[1, 0, 0] / m[0, 0, 0]
cy = m[0, 1, 0] / m[0, 0, 0]
cz = m[0, 0, 1] / m[0, 0, 0]
moments_central[0, 0, 0] = m[0, 0, 0]
# Note: all first order moments are 0
if order > 1:
# 2nd order moments
moments_central[0, 0, 2] = -cz*m[0, 0, 1] + m[0, 0, 2]
moments_central[0, 1, 1] = -cy*m[0, 0, 1] + m[0, 1, 1]
moments_central[0, 2, 0] = -cy*m[0, 1, 0] + m[0, 2, 0]
moments_central[1, 0, 1] = -cx*m[0, 0, 1] + m[1, 0, 1]
moments_central[1, 1, 0] = -cx*m[0, 1, 0] + m[1, 1, 0]
moments_central[2, 0, 0] = -cx*m[1, 0, 0] + m[2, 0, 0]
if order > 2:
# 3rd order moments
moments_central[0, 0, 3] = (2*cz**2*m[0, 0, 1]
- 3*cz*m[0, 0, 2]
+ m[0, 0, 3])
moments_central[0, 1, 2] = (-cy*m[0, 0, 2]
+ 2*cz*(cy*m[0, 0, 1] - m[0, 1, 1])
+ m[0, 1, 2])
moments_central[0, 2, 1] = (cy**2*m[0, 0, 1] - 2*cy*m[0, 1, 1]
+ cz*(cy*m[0, 1, 0] - m[0, 2, 0])
+ m[0, 2, 1])
moments_central[0, 3, 0] = (2*cy**2*m[0, 1, 0]
- 3*cy*m[0, 2, 0]
+ m[0, 3, 0])
moments_central[1, 0, 2] = (-cx*m[0, 0, 2]
+ 2*cz*(cx*m[0, 0, 1] - m[1, 0, 1])
+ m[1, 0, 2])
moments_central[1, 1, 1] = (-cx*m[0, 1, 1]
+ cy*(cx*m[0, 0, 1] - m[1, 0, 1])
+ cz*(cx*m[0, 1, 0] - m[1, 1, 0])
+ m[1, 1, 1])
moments_central[1, 2, 0] = (-cx*m[0, 2, 0]
- 2*cy*(-cx*m[0, 1, 0] + m[1, 1, 0])
+ m[1, 2, 0])
moments_central[2, 0, 1] = (cx**2*m[0, 0, 1]
- 2*cx*m[1, 0, 1]
+ cz*(cx*m[1, 0, 0] - m[2, 0, 0])
+ m[2, 0, 1])
moments_central[2, 1, 0] = (cx**2*m[0, 1, 0]
- 2*cx*m[1, 1, 0]
+ cy*(cx*m[1, 0, 0] - m[2, 0, 0])
+ m[2, 1, 0])
moments_central[3, 0, 0] = (2*cx**2*m[1, 0, 0]
- 3*cx*m[2, 0, 0]
+ m[3, 0, 0])
return moments_central.astype(float_dtype, copy=False)
def moments_raw_to_central(moments_raw):
ndim = moments_raw.ndim
order = moments_raw.shape[0] - 1
if ndim in [2, 3] and order < 4:
return _moments_raw_to_central_fast(moments_raw)
moments_central = np.zeros_like(moments_raw)
m = moments_raw
# centers as computed in centroid above
centers = tuple(m[tuple(np.eye(ndim, dtype=int))] / m[(0,)*ndim])
if ndim == 2:
# This is the general 2D formula from
# https://en.wikipedia.org/wiki/Image_moment#Central_moments
for p in range(order + 1):
for q in range(order + 1):
if p + q > order:
continue
for i in range(p + 1):
term1 = math.comb(p, i)
term1 *= (-centers[0]) ** (p - i)
for j in range(q + 1):
term2 = math.comb(q, j)
term2 *= (-centers[1]) ** (q - j)
moments_central[p, q] += term1*term2*m[i, j]
return moments_central
# The nested loops below are an n-dimensional extension of the 2D formula
# given at https://en.wikipedia.org/wiki/Image_moment#Central_moments
# iterate over all [0, order] (inclusive) on each axis
for orders in itertools.product(*((range(order + 1),) * ndim)):
# `orders` here is the index into the `moments_central` output array
if sum(orders) > order:
# skip any moment that is higher than the requested order
continue
# loop over terms from `m` contributing to `moments_central[orders]`
for idxs in itertools.product(*[range(o + 1) for o in orders]):
val = m[idxs]
for i_order, c, idx in zip(orders, centers, idxs):
val *= math.comb(i_order, idx)
val *= (-c) ** (i_order - idx)
moments_central[orders] += val
return moments_central
<file_sep>/skimage/future/__init__.py
"""Functionality with an experimental API.
.. warning::
Although you can count on the functions in this package being
around in the future, the API may change with any version update
**and will not follow the skimage two-version deprecation path**.
Therefore, use the functions herein with care, and do not use them
in production code that will depend on updated skimage versions.
"""
import lazy_loader as lazy
__getattr__, __dir__, __all__ = lazy.attach_stub(__name__, __file__)
<file_sep>/skimage/__init__.pyi
submodules = [
'color',
'data',
'draw',
'exposure',
'feature',
'filters',
'future',
'graph',
'io',
'measure',
'metrics',
'morphology',
'registration',
'restoration',
'segmentation',
'transform',
'util',
]
__all__ = submodules + ['__version__'] # noqa: F822
from . import (
color,
data,
draw,
exposure,
feature,
filters,
future,
graph,
io,
measure,
metrics,
morphology,
registration,
restoration,
segmentation,
transform,
util,
)
<file_sep>/tools/precompute/_precompute_nsphere_decompositions.py
"""Utility script that was used to precompute disk and sphere footprints in
terms of a series of small 3x3 (or 3x3x3) footprints.
This is a crude, brute force implementation that checks many combinations and
retains the one that has the minimum error between the composite footprint and
the desired one.
The generated footprints were stored as
skimage/morphology/ball_decompositions.npy
skimage/morphology/disk_decompositions.npy
Validation in `test_nsphere_series_approximation` in:
skimage/morphology/tests/test_footprints.py
"""
import numpy as np
from skimage.morphology import ball, disk
from skimage.morphology.footprints import (_t_shaped_element_series,
footprint_from_sequence)
def precompute_decompositions(
ndims=[2, 3], radius_max_per_ndim={2: 200, 3: 100}, strict_radius=False
):
assert all(d in radius_max_per_ndim for d in ndims)
best_vals = {}
for ndim in ndims:
dtype = np.uint8
# shape (3,) * ndim hyperoctahedron footprint
# i.e. d = diamond(radius=1) in 2D
# d = octahedron(radius=1) in 3D
d = np.zeros((3,) * ndim, dtype=dtype)
sl = [
slice(1, 2),
] * ndim
for ax in range(ndim):
sl[ax] = slice(None)
d[tuple(sl)] = 1
sl[ax] = slice(1, 2)
# shape (3,) * ndim hypercube footprint
sq3 = np.ones((3,) * ndim, dtype=dtype)
# shape (3, ) * ndim "T-shaped" footprints
all_t = _t_shaped_element_series(ndim=ndim, dtype=dtype)
radius_max = radius_max_per_ndim[ndim]
for radius in range(2, radius_max + 1):
if ndim == 2:
desired = disk(
radius, decomposition=None, strict_radius=strict_radius
)
elif ndim == 3:
desired = ball(
radius, decomposition=None, strict_radius=strict_radius
)
else:
raise ValueError(f"ndim={ndim} not currently supported")
all_actual = []
min_err = np.Inf
for n_t in range(radius // len(all_t) + 1):
if (n_t * len(all_t)) > radius:
n_t -= 1
len_t = n_t * len(all_t)
d_range = range(radius - len_t, -1, -1)
err_prev = np.Inf
for n_diamond in d_range:
r_rem = radius - len_t - n_diamond
n_square = r_rem
sequence = []
if n_t > 0:
sequence += [(t, n_t) for t in all_t]
if n_diamond > 0:
sequence += [(d, n_diamond)]
if n_square > 0:
sequence += [(sq3, n_square)]
sequence = tuple(sequence)
actual = footprint_from_sequence(sequence).astype(int)
all_actual.append(actual)
error = np.sum(
np.abs(desired - actual)
) # + 0.01 * n_square
if error > err_prev:
print(f"break at n_diamond = {n_diamond}")
break
err_prev = error
if error <= min_err:
min_err = error
best_vals[(ndim, radius)] = (n_t, n_diamond, n_square)
sequence = []
n_t, n_diamond, n_square = best_vals[(ndim, radius)]
print(
f'radius = {radius}, sum = {desired.sum()}, '
f'error={min_err}:\n\tn_t={n_t}, '
f'n_diamond={n_diamond}, n_square={n_square}\n'
)
if n_t > 0:
sequence += [(t, n_t) for t in all_t]
if n_diamond > 0:
sequence += [(d, n_diamond)]
if n_square > 0:
sequence += [(sq3, n_square)]
sequence = tuple(sequence)
actual = footprint_from_sequence(sequence).astype(int)
opt_vals = np.zeros((radius_max + 1, 3), dtype=np.uint8)
best_vals[(ndim, 1)] = (0, 0, 1)
for i in range(1, radius_max + 1):
opt_vals[i, :] = best_vals[(ndim, i)]
if ndim == 3:
fname = "ball_decompositions.npy"
elif ndim == 2:
fname = "disk_decompositions.npy"
else:
fname = f"{ndim}sphere_decompositions.npy"
if strict_radius:
fname = fname.replace(".npy", "_strict.npy")
np.save(fname, opt_vals)
if __name__ == "__main__":
precompute_decompositions(
ndims=[2, 3], radius_max_per_ndim={2: 250, 3: 100}, strict_radius=False
)
<file_sep>/skimage/measure/tests/test_find_contours.py
import numpy as np
from skimage.measure import find_contours
from skimage._shared.testing import assert_array_equal
import pytest
a = np.ones((8, 8), dtype=np.float32)
a[1:-1, 1] = 0
a[1, 1:-1] = 0
x, y = np.mgrid[-1:1:5j, -1:1:5j]
r = np.sqrt(x**2 + y**2)
def test_binary():
ref = [[6.0, 1.5],
[5.0, 1.5],
[4.0, 1.5],
[3.0, 1.5],
[2.0, 1.5],
[1.5, 2.0],
[1.5, 3.0],
[1.5, 4.0],
[1.5, 5.0],
[1.5, 6.0],
[1.0, 6.5],
[0.5, 6.0],
[0.5, 5.0],
[0.5, 4.0],
[0.5, 3.0],
[0.5, 2.0],
[0.5, 1.0],
[1.0, 0.5],
[2.0, 0.5],
[3.0, 0.5],
[4.0, 0.5],
[5.0, 0.5],
[6.0, 0.5],
[6.5, 1.0],
[6.0, 1.5]]
contours = find_contours(a, 0.5, positive_orientation='high')
assert len(contours) == 1
assert_array_equal(contours[0][::-1], ref)
# target contour for mask tests
mask_contour = [
[6.0, 0.5],
[5.0, 0.5],
[4.0, 0.5],
[3.0, 0.5],
[2.0, 0.5],
[1.0, 0.5],
[0.5, 1.0],
[0.5, 2.0],
[0.5, 3.0],
[0.5, 4.0],
[0.5, 5.0],
[0.5, 6.0],
[1.0, 6.5],
[1.5, 6.0],
[1.5, 5.0],
[1.5, 4.0],
[1.5, 3.0],
[1.5, 2.0],
[2.0, 1.5],
[3.0, 1.5],
[4.0, 1.5],
[5.0, 1.5],
[6.0, 1.5],
]
mask = np.ones((8, 8), dtype=bool)
# Some missing data that should result in a hole in the contour:
mask[7, 0:3] = False
@pytest.mark.parametrize("level", [0.5, None])
def test_nodata(level):
# Test missing data via NaNs in input array
b = np.copy(a)
b[~mask] = np.nan
contours = find_contours(b, level, positive_orientation='high')
assert len(contours) == 1
assert_array_equal(contours[0], mask_contour)
@pytest.mark.parametrize("level", [0.5, None])
def test_mask(level):
# Test missing data via explicit masking
contours = find_contours(a, level, positive_orientation='high', mask=mask)
assert len(contours) == 1
assert_array_equal(contours[0], mask_contour)
@pytest.mark.parametrize("level", [0, None])
def test_mask_shape(level):
bad_mask = np.ones((8, 7), dtype=bool)
with pytest.raises(ValueError, match='shape'):
find_contours(a, level, mask=bad_mask)
@pytest.mark.parametrize("level", [0, None])
def test_mask_dtype(level):
bad_mask = np.ones((8, 8), dtype=np.uint8)
with pytest.raises(TypeError, match='binary'):
find_contours(a, level, mask=bad_mask)
def test_float():
contours = find_contours(r, 0.5)
assert len(contours) == 1
assert_array_equal(contours[0], [[2., 3.],
[1., 2.],
[2., 1.],
[3., 2.],
[2., 3.]])
@pytest.mark.parametrize("level", [0.5, None])
def test_memory_order(level):
contours = find_contours(np.ascontiguousarray(r), level)
assert len(contours) == 1
contours = find_contours(np.asfortranarray(r), level)
assert len(contours) == 1
def test_invalid_input():
with pytest.raises(ValueError):
find_contours(r, 0.5, 'foo', 'bar')
with pytest.raises(ValueError):
find_contours(r[..., None], 0.5)
def test_level_default():
# image with range [0.9, 0.91]
image = np.random.random((100, 100)) * 0.01 + 0.9
contours = find_contours(image) # use default level
# many contours should be found
assert len(contours) > 1
@pytest.mark.parametrize("image", [
[[0.13680, 0.11220, 0.0, 0.0, 0.0, 0.19417, 0.19417, 0.33701],
[0.0, 0.15140, 0.10267, 0.0, np.nan, 0.14908, 0.18158, 0.19178],
[0.0, 0.06949, 0.0, 0.0, 0.0, 0.0, 0.0, 0.01860],
[0.0, 0.06949, 0.0, 0.17852, 0.08469, 0.02135, 0.08198, np.nan],
[0.0, 0.08244, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan],
[0.12342, 0.21330, 0.0, np.nan, 0.01301, 0.04335, 0.0, 0.0]],
[[0.08, -0.03, -0.17, -0.08, 0.24, 0.06, 0.17, -0.02],
[0.12, 0., np.nan, 0.24, 0., -0.53, 0.26, 0.16],
[0.39, 0., 0., 0., 0., -0.02, -0.3, 0.01],
[0.28, -0.04, -0.03, 0.16, 0.12, 0.01, -0.87, 0.16],
[0.26, 0.08, 0.08, 0.08, 0.12, 0.13, 0.11, 0.19],
[0.27, 0.24, 0., 0.25, 0.32, 0.19, 0.26, 0.22]],
[[-0.18, np.nan, np.nan, 0.22, -0.14, -0.23, -0.2, -0.17, -0.19, -0.24],
[0., np.nan, np.nan, np.nan, -0.1, -0.24, -0.15, -0.02, -0.09, -0.21],
[0.43, 0.19, np.nan, np.nan, -0.01, -0.2, -0.22, -0.18, -0.16, -0.07],
[0.23, 0., np.nan, -0.06, -0.07, -0.21, -0.24, -0.25, -0.23, -0.13],
[-0.05, -0.11, 0., 0.1, -0.19, -0.23, -0.23, -0.18, -0.19, -0.16],
[-0.19, -0.05, 0.13, -0.08, -0.22, -0.23, -0.26, -0.15, -0.12, -0.13],
[-0.2, -0.11, -0.11, -0.24, -0.29, -0.27, -0.35, -0.36, -0.27, -0.13],
[-0.28, -0.33, -0.31, -0.36, -0.39, -0.37, -0.38, -0.32, -0.34, -0.2],
[-0.28, -0.33, -0.39, -0.4, -0.42, -0.38, -0.35, -0.39, -0.35, -0.34],
[-0.38, -0.35, -0.41, -0.42, -0.39, -0.36, -0.34, -0.36, -0.28, -0.34]]
])
def test_keyerror_fix(image):
"""Failing samples from issue #4830
"""
find_contours(np.array(image, np.float32), 0)
<file_sep>/doc/source/release_notes/index.rst
Release notes
=============
This is the list of changes to scikit-image between each release. For full details, see
the `commit logs`_.
.. _commit logs: https://github.com/scikit-image/scikit-image/commits/
.. naturalsortedtoctree::
:maxdepth: 1
:glob:
:reversed:
release_[0-9d]*
<file_sep>/skimage/filters/tests/test_lpi_filter.py
import numpy as np
import pytest
from numpy.testing import assert_, assert_equal, assert_array_almost_equal
from skimage._shared.utils import _supported_float_type
from skimage.data import camera, coins
from skimage.filters import (
LPIFilter2D, filter_inverse, filter_forward, wiener, gaussian
)
def test_filter_forward():
def filt_func(r, c, sigma=2):
return (1 / (2 * np.pi * sigma**2)) * np.exp(-(r**2 + c**2) / (2 * sigma ** 2))
gaussian_args = {
'sigma': 2,
'preserve_range': True,
'mode': 'constant',
'truncate': 20 # LPI filtering is more precise than the truncated
# Gaussian, so don't truncate at the default of 4 sigma
}
# Odd image size
image = coins()[:303, :383]
filtered = filter_forward(image, filt_func)
filtered_gaussian = gaussian(image, **gaussian_args)
assert_array_almost_equal(filtered, filtered_gaussian)
# Even image size
image = coins()
filtered = filter_forward(image, filt_func)
filtered_gaussian = gaussian(image, **gaussian_args)
assert_array_almost_equal(filtered, filtered_gaussian)
class TestLPIFilter2D:
img = camera()[:50, :50]
def filt_func(self, r, c):
return np.exp(-(r**2 + c**2) / 1)
def setup_method(self):
self.f = LPIFilter2D(self.filt_func)
@pytest.mark.parametrize(
'c_slice', [slice(None), slice(0, -5), slice(0, -20)]
)
def test_ip_shape(self, c_slice):
x = self.img[:, c_slice]
assert_equal(self.f(x).shape, x.shape)
@pytest.mark.parametrize(
'dtype', [np.uint8, np.float16, np.float32, np.float64]
)
def test_filter_inverse(self, dtype):
img = self.img.astype(dtype, copy=False)
expected_dtype = _supported_float_type(dtype)
F = self.f(img)
assert F.dtype == expected_dtype
g = filter_inverse(F, predefined_filter=self.f)
assert g.dtype == expected_dtype
assert_equal(g.shape, self.img.shape)
g1 = filter_inverse(F[::-1, ::-1], predefined_filter=self.f)
assert_((g - g1[::-1, ::-1]).sum() < 55)
# test cache
g1 = filter_inverse(F[::-1, ::-1], predefined_filter=self.f)
assert_((g - g1[::-1, ::-1]).sum() < 55)
g1 = filter_inverse(F[::-1, ::-1], self.filt_func)
assert_((g - g1[::-1, ::-1]).sum() < 55)
@pytest.mark.parametrize(
'dtype', [np.uint8, np.float16, np.float32, np.float64]
)
def test_wiener(self, dtype):
img = self.img.astype(dtype, copy=False)
expected_dtype = _supported_float_type(dtype)
F = self.f(img)
assert F.dtype == expected_dtype
g = wiener(F, predefined_filter=self.f)
assert g.dtype == expected_dtype
assert_equal(g.shape, self.img.shape)
g1 = wiener(F[::-1, ::-1], predefined_filter=self.f)
assert_((g - g1[::-1, ::-1]).sum() < 1)
g1 = wiener(F[::-1, ::-1], self.filt_func)
assert_((g - g1[::-1, ::-1]).sum() < 1)
def test_non_callable(self):
with pytest.raises(ValueError):
LPIFilter2D(None)
<file_sep>/skimage/_shared/coord.py
import numpy as np
from scipy.spatial import cKDTree, distance
def _ensure_spacing(coord, spacing, p_norm, max_out):
"""Returns a subset of coord where a minimum spacing is guaranteed.
Parameters
----------
coord : ndarray
The coordinates of the considered points.
spacing : float
the maximum allowed spacing between the points.
p_norm : float
Which Minkowski p-norm to use. Should be in the range [1, inf].
A finite large p may cause a ValueError if overflow can occur.
``inf`` corresponds to the Chebyshev distance and 2 to the
Euclidean distance.
max_out: int
If not None, at most the first ``max_out`` candidates are
returned.
Returns
-------
output : ndarray
A subset of coord where a minimum spacing is guaranteed.
"""
# Use KDtree to find the peaks that are too close to each other
tree = cKDTree(coord)
indices = tree.query_ball_point(coord, r=spacing, p=p_norm)
rejected_peaks_indices = set()
naccepted = 0
for idx, candidates in enumerate(indices):
if idx not in rejected_peaks_indices:
# keep current point and the points at exactly spacing from it
candidates.remove(idx)
dist = distance.cdist([coord[idx]],
coord[candidates],
distance.minkowski,
p=p_norm).reshape(-1)
candidates = [c for c, d in zip(candidates, dist)
if d < spacing]
# candidates.remove(keep)
rejected_peaks_indices.update(candidates)
naccepted += 1
if max_out is not None and naccepted >= max_out:
break
# Remove the peaks that are too close to each other
output = np.delete(coord, tuple(rejected_peaks_indices), axis=0)
if max_out is not None:
output = output[:max_out]
return output
def ensure_spacing(coords, spacing=1, p_norm=np.inf, min_split_size=50,
max_out=None, *, max_split_size=2000):
"""Returns a subset of coord where a minimum spacing is guaranteed.
Parameters
----------
coords : array_like
The coordinates of the considered points.
spacing : float
the maximum allowed spacing between the points.
p_norm : float
Which Minkowski p-norm to use. Should be in the range [1, inf].
A finite large p may cause a ValueError if overflow can occur.
``inf`` corresponds to the Chebyshev distance and 2 to the
Euclidean distance.
min_split_size : int
Minimum split size used to process ``coords`` by batch to save
memory. If None, the memory saving strategy is not applied.
max_out : int
If not None, only the first ``max_out`` candidates are returned.
max_split_size : int
Maximum split size used to process ``coords`` by batch to save
memory. This number was decided by profiling with a large number
of points. Too small a number results in too much looping in
Python instead of C, slowing down the process, while too large
a number results in large memory allocations, slowdowns, and,
potentially, in the process being killed -- see gh-6010. See
benchmark results `here
<https://github.com/scikit-image/scikit-image/pull/6035#discussion_r751518691>`_.
Returns
-------
output : array_like
A subset of coord where a minimum spacing is guaranteed.
"""
output = coords
if len(coords):
coords = np.atleast_2d(coords)
if min_split_size is None:
batch_list = [coords]
else:
coord_count = len(coords)
split_idx = [min_split_size]
split_size = min_split_size
while coord_count - split_idx[-1] > max_split_size:
split_size *= 2
split_idx.append(split_idx[-1] + min(split_size,
max_split_size))
batch_list = np.array_split(coords, split_idx)
output = np.zeros((0, coords.shape[1]), dtype=coords.dtype)
for batch in batch_list:
output = _ensure_spacing(np.vstack([output, batch]),
spacing, p_norm, max_out)
if max_out is not None and len(output) >= max_out:
break
return output
<file_sep>/doc/examples/developers/README.txt
Examples for developers
-----------------------
In this folder, we have examples for advanced topics, including detailed
explanations of the inner workings of certain algorithms.
These examples require some basic knowledge of image processing. They are
targeted at existing or would-be scikit-image developers wishing to develop
their knowledge of image processing algorithms.
<file_sep>/skimage/util/tests/test_slice_along_axes.py
import numpy as np
import pytest
from skimage.util import slice_along_axes
rng = np.random.default_rng()
def test_2d_crop_0():
data = rng.random((50, 50))
out = slice_along_axes(data, [(0, 25)])
np.testing.assert_array_equal(out, data[:25, :])
def test_2d_crop_1():
data = rng.random((50, 50))
out = slice_along_axes(data, [(0, 25), (0, 10)])
np.testing.assert_array_equal(out, data[:25, :10])
def test_2d_crop_2():
data = rng.random((50, 50))
out = slice_along_axes(data, [(0, 25), (0, 30)], axes=[1, 0])
np.testing.assert_array_equal(out, data[:30, :25])
def test_2d_negative():
data = rng.random((50, 50))
out = slice_along_axes(data, [(5, -5), (6, -6)])
np.testing.assert_array_equal(out, data[5:-5, 6:-6])
def test_copy():
data = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
out_without_copy = slice_along_axes(data, [(0, 3)], axes=[1], copy=False)
out_copy = slice_along_axes(data, [(0, 3)], axes=[0], copy=True)
assert out_without_copy.base is data
assert out_copy.base is not data
def test_nd_crop():
data = rng.random((50, 50, 50))
out = slice_along_axes(data, [(0, 25)], axes=[2])
np.testing.assert_array_equal(out, data[:, :, :25])
def test_axes_invalid():
data = np.empty((2, 3))
with pytest.raises(ValueError):
slice_along_axes(data, [(0, 3)], axes=[2])
def test_axes_limit_invalid():
data = np.empty((50, 50))
with pytest.raises(ValueError):
slice_along_axes(data, [(0, 51)], axes=[0])
def test_too_many_axes():
data = np.empty((10, 10))
with pytest.raises(ValueError):
slice_along_axes(data, [(0, 1), (0, 1), (0, 1)])
<file_sep>/doc/source/release_notes/release_0.8.rst
scikits-image 0.8.0 release notes
=================================
We're happy to announce the 8th version of scikit-image!
scikit-image is an image processing toolbox for SciPy that includes algorithms
for segmentation, geometric transformations, color space manipulation,
analysis, filtering, morphology, feature detection, and more.
For more information, examples, and documentation, please visit our website:
http://scikit-image.org
New Features
------------
- New rank filter package with many new functions and a very fast underlying
local histogram algorithm, especially for large structuring elements
`skimage.filter.rank.*`
- New function for small object removal
`skimage.morphology.remove_small_objects`
- New circular hough transformation `skimage.transform.hough_circle`
- New function to draw circle perimeter `skimage.draw.circle_perimeter` and
ellipse perimeter `skimage.draw.ellipse_perimeter`
- New dense DAISY feature descriptor `skimage.feature.daisy`
- New bilateral filter `skimage.filter.denoise_bilateral`
- New faster TV denoising filter based on split-Bregman algorithm
`skimage.filter.denoise_tv_bregman`
- New linear hough peak detection `skimage.transform.hough_peaks`
- New Scharr edge detection `skimage.filter.scharr`
- New geometric image scaling as convenience function
`skimage.transform.rescale`
- New theme for documentation and website
- Faster median filter through vectorization `skimage.filter.median_filter`
- Grayscale images supported for SLIC segmentation
- Unified peak detection with more options `skimage.feature.peak_local_max`
- `imread` can read images via URL and knows more formats `skimage.io.imread`
Additionally, this release adds lots of bug fixes, new examples, and
performance enhancements.
Contributors to this release
----------------------------
This release was only possible due to the efforts of many contributors, both
new and old.
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME> (Mac)
- <NAME>-Iglesias
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
<file_sep>/doc/source/release_notes/release_0.6.rst
scikits-image 0.6 release notes
===============================
We're happy to announce the 6th version of scikits-image!
Scikits-image is an image processing toolbox for SciPy that includes algorithms
for segmentation, geometric transformations, color space manipulation,
analysis, filtering, morphology, feature detection, and more.
For more information, examples, and documentation, please visit our website
http://skimage.org
New Features
------------
- Packaged in Debian as ``python-skimage``
- Template matching
- Fast user-defined image warping
- Adaptive thresholding
- Structural similarity index
- Polygon, circle and ellipse drawing
- Peak detection
- Region properties
- TiffFile I/O plugin
... along with some bug fixes and performance tweaks.
Contributors to this release
----------------------------
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- Tom (tangofoxtrotmike)
- <NAME>
- <NAME>
- <NAME>
<file_sep>/doc/source/release_notes/release_0.9.rst
scikit-image 0.9.0 release notes
================================
We're happy to announce the release of scikit-image v0.9.0!
scikit-image is an image processing toolbox for SciPy that includes algorithms
for segmentation, geometric transformations, color space manipulation,
analysis, filtering, morphology, feature detection, and more.
For more information, examples, and documentation, please visit our website:
http://scikit-image.org
New Features
------------
`scikit-image` now runs without translation under both Python 2 and 3.
In addition to several bug fixes, speed improvements and examples, the 204 pull
requests merged for this release include the following new features (PR number
in brackets):
Segmentation:
- 3D support in SLIC segmentation (#546)
- SLIC voxel spacing (#719)
- Generalized anisotropic spacing support for random_walker (#775)
- Yen threshold method (#686)
Transforms and filters:
- SART algorithm for tomography reconstruction (#584)
- Gabor filters (#371)
- Hough transform for ellipses (#597)
- Fast resampling of nD arrays (#511)
- Rotation axis center for Radon transforms with inverses. (#654)
- Reconstruction circle in inverse Radon transform (#567)
- Pixelwise image adjustment curves and methods (#505)
Feature detection:
- [experimental API] BRIEF feature descriptor (#591)
- [experimental API] Censure (STAR) Feature Detector (#668)
- Octagon structural element (#669)
- Add non rotation invariant uniform LBPs (#704)
Color and noise:
- Add deltaE color comparison and lab2lch conversion (#665)
- Isotropic denoising (#653)
- Generator to add various types of random noise to images (#625)
- Color deconvolution for immunohistochemical images (#441)
- Color label visualization (#485)
Drawing and visualization:
- Wu's anti-aliased circle, line, bezier curve (#709)
- Linked image viewers and docked plugins (#575)
- Rotated ellipse + bezier curve drawing (#510)
- PySide & PyQt4 compatibility in skimage-viewer (#551)
Other:
- Python 3 support without 2to3. (#620)
- 3D Marching Cubes (#469)
- Line, Circle, Ellipse total least squares fitting and RANSAC algorithm (#440)
- N-dimensional array padding (#577)
- Add a wrapper around `scipy.ndimage.gaussian_filter` with useful default behaviors. (#712)
- Predefined structuring elements for 3D morphology (#484)
API changes
-----------
The following backward-incompatible API changes were made between 0.8 and 0.9:
- No longer wrap ``imread`` output in an ``Image`` class
- Change default value of `sigma` parameter in ``skimage.segmentation.slic``
to 0
- ``hough_circle`` now returns a stack of arrays that are the same size as the
input image. Set the ``full_output`` flag to True for the old behavior.
- The following functions were deprecated over two releases:
`skimage.filter.denoise_tv_chambolle`,
`skimage.morphology.is_local_maximum`, `skimage.transform.hough`,
`skimage.transform.probabilistic_hough`,`skimage.transform.hough_peaks`.
Their functionality still exists, but under different names.
Contributors to this release
----------------------------
This release was made possible by the collaborative efforts of many
contributors, both new and old. They are listed in alphabetical order by
surname:
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- Thouis (<NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
- <NAME>
<file_sep>/skimage/data/_binary_blobs.py
import numpy as np
from .._shared.utils import deprecate_kwarg
from .._shared.filters import gaussian
@deprecate_kwarg({'seed': 'rng'}, deprecated_version='0.21',
removed_version='0.23')
def binary_blobs(length=512, blob_size_fraction=0.1, n_dim=2,
volume_fraction=0.5, rng=None):
"""
Generate synthetic binary image with several rounded blob-like objects.
Parameters
----------
length : int, optional
Linear size of output image.
blob_size_fraction : float, optional
Typical linear size of blob, as a fraction of ``length``, should be
smaller than 1.
n_dim : int, optional
Number of dimensions of output image.
volume_fraction : float, default 0.5
Fraction of image pixels covered by the blobs (where the output is 1).
Should be in [0, 1].
rng : {`numpy.random.Generator`, int}, optional
Pseudo-random number generator.
By default, a PCG64 generator is used (see :func:`numpy.random.default_rng`).
If `rng` is an int, it is used to seed the generator.
Returns
-------
blobs : ndarray of bools
Output binary image
Examples
--------
>>> from skimage import data
>>> data.binary_blobs(length=5, blob_size_fraction=0.2) # doctest: +SKIP
array([[ True, False, True, True, True],
[ True, True, True, False, True],
[False, True, False, True, True],
[ True, False, False, True, True],
[ True, False, False, False, True]])
>>> blobs = data.binary_blobs(length=256, blob_size_fraction=0.1)
>>> # Finer structures
>>> blobs = data.binary_blobs(length=256, blob_size_fraction=0.05)
>>> # Blobs cover a smaller volume fraction of the image
>>> blobs = data.binary_blobs(length=256, volume_fraction=0.3)
"""
rs = np.random.default_rng(rng)
shape = tuple([length] * n_dim)
mask = np.zeros(shape)
n_pts = max(int(1. / blob_size_fraction) ** n_dim, 1)
points = (length * rs.random((n_dim, n_pts))).astype(int)
mask[tuple(indices for indices in points)] = 1
mask = gaussian(mask, sigma=0.25 * length * blob_size_fraction,
preserve_range=False)
threshold = np.percentile(mask, 100 * (1 - volume_fraction))
return np.logical_not(mask < threshold)
| f30fa69c3a568eda5665301265ecafca4f4aaabf | [
"reStructuredText",
"Markdown",
"TOML",
"Python",
"Text",
"PHP",
"Shell"
] | 117 | Python | scikit-image/scikit-image | a45f2daf9fcac32e3e8d2c95ade807ac67351965 | 7cf7f29424a7f98815d69ee9f5193e5fc64d829e |
refs/heads/main | <file_sep>import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
tags:string = "";
allTags: string[] = [];
createTag(event: { keyCode: number; }){
if (event.keyCode === 13 || event.keyCode === 44) {
this.allTags.push(this.tags);
this.tags = ''
}
}
deleteTag(index: any) {
this.allTags.splice(index, 1);
}
}
<file_sep>import datetime
startDay = inp/ut("Enter start date: ")
# startDay = "20180728"
endDay = input("Enter end date: ")
# endDay = "20180927"
startDay = datetime.datetime.strptime(startDay, "%Y%m%d")
endDay = datetime.datetime.strptime(endDay, "%Y%m%d")
SATURDAY_VAL = 5;
NTH_VAL = 4;
def get_desired_dates(startDay, endDay):
if (startDay.year < 1900 or endDay.year > 2100):
print("Dates does not exist in the range from 1900 to 2100")
return
def daterange(startDay, endDay):
for n in range(int ((endDay - startDay).days)+1):
yield startDay + datetime.timedelta(n)
for dt in daterange(startDay, endDay):
condition1 = (int(datetime.datetime.strftime(dt, "%d")) % 5 == 0)
condition2 = (dt.day - 1) // 7 == (NTH_VAL - 1)
if dt.weekday() == SATURDAY_VAL:
if (condition1 ^ condition2):
# if ((condition1 and (not condition2)) or ((not condition1) and condition2)):
print(dt.strftime("%Y%m%d"))
get_desired_dates(startDay, endDay)
| 70aeeff5f4a32d1f0bd3cf17bead93514e270505 | [
"Python",
"TypeScript"
] | 2 | TypeScript | shivajit410/docskiff_machine_test | beac1f604c7bd8dbc198af2c18034e0ad5dc1ea3 | 66a13d87c52a48cee393abd68294d8dadafde4bc |
refs/heads/master | <repo_name>technolabs-pravesh/logutil<file_sep>/src/main/java/np/com/mshrestha/bookstore/controller/BookController.java
package np.com.mshrestha.bookstore.controller;
import java.util.Map;
import np.com.mshrestha.bookstore.model.Book;
import np.com.mshrestha.bookstore.model.DocRequest;
import np.com.mshrestha.bookstore.model.DocResponse;
import np.com.mshrestha.bookstore.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
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.ResponseBody;
@Controller
@RequestMapping("/book")
public class BookController {
@Autowired
private BookService bookService;
@RequestMapping(value = { "/", "/listBooks" })
public String listBooks(Map<String, Object> map) {
map.put("book", new Book());
map.put("bookList", bookService.listBooks());
return "/book/listBooks";
}
@RequestMapping("/get/{bookId}")
public String getBook(@PathVariable Long bookId, Map<String, Object> map) {
Book book = bookService.getBook(bookId);
map.put("book", book);
return "/book/bookForm";
}
@RequestMapping(value = "/save", method = RequestMethod.POST)
public String saveBook(@ModelAttribute("book") Book book,
BindingResult result) {
bookService.saveBook(book);
/*
* Note that there is no slash "/" right after "redirect:" So, it
* redirects to the path relative to the current path
*/
return "redirect:listBooks";
}
@RequestMapping("/delete/{bookId}")
public String deleteBook(@PathVariable("bookId") Long id) {
bookService.deleteBook(id);
/*
* redirects to the path relative to the current path
*/
// return "redirect:../listBooks";
/*
* Note that there is the slash "/" right after "redirect:" So, it
* redirects to the path relative to the project root path
*/
return "redirect:/book/listBooks";
}
@RequestMapping("/s")
@ResponseBody
public DocResponse listBooksJ(Map<String, Object> map) {
DocResponse docResponse = new DocResponse();
docResponse.setCode(200);
docResponse.setBooks(bookService.listBooks());
System.out.println(bookService.listBooks().size());
return docResponse;
}
@RequestMapping("/getJ/{bookId}")
@ResponseBody
public DocResponse getBookJ(@PathVariable Long bookId, Map<String, Object> map) {
DocResponse docResponse = new DocResponse();
try{
Book book = bookService.getBook(bookId);
docResponse.setCode(200);
if (docResponse.getCode() == 200) {
throw new Exception("Something happened");
}else{
docResponse.setBook(book);
}
}catch(Exception e){
docResponse.setCode(401);
DocResponse.Error docError = docResponse.new Error();
docError.setField("fields");
docError.setMessage("Message is :"+e.getMessage());
docResponse.setError(docError);
}
return docResponse;
}
@RequestMapping(value = "/reg", method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
public @ResponseBody DocResponse createChangeRequest(@RequestBody DocRequest doc) {
DocResponse docResponse = new DocResponse();
docResponse.setCode(200);
if(doc.getBook().getCode()!=null){
docResponse.setBooks(bookService.listBooksForCode(Integer.parseInt(doc.getBook().getCode())));
}else{
docResponse.setBooks(bookService.listBooks());
}
return docResponse;
}
}
<file_sep>/src/main/java/np/com/mshrestha/bookstore/model/DocResponse.java
package np.com.mshrestha.bookstore.model;
import java.util.List;
import org.codehaus.jackson.map.annotate.JsonSerialize;
import np.com.mshrestha.bookstore.model.Book;
//@JsonInclude(Include.NON_NULL)
@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)
public class DocResponse {
private int code;
private Book book;
private Error error;
private List<Book> books;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public Book getBook() {
return book;
}
public void setBook(Book book) {
this.book = book;
}
public Error getError() {
return error;
}
public void setError(Error error) {
this.error = error;
}
public class Error{
private String field;
private String message;
public String getField() {
return field;
}
public void setField(String field) {
this.field = field;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
public List<Book> getBooks() {
return books;
}
public void setBooks(List<Book> books) {
this.books = books;
}
}
| 3672d921afab8ee5794442e8c07158a348f37231 | [
"Java"
] | 2 | Java | technolabs-pravesh/logutil | 66795c701623dc151574ed5d0f380432c6740391 | c39f5bd655cb2ccb320a0af51bab38f8b2472072 |
refs/heads/master | <repo_name>DOCjx/ourJXNU<file_sep>/README.md
# ourJXNU
我们的师大微信小程序
* 最初的版本
* 带后台版在另一个分支
<file_sep>/pages/home/index.js
//index.js
//获取应用实例
var app = getApp()
const request=require("../../utils/requests");
var star = require("../../utils/star");
Page({
data: {
userInfo: {},
shareData: {
title: '我们的师大',
desc: '身边的小帮手',
path: '/pages/home/index'
},
imgUrls:[
"../../images/pic/banner5.jpg",
"../../images/pic/banner4.jpg"
],
navTo: 1,
switchChecked: true,
indicatorDots: true,
autoplay: true,
interval: 5000,
duration: 2000,
count: 0,
toRe:0
},
onShareAppMessage: function () {
return this.data.shareData
},
switchChange: function (e){
// console.log(e.detail);
// console.log('switch1 发生 change 事件,携带值为', e.detail.value)
if( e.detail.value ){
this.setData({
switchChecked : false
});
}else{
this.setData({
switchChecked : true
});
}
},
navTo:function(e){
// console.log(e)
this.setData({
navTo : e.currentTarget.dataset.navto
});
// var wapperContent=document.getElementsByClassName('wapperContent')
// console.log(wapperContent)
},
toHandel:function () {
var that=this;
wx.showToast({
title: '加载中',
icon: 'loading',
duration: 1000
})
request.getBookList(that.data.toRe,"",function(res){
var types = res.data.books;
// console.log(res.data.books);
if(res.data.count==0){
return;
}
that.setData({List:res.data.books,count:that.data.count+res.data.count});
});
},
toRefresh: function (e) {
var that=this;
this.setData({
toRe : star.toRefresh()
});
that.toHandel();
console.log("随机换一个栏目ID");
console.log(that.data.toRe);
},
/* toRefresh:function(){
var that=this;
this.setData({start:0});
that.searchHandel();
},*/
upper: function(e) {
console.log("已到顶部");
},
lower: function(e) {
console.log("已到低部");
var that=this;
wx.showToast({
title: '加载中',
icon: 'loading',
duration: 10000
});
request.getBookList(that.data.toRe,{start:that.data.count},function(res){
var types = res.data.books;
for (var i = 0; i < types.length; ++i) {
var book = types[i];
var rating = book.rating;
rating.block = star.get_star(rating.average);
}
res.data.books = types;
console.log(res.data.books);
if(res.data.count==0){return;}
that.setData({List:that.data.List.concat(res.data.books),count:that.data.count+res.data.count});
wx.hideToast();
})
},
onLoad:function (options) {
var that=this;
that.setData({
toRe : star.toRefresh()
});
console.log("加载");
console.log(that.data);
request.getBookList(that.data.toRe,"",function(res){
var types = res.data.books;
console.log(res.data.books);
if(res.data.count==0){
return;
}
that.setData({List:res.data.books,count:that.data.count+res.data.count});
});
},
// onLoad: function () {
// console.log('onLoad')
// var that = this
// // console.log(wx)
// //调用应用实例的方法获取全局数据
// app.getUserInfo(function(userInfo){
// //更新数据
// // console.log(this)
// that.setData({
// userInfo:userInfo
// })
// })
// }
})
<file_sep>/pages/common/wrapperContent2/wrapperContent2.js
//wrapperContent.js
| fa89587b4dd5004bbcd6fb44c66d2e7079192aa6 | [
"Markdown",
"JavaScript"
] | 3 | Markdown | DOCjx/ourJXNU | 7befe90a135e3c60d0e6175fe6d76b544d5ce436 | 7b0ae11b89d59f2e5c799fd39394c47121572352 |
refs/heads/master | <repo_name>vellankikoti/watchdog_test<file_sep>/README.md
# watchdog_test
Watchdog for a directory
<file_sep>/watchdog1.py
#This is Watchdog Test Program
# Firsy you need to install watchdog to your system as:'pip install watchdog'
import sys
import time
import logging
from watchdog.observers import Observer
from watchdog.events import LoggingEventHandler
if __name__ == "__main__":
# print(sys.argv[0])
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s - %(message)s')
path = sys.argv[1] if len(sys.argv) > 1 else '.'
event_handler = LoggingEventHandler()
observer = Observer()
observer.schedule(event_handler, path, recursive=True)
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
#This will give you the logging details of the directory in your editor
# Usage and Running
''' 1. Goto your command prompt or editor you are using
2.open watchdog1.py file containg folder
3.use 'python watchdog1.py' #without quotations
4. Try to make changes in files of your directory, Now you will able to see the log in command prompt itself
'''
#if you want to create the logging details in a new document say 'mylogging.log' we can do that also as follows
import sys
import time
import logging
from watchdog.observers import Observer
from watchdog.events import LoggingEventHandler
if __name__ == "__main__":
# print(sys.argv[0])
logging.basicConfig(filename ='mylogging.log',level=logging.DEBUG,
format='%(asctime)s - %(message)s',filemode='a')
path = sys.argv[1] if len(sys.argv) > 1 else '.'
event_handler = LoggingEventHandler()
observer = Observer()
observer.schedule(event_handler, path, recursive=True)
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
# Usage and Running
''' 1. Goto your command prompt or editor you are using
2.open watchdog1.py file containg folder
3.use 'python watchdog1.py' #without quotations
4. Try to make changes in files of your directory
5. Now open your directory and find 'mylogging.log' which have all your logging details
'''
'''Note:
if you want to keep all the logs in 'mylogging.log', you can keep the filemode as 'a'(in line 48)
or if you don't want to keep logs then you can change filemode.
I hope you are aware of file operations, like
r,
r+,
w,
w+,
a,
a+ modes.
Happy Coding!
'''
| ab3a197baa5efce9c943a7937d268ef6eb51bb8a | [
"Markdown",
"Python"
] | 2 | Markdown | vellankikoti/watchdog_test | 82752f50f957f17659911decbc69f8a1752cfbad | 0a5e624595634d2a24a7f7799552b4d9ba177d75 |
refs/heads/master | <file_sep>package model;
import ui.Main;
import java.util.*;
public class Operation {
public static final double DESIGN_STAGE = 1300000;
public static final double POST_CONSTRUCTION = 2600000;
public static final double PAINT = 980000;
/**
Returns the smallest between three numbers
<b>pre: </b> <br>
<b>post: Calculates what the best price for x item is </b> <br>
@param a Price in store #1
@param b Price in store #2
@param c Price in store #3
*/
public double bestPrice(double a, double b, double c){
double lowest = 0;
if (b < a && b < c){
lowest = b;
}
else if (c < a && c < b){
lowest = c;
}
else if (a < b && a < c){
lowest = a;
}
else if (a == b){
lowest = a;
}
else if(b == c){
lowest = b;
}
else if (c == a){
lowest = c;
}
return lowest;
}
/**
Shows what the best place to purchase an item is depending on its price
<b>pre: The best price amongst 3 previously inputted prices has to be calculated and saved to be compared </b> <br>
<b>post: Returns a String with the name of the best place to purchase x item comparing its price at x store with the best price found amongst all stores </b> <br>
@param bestPrice Best price amongst those introduced by user (at different stores)
@param homeCenter Price at Home Center
@param ferreteriaBarrio Price at Ferreteria del Barrio
@param ferreteriaCentro Price at Ferreteria del Centro
*/
public String bestPlace(double bestPrice, double homeCenter, double ferreteriaBarrio, double ferreteriaCentro){
String bestPlace = "";
if (bestPrice == ferreteriaBarrio && bestPrice == ferreteriaCentro){
bestPlace = "Ferreteria del Barrio o Ferreteria del Centro";
}
else if (bestPrice == ferreteriaBarrio && bestPrice == homeCenter){
bestPlace = "Ferreteria del Barrio o Home Center";
}
else if (bestPrice == ferreteriaCentro && bestPrice == homeCenter){
bestPlace = "Ferreteria del Centro o Home Center";
}
else if (bestPrice == homeCenter && bestPrice == ferreteriaBarrio && bestPrice == ferreteriaCentro){
bestPlace = "Home Center,Ferreteria del Centro, Ferreteria del Barrio";
}
else if (bestPrice == ferreteriaCentro){
bestPlace = "Ferreteria del Centro";
}
else if (bestPrice== ferreteriaBarrio){
bestPlace = "Ferreteria del Barrio";
}
else if (bestPrice == homeCenter) {
bestPlace = "Home Center";
}
return bestPlace;
}
/**
Calculates the delivery fee of the products based on the user's location
<b>pre: Saved an array containing the best prices and saved the location of the user </b> <br>
<b>post: Returns the delivery fee based on location and total cost of items </b> <br>
@param bestPrice best price amongst those introduced by user. bestPrice != null.
@param location user's location. location != "".
*/
public double sumTotal(double[] bestPrice, String location) {
double sum = 0;
for (int i = 0; i < bestPrice.length;i++){
sum = sum + bestPrice[i];
}
if (location.equalsIgnoreCase("n")){
if(80000 < sum && sum < 300000){
sum = sum + 28000;
}
if (sum < 80000){
sum = sum + 120000;
}
if (300000<=sum){
sum = sum;
}
}
if (location.equalsIgnoreCase("c")){
if(80000 < sum && sum < 300000){
sum = sum;
}
if (sum < 80000){
sum = sum + 50000;
}
if (300000<=sum){
sum = sum;
}
}
if (location.equalsIgnoreCase("s")){
if(80000 < sum && sum < 300000){
sum = sum + 55000;
}
if (sum < 80000){
sum = sum + 120000;
}
if (300000<=sum){
sum = sum;
}
}
return sum;
}
/**
Prints what the best price, place and and name of a material for x category
<b>pre: Materials array has to be ready and the best prices and places to buy every material have to have been calculated and stored accordingly </b> <br>
<b>post: Returns a String with the best place, price and name of every material comparing its index inside a category array with the material's list </b> <br>
@param numberMaterials total amount of items. numberMaterials > 0.
@param stage array of all items belonging to x category.
@param materials list of all materials inputted by the user.
@param bestPrice best price to buy x item. bestPrice != null.
@param bestPlace best place to purchase x item.
*/
public void asignPlace (int numberMaterials, String [] stage, String [] materials, double [] bestPrice, String [] bestPlace){
for (int m = 0; m<numberMaterials;m++){
if (stage[m]!=null){
for (int s = 0; s < materials.length;s++){
if (stage[m] == materials[s]){
System.out.println("El mejor precio para comprar "+ materials[s] + " es de " + bestPrice[s]+ " en " + bestPlace[s]);
}
}
}
}
}
}
<file_sep># Tarea-Integradora
Beginner University project with the objective of accounting for a construction work budget.
| e4f40de7dc18b424a1616ecada74fd64334cae7c | [
"Markdown",
"Java"
] | 2 | Java | mariajosepa/Tarea-Integradora | e56af64562f303780bd452baee263b2bc9159540 | 9fb60f7532fd0ad02607d4ce87ce070106a07f8c |
refs/heads/master | <repo_name>danners/SpringerDownloader<file_sep>/README.md
SpringerDownloader
==================
This tool written in Java is able to download books from [SpringerLink](http://www.springerlink.com) and merge the individual pdf files per chapter in one pdf while creating bookmarks with the correct chapter names. It relies on jSoup for parsing the website und Apache PDFBox for PDF-merging and bookmark creation.
Only books, which you have full access to can be downloaded. This is often the case if you are student and your university has bought a license. If your university offers VPN access, just connect to the VPN and you should be able to download books. Book urls should be of the form:
http://link.springer.com/book/10.1007/978-0-387-71613-8/page/1
You must have full access to all chapters.
<file_sep>/src/springerdownloader/SpringerDownloader.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package springerdownloader;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JProgressBar;
import javax.swing.SwingWorker;
/**
*
* @author Olli
*/
public class SpringerDownloader extends javax.swing.JFrame implements PropertyChangeListener{
private Book book;
private File downloadFolder;
private Parser parser;
private Downloader downloader;
public SpringerDownloader() {
initComponents();
}
public Book getBook() {
return book;
}
public void setBook(Book book) {
this.book = book;
}
public File getDownloadFolder() {
return downloadFolder;
}
public String getURL() {
return urlField.getText();
}
public void setChapterTable(JList chapterTable) {
this.chapterTable = chapterTable;
}
public JList getChapterTable() {
return chapterTable;
}
public JProgressBar getProgressBar() {
return progressBar;
}
@Override
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getPropertyName() == "progress") {
progressBar.setValue((int) evt.getNewValue());
}
if (evt.getPropertyName() == "state") {
if (evt.getNewValue() == SwingWorker.StateValue.DONE) {
progressBar.setIndeterminate(false);
progressBar.setValue(progressBar.getMaximum());
progressBar.setStringPainted(true);
}
if (evt.getNewValue() == SwingWorker.StateValue.STARTED) {
progressBar.setValue(0);
progressBar.setString(null);
}
}
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
urlField = new javax.swing.JTextField();
loadButton = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
chapterTable = new javax.swing.JList();
downloadFolderTextBox = new javax.swing.JTextField();
downloadFolderLabel = new javax.swing.JLabel();
selectDownloadFolder = new javax.swing.JButton();
downloadAndMergeButton = new javax.swing.JButton();
progressBar = new javax.swing.JProgressBar();
menuBar = new javax.swing.JMenuBar();
fileMenu = new javax.swing.JMenu();
openMenuItem = new javax.swing.JMenuItem();
saveMenuItem = new javax.swing.JMenuItem();
saveAsMenuItem = new javax.swing.JMenuItem();
exitMenuItem = new javax.swing.JMenuItem();
editMenu = new javax.swing.JMenu();
cutMenuItem = new javax.swing.JMenuItem();
copyMenuItem = new javax.swing.JMenuItem();
pasteMenuItem = new javax.swing.JMenuItem();
deleteMenuItem = new javax.swing.JMenuItem();
helpMenu = new javax.swing.JMenu();
contentsMenuItem = new javax.swing.JMenuItem();
aboutMenuItem = new javax.swing.JMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
urlField.setText("Enter Url here");
loadButton.setText("Load Book");
loadButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
loadButtonActionPerformed(evt);
}
});
jScrollPane1.setViewportView(chapterTable);
downloadFolderTextBox.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
downloadFolderTextBoxActionPerformed(evt);
}
});
downloadFolderLabel.setText("Download Folder");
selectDownloadFolder.setText("Select");
selectDownloadFolder.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
selectDownloadFolderActionPerformed(evt);
}
});
downloadAndMergeButton.setText("Download and Merge");
downloadAndMergeButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
downloadAndMergeButtonActionPerformed(evt);
}
});
progressBar.setStringPainted(true);
fileMenu.setMnemonic('f');
fileMenu.setText("File");
openMenuItem.setMnemonic('o');
openMenuItem.setText("Open");
fileMenu.add(openMenuItem);
saveMenuItem.setMnemonic('s');
saveMenuItem.setText("Save");
fileMenu.add(saveMenuItem);
saveAsMenuItem.setMnemonic('a');
saveAsMenuItem.setText("Save As ...");
saveAsMenuItem.setDisplayedMnemonicIndex(5);
fileMenu.add(saveAsMenuItem);
exitMenuItem.setMnemonic('x');
exitMenuItem.setText("Exit");
exitMenuItem.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
exitMenuItemActionPerformed(evt);
}
});
fileMenu.add(exitMenuItem);
menuBar.add(fileMenu);
editMenu.setMnemonic('e');
editMenu.setText("Edit");
cutMenuItem.setMnemonic('t');
cutMenuItem.setText("Cut");
editMenu.add(cutMenuItem);
copyMenuItem.setMnemonic('y');
copyMenuItem.setText("Copy");
editMenu.add(copyMenuItem);
pasteMenuItem.setMnemonic('p');
pasteMenuItem.setText("Paste");
editMenu.add(pasteMenuItem);
deleteMenuItem.setMnemonic('d');
deleteMenuItem.setText("Delete");
editMenu.add(deleteMenuItem);
menuBar.add(editMenu);
helpMenu.setMnemonic('h');
helpMenu.setText("Help");
contentsMenuItem.setMnemonic('c');
contentsMenuItem.setText("Contents");
helpMenu.add(contentsMenuItem);
aboutMenuItem.setMnemonic('a');
aboutMenuItem.setText("About");
helpMenu.add(aboutMenuItem);
menuBar.add(helpMenu);
setJMenuBar(menuBar);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(urlField, javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(downloadFolderLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))
.addGroup(layout.createSequentialGroup()
.addComponent(loadButton)
.addGap(3, 3, 3)))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(downloadAndMergeButton, javax.swing.GroupLayout.PREFERRED_SIZE, 197, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addComponent(downloadFolderTextBox, javax.swing.GroupLayout.PREFERRED_SIZE, 363, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(selectDownloadFolder))))
.addComponent(progressBar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(6, 6, 6)
.addComponent(urlField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(loadButton)
.addComponent(downloadAndMergeButton))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(downloadFolderTextBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(downloadFolderLabel)
.addComponent(selectDownloadFolder))
.addGap(12, 12, 12)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 356, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(31, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void exitMenuItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitMenuItemActionPerformed
System.exit(0);
}//GEN-LAST:event_exitMenuItemActionPerformed
private void loadButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_loadButtonActionPerformed
SupportedSite siteToParse = SupportedSite.checkURL(urlField.getText());
if (siteToParse == null) {
JOptionPane.showMessageDialog(this,
"The URL you entered is not supported", "Error", JOptionPane.ERROR_MESSAGE, null);
} else {
parser = new Parser(this, siteToParse);
parser.execute();
progressBar.setIndeterminate(true);
progressBar.setStringPainted(false);
}
}//GEN-LAST:event_loadButtonActionPerformed
private void downloadFolderTextBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_downloadFolderTextBoxActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_downloadFolderTextBoxActionPerformed
private void selectDownloadFolderActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_selectDownloadFolderActionPerformed
final JFileChooser fc = new JFileChooser();
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int returnVal = fc.showOpenDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
downloadFolder = fc.getSelectedFile();
downloadFolderTextBox.setText(downloadFolder.getAbsolutePath());
}
}//GEN-LAST:event_selectDownloadFolderActionPerformed
private void downloadAndMergeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_downloadAndMergeButtonActionPerformed
if (book == null) {
JOptionPane.showMessageDialog(this,
"You need to load a book first", "Error", JOptionPane.ERROR_MESSAGE, null);
} else {
downloader = new Downloader(this);
downloader.execute();
}
}//GEN-LAST:event_downloadAndMergeButtonActionPerformed
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
*/
//</editor-fold>
/*
* Create and display the form
*/
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new SpringerDownloader().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JMenuItem aboutMenuItem;
private javax.swing.JList chapterTable;
private javax.swing.JMenuItem contentsMenuItem;
private javax.swing.JMenuItem copyMenuItem;
private javax.swing.JMenuItem cutMenuItem;
private javax.swing.JMenuItem deleteMenuItem;
private javax.swing.JButton downloadAndMergeButton;
private javax.swing.JLabel downloadFolderLabel;
private javax.swing.JTextField downloadFolderTextBox;
private javax.swing.JMenu editMenu;
private javax.swing.JMenuItem exitMenuItem;
private javax.swing.JMenu fileMenu;
private javax.swing.JMenu helpMenu;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JButton loadButton;
private javax.swing.JMenuBar menuBar;
private javax.swing.JMenuItem openMenuItem;
private javax.swing.JMenuItem pasteMenuItem;
private javax.swing.JProgressBar progressBar;
private javax.swing.JMenuItem saveAsMenuItem;
private javax.swing.JMenuItem saveMenuItem;
private javax.swing.JButton selectDownloadFolder;
private javax.swing.JTextField urlField;
// End of variables declaration//GEN-END:variables
}
<file_sep>/src/springerdownloader/Book.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package springerdownloader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
*
* @author Olli
*/
public class Book {
private String title;
private List<Chapter> chapters = new ArrayList<>();
private boolean partioned = false;
private Map<String, String> cookies;
public Book(String title, List<Chapter> chapters, boolean hasParts) throws Exception {
this.title = title;
this.chapters = chapters;
this.partioned = hasParts;
}
public List<String> getChapterNames() {
List<String> names = new ArrayList();
for (Chapter chapter : chapters) {
names.add(chapter.getName());
}
return names;
}
public List<Chapter> getChapters() {
return chapters;
}
public String getTitle() {
return title;
}
public boolean isPartioned() {
return partioned;
}
public void setCookies(Map<String, String> cookies) {
this.cookies = cookies;
}
public Map<String, String> getCookies() {
return cookies;
}
}
| 3c81fd7b3004212561efef0c25e5aa143b43836e | [
"Markdown",
"Java"
] | 3 | Markdown | danners/SpringerDownloader | 19d45c69eb0f8e397ff2636464684bb1de04433d | 7e44d53e8b38afe7c3b288ab88544bdc2569f60e |
refs/heads/main | <file_sep>import Counts from "./Counts";
export default function ParentComponent() {
return (
<>
<Counts />
</>
);
}
<file_sep>import "./styles.css";
import ParentComponent from "./component/parent-component";
export default function App() {
return (
<div className="text-center dark:text-gray-10 mt-10">
<ParentComponent />
<h2>Start editing to see some magic happen!</h2>
</div>
);
}
<file_sep>function Counts() {
return <div>Count</div>;
}
export default Counts;
<file_sep># ReactMemo
Created with CodeSandbox
| 288c94450e9498f1469231756209b7c27a4d8331 | [
"JavaScript",
"Markdown"
] | 4 | JavaScript | jozcar/ReactMemo | 29b5c07d13c04fbc2d8e30ad6a663154f10ec542 | 9520a3f584bbc812c9a42cd4658bde044080c6e7 |
refs/heads/master | <file_sep>angular.module("tableApp").service("tableService", function($q, $http) {
/**
* get all without pagination
*/
this.getAllCount = function() {
return $http.get(API_ENDPOINT + `locations`);
};
/**
* get all the locations
*
* return promise
*/
this.getData = function(pageNo, limit) {
return $http.get(
API_ENDPOINT + `locations?_page=${pageNo + 1}&_limit=${limit}`
);
};
/**
* @param {string} key used to search table data
*
* return promise
*
*/
this.search = function(key = "", pageNo, limit) {
return $http.get(
API_ENDPOINT + `locations?q=${key}&_page=${pageNo + 1}&_limit=${limit}`
);
};
/**
* @param {number} id id of data which is to be patched
*
* @param {bool} status set the location active/not-active of given id
*
* return promise
*/
this.patchStatus = function(ids, status) {
return $q.all(
ids.map(id =>
$http.patch(API_ENDPOINT + `locations/${id}`, { isActive: status })
)
);
};
this.deleteLocation = function(id) {
return $http.delete(API_ENDPOINT + `locations/${id}`);
};
});
<file_sep>function tableController(tableService) {
var self = this;
self.searchKey = "";
self.data = []; // tableService.getData();
self.totalData = 0; //self.data.length;
self.loading = true;
self.count = 0;
self.selectedRows = [];
self.isChecked = false;
self.pagination = [];
self.currentPage = 0;
self.perPage = 5;
self.activateLoading = false;
self.deactivateLoading = false;
self.$onInit = function() {
self.fetchAll();
self.countTotal();
};
// search automatic when user make input
self.search = function() {
self.loading = true;
self.currentPage = 0;
tableService
.search(self.searchKey, self.currentPage, self.perPage)
.then(function(response) {
self.data = response.data;
self.totalData = self.data.length;
self.loading = false;
});
};
//create pagination array
self.makePaginationArray = function() {
let i;
self.pagination = [];
for (i = 0; i < Math.ceil(self.count / self.perPage); ++i) {
self.pagination.push(i);
}
};
//fetch data with pagination
self.fetchAll = function() {
self.loading = true;
tableService
.getData(self.currentPage, self.perPage)
.then(function(response) {
self.data = response.data;
self.totalData = self.data.length;
self.loading = false;
self.makePaginationArray();
});
};
//count total data without pagination
self.countTotal = function() {
tableService.getAllCount().then(function(response) {
self.count = response.data.length;
self.makePaginationArray();
});
};
//operation need when page is clicked
self.changePage = function(page) {
self.currentPage = page;
self.fetchAll();
};
/**
* @param {number} id id of checked row
*
* @param {bool} isChecked whether row is selected or not
*
* return none
*/
self.rowSelectionChange = function(id, isChecked) {
if (isChecked) {
self.selectedRows.push(id);
} else {
self.selectedRows = self.selectedRows.filter(function(x) {
return x !== id;
});
}
};
/**
* toggle status of each selected id
*
* @param {bool} sttatus whether to activate or deactivate the location
*
* return none
*/
self.alterStatus = function(status) {
status ? (self.activateLoading = true) : (self.deactivateLoading = true);
tableService
.patchStatus(self.selectedRows, status)
.then(function(response) {
status
? (self.activateLoading = false)
: (self.deactivateLoading = false);
self.selectedRows = [];
self.fetchAll();
});
};
/**
* delete the particular data
*
* @param {number} id of row to be deleted
*
*/
self.delete = function(id) {
tableService.deleteLocation(id).then(function(response) {
self.countTotal();
self.fetchAll();
});
};
}
<file_sep>angular.module("tableApp").component("tableComponent", {
templateUrl: "./app/component/table/table.html",
controller: tableController
});
<file_sep>(function(angular) {
angular.module("todoApp", ["ngRoute"]);
})(window.angular);
const API_ENDPOINT = "https://rest-api-grid.herokuapp.com/";
angular.module("tableApp", []).component("paginationComponent", {
templateUrl: "./app/component/pagination/pagination.html",
controller: paginationController,
bindings: {
total: "@"
}
});
function paginationController($scope) {
var self = this;
this.perPage = 5;
this.currentPage = 1;
}
angular.module("tableApp").component("tableComponent", {
templateUrl: "./app/component/table/table.html",
controller: tableController
});
function tableController(tableService) {
var self = this;
self.searchKey = "";
self.data = []; // tableService.getData();
self.totalData = 0; //self.data.length;
self.loading = true;
self.count = 0;
self.selectedRows = [];
self.isChecked = false;
self.pagination = [];
self.currentPage = 0;
self.perPage = 5;
self.activateLoading = false;
self.deactivateLoading = false;
self.$onInit = function() {
self.fetchAll();
self.countTotal();
};
// search automatic when user make input
self.search = function() {
self.loading = true;
self.currentPage = 0;
tableService
.search(self.searchKey, self.currentPage, self.perPage)
.then(function(response) {
self.data = response.data;
self.totalData = self.data.length;
self.loading = false;
});
};
//create pagination array
self.makePaginationArray = function() {
let i;
self.pagination = [];
for (i = 0; i < Math.ceil(self.count / self.perPage); ++i) {
self.pagination.push(i);
}
};
//fetch data with pagination
self.fetchAll = function() {
self.loading = true;
tableService
.getData(self.currentPage, self.perPage)
.then(function(response) {
self.data = response.data;
self.totalData = self.data.length;
self.loading = false;
self.makePaginationArray();
});
};
//count total data without pagination
self.countTotal = function() {
tableService.getAllCount().then(function(response) {
self.count = response.data.length;
self.makePaginationArray();
});
};
//operation need when page is clicked
self.changePage = function(page) {
self.currentPage = page;
self.fetchAll();
};
/**
* @param {number} id id of checked row
*
* @param {bool} isChecked whether row is selected or not
*
* return none
*/
self.rowSelectionChange = function(id, isChecked) {
if (isChecked) {
self.selectedRows.push(id);
} else {
self.selectedRows = self.selectedRows.filter(function(x) {
return x !== id;
});
}
};
/**
* toggle status of each selected id
*
* @param {bool} sttatus whether to activate or deactivate the location
*
* return none
*/
self.alterStatus = function(status) {
status ? (self.activateLoading = true) : (self.deactivateLoading = true);
tableService
.patchStatus(self.selectedRows, status)
.then(function(response) {
status
? (self.activateLoading = false)
: (self.deactivateLoading = false);
self.selectedRows = [];
self.fetchAll();
});
};
/**
* delete the particular data
*
* @param {number} id of row to be deleted
*
*/
self.delete = function(id) {
tableService.deleteLocation(id).then(function(response) {
self.countTotal();
self.fetchAll();
});
};
}
angular.module("tableApp").service("tableService", function($q, $http) {
/**
* get all without pagination
*/
this.getAllCount = function() {
return $http.get(API_ENDPOINT + `locations`);
};
/**
* get all the locations
*
* return promise
*/
this.getData = function(pageNo, limit) {
return $http.get(
API_ENDPOINT + `locations?_page=${pageNo + 1}&_limit=${limit}`
);
};
/**
* @param {string} key used to search table data
*
* return promise
*
*/
this.search = function(key = "", pageNo, limit) {
return $http.get(
API_ENDPOINT + `locations?q=${key}&_page=${pageNo + 1}&_limit=${limit}`
);
};
/**
* @param {number} id id of data which is to be patched
*
* @param {bool} status set the location active/not-active of given id
*
* return promise
*/
this.patchStatus = function(ids, status) {
return $q.all(
ids.map(id =>
$http.patch(API_ENDPOINT + `locations/${id}`, { isActive: status })
)
);
};
this.deleteLocation = function(id) {
return $http.delete(API_ENDPOINT + `locations/${id}`);
};
});
<file_sep>function paginationController($scope) {
var self = this;
this.perPage = 5;
this.currentPage = 1;
}
<file_sep>angular.module("tableApp", []).component("paginationComponent", {
templateUrl: "./app/component/pagination/pagination.html",
controller: paginationController,
bindings: {
total: "@"
}
});
<file_sep>const API_ENDPOINT = "https://rest-api-grid.herokuapp.com/";
<file_sep>import os
path='./app'
dest_path = './dest'
dest_file = 'bundle.js'
files = []
print('python is bundling js......')
for root,directory,file in os.walk(path):
for f in file:
if '.js' in f:
files.append(os.path.join(root, f))
with open(dest_file,'w+') as bundle:
for file in files:
with open(file,'r') as infile:
bundle.write(infile.read())
print('all js inside app bundled successfully....')<file_sep>## git clone
## npm install
## run json server inside api
## python bundle.py
### make sure of python 3
| d4da4dbd5d10fbfb417f3c8a766dc94dc4e04388 | [
"JavaScript",
"Python",
"Markdown"
] | 9 | JavaScript | mlnlmsl/grid-component | 45734b0d8d26f1ff64b502dcd662958cb168c87f | 71f3f599138f7262784402ee86eddee1cc1faa02 |
refs/heads/master | <repo_name>jordi13/ZombieLandNavMesh<file_sep>/New Unity Project/Assets/prova.js
#pragma strict
private var nav : NavMeshAgent;
private var player : Transform;
function Start () {
player = GameObject.FindGameObjectWithTag ("Player").transform;
nav = GetComponent (NavMeshAgent);
}
function Update () {
transform.GetComponent(NavMeshAgent).destination = player.position;
}<file_sep>/New Unity Project/Assets/Scripts/Scripts/Scripts/AutoDestroy.cs
//====================================================================================================
//
// Script : AutoDestroy
// Programador : <NAME>. "Jocyf"
//
// Date: 05/04/2013
// Version : 1.3
//
// Description: Destroy a gameobject at the time specified.
// The time have to be a value greater than zero.
// To destroy inmediatly call DestroyInmediate() function.
//
//====================================================================================================
using UnityEngine;
using System.Collections;
[AddComponentMenu( "Utilities/AutoDestroy")]
public class AutoDestroy : MonoBehaviour {
public float DestroyTime = 0.5f;
// Use this for initialization
void Start () {
// Only destroy the object if time is greater than zero.
if(DestroyTime > 0)
Destroy(this.gameObject, DestroyTime);
}
public void SetTimeToDestroy(float _Time){
// Only destroy the object if time is greater than zero.
if(_Time > 0){
DestroyTime = _Time;
Destroy(this.gameObject, _Time);
}
}
// Destroy inmediatly. Be carefull because there is a DestroyInmediate in Unity's API,
// that is used to destroy gameobjects in the editor (see Unity's docs).
public void DestroyInmediate(){
Destroy(this.gameObject);
}
}
<file_sep>/New Unity Project/Assets/Scripts/Scripts/Scripts/GUIAdjust.cs
//=============================================================================================================
//
// Script : GUIAdjustResolution
// Programador : <NAME>. "Jocyf"
//
// Date: 05/04/2013
// Version : 1.3
//
// Description: Adjust a GUI (GUIText or GUITexture can be used) resolution to the screen resolution.
// Note : It doesn't work if change not resolution but also the Aspect Ratio of the screen (4:3, 16:9, etc...)
//
//=============================================================================================================
//=============================================================================================================
//
// Otros scripts en la wiki para escalar GUIs
// http://wiki.unity3d.com/index.php/GUIScaler
// http://wiki.unity3d.com/index.php?title=AspectRatioEnforcer
// http://wiki.unity3d.com/index.php/GuiRatioFixer2
// http://wiki.unity3d.com/index.php/GUIUtils
// Hacer que un GUI sigua a un objeto.
// http://wiki.unity3d.com/index.php/ObjectLabel
//
//=============================================================================================================
using UnityEngine;
using System.Collections;
[AddComponentMenu( "Utilities/GUIAdjust")]
public class GUIAdjust : MonoBehaviour {
// Valores originales de los graficos tal y como se crearon para la resolucion destino original.
public float customWidth = 1024; //Set this value to the Width of your Game Tab in the Editor
public float customHeight = 768; //Set this value to the Height of your Game Tab in the Editor
public bool AdjustSize = false;
public bool AdjustInUpdate = false;
private Rect OrigRect;
private Vector2 OrigOffset;
// Use this for initialization
void Awake() {
if(this.guiTexture != null)
OrigRect = this.guiTexture.pixelInset;
else
if(this.guiText != null)
OrigOffset = this.guiText.pixelOffset;
AdjustResOneTime();
}
// Update is called once per frame
void Update () {
if(AdjustInUpdate)
AdjustResOneTime();
}
public void TextureRatio(){
}
public void AdjustResOneTime(){
if(this.guiTexture != null)
this.guiTexture.pixelInset = scaledRect(OrigRect);
else
if(this.guiText != null)
this.guiText.pixelOffset = scaledOffset(OrigOffset);
}
Rect scaledRect (Rect _Rect) {
Rect returnRect = _Rect;
returnRect.x = (_Rect.x*Screen.width) / customWidth;
returnRect.y = (_Rect.y*Screen.height) / customHeight;
if(AdjustSize){
returnRect.width = (_Rect.width*Screen.width) / customWidth;
returnRect.height = (_Rect.height*Screen.height) / customHeight;
}
return returnRect;
}
Vector2 scaledOffset (Vector2 _Offset) {
Vector2 returnOffset = _Offset;
returnOffset.x = (_Offset.x*Screen.width) / customWidth;
returnOffset.y = (_Offset.y*Screen.height) / customHeight;
return returnOffset;
}
}
<file_sep>/New Unity Project/Assets/Scripts/Scripts/Disparo Pistola.js
//public var PuntoDisparo : Transform;
public var SplashObject : GameObject;
public var UseRotation : boolean = false;
//public var Blanco : GameObject;
function Update () {
if(Input.GetButtonDown ("Fire1")){
var hit : RaycastHit;
if(Physics.Raycast(Camera.main.transform.position, Camera.main.transform.forward, hit, 1000)){
var pos : Vector3 = hit.point;
var rot : Quaternion = Quaternion.identity;
if(UseRotation == true)
rot = Quaternion.FromToRotation(Vector3.up, hit.normal);
Instantiate(SplashObject, pos, rot);
}
}
}<file_sep>/New Unity Project/Assets/Scripts/Scripts/DisparoSelectivo.js
public var NumeroArma : int = 0;
public var PuntoDisparo : Transform;
public var Armas : GameObject[];
public var ManejadorDeDibujoDeArmas : GameObject;
public var GUIArmas : GUITexture;
public var GUITexturasArmas : Texture2D[];
public var GUIMunicion : GUIText;
private var TiempoDeDisparo : float = 0;
private var PropArmas : ArmasEstado;
function Start(){
PropArmas = Armas[NumeroArma].GetComponent(ArmasEstado);
GUIArmas.texture = GUITexturasArmas[NumeroArma];
for(var i : int = 0; i < Armas.Length; i++){
var ArmasScript : ArmasEstado = Armas[i].GetComponent(ArmasEstado);
ArmasScript.MunicionActual = ArmasScript.MunicionTotal * ArmasScript.PorcentajeRecargaMunicion / 100;
}
GUIMunicion.text = PropArmas.MunicionActual.ToString();
}
function Update () {
if(Input.GetKey ("1")){
NumeroArma = 0;
PropArmas = Armas[0].GetComponent(ArmasEstado);
GUIArmas.texture = GUITexturasArmas[0];
GUIMunicion.text = PropArmas.MunicionActual.ToString();
ManejadorDeDibujoDeArmas.SendMessage ("ActivarArma", 0);
}
if(Input.GetKey ("2")){
NumeroArma = 1;
PropArmas = Armas[1].GetComponent(ArmasEstado);
GUIArmas.texture = GUITexturasArmas[1];
GUIMunicion.text = PropArmas.MunicionActual.ToString();
ManejadorDeDibujoDeArmas.SendMessage ("ActivarArma", 1);
}
if(Input.GetKey ("3")){
NumeroArma = 2;
PropArmas = Armas[2].GetComponent(ArmasEstado);
GUIArmas.texture = GUITexturasArmas[2];
GUIMunicion.text = PropArmas.MunicionActual.ToString();
ManejadorDeDibujoDeArmas.SendMessage ("ActivarArma", 2);
}
if(Input.GetButton("Fire1") && (Time.time > TiempoDeDisparo) ){
// Decremento la municion y la escribo
if(PropArmas.MunicionActual > 0){
PropArmas.MunicionActual--;
GUIMunicion.text = PropArmas.MunicionActual.ToString();
}
Instantiate(PropArmas.Destello, PuntoDisparo.position, Camera.main.transform.rotation);
// Crear el disparo.
if(PropArmas.Tipo == TiposDisparo.Proyectil){
if(PropArmas.MunicionActual > 0){
var CloneFire : GameObject = Instantiate (Armas[NumeroArma], PuntoDisparo.position, Camera.main.transform.rotation);
CloneFire.rigidbody.AddRelativeForce(new Vector3(0, 0, PropArmas.Aceleracion), ForceMode.VelocityChange);
}
}
else
if(PropArmas.Tipo == TiposDisparo.Inmediato){
if(PropArmas.MunicionActual > 0){
var hit : RaycastHit;
if(Physics.Raycast(Camera.main.transform.position, Camera.main.transform.forward, hit, 1000)){
var pos : Vector3 = hit.point;
var rot : Quaternion = Quaternion.identity;
if(PropArmas.UseRotation == true)
rot = Quaternion.FromToRotation(Vector3.up, hit.normal);
Instantiate(PropArmas.SplashObject, pos, rot);
var rotDecall : Quaternion= Quaternion.FromToRotation(Vector3.up, hit.normal);
var DecallObj : GameObject = Instantiate(PropArmas.Decall, pos, rotDecall);
DecallObj.transform.position.y += 0.1;
DecallObj.transform.parent = hit.transform;
if(hit.collider.gameObject.tag == "Blanco")
hit.collider.gameObject.SendMessage ("DecrementaSalud", PropArmas.Damage);
}
}
}
TiempoDeDisparo = Time.time + PropArmas.RatioDeDisparo;
}
}<file_sep>/New Unity Project/Assets/provaanimations.js
#pragma strict
var attack1 : AnimationClip;
var attack2 : AnimationClip;
var death : AnimationClip;
var idle : AnimationClip;
var run : AnimationClip;
function Start () {
/*
animation[attack1.name].speed = 1;
animation[attack1.name].wrapMode = WrapMode.Loop;
animation[attack2.name].speed = 1;
animation[attack2.name].wrapMode = WrapMode.Loop;
animation[death.name].speed = 1;
animation[death.name].wrapMode = WrapMode.Loop;
animation[idle.name].speed = 1;
animation[idle.name].wrapMode = WrapMode.Loop;
animation[run.name].speed = 1;
animation[run.name].wrapMode = WrapMode.Loop;
*/
//animation.Play(idle.name);
//Animation.Play(idle.name);
animation.Play("idle");
}
function Update () {
}<file_sep>/New Unity Project/Assets/Scripts/Scripts/FpsMouseLook.cs
using UnityEngine;
using System.Collections;
public class FpsMouseLook : MonoBehaviour {
public enum RotationAxis {MouseX = 1, MouseY = 2}
public RotationAxis RotXY = RotationAxis.MouseX | RotationAxis.MouseY;
// X Axis
public float SensitivityX = 400f;
public float MinimumX = -360f;
public float MaximumX = 360f;
private float RotationX = 0f;
// Y Axis
public float SensitivityY = 400f;
public float MinimumY = -500f;
public float MaximumY = 50f;
private float RotationY = 0f;
public Quaternion OriginalRotation;
// Use this for initialization
void Start () {
OriginalRotation = transform.localRotation;
}
// Update is called once per frame
void Update () {
if(RotXY == RotationAxis.MouseX){
RotationX += Input.GetAxis("Mouse X") * SensitivityX * Time.deltaTime;
Quaternion XQuaternion = Quaternion.AngleAxis(RotationX, Vector3.up);
transform.localRotation = OriginalRotation * XQuaternion;
}
// No hacabat tutorial -->
}
}
<file_sep>/New Unity Project/Assets/Scripts/Scripts/Scripts/Examples/PickupManager.cs
//=========================================================================================================
//
// Script : AutoMove
// Programador : <NAME>. "Jocyf"
//
// Date: 05/04/2013
// Version : 1.4
//
// Description: Moves a gameobject to a destination at a given time. The destiny can be a point in
// space or a target gameobject. If the target Object exist, the destination point is ignored.
//
//=========================================================================================================
using UnityEngine;
using System.Collections;
public class PickupManager : MonoBehaviour {
public enum pickupType { Health, Ammo, Mana };
public pickupType type = pickupType.Health;
//public Transform destTransform; // The destination object where we wanna go.
public Vector3 destPoint = new Vector3(0, 1, 0); // Destination point if needed (there isnt an object to go to)
public float moveTime = 2; // The time that gets to reach destination.
public float spinSpeed = 180; // The time that gets to reach destination.
private bool isCyclic = true;
private bool isActive = true;
// private values to make all work perfectly fine.
private bool Increase = true; // are we going or returning?
private Vector3 OriginalPosition; // Thats my inicial original position (so i can come back).
private Transform myTransform; // My actual tranform (no need to get the Unity's tranform anymore in the script).
private float rate = 0; // rate used to do my interpolation (the lerp function)
private float i = 0; // used to do my interpolation too (the lerp function)
private float moveTimePrev = 2;
void Inicialize(){
OriginalPosition = myTransform.position;
destPoint = OriginalPosition + destPoint;
rate = 1.0f/moveTime; // needed to do the lerp in the right way.
i = 0;
}
void Start () {
// Get some values and save them just at the begining.
myTransform = transform;
Inicialize();
moveTimePrev = moveTime; // used to detect user changes in inspector.
}
void Update () {
if(!isActive)
return;
// Make sure that time is never zero.
if(moveTime <= 0)
moveTime = 0.01f;
// Detect any change that the user can do in inspector.
if(moveTimePrev != moveTime){
rate = 1.0f/moveTime;
moveTimePrev = moveTime;
}
myTransform.Rotate(Vector3.up, spinSpeed * Time.deltaTime, Space.World);
// If the position where we wanna go is the same that the object starting position
// then there isn't any movement to do.
//if(!destTransform && OriginalPosition == destPoint){ return; }
// Update the movement of our object.
LerpPosition();
}
// We fo a interpolation betwen our position and dest position, so the gameobject
// will move at certain speed to get there in the time specified by the user.
void LerpPosition(){
if (i < 1.0f){
// i goes from zero to 1 at certain rate (given by the movetime).
i += Time.deltaTime * rate;
// Do our interpolations from one point in space to another (going & returning).
if(Increase)
myTransform.position = Vector3.Lerp(OriginalPosition, destPoint, i);
else
myTransform.position = Vector3.Lerp(destPoint, OriginalPosition, i);
}
else
if(isCyclic){ // if is a cyclic movement, make it to start again returning/going from one point to another.
Increase = !Increase;
i = 0;
}
}
// Update is called once per frame
void OnTriggerEnter(Collider other) {
if(other.tag == "Player"){
switch (type){
case pickupType.Health:
// TO-DO : Add health to the main player.
// MyPlayer.Health += 10; // Example.
Debug.Log("DetectPickup : Health picked!.");
break;
case pickupType.Ammo:
// TO-DO : Add ammo to the main player.
Debug.Log("DetectPickup : Ammo picked!.");
break;
case pickupType.Mana:
// TO-DO : Add mana to the main player.
Debug.Log("DetectPickup : Mana picked!.");
break;
default :
// TO-DO : ¿do nothing? ¿Display a warning msg?.
Debug.Log("DetectPickup : This Pickup doesnt have a type.");
break;
}
}
}
}<file_sep>/New Unity Project/Assets/Scripts/Scripts/DibujadorArmas.js
public var Armas : GameObject[];
function Start () {
var FPS : GameObject = gameObject.Find("First Person Controller");
var DisparoScript : DisparoSelectivo = FPS.GetComponent(DisparoSelectivo);
ActivarArma(DisparoScript.NumeroArma);
}
function ActivarArma (NumeroArma : int) {
for(var i : int = 0; i < Armas.Length; i++){
if(i == NumeroArma)
Armas[i].SetActiveRecursively(true);
else
Armas[i].SetActiveRecursively(false);
}
}<file_sep>/New Unity Project/Assets/Scripts/Scripts/Scripts/DrawRay.cs
//====================================================================================================
//
// Script : DrawRay
// Programador : <NAME>. "Jocyf"
//
// Date: 06/04/2013
// Version : 1.1
//
// Description: Draws a ray from the camera to a target or forward a given lenght.
// Drag this script to any gameobect (the MainCamera is the most used option).
//
//====================================================================================================
using UnityEngine;
using System.Collections;
[ExecuteInEditMode]
[AddComponentMenu( "Utilities/DrawRay")]
public class DrawRay : MonoBehaviour {
public Color rayColor = Color.green; // Color of the ray.
public Transform target; // Gameobject that will be the target of the ray (optional).
public bool LookatTarget = false; // Will de camera look at the target?
public int lenght = 10; // Lenght of the ray if there isn't a target.
private Vector3 forward = Vector3.zero; // Private vector used to setup de ray direction.
void Update() {
// If is there a target
if(target){
// the current gameobject is gonna look always to the target (follow it),
if(LookatTarget)
transform.LookAt(target);
// we need de vector that goes from the target to our gameobject.
forward = target.position - transform.position;
}
// There is no target, just look forward this gameobject.
else
forward = transform.TransformDirection(Vector3.forward) * lenght;
// Draw the ray
Debug.DrawRay (transform.position, forward, rayColor);
}
}<file_sep>/New Unity Project/Assets/Scripts/Scripts/Scripts/Examples/DoorMoving2.cs
using UnityEngine;
using System.Collections;
public class DoorMoving2 : MonoBehaviour {
public GameObject doorObject;
public float movingTime = 2;
public float delayTime = 5;
public Transform destTransform;
private Vector3 destPoint;
private Vector3 OriginalPoint = Vector3.zero;
private bool Increase = false; // are we going or returning?
private float internalDelayTime = 1;
private float rate = 0; // rate used to do my interpolation (the lerp function)
private float i = 1; // used to do my interpolation too (the lerp function)
// Get our rotate script component from the door itself (this is the trigger
// that 'fires' all the opening/closing door functionality).
void Start() {
OriginalPoint = this.transform.position;
destPoint = destTransform.position;
rate = 1.0f/movingTime; // needed to do the lerp in the right way.
}
// When the player enter in the door's trigger, rotate it
// and call to the return function
void OnTriggerEnter(Collider other) {
if(other.tag == "Player"){
Increase = true;
i = 0;
internalDelayTime = Time.time + delayTime;
}
}
void Update(){
if (i < 1.0f){
// i goes from zero to 1 at certain rate (given by the movetime).
i += Time.deltaTime * rate;
// Do our interpolations from one point in space to another (going & returning).
if(Increase)
doorObject.transform.position = Vector3.Lerp(OriginalPoint, destPoint, i);
else
doorObject.transform.position = Vector3.Lerp(destPoint, OriginalPoint, i);
}
if(Time.time >= internalDelayTime && Increase){
Increase = false;
i = 0;
}
}
}
<file_sep>/New Unity Project/Assets/EnemyMovement.js
private var player : Transform;
var gunController : GameObject;
private var nav : NavMeshAgent;
var damage : int = 20;
var distance;
var speed : float;
static var myPosition;
private var anim : Animator;
var other : BloodSplatJS;
var attack1Sound : AudioClip;
function Awake ()
{
player = GameObject.FindGameObjectWithTag ("Player").transform;
gunController = GameObject.FindGameObjectWithTag("Player");
nav = GetComponent (NavMeshAgent);
anim = GetComponent(Animator);
}
function Update ()
{
myPosition = transform.position;
//SABER QUE ANIMACION EJECUTA
var stateInfo : AnimatorStateInfo = anim.GetCurrentAnimatorStateInfo(0);
if(!stateInfo.IsName("death")){
other = gunController.GetComponent(BloodSplatJS);
//nav.SetDestination (player.position);
transform.GetComponent(NavMeshAgent).destination = player.position;
//nav.destination(player.position);
distance = Vector3.Distance(nav.transform.position,player.transform.position);
anim.SetFloat("Distance",distance);
speed = Vector3.Project(nav.desiredVelocity, transform.forward).magnitude;
anim.SetFloat("Speed",speed);
}
if(stateInfo.IsName("death")){
Debug.Log("Esta muerto");
nav.enabled = false;
//rigidbody.isKinematic = false;
WaitAndDestroy();
}
}
function SacarVidaAttack(){
GeneralVars.nSalud = GeneralVars.nSalud - damage;
playSoundAttack(attack1Sound);
}
function bloodSplat(){
other.ApplyDamage();
}
function playSoundAttack(soundClip:AudioClip){
this.audio.clip = soundClip;
this.audio.Play();
}
function WaitAndDestroy(){
Destroy(gameObject.collider);
yield WaitForSeconds(2.0);
Destroy(transform.gameObject);
}
<file_sep>/New Unity Project/Assets/Scripts/Scripts/Scripts/CursorManager.cs
//====================================================================================================
//
// Script : CursorManager
// Programador : <NAME>. "Jocyf"
//
// Date: 06/04/2013
// Version : 1.0
//
// Description: Make the mouse cursor dissapear and lock it at the center of the screen
//
//====================================================================================================
using UnityEngine;
using System.Collections;
[AddComponentMenu( "Utilities/CursorManager")]
public class CursorManager : MonoBehaviour {
public bool ShowCursor = true;
// Update is called once per frame
void Update () {
Screen.showCursor = ShowCursor;
Screen.lockCursor = !ShowCursor;
}
}
<file_sep>/New Unity Project/Assets/NavMeshAI.js
#pragma strict
var target : Transform ;
function Start () {
}
function Update () {
GetComponent(NavMeshAgent).destination = target.position;
}<file_sep>/New Unity Project/Assets/BloodSplat.cs
using UnityEngine;
using System.Collections;
public class BloodSplat : MonoBehaviour {
public Texture2D splat;
private float alpha = 1;
public float speed;
public bool test;
void OnGUI()
{
if (alpha > 0.0)
{
Color color = Color.white;
color.a = alpha;
GUI.color = color;
GUI.DrawTexture (new Rect(0, 0, Screen.width, Screen.height), splat);
alpha -= speed*Time.deltaTime;
}
}
void ApplyDamage ()
{
alpha = 1f;
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (Input.GetKeyDown (KeyCode.H) & test)
{
ApplyDamage();
}
}
}
<file_sep>/New Unity Project/Assets/Scripts/Scripts/Scripts/PlayAnimations.cs
//====================================================================================================
//
// Script : PlayAnimations
// Programador : <NAME>. "Jocyf"
//
// Date: 05/04/2013
// Version : 1.3
//
// Description: Play all the animations stored in the 'Animation' Component.
// A pauseTime can be used to pause betwen animations.
//
//====================================================================================================
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
[AddComponentMenu( "Utilities/PlayAnimations")]
[RequireComponent(typeof(Animation))]
public class PlayAnimations : MonoBehaviour {
[Range(0, 5)] public float pauseTime = 1;
[Range(0.1f, 2.0f)] public float playSpeed = 1;
private List<AnimationState> myAnimStates = new List<AnimationState>();
private float TimeToWait = 0;
private int count = 0;
// Use this for initialization
void Start () {
animation.playAutomatically = false;
count = animation.GetClipCount();
getAllAnimations();
}
// Update is called once per frame
void Update () {
PlayAllAnimations();
}
AnimationState GetAnimationClip (int index){
int i = 0;
foreach(AnimationState AnimState in animation){
if(i == index)
return AnimState;
i++;
}
return null;
}
void getAllAnimations(){
for(int i = 0; i < animation.GetClipCount(); i++)
myAnimStates.Add(GetAnimationClip(i));
}
void PlayAllAnimations(){
if(Time.time >= TimeToWait){
if(count < animation.GetClipCount()-1)
count++;
else
count = 0;
AnimationState myState = myAnimStates[count];
//Debug.Log (myState.clip.name+"-"+count);
myState.speed = playSpeed;
TimeToWait = Time.time + myState.clip.length+pauseTime;
animation.Play(myState.clip.name);
}
//animation.Stop();
}
}
<file_sep>/New Unity Project/Assets/Scripts/Scripts/Scripts/Examples/DoorRotating2.cs
using UnityEngine;
using System.Collections;
public class DoorRotating2 : MonoBehaviour {
public GameObject doorObject;
public float returningTime = 5;
public float speed = 30;
public float minDistance = 5;
private AutoRotate MyRotateScript;
private Transform MyCameraTransform;
// Get our rotate script component from the door itself (this is the trigger
// that 'fires' all the opening/closing door functionality).
void Start() {
MyRotateScript = doorObject.GetComponent<AutoRotate>();
MyCameraTransform = Camera.main.transform;
}
// When the player enter in the door's trigger, rotate it
// and call to the return function
void FixedUpdate() {
if(Vector3.Distance(this.transform.position, MyCameraTransform.position) < minDistance){
RaycastHit hit;
if(Physics.Raycast(MyCameraTransform.position, MyCameraTransform.TransformDirection(Vector3.forward), out hit, minDistance)){
if(hit.transform == this.transform && Input.GetKeyDown(KeyCode.F)){
MyRotateScript.angles = new Vector3(0,90,0); // axis and angles of the rotation.
MyRotateScript.speed = new Vector3(0,speed,0); // speed of the rotation en each axis.
MyRotateScript.RotateInmediate(); // Rotate it.
StartCoroutine(RotateAgain()); // Rotate back to it's origin position/rotation.
}
}
}
}
// Closes the door. It will wait "returningTime" seconds, before start rotating.
IEnumerator RotateAgain () {
yield return new WaitForSeconds(returningTime);
MyRotateScript.angles = new Vector3(0,0,0); // return to zero angles in the three axis.
MyRotateScript.speed = new Vector3(0,speed,0); // speed of the rotation (in Y in this case).
MyRotateScript.RotateInmediate(); // Mak the rotation.
}
}
<file_sep>/New Unity Project/Assets/Scripts/Scripts/Scripts/AutoMove.cs
//=========================================================================================================
//
// Script : AutoMove
// Programador : <NAME>. "Jocyf"
//
// Date: 05/04/2013
// Version : 1.4
//
// Description: Moves a gameobject to a destination at a given time. The destiny can be a point in
// space or a target gameobject. If the target Object exist, the destination point is ignored.
//
//=========================================================================================================
using UnityEngine;
using System.Collections;
[AddComponentMenu( "Utilities/AutoMove")]
public class AutoMove : MonoBehaviour {
public Transform destTransform; // The destination object where we wanna go.
public Vector3 destPoint = Vector3.zero; // Destination point if needed (there isnt an object to go to)
public float moveTime = 2; // The time that gets to reach destination.
public bool isCyclic = false;
public bool isLocal = false;
public bool isActive = false;
// private values to make all work perfectly fine.
private bool Increase = true; // are we going or returning?
private Vector3 OriginalPosition; // Thats my inicial original position (so i can come back).
private Transform myTransform; // My actual tranform (no need to get the Unity's tranform anymore in the script).
private float rate = 0; // rate used to do my interpolation (the lerp function)
private float i = 0; // used to do my interpolation too (the lerp function)
private float moveTimePrev = 2;
void Inicialize(){
if(isLocal)
OriginalPosition = myTransform.localPosition;
else
OriginalPosition = myTransform.position;
rate = 1.0f/moveTime; // needed to do the lerp in the right way.
i = 0;
}
void Start () {
// Get some values and save them just at the begining.
myTransform = transform;
Inicialize();
moveTimePrev = moveTime; // used to detect user changes in inspector.
}
void Update () {
if(!isActive)
return;
// Make sure that time is never zero.
if(moveTime <= 0)
moveTime = 0.01f;
// Detect any change that the user can do in inspector.
if(moveTimePrev != moveTime){
rate = 1.0f/moveTime;
moveTimePrev = moveTime;
}
// If the position where we wanna go is the same that the object starting position
// then there isn't any movement to do.
//if(!destTransform && OriginalPosition == destPoint){ return; }
// Update the movement of our object.
LerpPosition();
}
public void MoveInmediate(){
if (i < 1.0f)
return;
Increase = true;
i = 0;
//LerpPosition();
}
public void ReturnInmediate(){
if (i < 1.0f)
return;
Increase = false;
i = 0;
//LerpPosition();
}
// We fo a interpolation betwen our position and dest position, so the gameobject
// will move at certain speed to get there in the time specified by the user.
void LerpPosition(){
if (i < 1.0f){
// i goes from zero to 1 at certain rate (given by the movetime).
i += Time.deltaTime * rate;
// Do our interpolations from one point in space to another (going & returning).
if(Increase){
if(destTransform){
if(isLocal)
myTransform.localPosition = Vector3.Lerp(OriginalPosition, destTransform.localPosition, i);
else
myTransform.position = Vector3.Lerp(OriginalPosition, destTransform.position, i);
}
else{
if(isLocal)
myTransform.localPosition = Vector3.Lerp(OriginalPosition, destPoint, i);
else
myTransform.position = Vector3.Lerp(OriginalPosition, destPoint, i);
}
}
else{
if(destTransform){
if(isLocal)
myTransform.localPosition = Vector3.Lerp(destTransform.localPosition, OriginalPosition, i);
else
myTransform.position = Vector3.Lerp(destTransform.position, OriginalPosition, i);
}
else{
if(isLocal)
myTransform.localPosition = Vector3.Lerp(destPoint, OriginalPosition, i);
else
myTransform.position = Vector3.Lerp(destPoint, OriginalPosition, i);
}
}
}
else
if(isCyclic){ // if is a cyclic movement, make it to start again returning/going from one point to another.
Increase = !Increase;
i = 0;
}
}
}<file_sep>/New Unity Project/Assets/Scripts/Scripts/Scripts/AutoScale.cs
//====================================================================================================
//
// Script : AutoScale
// Programador : <NAME>. "Jocyf"
//
// Date: 05/04/2013
// Version : 1.3
//
// Description: Scale a GameObject in any axis at a given speed.
// It uses a delay time if needed (zero if doesn't).
//
//====================================================================================================
using UnityEngine;
using System.Collections;
[AddComponentMenu( "Utilities/AutoScale")]
public class AutoScale : MonoBehaviour {
public Vector3 targetScale = new Vector3(2.0f, 2.0f, 2.0f);
public float scaleTime = 2;
public float delayTime = 1; // Delay to start increasing/decreasing the intendity.
public bool isCyclic = true;
private bool Increase = true;
private Vector3 OriginalScale;
private Transform myTransform;
private float internalTime = 0;
private float rate = 0;
private float i = 0;
void Start () {
myTransform = transform;
OriginalScale = myTransform.localScale;
rate = 1.0f/scaleTime;
internalTime = Time.time + delayTime; // setup the first internal delay timer.
}
void LerpScale(){
if (i < 1.0f){
i += Time.deltaTime * rate;
if(Increase)
myTransform.localScale = Vector3.Lerp(OriginalScale, targetScale, i);
else
myTransform.localScale = Vector3.Lerp(targetScale, OriginalScale, i);
}
else
if(isCyclic){
Increase = !Increase;
i = 0;
internalTime = Time.time + delayTime; // setup the first internal delay timer.
}
}
void Update () {
if(Time.time >= internalTime) // is the time reached our internal delay time?
LerpScale();
}
}<file_sep>/New Unity Project/Assets/Scripts/Scripts/Scripts/ScreenSize.cs
//=============================================================================================================
//
// Script : GUIAdjustResolution
// Programador : Unity's Wiki & <NAME>. "Jocyf"
//
// Date: 05/04/2013
// Version : 1.3
//
// Description: Adjust a GUI (GUIText or GUITexture can be used) resolution to the screen resolution.
// Note : It doesn't work if change not resolution but also the Aspect Ratio of the screen (4:3, 16:9, etc...)
//
//=============================================================================================================
// Unable to locate the link to the original code & autor.
// Changed to work in a GUIText too. 02/02/2013
// Chaged to display ratio 05/03/2013.
using UnityEngine;
using System.Collections;
[AddComponentMenu( "Utilities/ScreenSize")]
public class ScreenSize : MonoBehaviour {
public Rect startRect = new Rect( 100, 10, 215, 30 ); // The rect the window is initially displayed at.
public bool allowDrag = true; // Do you want to allow the dragging of the FPS window
public Color color = Color.white; // The color of the GUI,
public Color textColor = Color.white; // The color of the Text.
private float MyWidth = 0;
private float MyHeight = 0;
private string ScreenText;
private GUIStyle style; // The style the text will be displayed at, based en defaultSkin.label.
void Update () {
if(MyWidth != Screen.width || MyHeight != Screen.height){
MyWidth = Screen.width;
MyHeight = Screen.height;
ScreenText = "Screen : "+MyWidth.ToString()+"x"+MyHeight.ToString()+" Ratio:"+(MyWidth/MyHeight).ToString();
if(guiText)
guiText.text = ScreenText;
}
}
void OnGUI(){
if(!guiText){
// Copy the default label skin, change the color and the alignement
if( style == null ){
style = new GUIStyle( GUI.skin.label );
//style.normal.textColor = textColor;
style.alignment = TextAnchor.MiddleCenter;
}
style.normal.textColor = textColor;
GUI.color = color;
startRect = GUI.Window(0, startRect, DoMyWindowScreen, "");
}
}
void DoMyWindowScreen(int windowID){
GUI.Label( new Rect(0, 0, startRect.width, startRect.height), ScreenText, style );
if( allowDrag ) GUI.DragWindow(new Rect(0, 0, Screen.width, Screen.height));
}
}
<file_sep>/New Unity Project/Assets/Scripts/Scripts/Armas/ArmasEstado.js
enum TiposDisparo { Inmediato = 0, Proyectil = 1, Rayo = 2 }
public var Tipo : TiposDisparo = TiposDisparo.Inmediato;
public var nTime : float = 10;
public var SplashObject : GameObject;
public var Decall : GameObject;
public var Aceleracion : float = 1;
public var UseRotation : boolean = false;
public var ProyectilAutoRotacion : boolean = false;
public var VelocidadRotacion : Vector3 = Vector3 (2, 2, 2);
public var MunicionTotal : int = 100;
public var MunicionActual : int = 10;
public var PorcentajeRecargaMunicion : int = 10;
public var Damage : int = 45;
public var Destello : GameObject;
public var RatioDeDisparo : float = 1;
function Start () {
Destroy(this.gameObject, nTime);
}
function Update () {
if(ProyectilAutoRotacion == true){
transform.Rotate(Vector3.right, VelocidadRotacion.x, Space.World);
transform.Rotate(Vector3.up, VelocidadRotacion.y, Space.World);
transform.Rotate(Vector3.forward, VelocidadRotacion.z, Space.World);
}
}
function OnCollisionEnter (other : Collision) {
// Crea el splash al detectar el impacto (la colision)
// Rota el objeto para que tenga la direccion de la normal
var contacto : ContactPoint = other.contacts[0];
var pos : Vector3 = contacto.point;
var rot : Quaternion = Quaternion.identity;
if(UseRotation == true)
rot = Quaternion.FromToRotation(Vector3.up, contacto.normal);
Instantiate(SplashObject, pos, rot);
// Creo un decall.
var rotDecall : Quaternion= Quaternion.FromToRotation(Vector3.up, contacto.normal);
var DecallObj : GameObject = Instantiate(Decall, pos, rotDecall);
DecallObj.transform.localPosition.y += 0.1;
//other.gameObject.transform.parent = DecallObj.transform;
DecallObj.transform.parent = other.transform;
// Destruye la bala ahora mismo.
Destroy (gameObject);
}
<file_sep>/New Unity Project/Assets/puntuacion.js
function Update () {
this.guiText.text = " " + GeneralVars.puntuacion.ToString();
}<file_sep>/New Unity Project/Assets/ExitScript.js
function OnMouseDown(){
Debug.Log("Salir pulsado");
Application.Quit();
}<file_sep>/README.md
# ZombieLandNavMesh
Proyecto ZombieLand con unity 4.6 para usar navMesh
<file_sep>/New Unity Project/Assets/Scripts/Scripts/Scripts/SlowMotion.cs
//=============================================================================================================
//
// Script : SlowMotion
// Programador : <NAME>. "Jocyf"
//
// Date: 05/04/2013
// Version : 1.3
//
// Description: Create a bullet Time effect.
// Changing the value will trigger the effect.
// Setting any initial value will be trigger the effet only when pressing key 'E'.
//
//=============================================================================================================
using UnityEngine;
using System.Collections;
[AddComponentMenu( "Utilities/SlowMotion")]
public class SlowMotion : MonoBehaviour {
[Range(0, 2)] public float timeToScale = 0.1f;
private bool isActive = false;
private float timeScaleOriginal = 1;
private float previosTimeToScale = 0;
// Use this for initialization
void Start () {
timeScaleOriginal = Time.timeScale;
previosTimeToScale = timeToScale;
}
// Update is called once per frame
void Update () {
if(timeToScale == 1)
isActive = false;
if(timeToScale != previosTimeToScale)
isActive = true;
if(Input.GetKeyDown(KeyCode.E))
isActive = !isActive;
if(isActive && Time.timeScale != timeToScale)
Time.timeScale = timeToScale;
else
if(!isActive && Time.timeScale != timeScaleOriginal)
Time.timeScale = timeScaleOriginal;
}
public void SetSlowMotion(bool _active){
isActive = _active;
}
}
<file_sep>/New Unity Project/Assets/Scripts/Scripts/Disparo.js
public var PuntoDisparo : Transform;
public var Arma : GameObject;
private var Aceleracion : float = 1;
//public var Blanco : GameObject;
function Start(){
var PropArmas : ArmasEstado = Arma.GetComponent(ArmasEstado);
Aceleracion = PropArmas.Aceleracion;
}
function Update () {
if(Input.GetButtonDown ("Fire1")){
var CloneFire : GameObject = Instantiate (Arma, PuntoDisparo.position, Camera.main.transform.rotation);
CloneFire.rigidbody.AddRelativeForce(new Vector3(0, 0, Aceleracion), ForceMode.VelocityChange);
}
}<file_sep>/New Unity Project/Assets/Scripts/Scripts/Scripts/Examples/Elevator.cs
//====================================================================================================
//
// Script : Elevator
// Programador : <NAME>. "Jocyf"
//
// Date: 09/04/2013
// Version : 1.5
//
// Description: Start the movement of the elevator, based on trigger events.
// The AutoMove has to have all to zero and all option disabled.
//
//====================================================================================================
using UnityEngine;
using System.Collections;
public class Elevator : MonoBehaviour {
public Vector3 destPoint = Vector3.zero;
public float movingTime = 30;
public float delayTime = 5;
public bool stay = false; // is the elevator stays at dest position or it will return after a delayTime (returningTime).
private GameObject doorObject;
private Vector3 OriginalPoint = Vector3.zero;
private AutoMove MyMoveScript;
// Get our rotate script component from the door itself (this is the trigger
// that 'fires' all the opening/closing door functionality).
void Start() {
doorObject = this.transform.parent.gameObject;
MyMoveScript = doorObject.GetComponent<AutoMove>();
OriginalPoint = doorObject.transform.position;
MyMoveScript.moveTime = movingTime;
}
// When the player enter in the door's trigger, rotate it
// and call to the return function
void OnTriggerEnter(Collider other) {
if(other.tag == "Player"){
MyMoveScript.isActive = true;
if(stay){
if(doorObject.transform.position == OriginalPoint){
MyMoveScript.destPoint = OriginalPoint+destPoint; // axis and angles of the rotation.
MyMoveScript.moveTime = movingTime; // speed of the rotation en each axis.
MyMoveScript.MoveInmediate(); // Rotate it.
}
else
if(doorObject.transform.position == OriginalPoint+destPoint)
MyMoveScript.ReturnInmediate();
}
else{
if(doorObject.transform.position == OriginalPoint){
MyMoveScript.destPoint = OriginalPoint+destPoint; // axis and angles of the rotation.
MyMoveScript.moveTime = movingTime; // speed of the rotation en each axis.
MyMoveScript.MoveInmediate(); // Rotate it.
StartCoroutine(MoveAgain()); // Rotate back to it's origin position/rotation.
}
else
if(doorObject.transform.position == OriginalPoint+destPoint)
MyMoveScript.ReturnInmediate();
}
}
}
// Closes the door. It will wait "returningTime" seconds, before start rotating.
IEnumerator MoveAgain () {
yield return new WaitForSeconds(delayTime);
MyMoveScript.ReturnInmediate();
}
}
<file_sep>/New Unity Project/Assets/EnemigoMierderNavMesh.js
var gunController : GameObject;
var Estado : int = 0;
var Target: GameObject; //El objetivo
private var RotInic : Quaternion;
var RotSpeed : float;
var VelMov : float;
var gravity : float = 9.8;
private var DistanciaCont : float;
var DistEnem : float = 0.5;
private var contador = 0.0;
var damage : int;
//0 vivo , 1 muerto
//var estaMuerto = 0;
private var estaMuerto : boolean = false;
//Animaciones
var IdleAnim : AnimationClip;
var RunAnim : AnimationClip;
var GuardAnim : AnimationClip;
var AttackAnim : AnimationClip;
var AttackAnim2 : AnimationClip;
var MuerteAnim : AnimationClip;
//Sonidos
var attack1: AudioClip;
var attack2: AudioClip;
var muerto: AudioClip;
//PROVA INSTANCIAR CAIXAS
static var myPosition ;
function Start ()
{
gunController = GameObject.FindGameObjectWithTag("Player");
//wrapMode puede ser: Once, Loop, PingPong, Default o ClampForever
animation[IdleAnim.name].speed = 1;
animation[IdleAnim.name].wrapMode = WrapMode.Loop;
animation[RunAnim.name].speed = 1;
animation[RunAnim.name].wrapMode = WrapMode.Loop;
animation[GuardAnim.name].speed = 1;
animation[GuardAnim.name].wrapMode = WrapMode.Loop;
animation[AttackAnim.name].speed = 2;
animation[AttackAnim.name].wrapMode = WrapMode.Once;
animation[AttackAnim2.name].speed = 2;
animation[AttackAnim2.name].wrapMode = WrapMode.Once;
animation[MuerteAnim.name].speed = 1;
animation[MuerteAnim.name].wrapMode = WrapMode.ClampForever;
RotInic = transform.rotation;
animation.Play(IdleAnim.name);
if (Target == null)
{
Target = GameObject.FindGameObjectWithTag("Player");
}
}
function Update ()
{
//PROVA INSTANCIAR CAIXAS
myPosition = transform.position;
////////////
var other : BloodSplatJS = gunController.GetComponent(BloodSplatJS);
var controller : CharacterController = GetComponent(CharacterController);
if (Estado == 0 && estaMuerto == false)
{
//Acción
//Cambio de Estado y Activar siguiente animación.
//Se cambia mediante un disparador externo.
}
if (Estado == 1 && estaMuerto == false) //Perseguir
{
//Acción
//Girar y avanzar.
/* transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(Target.transform.position - transform.position), RotSpeed * Time.deltaTime);
transform.rotation.x = RotInic.x;
transform.rotation.z = RotInic.z; */
//Cambio de Estado y Activar siguiente animación.
/* controller.Move(transform.forward * VelMov * Time.deltaTime);
//Aplicar gravedad
controller.Move(transform.up * -gravity * Time.deltaTime);
*/
//Cambio de Estado y Activar siguiente animación.
DistanciaCont = Vector3.Distance(Target.transform.position, transform.position);
if (DistanciaCont <= DistEnem)
{
Estado = 2;
animation.CrossFade(GuardAnim.name);
}
}
if (Estado == 2 && estaMuerto == false) //Guardia
{
//Acción
//Cambio de Estado y Activar siguiente animación.
DistanciaCont = Vector3.Distance(Target.transform.position, transform.position);
if (DistanciaCont > DistEnem)
{
Estado = 1; //Pasa al estado de perseguir.
animation.CrossFade(RunAnim.name);
}if(DistanciaCont < DistEnem){
Estado = 3;//Pasa al estado de Atacar.
//Hago un Random para variar entre las animaciones de ataque
//Pongo entre 0 y 2 porque Random.Range excluye el valor max , por tanto es entre 0 y 1
var aux = Random.Range(0,2);
if (aux == 0){
contador = Time.time + (animation[AttackAnim.name].clip.length * 0.8);
//El tiempo actual + (el tiempo de la animación y un pelín más)
animation.Play(AttackAnim.name);
//Restar vida con delay
SacarVidaAttack();
//Aplicar Blood Splat
other.ApplyDamage();
//BloodSplatJS.ApplyDamage();
//Sonido ataque 1
playSoundAttack (attack1);
}
if (aux == 1){
contador = Time.time + (animation[AttackAnim2.name].clip.length * 0.8);
//El tiempo actual + (el tiempo de la animación y un pelín más)
animation.Play(AttackAnim2.name);
//Restar vida con delay
SacarVidaAttack();
//Aplicar Blood Splat
other.ApplyDamage();
//BloodSplatJS.ApplyDamage();
//Sonido ataque 2
playSoundAttack (attack2);
}
}
}
if (Estado == 3 && estaMuerto == false) // Atacar
{
//Acción
//Cambio de Estado y Activar siguiente animación.
if (Time.time > contador)
{
Estado = 2;
animation.CrossFade(GuardAnim.name, 2.0f);
}
}
}
function SacarVidaAttack()
{
//Delay de la animación y resto vida
yield WaitForSeconds(0.7);
GeneralVars.nSalud = GeneralVars.nSalud - damage;
}
function playSoundAttack (soundClip:AudioClip){
this.audio.clip = soundClip;
yield WaitForSeconds (0.5);
this.audio.Play();
}
function playSoundMuerte (soundClip:AudioClip){
this.audio.clip = soundClip;
// yield WaitForSeconds (0.5);
this.audio.Play();
}
function Muerte ()
{
Estado =9;
animation.Play (MuerteAnim.name);
estaMuerto = true;
playSoundMuerte(muerto);
WaitAndDestroy();
}
function DoActivateTrigger ()
{
if (estaMuerto == false){
Estado = 1;
animation.CrossFade(RunAnim.name);
}
}
function DoDesactivateTrigger ()
{
if (estaMuerto == false){
Estado = 0; //cambiar a al estado de Inactivo
animation.Play(IdleAnim.name);
}
}
function WaitAndDestroy(){
Destroy(gameObject.collider);
yield WaitForSeconds(2.0);
Destroy(transform.parent.gameObject);
}<file_sep>/New Unity Project/Assets/Scripts/Scripts/CargarMenu.js
function Update () {
if(GeneralVars.nSalud == 0)
Application.LoadLevel ("Menu");
}<file_sep>/New Unity Project/Assets/Scripts/Scripts/Scripts/Examples/DoorRotating1.cs
using UnityEngine;
using System.Collections;
public class DoorRotating1 : MonoBehaviour {
public GameObject doorObject;
public float returningTime = 5;
public float speed = 30;
public bool useKey = false;
private AutoRotate MyRotateScript;
private bool hasEnter = false;
private Vector3 OrigRotation = Vector3.zero;
// Get our rotate script component from the door itself (this is the trigger
// that 'fires' all the opening/closing door functionality).
void Start() {
MyRotateScript = doorObject.GetComponent<AutoRotate>();
OrigRotation = doorObject.transform.eulerAngles;
}
// When the player enter in the door's trigger, rotate it
// and call to the return function
void OnTriggerEnter(Collider other) {
if(other.tag == "Player")
hasEnter = true;
}
void OnTriggerExit(Collider other) {
if(other.tag == "Player")
hasEnter = false;
}
void Update(){
if(!useKey && hasEnter)
OpenDoor();
else
if(useKey && hasEnter && Input.GetKeyDown(KeyCode.F))
OpenDoor();
}
void OpenDoor(){
MyRotateScript.angles = OrigRotation + new Vector3(0,90,0); // axis and angles of the rotation.
MyRotateScript.speed = new Vector3(0,speed,0); // speed of the rotation en each axis.
MyRotateScript.RotateInmediate(); // Rotate it.
StartCoroutine(RotateAgain()); // Rotate back to it's origin position/rotation.
}
// Closes the door. It will wait "returningTime" seconds, before start rotating.
IEnumerator RotateAgain () {
yield return new WaitForSeconds(returningTime);
MyRotateScript.angles = OrigRotation; // return to zero angles in the three axis.
MyRotateScript.speed = new Vector3(0,speed,0); // speed of the rotation (in Y in this case).
MyRotateScript.RotateInmediate(); // Mak the rotation.
}
}
<file_sep>/New Unity Project/Assets/Scripts/Scripts/Scripts/DrawGizmos.cs
//====================================================================================================
//
// Script : DrawGizmos
// Programador : <NAME>. "Jocyf"
//
// Date: 06/04/2013
// Version : 1.0
//
// Description: Draw icon gizmos in the scene window.
// Obsolete : Unity provides an integrated way to do this.
//
//====================================================================================================
using UnityEngine;
using System.Collections;
[AddComponentMenu( "Utilities/DrawGizmos")]
public class DrawGizmos : MonoBehaviour {
public Texture2D icon;
// Implement this OnDrawGizmosSelected
// if you want to draw gizmos only if the
// object is selected.
void OnDrawGizmosSelected () {
if(icon != null)
Gizmos.DrawIcon (transform.position, icon.name);
}
// Implement this OnDrawGizmos if you want
// to draw gizmos that are also pickable
// and always drawn.
void OnDrawGizmos () {
if(icon != null)
Gizmos.DrawIcon (transform.position, icon.name);
}
}
<file_sep>/New Unity Project/Assets/Scripts/Scripts/Scripts/Examples/MoveMissile.cs
//=========================================================================================================
//
// Script : AutoMove
// Programador : <NAME>. "Jocyf"
//
// Date: 05/04/2013
// Version : 1.4
//
// Description: Moves a gameobject to a destination at a given time. The destiny can be a point in
// space or a target gameobject. If the target Object exist, the destination point is ignored.
//
//=========================================================================================================
using UnityEngine;
using System.Collections;
public class MoveMissile : MonoBehaviour {
public float speed = 2; // The time that gets to reach destination.
private Transform myTransform; // My actual tranform (no need to get the Unity's tranform anymore in the script).
private Transform target;
void Start () {
// Get some values and save them just at the beg ining.
myTransform = transform;
//target = GameObject.Find("First Person Controller").transform;
target = Camera.main.transform;
}
void Update () {
float dist = Vector3.Distance(myTransform.position, target.position);
if(dist < 0.3f){
Debug.Log("Missile hit!!!!");
}
myTransform.Translate(Vector3.forward*speed*Time.deltaTime, Space.Self);
}
}<file_sep>/New Unity Project/Assets/Scripts/Scripts/Scripts/Examples/CannonFire.cs
using UnityEngine;
using System.Collections;
public class CannonFire : MonoBehaviour {
public Transform puntoDisparo;
public GameObject bala;
public float acel = 20;
public float ratio = 2;
private float internalTime = 0;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void FixedUpdate () {
if(Time.time >= internalTime){
RaycastHit hit;
if(Physics.Raycast(this.transform.position, this.transform.TransformDirection(Vector3.forward), out hit, 1000)){
if(hit.transform.tag == "Player")
Fire();
}
}
}
void Fire(){
if(Time.time >= internalTime){
GameObject CloneFire = (GameObject) Instantiate (bala, puntoDisparo.position, puntoDisparo.rotation);
CloneFire.rigidbody.AddRelativeForce(new Vector3(0, 0, acel), ForceMode.VelocityChange);
internalTime = Time.time + ratio;
}
}
}
<file_sep>/New Unity Project/Assets/Scripts/Scripts/Scripts/AutoPlayVideo.cs
//===================================================================================
// Script : AutoPlayVideo
// Programador : <NAME> 'Jocyf'
//
// Date: 01/02/2013
// Version : 1.4
//
// Description: Play/stop a movietexture just ckicking on the texture itself.
// Or pressing the 'A' key in the keyboard.
//
// Note : Only work with Pro version.
//
//===================================================================================
using UnityEngine;
using System.Collections;
[AddComponentMenu( "Utilities/AutoPlayVideo")]
public class AutoPlayVideo : MonoBehaviour {
public bool isPlaying = false;
private MovieTexture myMovie;
void Start (){
myMovie = (MovieTexture)guiTexture.texture;
}
void Update(){
// detect when user press the 'A' key in keyboard.
if(Input.GetKeyDown(KeyCode.A)) // Change "KeyCode.A" to use another keyboard's key
isPlaying = !isPlaying;
if(isPlaying && !myMovie.isPlaying)
myMovie.Play();
else
if(!isPlaying && myMovie.isPlaying)
myMovie.Stop();
}
// Detect the texture click.
void OnMouseDown (){
isPlaying = !isPlaying;
}
}<file_sep>/New Unity Project/Assets/ControlsScript.js
function OnMouseDown(){
Debug.Log("Controles pulsado");
Application.LoadLevel("Controls");
}<file_sep>/New Unity Project/Assets/Scripts/Scripts/Scripts/AutoBlink.cs
using UnityEngine;
using System.Collections;
public class AutoBlink : MonoBehaviour {
public float delayTime = 1;
private bool isHidding = true;
private float internalTime = 0;
// Get our rotate script component from the door itself (this is the trigger
// that 'fires' all the opening/closing door functionality).
void Start() {
this.SendMessage("SetTimeToHide", .0f);
internalTime = Time.time + delayTime;
}
void Update(){
if(Time.time >= internalTime){
if(isHidding){
this.SendMessage("HideInmediate");
this.SendMessage("SetTimeToShow", .0f);
}
else{
this.SendMessage("ShowInmediate");
this.SendMessage("SetTimeToHide", .0f);
}
isHidding = !isHidding;
internalTime = Time.time + delayTime;
}
}
}
<file_sep>/New Unity Project/Assets/Scripts/Scripts/Scripts/AutoRotate.cs
//====================================================================================================
// Copyright <NAME> "Jocyf" 2013 - 29-01-2013
// AutoSpin v1.1
// Rotate a GameObject in any axis, using local o global coordinates.
//
// How to use it:
// Drag this script to any gameobect and write the desired speed in each axis (zero for no rotation).
//
///==================================================================================================
using UnityEngine;
using System.Collections;
[AddComponentMenu( "Utilities/AutoRotate")]
public class AutoRotate : MonoBehaviour {
public Vector3 angles = new Vector3 (0, 0, 0); // Speed of the rotation in each axis.
public Vector3 speed = new Vector3 (0, 0, 0); // Speed of the rotation in each axis.
public bool local = false; // Is the rotation in local space (or in global)
public bool randomize = false; // Make the velocity randomized (min is zero , max is the velocity of speed var.)
public bool cyclic = false;
private Vector3 anglesAux = Vector3.zero;
private Vector3 localAnglesAux = Vector3.zero;
private bool isComplete = false;
private bool isGoingUp = true;
private Transform MyTransform;
private Vector3 OrigEulerAngles = Vector3.zero;
private Vector3 OrigLocalEulerAngles = Vector3.zero;
void ResetUnusedAngles(){
if(local){
if(speed.x == 0)
angles.x = OrigLocalEulerAngles.x;
if(speed.y == 0)
angles.y = OrigLocalEulerAngles.y;
if(speed.z == 0)
angles.z = OrigLocalEulerAngles.z;
}
else{
if(speed.x == 0)
angles.x = OrigEulerAngles.x;
if(speed.y == 0)
angles.y = OrigEulerAngles.y;
if(speed.z == 0)
angles.z = OrigEulerAngles.z;
}
}
void Start(){
MyTransform = this.transform;
OrigEulerAngles = MyTransform.eulerAngles;
OrigLocalEulerAngles = MyTransform.localEulerAngles;
ResetUnusedAngles();
if(randomize)
speed = new Vector3(Random.Range(0,speed.x), Random.Range(0,speed.y), Random.Range(0,speed.z));
}
void Update(){
if(isComplete && cyclic){
isGoingUp = !isGoingUp;
isComplete = false;
}
if(isGoingUp)
RotatingUp();
else
RotatingDown();
}
public void RotateInmediate(){
isGoingUp = true;
isComplete = false;
ResetUnusedAngles();
RotatingUp();
}
void RotatingUp(){
if(speed.x > 0){
if(local)
localAnglesAux.x = Mathf.MoveTowardsAngle(transform.localEulerAngles.x, angles.x, speed.x * Time.deltaTime);
else
anglesAux.x = Mathf.MoveTowardsAngle(transform.eulerAngles.x, angles.x, speed.x * Time.deltaTime);
}
if(speed.y > 0){
if(local)
localAnglesAux.y = Mathf.MoveTowardsAngle(transform.localEulerAngles.y, angles.y, speed.y * Time.deltaTime);
else
anglesAux.y = Mathf.MoveTowardsAngle(transform.eulerAngles.y, angles.y, speed.y * Time.deltaTime);
}
if(speed.z > 0){
if(local)
localAnglesAux.z = Mathf.MoveTowardsAngle(transform.localEulerAngles.z, angles.z, speed.z * Time.deltaTime);
else
anglesAux.z = Mathf.MoveTowardsAngle(transform.eulerAngles.z, angles.z, speed.z * Time.deltaTime);
}
if(local)
transform.localEulerAngles = localAnglesAux;
else
transform.eulerAngles = anglesAux;
if(local && Vector3.Distance(angles, transform.localEulerAngles) < 0.1f)
isComplete = true;
else
if(!local && Vector3.Distance(angles, transform.eulerAngles) < 0.1f)
isComplete = true;
}
void RotatingDown(){
if(speed.x > 0){
if(local)
localAnglesAux.x = Mathf.MoveTowardsAngle(transform.localEulerAngles.x, OrigLocalEulerAngles.x, speed.x * Time.deltaTime);
else
anglesAux.x = Mathf.MoveTowardsAngle(transform.eulerAngles.x, OrigEulerAngles.x, speed.x * Time.deltaTime);
}
if(speed.y > 0){
if(local)
localAnglesAux.y = Mathf.MoveTowardsAngle(transform.localEulerAngles.y, OrigLocalEulerAngles.y, speed.y * Time.deltaTime);
else
anglesAux.y = Mathf.MoveTowardsAngle(transform.eulerAngles.y, OrigEulerAngles.y, speed.y * Time.deltaTime);
}
if(speed.z > 0){
if(local)
localAnglesAux.z = Mathf.MoveTowardsAngle(transform.localEulerAngles.z, OrigLocalEulerAngles.z, speed.z * Time.deltaTime);
else
anglesAux.z = Mathf.MoveTowardsAngle(transform.eulerAngles.z, OrigEulerAngles.z, speed.z * Time.deltaTime);
}
if(local)
transform.localEulerAngles = localAnglesAux;
else
transform.eulerAngles = anglesAux;
if(local && Vector3.Distance(OrigLocalEulerAngles, transform.localEulerAngles) < 0.1f)
isComplete = true;
else
if(!local && Vector3.Distance(OrigEulerAngles, transform.eulerAngles) < 0.1f)
isComplete = true;
}
}<file_sep>/New Unity Project/Assets/Scripts/Scripts/Scripts/Examples/BillboardMissile.cs
//====================================================================================================
//
// Script : BillboardMissile
// Programador : <NAME>. "Jocyf"
//
// Date: 05/04/2013
// Version : 1.3
//
// Description: Rotate the missile to look forward the target directly.
// Changes the rigidbody values to make a missile seeker.
// Also checks collision to display a Msg.
//
//====================================================================================================
using UnityEngine;
using System.Collections;
public class BillboardMissile : MonoBehaviour{
public float accuracy = 10;
public float speed = 10;
private Transform target;
private Transform MyTransform;
void Start(){
target = GameObject.Find("First Person Controller").transform;
MyTransform = this.transform;
}
void Update(){
MyTransform.LookAt(target.position);
//this.rigidbody.velocity = Vector3.zero;
this.rigidbody.AddRelativeForce(new Vector3(0, 0, accuracy), ForceMode.Force);
this.rigidbody.AddRelativeForce(new Vector3(0, 0, speed), ForceMode.VelocityChange);
}
void OnCollisionEnter(Collision collision) {
if(collision.transform.tag == "Player"){
Debug.Log("Missile Damage!!!");
}
}
}<file_sep>/New Unity Project/Assets/Scripts/Scripts/Scripts/GUIFullScreen.cs
//====================================================================================================
//
// Script : GUIFullScreen
// Programador : <NAME>. "Jocyf"
//
// Date: 05/04/2013
// Version : 1.3
//
// Description: Scale a GUITexture to the screen's size.
// Get a wrong aspect if changes the ratio of the screen.
// Depending on the ratio two images shold be used (one for 4:3 an another for 16:9)
//
//====================================================================================================
using UnityEngine;
using System.Collections;
[AddComponentMenu( "Utilities/GUIFullScreen")]
[RequireComponent(typeof(GUITexture))]
public class GUIFullScreen : MonoBehaviour {
public Texture2D texture43; // Ratio : 1.33
public Texture2D texture169; // Ratio : 1.77
public bool AdjustInUpdate = false;
private float ratio = 1.3f;
void Start() {
this.transform.position = Vector3.zero;
ratio = (float)Screen.width / (float)Screen.height;
if(guiTexture){
guiTexture.pixelInset = new Rect(0, 0, Screen.width, Screen.height);
if(ratio < 1.6f)
guiTexture.texture = texture43;
else
guiTexture.texture = texture169;
}
}
void Update(){
if(AdjustInUpdate && guiTexture){
guiTexture.pixelInset = new Rect(0, 0, Screen.width, Screen.height);
ratio = (float)Screen.width / (float)Screen.height;
if(ratio < 1.6f)
guiTexture.texture = texture43;
else
guiTexture.texture = texture169;
}
}
}<file_sep>/New Unity Project/Assets/Scripts/Scripts/Scripts/AutoSpin.cs
//====================================================================================================
//
// Script : AutoSpin
// Programador : <NAME>. "Jocyf"
//
// Date: 05/04/2013
// Version : 1.3
//
// Description: Rotate a GameObject in any axis, using local o global coordinates.
// It uses a delay time if needed (zero if doesn't).
//
//====================================================================================================
using UnityEngine;
using System.Collections;
[AddComponentMenu( "Utilities/AutoSpin")]
public class AutoSpin : MonoBehaviour {
public Vector3 speed = new Vector3 (2, 2, 2); // Speed of the rotation in each axis.
public bool local = false; // Is the rotation in local space (or in global)
public bool randomize = false; // Make the velocity randomized (min is zero , max is the velocity of speed var.)
private Transform MyTransform;
void Start(){
MyTransform = this.transform;
if(randomize)
speed = new Vector3(Random.Range(0,speed.x), Random.Range(0,speed.y), Random.Range(0,speed.z));
}
void Update() {
if(speed.x > 0){
if(local)
MyTransform.Rotate(Vector3.right, speed.x * Time.deltaTime, Space.Self);
else
MyTransform.Rotate(Vector3.right, speed.x * Time.deltaTime, Space.World);
}
if(speed.y > 0){
if(local)
MyTransform.Rotate(Vector3.up, speed.y * Time.deltaTime, Space.Self);
else
MyTransform.Rotate(Vector3.up, speed.y * Time.deltaTime, Space.World);
}
if(speed.z > 0){
if(local)
MyTransform.Rotate(Vector3.forward, speed.z * Time.deltaTime, Space.Self);
else
MyTransform.Rotate(Vector3.forward, speed.z * Time.deltaTime, Space.World);
}
}
}<file_sep>/New Unity Project/Assets/Scripts/Scripts/Scripts/AutoLightIntensity.cs
//====================================================================================================
//
// Script : AutoLightIntensity
// Programador : <NAME>. "Jocyf"
//
// Date: 05/04/2013
// Version : 1.4
//
// Description: Increase, decrease (or both doing a cycle) the intensity of a light at given speed.
//
//
//====================================================================================================
// http://wiki.unity3d.com/index.php/Flickering_Light
// http://wiki.unity3d.com/index.php/Flickering_Light2
using UnityEngine;
using System.Collections;
[AddComponentMenu( "Utilities/AutoLightIntensity")]
[RequireComponent(typeof(Light))]
public class AutoLightIntensity : MonoBehaviour {
[Range(0,8)] public float minIntensity = 0; // Maximun and Minimun intensity.
[Range(0,8)] public float maxIntensity = 7;
public float speed = 1; // the speed the light changes it's intensity
public float delayTime = 1; // Delay to start increasing/decreasing the intendity.
public bool isGoingUp = true; // Start going to máximum)
public bool isCyclic = true; // Is gonna be a cycle going up & down?
private Light myPointLight;
private float currentIntensity = 0;
private float internalTime = 0;
// Use this for initialization
void Start () {
myPointLight = GetComponent(typeof(Light)) as Light;
currentIntensity = myPointLight.intensity;
internalTime = Time.time + delayTime; // setup the first internal delay timer.
}
// Update is called once per frame
void Update () {
if(Time.time >= internalTime){ // is the time reached our internal delay time?
if(isGoingUp) // increase the light intensity.
if(currentIntensity < maxIntensity)
currentIntensity += speed * Time.deltaTime;
else{
currentIntensity = maxIntensity;
if(isCyclic){
internalTime = Time.time + delayTime; // setup our internal delay timer.
isGoingUp = false;
}
}
else
if(currentIntensity > minIntensity) // decrease the light intensity.
currentIntensity -= speed * Time.deltaTime;
else{
currentIntensity = minIntensity;
if(isCyclic){
internalTime = Time.time + delayTime; // setup our internal delay timer.
isGoingUp = true;
}
}
myPointLight.intensity = currentIntensity;
}
}
}
<file_sep>/New Unity Project/Assets/Scripts/Scripts/Scripts/AutoShow.cs
//====================================================================================================
//
// Script : AutoShow
// Programador : <NAME>. "Jocyf"
//
// Date: 06/04/2013
// Version : 1.3
//
// Description: Shows a gameobject, GUItext or GUITexture in the time specified.
// The time must be a value greater than zero.
// To show inmediatly call ShowInmediate() function.
//
//====================================================================================================
using UnityEngine;
using System.Collections;
[AddComponentMenu( "Utilities/AutoShow")]
public class AutoShow : MonoBehaviour {
public float delayTime = 0;
public bool fadeIn = false;
public float fadeSpeed = 1;
public bool isActive = false;
private bool hasFinished = true;
// Only shows the object if time is greater than zero.
void Start() {
if(isActive)
StartCoroutine(DelayShow());
}
IEnumerator DelayShow(){
yield return new WaitForSeconds(delayTime);
if(!fadeIn)
InmediateShow();
else{
isActive = true;
hasFinished = false;
}
}
void InmediateShow(){
if(renderer){
Color _color = renderer.material.GetColor("_Color"); // Normal Transparent shader
_color.a = 1;
renderer.material.SetColor("_Color", _color); // Normal Transparent shader
//renderer.enabled = true;
}
else
if(guiText){
Color _color = guiText.material.color;
_color.a = 1;
guiText.material.color = _color;
//guiText.enabled = true;
}
else
if(guiTexture){
Color _color = guiTexture.color;
_color.a = 1;
guiTexture.color = _color;
//guiTexture.enabled = true;
}
hasFinished = true;
isActive = false;
}
void Update(){
if(!isActive)
return;
if(fadeIn && !hasFinished){
if(guiTexture){
Color _color = guiTexture.color;
_color.a = Mathf.Lerp(_color.a, 1F, fadeSpeed*Time.deltaTime);
if(_color.a > .98F){
_color.a = 1;
hasFinished = true;
}
guiTexture.color = _color;
}
else
if(guiText){
Color _color = guiText.material.color;
_color.a = Mathf.Lerp(_color.a, 1F, fadeSpeed*Time.deltaTime);
if(_color.a > .98F){
_color.a = 1;
hasFinished = true;
}
guiText.material.color = _color;
}
else
if(renderer){
Color _color = renderer.material.GetColor("_Color"); // Normal Transparent shader
//Color _color = renderer.material.GetColor("_TintColor"); // Use this with Particles shaders
_color.a = Mathf.Lerp(_color.a, 1F, fadeSpeed*Time.deltaTime);
if(_color.a > .98F){
_color.a = 1;
hasFinished = true;
}
renderer.material.SetColor("_Color", _color); // Normal Transparent shader
//renderer.material.SetColor("_TintColor", _color); // Use this with Particles shaders
}
}
else
if(fadeIn && hasFinished)
isActive = false;
}
public void SetTimeToShow(float _Time){
isActive = true;
delayTime = _Time;
if(fadeIn)
hasFinished = false;
StartCoroutine(DelayShow());
}
// Show inmediatly.
public void ShowInmediate(){
delayTime = 0;
isActive = true;
//fadeIn = false;
hasFinished = true;
InmediateShow();
}
}<file_sep>/New Unity Project/Assets/Scripts/Scripts/MenuGUI.js
function OnGUI(){
GUI.Label (Rect(Screen.width/2 - 60, Screen.height/2 - 60, 60, 60), "Prueba");
if (GUI.Button (Rect(Screen.width/2 - 60, Screen.height/2 - 60 + 20, 60, 60), "Play")){
GeneralVars.nSalud = 100;
Application.LoadLevel("Test1");
}
}<file_sep>/New Unity Project/Assets/AtaqueCuchillo.js
#pragma strict
var objetivo: GameObject;
function Start () {
}
function Update () {
if (Input.GetButtonDown("Fire1")||Input.GetButtonDown("Fire2")){
Ataque();
}
}
function Ataque(){
var saludEnemigo:ManejadordeBlancos = objetivo.GetComponent("Salud");
//saludEnemigo.DecrementaSalud(-50);
}<file_sep>/New Unity Project/Assets/armasEstado.js
#pragma strict
//var SplashObject:GameObject;
public var Damage:int = 45;
public var nTime : float = 3;
function Start () {
Destroy(this.gameObject,nTime);
}
function OnCollisionEnter (other:Collision) {
var contacto:ContactPoint = other.contacts[0];
var pos:Vector3 = contacto.point;
var rot:Quaternion = Quaternion.identity;
//Instantiate(SplashObject,pos,rot);
Destroy(gameObject);
}<file_sep>/New Unity Project/Assets/Scripts/Scripts/Scripts/TotalTimeCounter.cs
// Changed to work in a GUIText too. 02/02/2013
using UnityEngine;
using System.Collections;
[AddComponentMenu( "Utilities/TotalTimeCounter")]
public class TotalTimeCounter : MonoBehaviour {
public Rect startRect = new Rect( 390, 10, 150, 30 ); // The rect the time-label is initially displayed at.
public Color textColor = Color.white;
public int countUntill = 0; // Maximun time to count (then stops). if zero then there is no top.
public int delayTime = 5; // Deay time to start counting.
private float internalTime = 0;
private float TotalTimePlayed = 0;
private string textToDisplay = "";
private GUIStyle style; // The style the text will be displayed at, based en defaultSkin.label.
public bool IsFinished(){ return countUntill != 0 && TotalTimePlayed >= countUntill; }
// Use this for initialization
void Start () {
internalTime = Time.time + delayTime;
textToDisplay = "00:00";
}
// Update is called once per frame
void Update () {
if(Time.time >= internalTime){
if( (countUntill != 0 && TotalTimePlayed < countUntill) || (countUntill == 0) )
TotalTimePlayed += Time.deltaTime;
textToDisplay = FormatTime(TotalTimePlayed);
}
}
string FormatTime(float time) {
int minutes = (int)(time / 60);
int seconds = (int)time % 60;
string timeText = string.Format ("{0:00}:{1:00}", minutes, seconds);
return timeText;
}
void OnGUI(){
// Copy the default label skin, change the color and the alignement
if( style == null ){
style = new GUIStyle( GUI.skin.label );
style.normal.textColor = textColor;
style.alignment = TextAnchor.MiddleCenter;
}
GUI.color = textColor;
GUI.Label( startRect, textToDisplay, style );
}
}
<file_sep>/New Unity Project/Assets/Scripts/Scripts/Scripts/Examples/DoorMoving.cs
using UnityEngine;
using System.Collections;
public class DoorMoving : MonoBehaviour {
public GameObject doorObject;
public float movingTime = 30;
public float delayTime = 5;
public Vector3 destPoint = Vector3.zero;
private Vector3 OriginalPoint = Vector3.zero;
private AutoMove MyMoveScript;
// Get our rotate script component from the door itself (this is the trigger
// that 'fires' all the opening/closing door functionality).
void Start() {
MyMoveScript = doorObject.GetComponent<AutoMove>();
OriginalPoint = this.transform.position;
}
// When the player enter in the door's trigger, rotate it
// and call to the return function
void OnTriggerEnter(Collider other) {
MyMoveScript.isActive = true;
if(other.tag == "Player"){
MyMoveScript.destPoint = OriginalPoint+destPoint; // axis and angles of the rotation.
MyMoveScript.moveTime = movingTime; // speed of the rotation en each axis.
MyMoveScript.MoveInmediate(); // Rotate it.
StartCoroutine(MoveAgain()); // Rotate back to it's origin position/rotation.
}
}
// Closes the door. It will wait "returningTime" seconds, before start rotating.
IEnumerator MoveAgain () {
yield return new WaitForSeconds(delayTime);
//MyMoveScript.destPoint = OriginalPoint; // return to zero angles in the three axis.
//MyMoveScript.moveTime = movingTime; // speed of the rotation (in Y in this case).
MyMoveScript.ReturnInmediate(); // Mak the rotation.
}
}
<file_sep>/New Unity Project/Assets/Guns/Scripts/LoadGun.js
#pragma strict
var toolbarInt : int = 0;
// he borrado string "Gun0"
var toolbarStrings : String[] = ["Gun1", "Gun2","Gun3","Gun4","Gun5", "Reload"];
private var sfx:boolean=false;
private var sfxSpeed=2.0;
private var gun:GameObject;
//var bayonet:boolean=true;
var gun01:boolean=true;
var gun02:boolean=false;
var gun03:boolean=false;
var gun04:boolean=false;
var gun05:boolean=false;
//var bayonetPrefab:GameObject;
var Gun01Prefab:GameObject;
var Gun02Prefab:GameObject;
var Gun03Prefab:GameObject;
var Gun04Prefab:GameObject;
var Gun05Prefab:GameObject;
var walkSound: AudioClip;
var jumpSound: AudioClip;
//MUNICIO
static var munAct1 = 30;
static var munMax1 = 30;
static var munAct2 = 5;
static var munMax2 = 5;
static var munAct3 = 30;
static var munMax3 = 30;
static var munAct4 = 12;
static var munMax4 = 12;
static var munAct5 = 8;
static var munMax5 = 8;
static var municionTotal = 30;
static var municionActual = 30;
var numArma = 1;
var diferencia = 0;
var style : GUIStyle;
style.fontSize = 30;
style.normal.textColor = Color.white;
function OnGUI()
{
GUI.Label(Rect(50, 660, 400, 20), municionActual.ToString()+" / "+municionTotal.ToString(), style);
}
/////////
function Start () {
loadGun (Gun01Prefab);
}
function LateUpdate () {
var getFire=Input.GetButton ("Fire1")||Input.GetButton ("Fire2");
var getMove =Input.GetAxisRaw("Vertical")||Input.GetAxisRaw("Horizontal");
var jump=Input.GetButton ("Jump");
/*if (Input.GetKeyDown ("0"))
{
Destroy (gun);
loadGun (bayonetPrefab);
}*/
////PROVA RECARGAS CON Y SIN BALAS EN EL CARGADOR
if(GunPlayer.numeroArma == 1 ){
if(municionActual == 0 && municionTotal > 0){
GunPlayer.reload = true;
if(municionTotal >= 30){
municionActual = 30 ;
munAct1 = municionActual;
municionTotal = munMax1 - 30;
munMax1 = municionTotal;
}
else{
municionActual = municionTotal;
munAct1 = municionActual;
municionTotal = 0;
munMax1 = municionTotal;
}
}
if(Input.GetKeyDown("r") && municionTotal > 0 && municionActual < 30){
GunPlayer.reload = true;
if(municionTotal >= 30){
diferencia = 30 - municionActual;
municionActual = 30 ;
munAct1 = municionActual;
municionTotal = munMax1 - diferencia;
munMax1 = municionTotal;
}
else{
GunPlayer.reload = true;
diferencia = 30 - municionActual;
if(municionTotal >= diferencia){
municionActual = 30;
munAct1 = municionActual;
municionTotal = munMax1 - diferencia;
munMax1 = municionTotal;
}
else{
municionActual = municionActual + municionTotal;
munAct1 = municionActual;
municionTotal = 0;
munMax1 = municionTotal;
}
}
}
}
////////////// 2
if(GunPlayer.numeroArma == 2 ){
if(municionActual == 0 && municionTotal > 0){
GunPlayer.reload = true;
if(municionTotal >= 5){
municionActual = 5 ;
munAct2 = municionActual;
municionTotal = munMax2 - 5;
munMax2 = municionTotal;
}
else{
municionActual = municionTotal;
munAct2 = municionActual;
municionTotal = 0;
munMax2 = municionTotal;
}
}
if(Input.GetKeyDown("r") && municionTotal > 0 && municionActual < 5){
GunPlayer.reload = true;
if(municionTotal >= 5){
diferencia = 5 - municionActual;
municionActual = 5 ;
munAct2 = municionActual;
municionTotal = munMax2 - diferencia;
munMax2 = municionTotal;
}
else{
GunPlayer.reload = true;
diferencia = 5 - municionActual;
if(municionTotal >= diferencia){
municionActual = 5;
munAct2 = municionActual;
municionTotal = munMax2 - diferencia;
munMax2 = municionTotal;
}
else{
municionActual = municionActual + municionTotal;
munAct2 = municionActual;
municionTotal = 0;
munMax2 = municionTotal;
}
}
}
}
/////////////////// 3
if(GunPlayer.numeroArma == 3 ){
if(municionActual == 0 && municionTotal > 0){
GunPlayer.reload = true;
if(municionTotal >= 30){
municionActual = 30 ;
munAct3 = municionActual;
municionTotal = munMax3 - 30;
munMax3 = municionTotal;
}
else{
municionActual = municionTotal;
munAct3 = municionActual;
municionTotal = 0;
munMax3 = municionTotal;
}
}
if(Input.GetKeyDown("r") && municionTotal > 0 && municionActual < 30){
GunPlayer.reload = true;
if(municionTotal >= 30){
diferencia = 30 - municionActual;
municionActual = 30 ;
munAct3 = municionActual;
municionTotal = munMax3 - diferencia;
munMax3 = municionTotal;
}
else{
GunPlayer.reload = true;
diferencia = 30 - municionActual;
if(municionTotal >= diferencia){
municionActual = 30;
munAct3 = municionActual;
municionTotal = munMax3 - diferencia;
munMax3 = municionTotal;
}
else{
municionActual = municionActual + municionTotal;
munAct3 = municionActual;
municionTotal = 0;
munMax3 = municionTotal;
}
}
}
}
/////////////////// 4
if(GunPlayer.numeroArma == 4 ){
if(municionActual == 0 && municionTotal > 0){
GunPlayer.reload = true;
if(municionTotal >= 12){
municionActual = 12 ;
munAct4 = municionActual;
municionTotal = munMax4 - 12;
munMax4 = municionTotal;
}
else{
municionActual = municionTotal;
munAct4 = municionActual;
municionTotal = 0;
munMax4 = municionTotal;
}
}
if(Input.GetKeyDown("r") && municionTotal > 0 && municionActual < 12){
GunPlayer.reload = true;
if(municionTotal >= 12){
diferencia = 12 - municionActual;
municionActual = 12 ;
munAct4 = municionActual;
municionTotal = munMax4 - diferencia;
munMax4 = municionTotal;
}
else{
GunPlayer.reload = true;
diferencia = 12 - municionActual;
if(municionTotal >= diferencia){
municionActual = 12;
munAct4 = municionActual;
municionTotal = munMax4 - diferencia;
munMax4 = municionTotal;
}
else{
municionActual = municionActual + municionTotal;
munAct4 = municionActual;
municionTotal = 0;
munMax4 = municionTotal;
}
}
}
}
/////////////////// 5
if(GunPlayer.numeroArma == 5 ){
if(municionActual == 0 && municionTotal > 0){
GunPlayer.reload = true;
if(municionTotal >= 8){
municionActual = 8;
munAct5 = municionActual;
municionTotal = munMax5 - 8;
munMax5 = municionTotal;
}
else{
municionActual = municionTotal;
munAct5 = municionActual;
municionTotal = 0;
munMax5 = municionTotal;
}
}
if(Input.GetKeyDown("r") && municionTotal > 0 && municionActual < 8){
GunPlayer.reload = true;
if(municionTotal >= 8){
diferencia = 8 - municionActual;
municionActual = 8 ;
munAct5 = municionActual;
municionTotal = munMax5 - diferencia;
munMax5 = municionTotal;
}
else{
GunPlayer.reload = true;
diferencia = 8 - municionActual;
if(municionTotal >= diferencia){
municionActual = 8;
munAct5 = municionActual;
municionTotal = munMax5 - diferencia;
munMax5 = municionTotal;
}
else{
municionActual = municionActual + municionTotal;
munAct5 = municionActual;
municionTotal = 0;
munMax5 = municionTotal;
}
}
}
}
//////////////
if (Input.GetKeyDown ("1"))
{
Destroy (gun);
loadGun (Gun01Prefab);
municionActual = munAct1;
municionTotal = munMax1;
}
if (Input.GetKeyDown ("2"))
{
Destroy (gun);
loadGun (Gun02Prefab);
municionActual = munAct2;
municionTotal = munMax2;
}
if (Input.GetKeyDown ("3"))
{
Destroy (gun);
loadGun (Gun03Prefab);
municionActual = munAct3;
municionTotal = munMax3;
}
if (Input.GetKeyDown ("4"))
{
Destroy (gun);
loadGun (Gun04Prefab);
municionActual = munAct4;
municionTotal = munMax4;
}
if (Input.GetKeyDown ("5"))
{
Destroy (gun);
loadGun (Gun05Prefab);
municionActual = munAct5;
municionTotal = munMax5;
}
if (getMove)
{
if (!sfx&& !jump)
playSound (walkSound,sfxSpeed);
}
if (jump)
{
if (!sfx){
playSound (jumpSound,0.50);
}
}
if (!jump&& getMove==0 &&!getFire)
{
}
}
function playSound (soundClip:AudioClip, speed:float){
this.audio.clip = soundClip;
this.audio.pitch=speed;
this.audio.Play();
sfx=true;
yield WaitForSeconds (soundClip.length/speed);
sfx=false;
}
function waitTime (wTime:float)
{
yield WaitForSeconds (wTime);
}
function loadGun (gunPrefab:GameObject) {
gun =Instantiate (gunPrefab, this.transform.localPosition+gunPrefab.transform.localPosition, gunPrefab.transform.localRotation);
gun.transform.parent=this.transform;
gun.transform.localPosition=gunPrefab.transform.localPosition;
gun.transform.localRotation=gunPrefab.transform.localRotation;
}
<file_sep>/New Unity Project/Assets/Scripts/Scripts/GUI/HeathText.js
function Update () {
this.guiText.text = " " + GeneralVars.nSalud.ToString();
if(GeneralVars.nSalud <= 0){
Application.LoadLevel("Muerte");
}
}<file_sep>/New Unity Project/Assets/Scripts/Scripts/GUI/Gradient Bar.js
function Update () {
renderer.material.SetFloat("_Cutoff", Mathf.InverseLerp(0, 100, GeneralVars.nSalud));
}<file_sep>/New Unity Project/Assets/Scripts/Scripts/Scripts/Examples/DetectPickup.cs
using UnityEngine;
using System.Collections;
public class DetectPickup : MonoBehaviour {
public enum pickupType { Health, Ammo, Mana };
public pickupType type = pickupType.Health;
// Update is called once per frame
void OnTriggerEnter(Collider other) {
if(other.tag == "Player"){
switch (type){
case pickupType.Health:
// TO-DO : Add health to the main player.
// MyPlayer.Health += 10; // Example.
Debug.Log("DetectPickup : Health picked!.");
break;
case pickupType.Ammo:
// TO-DO : Add ammo to the main player.
Debug.Log("DetectPickup : Ammo picked!.");
break;
case pickupType.Mana:
// TO-DO : Add mana to the main player.
Debug.Log("DetectPickup : Mana picked!.");
break;
default :
// TO-DO : ¿do nothing? ¿Display a warning msg?.
Debug.Log("DetectPickup : This Pickup doesnt have a type.");
break;
}
}
}
}
<file_sep>/New Unity Project/Assets/municion.js
#pragma strict
public var municionTotal = 100;
public var municionActual = 10;
var numArma;
var style : GUIStyle;
style.fontSize = 30;
style.normal.textColor = Color.white;
////////
function Start () {
}
function Update () {
}
function reducirMunicion(){
municionActual --;
}
function OnGUI()
{
GUI.Label(Rect(700, 10, 400, 20), municionActual.ToString()+" / "+municionTotal.ToString()+" "+numArma.ToString(), style);
/*if (numArma == 1){
GUI.Label(Rect(700, 10, 400, 20), munAct.ToString()+numArma.ToString(), style);
}
if(numArma == 2){
GUI.Label(Rect(700, 10, 400, 20), munAct2.ToString()+numArma.ToString(), style);
}*/
}
function setNumArma(numeroArma : int){
numArma = numeroArma;
}
function setMunMax(munMax : int){
municionTotal = munMax;
}
function setMunAct(munAct : int){
municionActual = munAct;
}<file_sep>/New Unity Project/Assets/Scripts/Scripts/GUI/Health Bar pictures.js
var health100 : Texture2D;
var health75 : Texture2D;
var health50 : Texture2D;
var health25 : Texture2D;
var health10 : Texture2D;
function Update () {
if(GeneralVars.nSalud == 100)
this.guiTexture.texture = health100;
else
if(GeneralVars.nSalud >= 75 && GeneralVars.nSalud < 100)
this.guiTexture.texture = health75;
else
if(GeneralVars.nSalud >= 50 && GeneralVars.nSalud < 75)
this.guiTexture.texture = health50;
else
if(GeneralVars.nSalud >= 25 && GeneralVars.nSalud < 50)
this.guiTexture.texture = health25;
else
if(GeneralVars.nSalud >= 0 && GeneralVars.nSalud < 25)
this.guiTexture.texture = health10;
}<file_sep>/New Unity Project/Assets/cajaMunicion.js
#pragma strict
function Start () {
}
function Update () {
}
function OnTriggerEnter(other:Collider){
if(other.tag == "Player"){
// Si la arma seleccionada es la 1
if (GunPlayer.numeroArma == 1) {
if(LoadGun.munAct2 == 0){
LoadGun.municionTotal = LoadGun.municionTotal + 30;
LoadGun.munMax1 = LoadGun.munMax1 + 30;
LoadGun.munAct2 = LoadGun.munAct2 + 5;
LoadGun.munMax3 = LoadGun.munMax3 + 30;
LoadGun.munMax4 = LoadGun.munMax4 + 12;
LoadGun.munMax5 = LoadGun.munMax5 + 8;
}
else if(LoadGun.munAct3 == 0){
LoadGun.municionTotal = LoadGun.municionTotal + 30;
LoadGun.munMax1 = LoadGun.munMax1 + 30;
LoadGun.munMax2 = LoadGun.munMax2 + 5;
LoadGun.munAct3 = LoadGun.munAct3 + 30;
LoadGun.munMax4 = LoadGun.munMax4 + 12;
LoadGun.munMax5 = LoadGun.munMax5 + 8;
}
else if(LoadGun.munAct4 == 0){
LoadGun.municionTotal = LoadGun.municionTotal + 30;
LoadGun.munMax1 = LoadGun.munMax1 + 30;
LoadGun.munMax2 = LoadGun.munMax2 + 5;
LoadGun.munMax3 = LoadGun.munMax3 + 30;
LoadGun.munAct4 = LoadGun.munAct4 + 12;
LoadGun.munMax5 = LoadGun.munMax5 + 8;
}
else if(LoadGun.munAct5 == 0){
LoadGun.municionTotal = LoadGun.municionTotal + 30;
LoadGun.munMax1 = LoadGun.munMax1 + 30;
LoadGun.munMax2 = LoadGun.munMax2 + 5;
LoadGun.munMax3 = LoadGun.munMax3 + 30;
LoadGun.munMax4 = LoadGun.munMax4 + 12;
LoadGun.munAct5 = LoadGun.munAct5 + 8;
}
else{
LoadGun.municionTotal = LoadGun.municionTotal + 30;
LoadGun.munMax1 = LoadGun.munMax1 + 30;
LoadGun.munMax2 = LoadGun.munMax2 + 5;
LoadGun.munMax3 = LoadGun.munMax3 + 30;
LoadGun.munMax4 = LoadGun.munMax4 + 12;
LoadGun.munMax5 = LoadGun.munMax5 + 8;
}
}
// Si la arma seleccionada es la 2
if (GunPlayer.numeroArma == 2) {
if(LoadGun.munAct1 == 0){
LoadGun.municionTotal = LoadGun.municionTotal + 5;
LoadGun.munAct1 = LoadGun.munAct1 + 30;
LoadGun.munMax2 = LoadGun.munMax2 + 5;
LoadGun.munMax3 = LoadGun.munMax3 + 30;
LoadGun.munMax4 = LoadGun.munMax4 + 12;
LoadGun.munMax5 = LoadGun.munMax5 + 8;
}
else if(LoadGun.munAct3 == 0){
LoadGun.municionTotal = LoadGun.municionTotal + 5;
LoadGun.munMax1 = LoadGun.munMax1 + 30;
LoadGun.munMax2 = LoadGun.munMax2 + 5;
LoadGun.munAct3 = LoadGun.munAct3 + 30;
LoadGun.munMax4 = LoadGun.munMax4 + 12;
LoadGun.munMax5 = LoadGun.munMax5 + 8;
}
else if(LoadGun.munAct4 == 0){
LoadGun.municionTotal = LoadGun.municionTotal + 5;
LoadGun.munMax1 = LoadGun.munMax1 + 30;
LoadGun.munMax2 = LoadGun.munMax2 + 5;
LoadGun.munMax3 = LoadGun.munMax3 + 30;
LoadGun.munAct4 = LoadGun.munAct4 + 12;
LoadGun.munMax5 = LoadGun.munMax5 + 8;
}
else if(LoadGun.munAct5 == 0){
LoadGun.municionTotal = LoadGun.municionTotal + 5;
LoadGun.munMax1 = LoadGun.munMax1 + 30;
LoadGun.munMax2 = LoadGun.munMax2 + 5;
LoadGun.munMax3 = LoadGun.munMax3 + 30;
LoadGun.munMax4 = LoadGun.munMax4 + 12;
LoadGun.munAct5 = LoadGun.munAct5 + 8;
}
else{
LoadGun.municionTotal = LoadGun.municionTotal + 5;
LoadGun.munMax1 = LoadGun.munMax1 + 30;
LoadGun.munMax2 = LoadGun.munMax2 + 5;
LoadGun.munMax3 = LoadGun.munMax3 + 30;
LoadGun.munMax4 = LoadGun.munMax4 + 12;
LoadGun.munMax5 = LoadGun.munMax5 + 8;
}
}
// Si la arma seleccionada es la 3
if (GunPlayer.numeroArma == 3) {
if(LoadGun.munAct1 == 0){
LoadGun.municionTotal = LoadGun.municionTotal + 30;
LoadGun.munAct1 = LoadGun.munAct1 + 30;
LoadGun.munMax2 = LoadGun.munMax2 + 5;
LoadGun.munMax3 = LoadGun.munMax3 + 30;
LoadGun.munMax4 = LoadGun.munMax4 + 12;
LoadGun.munMax5 = LoadGun.munMax5 + 8;
}
else if(LoadGun.munAct2 == 0){
LoadGun.municionTotal = LoadGun.municionTotal + 30;
LoadGun.munMax1 = LoadGun.munMax1 + 30;
LoadGun.munAct2 = LoadGun.munAct2 + 5;
LoadGun.munMax3 = LoadGun.munMax3 + 30;
LoadGun.munMax4 = LoadGun.munMax4 + 12;
LoadGun.munMax5 = LoadGun.munMax5 + 8;
}
else if(LoadGun.munAct4 == 0){
LoadGun.municionTotal = LoadGun.municionTotal + 30;
LoadGun.munMax1 = LoadGun.munMax1 + 30;
LoadGun.munMax2 = LoadGun.munMax2 + 5;
LoadGun.munMax3 = LoadGun.munMax3 + 30;
LoadGun.munAct4 = LoadGun.munAct4 + 12;
LoadGun.munMax5 = LoadGun.munMax5 + 8;
}
else if(LoadGun.munAct5 == 0){
LoadGun.municionTotal = LoadGun.municionTotal + 30;
LoadGun.munMax1 = LoadGun.munMax1 + 30;
LoadGun.munMax2 = LoadGun.munMax2 + 5;
LoadGun.munMax3 = LoadGun.munMax3 + 30;
LoadGun.munMax4 = LoadGun.munMax4 + 12;
LoadGun.munAct5 = LoadGun.munAct5 + 8;
}
else{
LoadGun.municionTotal = LoadGun.municionTotal + 30;
LoadGun.munMax1 = LoadGun.munMax1 + 30;
LoadGun.munMax2 = LoadGun.munMax2 + 5;
LoadGun.munMax3 = LoadGun.munMax3 + 30;
LoadGun.munMax4 = LoadGun.munMax4 + 12;
LoadGun.munMax5 = LoadGun.munMax5 + 8;
}
}
// Si la arma seleccionada es la 4
if (GunPlayer.numeroArma == 4) {
if(LoadGun.munAct1 == 0){
LoadGun.municionTotal = LoadGun.municionTotal + 12;
LoadGun.munAct1 = LoadGun.munAct1 + 30;
LoadGun.munMax2 = LoadGun.munMax2 + 5;
LoadGun.munMax3 = LoadGun.munMax3 + 30;
LoadGun.munMax4 = LoadGun.munMax4 + 12;
LoadGun.munMax5 = LoadGun.munMax5 + 8;
}
else if(LoadGun.munAct2 == 0){
LoadGun.municionTotal = LoadGun.municionTotal + 12;
LoadGun.munMax1 = LoadGun.munMax1 + 30;
LoadGun.munAct2 = LoadGun.munAct2 + 5;
LoadGun.munMax3 = LoadGun.munMax3 + 30;
LoadGun.munMax4 = LoadGun.munMax4 + 12;
LoadGun.munMax5 = LoadGun.munMax5 + 8;
}
else if(LoadGun.munAct3 == 0){
LoadGun.municionTotal = LoadGun.municionTotal + 12;
LoadGun.munMax1 = LoadGun.munMax1 + 30;
LoadGun.munMax2 = LoadGun.munMax2 + 5;
LoadGun.munAct3 = LoadGun.munAct3 + 30;
LoadGun.munMax4 = LoadGun.munMax4 + 12;
LoadGun.munMax5 = LoadGun.munMax5 + 8;
}
else if(LoadGun.munAct5 == 0){
LoadGun.municionTotal = LoadGun.municionTotal + 12;
LoadGun.munMax1 = LoadGun.munMax1 + 30;
LoadGun.munMax2 = LoadGun.munMax2 + 5;
LoadGun.munMax3 = LoadGun.munMax3 + 30;
LoadGun.munMax4 = LoadGun.munMax4 + 12;
LoadGun.munAct5 = LoadGun.munAct5 + 8;
}
else{
LoadGun.municionTotal = LoadGun.municionTotal + 12;
LoadGun.munMax1 = LoadGun.munMax1 + 30;
LoadGun.munMax2 = LoadGun.munMax2 + 5;
LoadGun.munMax3 = LoadGun.munMax3 + 30;
LoadGun.munMax4 = LoadGun.munMax4 + 12;
LoadGun.munMax5 = LoadGun.munMax5 + 8;
}
}
// Si la arma seleccionada es la 5
if (GunPlayer.numeroArma == 5) {
if(LoadGun.munAct1 == 0){
LoadGun.municionTotal = LoadGun.municionTotal + 8;
LoadGun.munAct1 = LoadGun.munAct1 + 30;
LoadGun.munMax2 = LoadGun.munMax2 + 5;
LoadGun.munMax3 = LoadGun.munMax3 + 30;
LoadGun.munMax4 = LoadGun.munMax4 + 12;
LoadGun.munMax5 = LoadGun.munMax5 + 8;
}
else if(LoadGun.munAct2 == 0){
LoadGun.municionTotal = LoadGun.municionTotal + 8;
LoadGun.munMax1 = LoadGun.munMax1 + 30;
LoadGun.munAct2 = LoadGun.munAct2 + 5;
LoadGun.munMax3 = LoadGun.munMax3 + 30;
LoadGun.munMax4 = LoadGun.munMax4 + 12;
LoadGun.munMax5 = LoadGun.munMax5 + 8;
}
else if(LoadGun.munAct3 == 0){
LoadGun.municionTotal = LoadGun.municionTotal + 8;
LoadGun.munMax1 = LoadGun.munMax1 + 30;
LoadGun.munMax2 = LoadGun.munMax2 + 5;
LoadGun.munAct3 = LoadGun.munAct3 + 30;
LoadGun.munMax4 = LoadGun.munMax4 + 12;
LoadGun.munMax5 = LoadGun.munMax5 + 8;
}
else if(LoadGun.munAct4 == 0){
LoadGun.municionTotal = LoadGun.municionTotal + 8;
LoadGun.munMax1 = LoadGun.munMax1 + 30;
LoadGun.munMax2 = LoadGun.munMax2 + 5;
LoadGun.munMax3 = LoadGun.munMax3 + 30;
LoadGun.munAct4 = LoadGun.munAct4 + 12;
LoadGun.munMax5 = LoadGun.munMax5 + 8;
}
else{
LoadGun.municionTotal = LoadGun.municionTotal + 8;
LoadGun.munMax1 = LoadGun.munMax1 + 30;
LoadGun.munMax2 = LoadGun.munMax2 + 5;
LoadGun.munMax3 = LoadGun.munMax3 + 30;
LoadGun.munMax4 = LoadGun.munMax4 + 12;
LoadGun.munMax5 = LoadGun.munMax5 + 8;
}
}
////////////
/*
if (GunPlayer.numeroArma == 3) {
LoadGun.munMax1 = LoadGun.munMax1 + 30;
LoadGun.munMax2 = LoadGun.munMax2 + 5;
LoadGun.municionTotal = LoadGun.municionTotal + 30;
LoadGun.munMax3 = LoadGun.munMax3 + 30;
LoadGun.munMax4 = LoadGun.munMax4 + 12;
LoadGun.munMax5 = LoadGun.munMax5 + 8;
}
if (GunPlayer.numeroArma == 4) {
LoadGun.munMax1 = LoadGun.munMax1 + 30;
LoadGun.munMax2 = LoadGun.munMax2 + 5;
LoadGun.munMax3 = LoadGun.munMax3 + 30;
LoadGun.municionTotal = LoadGun.municionTotal + 12;
LoadGun.munMax4 = LoadGun.munMax4 + 12;
LoadGun.munMax5 = LoadGun.munMax5 + 8;
}
if (GunPlayer.numeroArma == 5) {
LoadGun.munMax1 = LoadGun.munMax1 + 30;
LoadGun.munMax2 = LoadGun.munMax2 + 5;
LoadGun.munMax3 = LoadGun.munMax3 + 30;
LoadGun.munMax4 = LoadGun.munMax4 + 12;
LoadGun.municionTotal = LoadGun.municionTotal + 8;
LoadGun.munMax5 = LoadGun.munMax5 + 8;
}
*/
////
Destroy (this.gameObject);
}
}<file_sep>/New Unity Project/Assets/Scripts/Scripts/Scripts/Billboard.cs
//====================================================================================================
//
// Script : Billboard
// Programador : <NAME>. "Jocyf"
//
// Date: 05/04/2013
// Version : 1.3
//
// Description: Rotate the gameobject to look forward the target.
// If not target is selected, the maincamera will be used as target.
// The rotation can be smoothed or do it directly.
//
//====================================================================================================
using UnityEngine;
using System.Collections;
[AddComponentMenu( "Utilities/Billboard")]
public class Billboard : MonoBehaviour{
public Transform target;
public bool LerpRotation = false;
public float rotationSpeed = 6;
public bool AllowXrotation = true;
public bool AllowYrotation = true;
public bool AllowZrotation = true;
private Transform MyTransform;
void Start(){
if(target == null)
target = Camera.main.transform;
MyTransform = this.transform;
}
void Update(){
if(LerpRotation){
Vector3 direction = target.position - MyTransform.position;
if (direction.magnitude < 0.1f)
return;
if(!AllowXrotation && !AllowYrotation && AllowZrotation)
return;
// Rotate towards the target
MyTransform.rotation = Quaternion.Slerp (MyTransform.rotation, Quaternion.LookRotation(direction), rotationSpeed * Time.deltaTime);
// Check de axis rotations allowed.
if(AllowXrotation && AllowYrotation && AllowZrotation)
return;
else
if(AllowXrotation && AllowYrotation && !AllowZrotation)
MyTransform.eulerAngles = new Vector3(MyTransform.eulerAngles.x, MyTransform.eulerAngles.y, 0f);
else
if(AllowXrotation && !AllowYrotation && AllowZrotation)
MyTransform.eulerAngles = new Vector3(MyTransform.eulerAngles.x, 0f, MyTransform.eulerAngles.z);
else
if(AllowXrotation && !AllowYrotation && !AllowZrotation)
MyTransform.eulerAngles = new Vector3(MyTransform.eulerAngles.x, 0f, 0f);
else
if(!AllowXrotation && AllowYrotation && AllowZrotation)
MyTransform.eulerAngles = new Vector3(0f, MyTransform.eulerAngles.y, MyTransform.eulerAngles.z);
else
if(!AllowXrotation && AllowYrotation && !AllowZrotation)
MyTransform.eulerAngles = new Vector3(0f, MyTransform.eulerAngles.y, 0f);
else
if(!AllowXrotation && !AllowYrotation && AllowZrotation)
MyTransform.eulerAngles = new Vector3(0f, 0f, MyTransform.eulerAngles.z);
}
else
MyTransform.LookAt(target.position);
}
}<file_sep>/New Unity Project/Assets/Scripts/Scripts/Scripts/AutoHide.cs
//====================================================================================================
//
// Script : AutoHide
// Programador : <NAME>. "Jocyf"
//
// Date: 06/04/2013
// Version : 1.3
//
// Description: Hides a gameobject, GUItext or GUITexture in the time specified.
// The time must be a value greater than zero.
// To hide inmediatly call HideInmediate() function.
//
//====================================================================================================
using UnityEngine;
using System.Collections;
[AddComponentMenu( "Utilities/AutoHide")]
public class AutoHide : MonoBehaviour {
public float delayTime = 0.1f;
public bool fadeOut = false;
public float fadeSpeed = 1;
public bool isActive = false;
private bool hasFinished = true;
// Only hides the object if time is greater than zero.
void Start() {
if(isActive){
StartCoroutine(DelayHide());
}
}
IEnumerator DelayHide(){
yield return new WaitForSeconds(delayTime);
if(!fadeOut)
InmediateHide();
else{
isActive = true;
hasFinished = false;
}
}
void InmediateHide(){
if(renderer){
Color _color = renderer.material.GetColor("_Color"); // Normal Transparent shader
_color.a = 0;
renderer.material.SetColor("_Color", _color); // Normal Transparent shader
//renderer.enabled = false;
}
else
if(guiText){
Color _color = guiText.material.color;
_color.a = 0;
guiText.material.color = _color;
//guiText.enabled = false;
}
else
if(guiTexture){
Color _color = guiTexture.color;
_color.a = 0;
guiTexture.color = _color;
//guiTexture.enabled = false;
}
hasFinished = true;
isActive = false;
}
void Update(){
if(!isActive)
return;
if(fadeOut && !hasFinished){
if(guiTexture){
Color _color = guiTexture.color;
_color.a = Mathf.Lerp(_color.a, 0F, fadeSpeed*Time.deltaTime);
if(_color.a < .02F){
_color.a = 0;
hasFinished = true;
}
guiTexture.color = _color;
}
else
if(guiText){
Color _color = guiText.material.color;
_color.a = Mathf.Lerp(_color.a, 0F, fadeSpeed*Time.deltaTime);
if(_color.a < .02F){
_color.a = 0;
hasFinished = true;
}
guiText.material.color = _color;
}
else
if(renderer){
Color _color = renderer.material.GetColor("_Color"); // Normal Transparent shader
//Color _color = renderer.material.GetColor("_TintColor"); // Use this with Particles shaders
_color.a = Mathf.Lerp(_color.a, 0F, fadeSpeed*Time.deltaTime);
if(_color.a < .02F){
_color.a = 0;
hasFinished = true;
}
renderer.material.SetColor("_Color", _color); // Normal Transparent shader
//renderer.material.SetColor("_TintColor", _color); // Use this with Particles shaders
}
}
else
if(fadeOut && hasFinished)
isActive = false;
}
public void SetTimeToHide(float _Time){
delayTime = _Time;
isActive = true;
if(fadeOut)
hasFinished = false;
StartCoroutine(DelayHide());
}
// Hide inmediatly.
public void HideInmediate(){
delayTime = 0;
isActive = true;
//fadeOut = false;
hasFinished = true;
InmediateHide();
}
}<file_sep>/New Unity Project/Assets/DestroyBala.js
#pragma strict
function Start () {
}
function Update () {
}
function OnCollisonEnter(other : Collision){
Destroy(gameObject);
}
<file_sep>/New Unity Project/Assets/seguir_camera.js
var objetivo:Transform;
function LateUpdate () {
transform.position = new Vector3(objetivo.position.x,objetivo.position.y,objetivo.position.z);
} | b485115b000f5b28da04f6d26c8e40fcf1c8569b | [
"JavaScript",
"C#",
"Markdown"
] | 58 | JavaScript | jordi13/ZombieLandNavMesh | b4fb9c6e9d2a6bf3e4e4bf19f02c6a880956c818 | e54f9ec498f2ba65ecafd1f4369dc8e68c9af711 |
refs/heads/master | <repo_name>zhentaol/Coursera-Getting-and-Cleaning-Data-Course-Project<file_sep>/CodeBook.md
The data is taken from UCI HAR Dataset. This dataset provide the following variables for each activity:
1. subjectId - ID of participant
2. activityId - ID of activity type
3. These signals were used to estimate variables of the feature vector for each pattern:
'-XYZ' is used to denote 3-axial signals in the X, Y and Z directions.
tBodyAcc-XYZ
tGravityAcc-XYZ
tBodyAccJerk-XYZ
tBodyGyro-XYZ
tBodyGyroJerk-XYZ
tBodyAccMag
tGravityAccMag
tBodyAccJerkMag
tBodyGyroMag
tBodyGyroJerkMag
fBodyAcc-XYZ
fBodyAccJerk-XYZ
fBodyGyro-XYZ
fBodyAccMag
fBodyAccJerkMag
fBodyGyroMag
fBodyGyroJerkMag
The set of variables that were estimated from these signals are:
mean(): Mean value
std(): Standard deviation
mad(): Median absolute deviation
max(): Largest value in array
min(): Smallest value in array
sma(): Signal magnitude area
energy(): Energy measure. Sum of the squares divided by the number of values.
iqr(): Interquartile range
entropy(): Signal entropy
arCoeff(): Autorregresion coefficients with Burg order equal to 4
correlation(): correlation coefficient between two signals
maxInds(): index of the frequency component with largest magnitude
meanFreq(): Weighted average of the frequency components to obtain a mean frequency
skewness(): skewness of the frequency domain signal
kurtosis(): kurtosis of the frequency domain signal
bandsEnergy(): Energy of a frequency interval within the 64 bins of the FFT of each window.
angle(): Angle between to vectors.
Additional vectors obtained by averaging the signals in a signal window sample. These are used on the angle() variable:
gravityMean
tBodyAccMean
tBodyAccJerkMean
tBodyGyroMean
tBodyGyroJerkMean
The features selected for this database come from the accelerometer and gyroscope 3-axial raw signals tAcc-XYZ and tGyro-XYZ. These time domain signals (prefix 't' to denote time) were captured at a constant rate of 50 Hz. Then they were filtered using a median filter and a 3rd order low pass Butterworth filter with a corner frequency of 20 Hz to remove noise. Similarly, the acceleration signal was then separated into body and gravity acceleration signals (tBodyAcc-XYZ and tGravityAcc-XYZ) using another low pass Butterworth filter with a corner frequency of 0.3 Hz.
Subsequently, the body linear acceleration and angular velocity were derived in time to obtain Jerk signals (tBodyAccJerk-XYZ and tBodyGyroJerk-XYZ). Also the magnitude of these three-dimensional signals were calculated using the Euclidean norm (tBodyAccMag, tGravityAccMag, tBodyAccJerkMag, tBodyGyroMag, tBodyGyroJerkMag).
Finally a Fast Fourier Transform (FFT) was applied to some of these signals producing fBodyAcc-XYZ, fBodyAccJerk-XYZ, fBodyGyro-XYZ, fBodyAccJerkMag, fBodyGyroMag, fBodyGyroJerkMag. (Note the 'f' to indicate frequency domain signals).
TRANSFORMATIONS
Here are the data for the project:
https://d396qusza40orc.cloudfront.net/getdata%2Fprojectfiles%2FUCI%20HAR%20Dataset.zip
The following transformations were applied to the source data:
1. The training and test sets were merged to create one data set.
2. The measurements on the mean and standard deviation were extracted for each measurement, and the others were discarded.
3. Uses descriptive activity names to name the activities in the data set
- Replace the variable about activity
4. Appropriately labels the data set with descriptive variable names.
- The variable names were replaced with descriptive variable names (e.g. tBodyAcc-mean()-X was expanded to timeDomainBodyAccelerometerMeanX), using the following set of rules:
Special characters (i.e. (, ), and -) were removed
5. From the data set in step 4, creates a second, independent tidy data set with the average of each variable for each activity and each subject.
The collection of the source data and the transformations listed were implemented by the "run_analysis.R" R script.
<file_sep>/run_analysis.R
library(dplyr)
#1. Downloading and unzipping dataset#
zipUrl <- "https://d396qusza40orc.cloudfront.net/getdata%2Fprojectfiles%2FUCI%20HAR%20Dataset.zip"
zipFile <- "UCI HAR Dataset.zip"
if (!file.exists(zipFile)) {
download.file(zipUrl, zipFile, mode = "wb")
}
#Unzip
datapath <- "UCI HAR Dataset"
if(!file.exists(datapath)){
unzip(zipFile)
}
#1. Merges the training and test sets to create one data set
xtrain <- read.table(file.path(datapath , "train" , "X_train.txt"), col.names = features$functions)
ytrain <- read.table(file.path(datapath , "train" , "y_train.txt"), col.names = "activityId")
subjecttrain <- read.table(file.path(datapath , "train" , "subject_train.txt"), col.names = "subjectId")
xtest <- read.table(file.path(datapath , "test" , "X_test.txt"), col.names = features$functions)
ytest <- read.table(file.path(datapath , "test" , "y_test.txt"), col.names = "activityId")
subjecttest <- read.table(file.path(datapath , "test" , "subject_test.txt"), col.names = "subjectId")
activitylabels <- read.table(file.path(datapath , "activity_labels.txt"), col.names = c("activityId" , "activityType"))
features <- read.table(file.path(datapath , "features.txt") , col.names = c("n" , "functions"))
#Merging the train and test data
X <- rbind(xtrain, xtest)
Y <- rbind(ytrain, ytest)
Subject <- rbind(subjecttrain, subjecttest)
merge_data <- cbind(Subject, X, Y)
#2. Extracting only the measurements on the mean and standard deviation for each measurement
Tidy_Data <- merge_data %>% select(subjectId, activityId, contains("mean"), contains("std"))
#3. Uses descriptive activity names to name the activities in the data set
Tidy_Data$activityId <- activitylabels[Tidy_Data$activityId, 2]
#Step 4: Appropriately labels the data set with descriptive variable names.
names(Tidy_Data)[2] = "activityId"
names(Tidy_Data)<-gsub("Acc", "Accelerometer", names(Tidy_Data))
names(Tidy_Data)<-gsub("Gyro", "Gyroscope", names(Tidy_Data))
names(Tidy_Data)<-gsub("BodyBody", "Body", names(Tidy_Data))
names(Tidy_Data)<-gsub("Mag", "Magnitude", names(Tidy_Data))
names(Tidy_Data)<-gsub("^t", "Time", names(Tidy_Data))
names(Tidy_Data)<-gsub("^f", "Frequency", names(Tidy_Data))
names(Tidy_Data)<-gsub("tBody", "TimeBody", names(Tidy_Data))
names(Tidy_Data)<-gsub("-mean()", "Mean", names(Tidy_Data), ignore.case = TRUE)
names(Tidy_Data)<-gsub("-std()", "STD", names(Tidy_Data), ignore.case = TRUE)
names(Tidy_Data)<-gsub("-freq()", "Frequency", names(Tidy_Data), ignore.case = TRUE)
names(Tidy_Data)<-gsub("angle", "Angle", names(Tidy_Data))
names(Tidy_Data)<-gsub("gravity", "Gravity", names(Tidy_Data))
#Step 5: From the data set in step 4, creates a second, independent tidy data set with the average of each variable for each activity and each subject.
# Create a dataset with the mean of each column for 'subjectId' and 'activityId'
Final_Data <- Tidy_Data %>%
group_by(subjectId,activityId) %>%
summarise_all(funs(mean))
# Save the data frame created as a text file in working directory
write.table(Final_Data,"Final_Data.txt",row.name=FALSE)
message("The script was executed successfully. A new tidy data set "Final_Data.txt" was successfully created in the working directory.")
| d6d1a8f81cc3366da26e2c38765331fbcc174f99 | [
"Markdown",
"R"
] | 2 | Markdown | zhentaol/Coursera-Getting-and-Cleaning-Data-Course-Project | fcce8125f0c4dfe0240410f97e2db2ee889ab9f6 | c21a2f1a307eaeeb2c9e44e455065aa5a7f4712f |
refs/heads/master | <file_sep>This is an implementation of a guessing game, wherein the program asks questions to determine what animal the user is thinking about. If it guesses incorrectly, it will ask for another question that it can use in the future.
To install, enter "make" in a command line.
To run, enter "./animal_guess" or "animal_guess.exe" in the command line.<file_sep>//animal.h
//interface file for animal program
#ifndef ANIMAL_H
#define ANIMAL_H
typedef struct animal_tree
{
char *classification; //either a question or animal name
struct animal_tree *left; //left child
struct animal_tree *right; //right child
} animal_tree;
animal_tree new_tree(char *class);
void update_tree(animal_tree *t, animal_tree *left, animal_tree *right); //update the tree's left and right node
void add_question(animal_tree *t, char *new_q, animal_tree *new_animal, animal_tree *old_animal); //add question to the tree
#endif
<file_sep>#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#include "animal.h"
int main (int argc, char **argv)
{
char yn[3]; //stores yes/no answers in game
char again[3];//stores whether will play again
printf("Welcome to the animal game! Think of an animal, and I will try to guess it.\n");
//build initial question tree
animal_tree t = new_tree("Does the animal bark?"); //first question
animal_tree l = new_tree("horse"); //first "no" answer
animal_tree r = new_tree("dog"); //first "yes" answer
update_tree(&t, &l, &r);
do
{
animal_tree *p = &t; //pointer used for traversing tree
char *bottom = t.classification;
do //while there are children elements
{
printf("%s (y/n)\n", bottom); //ask the question
fgets(yn, 3, stdin); //get the answer
//the left child contains the "no answer", while the right contains the yes answer
if (strcmp("n\n", yn) == 0)
{
p = p->left;
}
else if (strcmp("y\n", yn) == 0)
{
p = p->right;
}
bottom = p->classification;
} while (p->left != NULL); //stop when there are no more child elements
printf("Your animal is a %s.\nIs this correct? (y/n)\n", bottom); //checking answer
fgets(yn, 3, stdin);
if (strcmp("y\n", yn) == 0)
printf("I win!\n");
else
{
printf("I lose.\nWhat was the correct answer?\n");
char correct_answer[100];
fgets(correct_answer, 100, stdin);
strtok(correct_answer, "\n"); //necessary in order to avoid storing the new animal with the newline
//request something that is true for the animal the user was considering but not the stored animal
printf("What is a question where the answer is yes for a %s but not for a %s?\n", correct_answer, bottom);
char *new_question = (char *) calloc(100, sizeof(char));
fgets(new_question, 100, stdin);
strtok(new_question, "\n");
//update the animal_tree
animal_tree old_animal = new_tree(p->classification);
animal_tree new_animal = new_tree(correct_answer);
p ->classification = new_question;
p->left = &old_animal;
p->right = &new_animal;
}
printf("\nDo you want to play again? (y/n) ");
fgets(again, 3, stdin);
} while (strcmp("y\n", again) == 0);
exit(0);
}
<file_sep># Makefile for animal_guess program
CFLAGS= -std=c99
SRC=animal-main.c animal.c
OBJ=animal-main.o animal.o
animal_guess: ${OBJ}
# New target
depend: makedepend -Y ${SRC} &> /dev/null
clean: rm -f ${OBJ} animal_guess Makefile.bak
install: animal_guess cp animal_guess ~/bin
animal-main.o: animal.h
animal.o: animal.h
<file_sep>//animal.c
//animal functions
#include "animal.h"
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
//create new tree
animal_tree new_tree(char *classification)
{
animal_tree *result = malloc(sizeof(animal_tree));
assert(result != NULL);
result->classification = classification;
result->left = NULL;
result->right = NULL;
animal_tree new;
new = *result;
return new;
}
//update tree
void update_tree(animal_tree *t, animal_tree *left, animal_tree *right)
{
t->left = left;
t->right = right;
}
| f7bbb78671884911014c8b9e783f1c925dfd74ef | [
"Makefile",
"C",
"Text"
] | 5 | Text | HalleyYoung/animal_guess | f28bd9ba64634bb0ba2ee4c18410ec6206757ece | e111da4c4fba0c1d1a2dd3d96ffdec2242aa4f19 |
refs/heads/master | <repo_name>adamCs2001/volleyballTourny_gp26<file_sep>/README.TXT
------------------------------------------------------------------------
This is the project README file. Here, you should describe your project.
Tell the reader (someone who does not know anything about this project)
all he/she needs to know. The comments should usually include at least:
------------------------------------------------------------------------
PROJECT TITLE: Volleyball Tournament
PURPOSE OF PROJECT: Assignment 4
VERSION or DATE:
HOW TO START THIS PROJECT:
AUTHORS: <NAME>, <NAME>, <NAME>
USER INSTRUCTIONS:
Two methods of using this program
1: Instantiating the league class manually. it runs the league setup and generates a league of 15 teams in 3 divisions.
getDivisionTeams() will print out a list of teams in each division. This is to make sure that when adding matches, teams
from the same division are added.
once a league class has been created, a user can use the method "addMatch" on the league class. the user then needs to
add team names for the teams that are facing each other, as well as a comma separated list of scores to represent each
set played. this will be stored on each team that played to be used for calculating standings.
After every match added, it's possible to check the standings of the teams. the user adds in a division by entering a
string "Division" plus 1, 2, or 3 (since there are only 3 divisions). it generates a list of teams by rank in decending order.
2: Using the Tournament Simulation. After a league is created, the tournament sim can be used to simulate each team from
every division playing each other team in the division. calculating the standing on the league will show the results of the
tournament <file_sep>/Team.java
import java.util.ArrayList;
import java.lang.Math;
/**
* Write a description of class Team here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Team
{
// instance variables
private String name;
private String division;
private ArrayList<Person> personList;
private int leaguePoints;
private int pointDiff;
/**
* Constructor for objects of class Team
*
* take in all the information to create a team. keeps a list of all the players
* and coaches associated with the team, currently only stores their names in a
* list
*
* Team keeps track of its current league points as well as the running tally of
* the point diff for each of the games that it's taken part of for standing purposes.
*
*
* @param name a name String for the team
* @param division an int to represent the division
* @param players an int to indicate the number of players that should be on a team
* @param coaches an int to indicate the number of coaches that should be on a team
*/
public Team(String name, int division, int players, int coaches)
{
this.name = name;
this.division = "Division " + division;
personList = new ArrayList<>();
this.leaguePoints = 0;
this.pointDiff = 0;
for (int x = 0; x < players; x++) {
int jerseyNum = (int)(Math.random() * 100) + 1;
Person player = new Player("player " + jerseyNum);
personList.add(player);
}
for (int x = 0; x < coaches; x++) {
int jerseyNum = (int)(Math.random() * 100) + 1;
Person coach = new Coach("Coach " + jerseyNum);
personList.add(coach);
}
}
/**
* returns the name of the team
*/
public String getName()
{
return this.name;
}
/**
* returns the division associated with this team
*/
public String getDivision()
{
return this.division;
}
/**
* returns the number of league points won by this team
*/
public int getLeaguePoints()
{
return this.leaguePoints;
}
/**
* returns the delta of points won/lost by this team
*/
public int getpointDiff()
{
return this.pointDiff;
}
/**
* updates the delta of points won/lost by this team
*/
public void updatePointDiff(int addPoints)
{
this.pointDiff += addPoints;
}
/**
* updates the league points won by this team
*/
public void updateLeaguePoints()
{
this.leaguePoints++;
}
}
<file_sep>/Coach.java
/**
* generates a coach for the team
*
* only has a name as a parameter, subclass of Person
*
*/
public class Coach extends Person
{
/**
* Constructor for objects of class Coach
*
* @param name Gives the coach a name
*/
public Coach(String name)
{
super(name);
}
}
| 9ad66d21637e4c2616e45aa9a26fc7e7c4de4953 | [
"Java",
"Text"
] | 3 | Text | adamCs2001/volleyballTourny_gp26 | facfa2f11b4f03653a6a9bc5891c12ee18f7ad3f | 403a64655a3a6130b77140cbee00bd94d5972f5d |
refs/heads/master | <repo_name>absentee-neptune/Personal-Projects<file_sep>/Python/PycharmProjects_1718/Week 6 Programming Assignment/backpack_of_stuff.py
import sys
itemsInBackpack = ["book", "computer", "keys", "travel mug"]
while True:
print("Would you like to:")
print("1. Add an item to the backpack?")
print("2. Check if an item is in the backpack?")
print("3. Quit")
userChoice = input()
if (userChoice == "1"):
print("What item do you want to add to the backpack?")
itemToAdd = input()
####### YOUR CODE HERE ######
itemsInBackpack.append(itemToAdd)
####### YOUR CODE HERE ######
if (userChoice == "2"):
print("What item do you want to check to see if it is in the backpack?")
itemToCheck = input()
####### YOUR CODE HERE ######
if itemToCheck in itemsInBackpack:
print('The ' + itemToCheck + ' was found in the backpack.')
elif itemToCheck not in itemsInBackpack:
print('The ' + itemToCheck + ', was not found in the backpack.')
####### YOUR CODE HERE ######
if (userChoice == "3"):
sys.exit()
<file_sep>/Python/PycharmProjects_1819/Week8_Lab/week8_tests.py
"""Tests for Week 8 Lab.
Prof. <NAME>
Champlain College
CSI-260 -- Spring 2019
"""
import unittest
from temperature import Temperature, TemperatureError
import sys
# define constants used by tests
STUDENT_CODE = ["temperature.py"]
VALID_TEMPERATURES = [-45, 55.2, "-14.75", "34C", "3.4C", "-10.2C",
"-11.2F", "23.5F", "74.5F", "245.3K"]
INVALID_TEMPERATURES = ["garbage", "34 degrees celsius", [], "45P", "34CC",
{"C": 23}]
DEGREES_CELSIUS = [-45.0, 55.2, -14.75, 34.0, 3.4, -10.2, -24.0,
-4.722222222222222, 23.61111111111111, -27.849999999999966]
DEGREES_FAHRENHEIT = [-49.0, 131.36, 5.449999999999999, 93.2, 38.12, 13.64,
-11.200000000000003, 23.5, 74.5, -18.12999999999994]
KELVINS = [228.14999999999998, 328.34999999999997, 258.4, 307.15,
276.54999999999995, 262.95, 249.14999999999998, 268.42777777777775,
296.76111111111106, 245.3]
AVERAGE_TEMPERATURE = sum(DEGREES_CELSIUS) / len(DEGREES_CELSIUS)
def equal_to_n_decimal_places(value1, value2, n):
"""Return if value1 is equal to value2 when rounded to n decimal places."""
return f"{value1:.{n}f}" == f"{value2:.{n}f}"
class TestWeek8(unittest.TestCase):
"""Main testing class for Week 8 Lab."""
def test_1_raises(self):
"""Test if the initializer raises errors as specified."""
for temp_value in INVALID_TEMPERATURES:
try:
Temperature(temp_value)
self.fail("Attempting to initialize a temperature"
f" with invalid value {temp_value} must"
" raise TemperatureError.")
except Exception as e:
self.assertIsInstance(e, TemperatureError,
"Attempting to initialize a temperature "
f"with invalid value {temp_value} must "
f"raise TemperatureError not {type(e)}.")
def test_2_inits(self):
"""Test if the initializer properly sets celcius."""
for temp_value, celsius in zip(VALID_TEMPERATURES, DEGREES_CELSIUS):
temperature = Temperature(temp_value)
try:
self.assertTrue(equal_to_n_decimal_places(temperature.celsius,
celsius, 4),
f"Temperature temperature initialized with "
f"{temp_value} should have temperature.celcius"
f" = {celsius}, but it is "
f"{temperature.celsius}")
except AttributeError:
self.fail(f"Temperature instance has no attribute "
"celcius.")
def test_3_fahrenheit(self):
"""Test if fahrenheit property exists and is computed properly."""
for temp_value, fahrenheit in zip(VALID_TEMPERATURES,
DEGREES_FAHRENHEIT):
temperature = Temperature(temp_value)
try:
self.assertTrue(equal_to_n_decimal_places(
temperature.fahrenheit,
fahrenheit, 4),
f"Temperature temperature initialized with "
f"{temp_value} should have "
f"temperature.fahrenheit = {fahrenheit}, "
f"but it is {temperature.fahrenheit}")
except AttributeError:
self.fail(f"Temperature instance has no property "
"fahrenheit.")
def test_4_kelvin(self):
"""Test if kelvin property exists and is computed properly."""
for temp_value, kelvin in zip(VALID_TEMPERATURES, KELVINS):
temperature = Temperature(temp_value)
try:
self.assertTrue(equal_to_n_decimal_places(temperature.kelvin,
kelvin, 4),
f"Temperature temperature initialized with "
f"{temp_value} should have temperature.kelvin "
f"= {kelvin}, but it is "
f"{temperature.kelvin}")
except AttributeError:
self.fail(f"Temperature instance has no property "
"kelvin.")
def test_5_conversions(self):
"""Test if setting various attributes works appropriately."""
for celcius, fahrenheit, kelvin in zip(DEGREES_CELSIUS,
DEGREES_FAHRENHEIT,
KELVINS):
temperature = Temperature()
temperature.celsius = celcius
self.assertTrue(equal_to_n_decimal_places(temperature.fahrenheit,
fahrenheit, 4))
self.assertTrue(equal_to_n_decimal_places(temperature.kelvin,
kelvin, 4))
temperature.fahrenheit = fahrenheit
self.assertTrue(equal_to_n_decimal_places(temperature.celsius,
celcius, 4))
self.assertTrue(equal_to_n_decimal_places(temperature.kelvin,
kelvin, 4))
temperature.kelvin = kelvin
self.assertTrue(equal_to_n_decimal_places(temperature.celsius,
celcius, 4))
self.assertTrue(equal_to_n_decimal_places(temperature.fahrenheit,
fahrenheit, 4))
def test_6_average(self):
"""Test if averaging works as specified."""
average_temperature = Temperature.average([Temperature(temp)
for temp in
VALID_TEMPERATURES]).celsius
self.assertTrue(equal_to_n_decimal_places(AVERAGE_TEMPERATURE,
average_temperature, 4),
f"Average temperature should be {AVERAGE_TEMPERATURE} "
f"degrees celcius, but is {average_temperature} "
"degrees celcius")
def test_7_style(self):
"""Run the linter and check that the header is there."""
try:
from flake8.api import legacy as flake8
# noqa on the following since just importing to test installed
import pep8ext_naming # noqa
import flake8_docstrings # noqa
print("\nLinting Code...\n" + "=" * 15)
style_guide = flake8.get_style_guide()
report = style_guide.check_files(STUDENT_CODE)
self.assertEqual(report.total_errors, 0,
"You should fix all linting errors "
"before submission in order to receive full "
"credit!")
for module in STUDENT_CODE:
self.check_header(module)
print("Passing linter tests!")
except ImportError:
print("""
### WARNING: Unable to import flake8 and/or extensions, so cannot \
properly lint your code. ###
Please install flake8, pep8-naming, and flake8-docstrings to auto-check \
whether you are adhering to proper style and docstring conventions.
To install, run:
pip install flake8 pep8-naming flake8-docstrings
""")
def check_header(self, module):
"""Check the header of the given module."""
docstring = sys.modules[module[:-3]].__doc__
for check in ['Author:', 'Class:', 'Assignment:',
'Certification of Authenticity:']:
self.assertIn(check, docstring,
"Missing '{}' in {}'s docstring".format(
check, module))
if __name__ == '__main__':
unittest.main(failfast=True)
<file_sep>/Python/PycharmProjects_1718/Class Notes/Week3_Notes.py
import math
def celcius_to_fahrenheit(temperature_in_celcius): #(parameter)
#This function converts a number from Celcius to Farenheit
#f = 9/5*c+32
#Arguments:
# temperature_in_celcius(float): The temperature to convert
#Returns:
#float: The temperature in Fahrenheit
#Assumptions:
#Assumes that temperature_in_celcius is a float
return ((9 / 5 * temperature_in_celcius) + 32)
def fahrenheit_to_celcius(temperature_in_fahrenheit):
return ((5 / 9 * temperature_in_fahrenheit) - 32)
print("Please enter 'F' to convert to Fahrenheit, 'C' to convert to Celcius, or 'E' to exit.")
action = input("Enter the function you wish to execute: ")
temperature_c = float(input("Enter the temperature in Celcius: "))
result_c = celcius_to_fahrenheit(temperature_c)
print(result_c)
temperature_f = float(input("Enter the temperature in Fahrenheit: "))
result_f = fahrenheit_to_celcius(temperature_f)
print(result_f)<file_sep>/AutomationScripting/Bash/Week15/SMTPlog.bash
#!/bin/bash
# Check to see if the file smtp.log exists. We've used -f several times to determine if a file exists.
# NOTE: Remember that the gzip -d will remove .gz extension from the filename so the file you work with
# will be named: smtp.log
FILE="$1"
if [[ -f "$FILE" ]] ;
then
# If the file exists, ask the user if they want to delete the file or keep it.
echo "[D]elete file or [K]eep file"
read option
case ${option} in
[Dd]) # If delete, then delete the file
rm -f smtp.log
#Download the file
wget https://www.secrepo.com/maccdc2012/smtp.log.gz
gzip -d smtp.log.gz
;;
[Kk]) # otherwise, if they want to keep the existing file, then let the user know.
echo "Okay, keeping the existing file"
sleep 2
esac
else if [[ ! -f "$FILE" ]];
then
# If the file doesn't exist, then download it.
wget https://www.secrepo.com/maccdc2012/smtp.log.gz
gzip -d smtp.log.gz
fi
# Use awk to create a header
awk ' BEGIN { FORMAT = "%-15s %-15s %s\n"
printf format, "SRC IP,", "DST IP,", "Message"}
{
q = "\""
cq = "\","
printf format, q$3cq, q$5cq, q$21q
}'
<file_sep>/Python/Python Assignments/sumN.py
n = int(input('Please enter a Number: '))
def sumN(n):
nSum = n + n
return nSum
def sumNCubes(n):
nCubes = n * n * n
sumNCubed = nCubes * 3
return sumNCubed
print(sumN(n))
print(sumNCubes(n))
<file_sep>/AutomationScripting/Bash/Week10/menu.bash
#!/bin/bash
# Admin and Security admin menu.
# Incident Response Collection submenu function
function IRC_menu() {
# Clear the screen
clear
# Create menu options
echo "| Incident Response Collection |"
echo ""
echo "1. Show all root users"
echo "2. Open ssh_config file"
echo "3. Check command history"
echo "4. Check attached devices"
echo "5. Check mounted devices"
echo "6. Show all USB buses and devices"
echo "7. Show CPU information"
echo "8. Show all PCI busses and devices"
echo "9. Check netowrk connections"
echo "10. Network Statistics command"
echo ""
echo "[R]eturn to Security Admistration Menu"
echo "[E]xit"
# Prompt for the menu option
echo ""
echo -n "Please enter an option: "
# Read in the user input
read option
# Case statement to process options
case ${option} in
1) cat /etc/sudoers | less
# command that shows users that have root access
# this is a good command as it can reveal compromised
#security through users that aren't supposed to be sudoers
;;
2) cat /root/etc/ssh/ssh_config | less
# command that opens ssh_config file
# this is a good command as it lets the admin
#search for any changed security settings that
#would allow for unauthorized access
;;
3) history
# allows access to command history
# this is good as if you want to check
#the command history of a certain user
#and see if there were any suspicious activity
#within their account
;;
4) locate rhosts
# defines which remote hosts can invoke
#certain commands on the local host
#without supplying a password
# This is a good command as the admin can determine
#if there are any security compromises with romote host access
;;
5) lsblk | less
# lists attached devices
# this is a good command as it gives the admin
#an overview what what is mounted to the system
#that is being evaluated
;;
6) lsusb | less
# prints all USB buses and devices
# This is a good command as you can determine if there is
#an unauthorized device connected to the system
#preventing any system and security issues
;;
7) lscpu | less
# prints CPU information
# This is a good command as the admin can easily view a
#systems cpu information and look for any issues
;;
8) lspci | less
# prints all PCI buses and devices
# This is a good command as the admin can easily view a
#systems PCI information and look for any issues and see
#if there are any unauthorized device connected to the system
#preventing any system and security issues
;;
9) ipconfig -a
# check the system's network connections
# this is a good command as if the incident involved
#the system network the admin can check the
#network connections for any security compromises
;;
10) netstat -anop | less
# network utility that displays network connections for
#TCP, routing tables, and a number of network interface
#and network protocol statistics
# This is a good command as it can check for
#suspicious connections and if the system is listening
#for unauthorized connections as well
;;
[Rr]) security_menu
;;
[Ee]) exit 0
;;
*) echo "| Invalid input |"
sleep 3
IRC_menu
;;
# Stops the case statement
esac
# Call IRC_menu
IRC_menu
} # end IRC_menu function
# Admin Menu function
function admin_menu() {
# Clear the screen
clear
# Create menu options
echo "| System Administration Menu |"
echo ""
echo "1. List Running Processes"
echo "2. Show Open Network Sockets"
echo "3. Check Logged in Users"
echo "4. Show current username and groups"
echo "5. Show last users logged on"
echo "6. Show all USB buses and devices"
echo "7. Show CPU information"
echo "8. Show all PCI buses and devices"
echo ""
echo "[R]eturn to Main Menu"
echo "[E]xit"
# Prompt for the menu option
echo ""
echo -n "Please enter an option: "
# Read in the user input
read option
# Case statement to process options
case ${option} in
1) ps -ef | less
;;
2) netstat -an --inet | less
# lsof -i -n | less
;;
3) w | less
;;
4) id | less
# Print real and effective user id (uid) and group id (gid),
#prints identity information about the given user
# This is a good command as is gives current identity information about the user
#to make sure they are in the right account and such
;;
5) last -a | less
# Prints the last users who logged on
# This is a good command as if an issue with the system arose
#the administrator can check who was last logged on and
#investigate their actions
;;
6) lsusb | less
# prints all USB buses and devices
# This is a good command as you can determine if there is
#an unauthorized device connected to the system
#preventing any system and security issues
;;
7) lscpu | less
# prints CPU information
# This is a good command as the admin can easily view a
#systems cpu information and look for any issues
;;
8) lspci | less
# prints all PCI buses and devices
# This is a good command as the admin can easily view a
#systems PCI information and look for any issues and see
#if there are any unauthorized device connected to the system
#preventing any system and security issues
;;
[Rr]) main_menu
;;
[Ee]) exit 0
;;
*) echo "| Invalid input |"
sleep 3
admin_menu
;;
# Stops the case statement
esac
# Call admin_menu
admin_menu
} # End admin_menu function
#Security Menu
function security_menu() {
# Clear the screen
clear
# Create menu options
echo "| Security Administration Menu |"
echo ""
echo "1. Show last logged in users"
echo "2. Check installed packages"
echo "3. Check all users and their ID"
echo ""
echo "[R]eturn to Main Menu"
echo "[I]ncident Response Collection"
echo "[E]xit"
# Prompt for the menu option
echo ""
echo -n "Please enter an option: "
# Read in the user input
read option
# Case statement to process options
case ${option} in
1) last -adx | less
;;
2) dpkg -l | less
;;
3) cut -d: -f1,3 /etc/passwd
;;
[Rr]) main_menu
;;
[Ii]) IRC_menu
;;
[Ee]) exit 0
;;
*) echo "| Invalid input |"
sleep 3
admin_menu
;;
# Stops the case statement
esac
# Call security menu
security_menu
} # End security_menu function
# Main Menu
function main_menu() {
# Clear the screen
clear
# Create menu options
echo "| Administration |"
echo ""
echo "1. System Admin Menu"
echo "2. Security Admin Menu"
echo ""
echo "[E]xit"
# Prompt for the menu option and read in the option
echo ""
echo -n "Please select a menu: "
read menuOption
if [[ ${menuOption} -eq 1 ]]
then
# Call the admin_menu function
admin_menu
elif [[ ${menuOption} -eq 2 ]]
then
# Call the security_menu function
security_menu
else
# Exit the program
exit 0
fi
} # End main_menu function
# Call main_menu function
main_menu
<file_sep>/Python/PycharmProjects_1819/Loops_Assignment/GuessingGame_Extended.py
from random import randint
# import [random] module
randomNum = randint(1, 100)
# a random integer would be chosen from between 1 and 100
name = input("Hi! What is your name? ")
while True:
# Keeps the following code in a loop until the guess is answered correctly
try:
guess = int(input("Please guess a number between 1 and 100, " + name + ": "))
except ValueError:
print("Uh-ooooohhhhh...(POOF)")
break
# the above code was influenced by this source: https://stackoverflow.com/questions/5424716/how-to-check-if-string-input-is-a-number
# I just tried to find something that would recognize that if user input was not an integer it would let the user try again or end the program
if guess == randomNum:
# If the random number chosen by the module is the same as the guess integer from the user
print("Congratulations, you guessed it!")
break
elif guess < 1 or guess > 100:
# If the guess integer from the user is not between 1 and 100
print("Uh-ooooohhhhh...(POOF)")
break
elif guess < randomNum:
# If the guess integer from the user is less than the chosen random integer
print("You guessed too low, try again.")
elif guess > randomNum:
# If the guess integer from the user is less than the chosen random integer
print("You guessed too high, try again.")
<file_sep>/Python/PycharmProjects_1718/Advanced_Python_Notes/Week5_Notes.py
# class A:
# """An example parent class."""
# def __init__(self, value):
# """Initialize from provided value."""
# self.value = value
#
# def do_something(self):
# """Do something interesting."""
# print("do something")
#
#
# class B(A):
# """An example child class (AKA subclass AKA derived class)"""
# pass
#
#
# if __name__ == "__main__":
# help(A)
class Person:
"""A person (base class)"""
def __init__(self, name, id_number):
"""Initialize person with given name and id number."""
self.name = name
self.id_number = id_number
class Student(Person):
"""A student is a more specific type of person."""
def __init__(self, name, id_number, major, graduation_year):
"""Initialize student with given name, id number, major, and graduation year."""
super().__init__(name, id_number)
self.major = major
self.graduation_year = graduation_year
class Faculty(Person):
def __init__(self, name, id_number, department, advisees=None):
super().__init__(name, id_number)
self.department = department
if advisees is None:
self.advisees = []
else:
self.advisees = advisees
def __str__(self):
result = f"{super().__str__()} teaches in the Dept. of {self.department}"
return result
if __name__ == "__main__":
joe = Student()<file_sep>/Python/PycharmProjects_1819/Class Notes/Week5_Notes.py
# y = 1, 2, 3, 4, 5
# for x in y:
# print(x)
# for x in range(0, 11, 2):
# print("The value in this range equals: ", x)
# x = 0
# while x < 10:
# print("The value of x is", x)
# break
# recursive 'for' loop (?)
# y = [1, 2, 3]
# for x in y:
# y.append(x)
# print(x)
# import random
# for i in range(5):
# print(random.randint(1, 10))
# from random import randint
# random_num = randint(0, 10)
#
# for x in range(3):
# guess = int(input("Guess a number between 0 and 10: "))
#
# if random_num == guess:
# print("You guessed right!")
#
# try_again = input("Would you like to try again? Enter 'YES' or 'NO'")
# if try_again == 'YES':
# True
# else:
# break
# elif random_num < guess:
# print("Oops, you guessed too high.")
# elif random_num > guess:
# print("Oops, you guessed too low.")
#
# print("Oops, you ran out of guesses.")
# Class Example Game
# name = input("What is your name? ")
# number = random.randint(1, 10)
# counter = 0
# print(number)
# y = 1, 2, 3
# for x in y:
# z = int(input("Hello " + name + ", please guess a number between 1 and 10: "))
# counter += 1
# if z == number:
# print("Congratulations, you guessed it!")
# break
# elif z < number:
# print("You guessed too low, try again an you have " + str(3-counter) + "guesses left.")
# elif z > number:
# print("You guessed too high, try again an you have " + str(3-counter) + "guesses left.")
# else:
# print("The system just blew up, it's over...")
# break
# LISTS
# list = holds multiple items (array) / brackets are symbolic (all values are indexed)
y = ["A", "B", "C", "D"]
z = ["E", "F", "G", "H", "I", "J", "K", "L"]
# print(y[0])
# y.append(z)
list_x = y + z
# print(y + z)
# print(list_x)
# length = len(list_x)
# print(length)
# list_a = list_x - z
# print(list_a)
# for i in range(length):
# print(list_x[i] + " is an element of the list 'x'.")
# user_input = input("What letter are you trying to find in the list: ")
# if list_x.index(user_input):
# print("YES")
# else:
# print("NO")
# half = len(list_x) // 2
# print(half)
#Print quarters of the list
fourth_a = list_x[0:3]
fourth_b = list_x[3:6]
fourth_c = list_x[6:9]
fourth_d = list_x[9:13]
print(fourth_a)
print(fourth_b)
print(fourth_c)
print(fourth_d)
#or
a = 0
b = c = len(list_x) // 4
for i in range(len(list_x) // c):
print(list_x[a:b])
a = b
b += c<file_sep>/Python/PycharmProjects_1819/Advanced_Python_Notes/Week7_Notes.py
print("hello")
a = 2
class InvalidInputError(Exception):
def __init__(self, value):
super().__init__()
self.value = value
def __str__(self):
return f"invalid input: {self.value}"
def prompt_user():
try:
value = input("enter an integer > ")
return int(value)
except ValueError as e:
raise InvalidInputError(value) from e
def prompt_for_n_values(n):
return [prompt_user() for _ in range(n)]
try:
values = prompt_for_n_values(3)
print(values)
except InvalidInputError as e:
print("There was problem > ", e)
while True:
try:
value = prompt_user()
except InvalidInputError as e:
print("Invalid Input", e.value)
else:
print(value / 2)
break
<file_sep>/Python/PycharmProjects_1819/Final_Project/AD_BASE.py
# The use of the [pyad] external library has been influenced from the Website:
# https://github.com/zakird/pyad
# All credit to the use of code from the [pyad] external library goes to Author <NAME>
# License: Apache Software License (Apache License, Version 2.0)
from pyad import pyad # a just in case thing
from pyad import aduser # imports code used for User manipulation in AD from the downloaded [pyad] library
from pyad import adgroup # imports code used for Group manipulation in AD from the downloaded [pyad] library
from pyad import adcomputer # imports code used for Computer manipulation in AD from the downloaded [pyad] library
from pyad import adcontainer # not sure if I will use
import csv # backup plan if I have time, in case connection to Active Directory does not work
import sys
# Admin Username and Password used for testing purposes
admin_username = "brianna.guest"
admin_password = "E10"
# The main menu for navigating the functions of the program
menu_text = "\n" \
"| Welcome to Active Directory |" \
"\n(1) Add Something" \
"\n(2) Remove Something" \
"\n(3) Create Computer" \
"\n(4) Manipulate Something" \
"\n(5) Quit the program" \
def create():
""" Give Admin the option to create a User, Group, or Computer.
It then navigates the Admin to the appropriate function to enter information.
:return (if Option 1 was entered): (function) create_user()
:return (if Option 2 was entered): (function) create_group()
:return (if Option 3 was entered): (function) create_computer()
"""
add_menu = "" \
"| Choose a Class to Create |" \
"\n(1) User" \
"\n(2) Group" \
"\n(3) Computer"
print(add_menu)
admin_choice = input("Enter here: ")
if admin_choice == "1":
create_user()
elif admin_choice == "2":
create_group()
elif admin_choice == "3":
create_computer()
else:
print("\n| Re-enter the option |\n")
def create_user():
""" Creates a User in Active Directory based on the input given by the Admin
:return: (string) The User has successfully been created
"""
new_user = input("| Enter the name of the User |")
password = input("| Enter the Password of the User |")
aduser.ADUser.create(new_user, password=<PASSWORD>, enable=True)
return "| User Created |"
def create_group():
""" Creates a Group in Active Directory based on the input given by the Admin
:return: (string) The Group has successfully been created
"""
new_group = input("| Enter the name of the Group |")
adgroup.ADGroup.create(new_group, security_enabled=True, scope='GLOBAL')
return "| Group created |"
def create_computer():
""" Creates a Computer in Active Directory based on the input given by the Admin
:return: (string) The Computer has successfully been created
"""
new_computer = input("| Enter the name of the Computer |")
adcomputer.ADComputer.create(new_computer, enable=True)
return "| Computer created |"
def remove():
""" Give Admin the option to remove a User, Group, or Computer.
It then navigates the Admin to the appropriate function to enter information.
:return (if Option 1 was entered): (function) remove_user()
:return (if Option 2 was entered): (function) remove_group()
:return (if Option 3 was entered): (function) remove_computer()
"""
remove_menu = "" \
"| Choose a Class to Remove |" \
"\n(1) User" \
"\n(2) Group" \
"\n(3) Computer"
print(remove_menu)
admin_choice = input("Enter here: ")
if admin_choice == "1":
remove_user()
elif admin_choice == "2":
remove_group()
elif admin_choice == "3":
remove_computer()
else:
print("\n| Re-enter the option |\n")
def remove_user():
""" Removes a User in Active Directory based on the input given by the Admin
:return: (string) The User has successfully been removed
"""
user_input = input("| Enter the name of the User |")
aduser.ADUser.from_cn(user_input).delete()
return "| User removed |"
def remove_group():
""" Removes a Group in Active Directory based on the input given by the Admin
:return: (string) The Group has successfully been removed
"""
group_input = input("| Enter the name of the Group |")
adgroup.ADGroup.from_dn(group_input).delete()
return "| Group Removed |"
def remove_computer():
""" Removes a User in Active Directory based on the input given by the Admin
:return: (string) The Computer has successfully been removed
"""
computer_input = input("| Enter the name of the Computer |")
adgroup.ADComputer.from_dn(computer_input).delete()
return "| Computer Removed |"
def manipulate():
""" Give Admin the option to manipulate an appropriate attribute for a User or Group.
It then navigates the Admin to the appropriate function to enter information.
:return (if Option 1 was entered): (function) manipulate_user()
:return (if Option 2 was entered): (function) manipulate_group()
"""
manipulate_menu = "" \
"| Choose a Class to Manipulate |" \
"\n(1) User" \
"\n(2) Group"
print(manipulate_menu)
admin_choice = input("Enter here: ")
if admin_choice == "1":
manipulate_user()
elif admin_choice == "2":
manipulate_group()
else:
print("\n| Re-enter the option |\n")
def manipulate_user():
""" Let's Admin manipulate attributes of an inputted User by either:
1. Setting a Password
2. Force the user to change the password at next login
:return: (string) Success
"""
user_manipulation = input("Enter name of User to Manipulate: ")
manipulate_menu_user = "" \
"| Choose how to Manipulate |" \
"\n(1) Set Password" \
"\n(2) Force User to Change Password at next login"
print(manipulate_menu_user)
admin_choice = input("Enter here: ")
if admin_choice == "1":
new_password = input("| Enter New Password |")
aduser.ADUser.set_password(user_manipulation, new_password)
print("| Password Set |")
elif admin_choice == "2":
aduser.ADUser.force_pwd_change_on_login(user_manipulation)
else:
print("\n| Re-enter the option |\n")
def manipulate_group():
"""Let's Admin manipulate attributes of an inputted Group by either:
1. Adding Members
2. Removing Members
3. Get a list of Members for a Group
:return: (string) Success
"""
group_manipulation = input("Enter name of Group to Manipulate: ")
manipulate_menu_group = "" \
"| Choose how to Manipulate |" \
"\n(1) Add Member" \
"\n(2) Remove Member" \
"\n(3) Get list of Members"
print(manipulate_menu_group)
admin_choice = input("Enter here: ")
if admin_choice == "1":
while True:
user_add = input("Enter User (Press Enter to end): ")
adgroup.ADGroup.add_members(group_manipulation, user_add)
print("| User Added |")
if user_add == "":
break
elif admin_choice == "2":
while True:
user_remove = input("Enter User (Press Enter to end): ")
adgroup.ADGroup.add_members(group_manipulation, user_remove)
print("| User Removed |")
if user_remove == "":
break
elif admin_choice == "3":
adgroup.ADGroup.get_members(group_manipulation, recursive=False, ignoreGroups=False)
else:
print("\n| Re-enter the option |\n")
while True: # Log-in to get to the main menu of the Active Directory functions menu
username_input = input("Enter username: ")
password_input = input("Enter password: ")
if password_input != admin_password:
print("\n| Username or Password Unknown |\n")
elif username_input != admin_username:
print("\n| Username or Password Unknown |\n")
elif username_input == admin_username and password_input == <PASSWORD>:
break
while True: # Navigation code for the main menu
print(menu_text)
admin_choice = input("\nEnter an option: ")
if admin_choice == '1':
create()
elif admin_choice == '2':
remove()
elif admin_choice == '3':
manipulate()
elif admin_choice == '4':
sys.exit()
else:
print("\n| Re-enter the option |\n")
<file_sep>/Python/PycharmProjects_1718/LibraryProject/main.py
"""The user interface of the Library Collection System.
Author: <NAME>
Class: CSI-260-01
Assignment: Library Project
Due Date: 2/27/2019 11:59 PM
Certification of Authenticity:
I certify that this is entirely my own work, except where I have given
fully-documented references to the work of others. I understand the definition
and consequences of plagiarism and acknowledge that the assessor of this
assignment may, for the purpose of assessing this assignment:
- Reproduce this assignment and provide a copy to another member of academic
- staff; and/or Communicate a copy of this assignment to a plagiarism checking
- service (which may then retain a copy of this assignment on its database for
- the purpose of future plagiarism checking)
"""
from library_system \
import BookRecord, MusicAlbumRecord, DVDRecord, \
Catalog, CategoryTag
import sys
import csv
# main menu of user interface
menu = "\nLibrary Catalog Menu\n" \
"1. Search catalog" \
"\n2. Print the entire catalog" \
"\n3. Add item to catalog" \
"\n4. Remove item from catalog" \
"\n5. Print all Category Tags" \
"\n6. Open Catalog from file" \
"\n7. Save Catalog to file" \
"\n8. Export to .csv file" \
"\n9. Exit System" \
"\n"
# menu of Add item option
add_menu = "\nType of Library Items\n" \
"1. Book" \
"\n2. Music Album" \
"\n3. DVD" \
"\n"
def main():
"""User Interface of the Library Collection system.
Provides the user interface and initialization of the Catalog Class,
thus the catalog itself.
"""
name = input("Enter the name of the Catalog: ")
catalog = Catalog(name)
while True:
print(menu)
user_input = input("Choose an option: ")
if user_input == '1':
filter_text = input("Search for: ")
catalog.search(filter_text)
elif user_input == '2':
try:
for item in catalog._collection:
print(f'{item}\n')
except TypeError:
print(catalog._collection)
elif user_input == '3':
collection = []
print(add_menu)
user_input = input("Choose an option: ")
if user_input == '1':
tag_list = []
name = input("Enter Name: ")
isbn = int(input("Enter ISBN Number: "))
genre = input("Enter Genre: ")
author = input("Enter Author: ")
while True:
user_input = input("Optionally - "
"Enter Category Tags"
"(Press Enter when finish): ")
if user_input != '':
tag_list.append(CategoryTag(user_input).__str__())
else:
break
# fix from previous submission (forgot to implement)
collection.\
append(BookRecord(
name, isbn, genre, author,
tag_list).__str__())
catalog.add_list(collection)
elif user_input == '2':
tag_list = []
name = input("Enter Name: ")
isbn = int(input("Enter ISBN Number: "))
genre = input("Enter Genre: ")
artist = input("Enter Artist: ")
label = input("Enter the Record Label of the Music Album: ")
while True:
user_input = input("Optionally - "
"Enter Category Tags"
"(Press Enter when finish): ")
if user_input != '':
tag_list.append(CategoryTag(user_input).__str__())
else:
break
# fix from previous submission (forgot to implement)
collection.append(MusicAlbumRecord(
name, isbn, genre, artist, label,
tag_list=tag_list).__str__())
catalog.add_list(collection)
elif user_input == '3':
tag_list = []
name = input("Enter Name: ")
isbn = int(input("Enter ISBN Number: "))
company = input("Enter Company: ")
genre = input("Enter Genre: ")
while True:
user_input = input("Optionally - "
"Enter Category Tags"
"(Press Enter when finish): ")
if user_input != '':
tag_list.append(CategoryTag(user_input).__str__())
else:
break
# fix from previous submission (forgot to implement)
collection.\
append(DVDRecord(name, isbn, company, genre,
tag_list).__str__())
catalog.add_list(collection)
elif user_input == '4':
remove_list = []
while True:
user_input = \
input("Enter the items to remove(Press Enter when done): ")
if user_input != '':
remove_list.append(user_input)
else:
break
for item in remove_list:
catalog.remove_list(item)
elif user_input == '5':
print(CategoryTag.all_category_tags())
elif user_input == '6':
catalog.load_catalog()
elif user_input == '7':
catalog.save_catalog(catalog)
elif user_input == '8':
with open('database.csv', 'a') as write_file:
writer = csv.writer(write_file)
writer.writerow(catalog._collection)
print("Export Complete")
# I wasn't able to get the import function to work so I decided not to include it
elif user_input == '9':
sys.exit()
if __name__ == "__main__":
main()
<file_sep>/Python/PycharmProjects_1718/Week 4 Programming Assignment/Voting_Test.py
age = int(input("To check if you are able to vote, please enter your age: "))
if age >= 18:
# If your age is greater than or equal to 18
print("You are of voting age.")
else:
# If your age is less than 18
print("You must be 18 to vote.")<file_sep>/Python/PycharmProjects_1819/Advanced_Python_Notes/Week8_Notes.py
'''
class Color:
def __init__(self, rgb_value, name):
self._attributes = [rgb_value, name]
def get_rgb_value(self):
return self._attributes[0]
def set_rgb_value(self, rgb_value):
if len(rgb_value) != 7:
raise ValueError("rgb_value must be 7 characters")
if rgb_value[0] != '#':
raise ValueError("rgb_value must start with #")
self._attributes[0] = rgb_value
def get_name(self):
return self._attributes[1]
def set_name(self, name):
self._attributes[1] = name
# More Pythonic Way
class Color:
def __init__(self, rgb_value, name):
self._rgb_value = rgb_value
self._name = name
@property
def rgb_value(self):
return self._rgb_value
@rgb_value.setter
def rgb_value(self, rgb_value):
if len(rgb_value) != 7:
raise ValueError("rgb_value must be 7 characters")
if rgb_value[0] != '#':
raise ValueError("rgb_value must start with #")
self._rgb_value = rgb_value
@property
def name(self):
return self._name
@name.setter
def name(self, name):
self._name = name
if __name__ == "__main__":
c = Color('#ff0000', 'bright red')
c.rgb_value = 'dhdhdhd'
c.name = 'red'
print(c.name, c.rgb_value)
'''
class Person:
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
@property
def full_name(self):
return f'{self.first_name} {self.last_name}'
@full_name.setter
def full_name(self, full_name):
if len(full_name.split()) != 2:
raise ValueError("full_name mist contain exactly 2 names")
self.first_name, self.last_name = full_name.split()
if __name__ == "__main__":
john = Person('John', "Smith")
john.first_name = 'Bob'
print(john.full_name)
john.full_name = '<NAME>'
print(john.first_name, john.last_name)<file_sep>/Python/PycharmProjects_1718/Week 10 Programming Assignment/Part2.py
user_string = input("Submit text here: ")
stringFreq = {}
user_string = user_string.split() # splits the sentence up by word
for word in user_string: # goes through the split string
stringFreq.setdefault(word, 0) # Sets each word counter to zero
stringFreq[word] = stringFreq[word] + 1 # if word in string is found, adds one to the counter
# Took inspiration from class examples from Week 9
print(stringFreq)
<file_sep>/Python/Python Assignments/sumList.py
nums = [1, 2, 3, 4, 5]
def sumList(nums):
return sum(nums)
print(sumList(nums))
<file_sep>/Python/PycharmProjects_1718/Final_Project/Final_Project/AD_BASE.py
# The use of the [pyad] external library has been influenced from the Website:
# https://github.com/zakird/pyad
# All credit to the use of code from the [pyad] external library goes to Author <NAME>
# License: Apache Software License (Apache License, Version 2.0)
# THIS PROGRAM CAN ONLY BE TESTED IN A SERVER ENVIRONMENT (sorry)
from pyad import pyad # a just in case thing
from pyad import aduser # imports code used for User manipulation in AD from the downloaded [pyad] library
from pyad import adgroup # imports code used for Group manipulation in AD from the downloaded [pyad] library
from pyad import adcomputer # imports code used for Computer manipulation in AD from the downloaded [pyad] library
from pyad import adcontainer # imports code used for Active Directory container manipulation from the [pyad] library
import sys
# Admin Username and Password used for testing purposes
admin_username = "brianna.guest"
admin_password = "E10"
# The main menu for navigating the functions of the program
menu_text = "\n" \
"| Welcome to Active Directory |" \
"\n(1) Add Something" \
"\n(2) Remove Something" \
"\n(3) Manipulate Something" \
"\n(4) Quit the Program" \
# The following three variables
# is supposed to set the organizational units to send user, group, or computer information
# for the create() and manipulate() functions, but there is an issue with server communication and they can't be used
# therefore there are issues when using the create_whatever() and manipulate_whatever() functions
# removing stuff works though
try: # error handling
users_ou = adcontainer.ADContainer.from_dn("ou=Users, dc=brianna, dc=local")
except: # prints error in neater format and doesn't exit the program
print("Unexpected Error: \n", sys.exc_info())
try: # error handling
groups_ou = adcontainer.ADContainer.from_dn("ou=Groups, dc=brianna, dc=local")
except: # prints error in neater format and doesn't exit the program
print("Unexpected Error: \n", sys.exc_info())
try: # error handling
computers_ou = adcontainer.ADContainer.from_dn("ou=Computers, dc=brianna, dc=local")
except: # prints error in neater format and doesn't exit the program
print("Unexpected Error: \n", sys.exc_info())
def create():
""" Give Admin the option to create a User, Group, or Computer.
It then navigates the Admin to the appropriate function to enter information.
:return (if Option 1 was entered): (function) create_user()
:return (if Option 2 was entered): (function) create_group()
:return (if Option 3 was entered): (function) create_computer()
"""
add_menu = "" \
"| Choose a Class to Create |" \
"\n(1) User" \
"\n(2) Group" \
"\n(3) Computer"
print(add_menu)
admin_choice = input("Enter here: ")
if admin_choice == "1": # sends the Admin to the create_user() function
create_user()
elif admin_choice == "2": # sends the Admin to the create_group() function
create_group()
elif admin_choice == "3": # sends the Admin to the create_computer() function
create_computer()
else:
print("\n| Re-enter the option |\n")
def create_user():
""" Creates a User in Active Directory based on the input given by the Admin
:return: (string) The User has successfully been created
"""
new_user = input("| Enter the name of the User | ")
password = input("| Enter the Password of the User | ")
try: # error handling
aduser.ADUser.create(new_user, container_object=none, password=<PASSWORD>, enable=True)
print("| User Created |")
except: # prints error in neater format and doesn't exit the program
print("Unexpected Error: \n", sys.exc_info())
def create_group():
""" Creates a Group in Active Directory based on the input given by the Admin
:return: (string) The Group has successfully been created
"""
new_group = input("| Enter the name of the Group | ")
try: # error handling
adgroup.ADGroup.create(new_group, container_object=none, security_enabled=True, scope='GLOBAL')
print("| Group created |")
except: # prints error in neater format and doesn't exit the program
print("Unexpected Error: \n", sys.exc_info())
def create_computer():
""" Creates a Computer in Active Directory based on the input given by the Admin
:return: (string) The Computer has successfully been created
"""
new_computer = input("| Enter the name of the Computer | ")
try: # error handling
adcomputer.ADComputer.create(new_computer, container_object=none, enable=True)
print("| Computer created |")
except: # prints error in neater format and doesn't exit the program
print("Unexpected Error: \n", sys.exc_info())
def remove():
""" Give Admin the option to remove a User, Group, or Computer.
It then navigates the Admin to the appropriate function to enter information.
:return (if Option 1 was entered): (function) remove_user()
:return (if Option 2 was entered): (function) remove_group()
:return (if Option 3 was entered): (function) remove_computer()
"""
remove_menu = "" \
"| Choose a Class to Remove |" \
"\n(1) User" \
"\n(2) Group" \
"\n(3) Computer"
print(remove_menu)
admin_choice = input("Enter here: ")
if admin_choice == "1": # sends the Admin to the remove_user() function
remove_user()
elif admin_choice == "2": # sends the Admin to the remove_group() function
remove_group()
elif admin_choice == "3": # sends the Admin to the remove_computer() function
remove_computer()
else:
print("\n| Re-enter the option |\n")
def remove_user():
""" Removes a User in Active Directory based on the input given by the Admin
:return: (string) The User has successfully been removed
"""
user_input = input("| Enter the name of the User | ")
try: # error handling
aduser.ADUser.from_cn(user_input).delete()
print("| User removed |")
except: # prints error in neater format and doesn't exit the program
print("Unexpected Error: \n", sys.exc_info())
def remove_group():
""" Removes a Group in Active Directory based on the input given by the Admin
:return: (string) The Group has successfully been removed
"""
group_input = input("| Enter the name of the Group | ")
try: # error handling
adgroup.ADGroup.from_dn(group_input).delete()
print("| Group Removed |")
except: # prints error in neater format and doesn't exit the program
print("Unexpected Error: \n", sys.exc_info())
def remove_computer():
""" Removes a User in Active Directory based on the input given by the Admin
:return: (string) The Computer has successfully been removed
"""
computer_input = input("| Enter the name of the Computer | ")
try: # error handling
adgroup.ADComputer.from_dn(computer_input).delete()
print("| Computer Removed |")
except: # prints error in neater format and doesn't exit the program
print("Unexpected Error: \n", sys.exc_info())
def manipulate():
""" Give Admin the option to manipulate an appropriate attribute for a User or Group.
It then navigates the Admin to the appropriate function to enter information.
:return (if Option 1 was entered): (function) manipulate_user()
:return (if Option 2 was entered): (function) manipulate_group()
"""
manipulate_menu = "" \
"| Choose a Class to Manipulate |" \
"\n(1) User" \
"\n(2) Group"
print(manipulate_menu)
admin_choice = input("Enter here: ")
if admin_choice == "1": # sends the Admin to the manipulate_user() function
manipulate_user()
elif admin_choice == "2": # sends the Admin to the manipulate_group() function
manipulate_group()
else:
print("\n| Re-enter the option |\n")
def manipulate_user():
""" Let's Admin manipulate attributes of an inputted User by either:
1. Setting a Password
2. Force the user to change the password at next login
:return: (string) Success
"""
user_manipulate = input("Enter name of User to Manipulate: ")
manipulate_menu_user = "" \
"| Choose how to Manipulate |" \
"\n(1) Set Password" \
"\n(2) Force User to Change Password at next login"
print(manipulate_menu_user)
admin_choice = input("Enter here: ")
if admin_choice == "1": # set a password for a user
try: # error handling
new_password = input("| Enter New Password | ")
aduser.ADUser.set_password(user_manipulate, new_password)
print("| Password Set |")
except: # prints error in neater format and doesn't exit the program
print("Unexpected Error: \n", sys.exc_info())
elif admin_choice == "2": # force a user to change their password when they next login
try: # error handling
aduser.ADUser.force_pwd_change_on_login(user_manipulate)
except: # prints error in neater format and doesn't exit the program
print("Unexpected Error: \n", sys.exc_info())
else:
print("\n| Re-enter the option |\n")
def manipulate_group():
"""Let's Admin manipulate attributes of an inputted Group by either:
1. Adding Members
2. Removing Members
3. Get a list of Members for a Group
:return: (string) Success
"""
group_manipulation = input("Enter name of Group to Manipulate: ")
manipulate_menu_group = "" \
"| Choose how to Manipulate |" \
"\n(1) Add Member" \
"\n(2) Remove Member" \
"\n(3) Get list of Members"
print(manipulate_menu_group)
admin_choice = input("Enter here: ")
if admin_choice == "1": # Add a user to a group
while True:
user_add = input("Enter User (Press Enter to end): ")
try: # error handling
adgroup.ADGroup.add_members(group_manipulation, user_add)
print("| User Added |")
except: # prints error in neater format and doesn't exit the program
print("Unexpected Error: \n", sys.exc_info())
if user_add == "":
break
elif admin_choice == "2": # removed a user from a group
while True:
user_remove = input("Enter User (Press Enter to end): ")
try: # error handling
adgroup.ADGroup.add_members(group_manipulation, user_remove)
print("| User Removed |")
except: # prints error in neater format and doesn't exit the program
print("Unexpected Error: \n", sys.exc_info())
if user_remove == "":
break
elif admin_choice == "3": # Get a list of members from a group
try: # error handling
adgroup.ADGroup.get_members(group_manipulation, recursive=False, ignoreGroups=False)
except: # prints error in neater format and doesn't exit the program
print("Unexpected Error: \n", sys.exc_info())
else:
print("\n| Re-enter the option |\n")
while True: # Log-in to get to the main menu of the Active Directory functions menu
username_input = input("\nEnter username: ")
password_input = input("Enter password: ")
if password_input != <PASSWORD>_password:
print("\n| Username or Password Unknown |\n")
elif username_input != admin_username:
print("\n| Username or Password Unknown |\n")
elif username_input == admin_username and password_input == <PASSWORD>_password:
break
while True: # Navigation code for the main menu
print(menu_text)
admin_choice = input("\nEnter an option: ")
if admin_choice == '1': # create a user, group, or computer on Active Directory
create()
elif admin_choice == '2': # remove a user, group, or computer on Active Directory
remove()
elif admin_choice == '3': # manipulate user or group settings
manipulate()
elif admin_choice == '4': # exit the program
sys.exit()
else:
print("\n| Re-enter the option |\n")
<file_sep>/Python/PycharmProjects_1819/Week11_Lab/options.py
"""Class Options for storing and retrieving options for a web server.
Author: <NAME>
Class: CSI-260-02
Assignment: Week 8 Lab
Due Date: March 8, 2019 11:59 PM
Certification of Authenticity:
I certify that this is entirely my own work, except where I have given
fully-documented references to the work of others. I understand the definition
and consequences of plagiarism and acknowledge that the assessor of this
assignment may, for the purpose of assessing this assignment:
- Reproduce this assignment and provide a copy to another member of academic
- staff; and/or Communicate a copy of this assignment to a plagiarism checking
- service (which may then retain a copy of this assignment on its database for
- the purpose of future plagiarism checking)
"""
class Options(dict):
"""Store and retrieve options for a Web Server."""
def __init__(self, *args, **kwargs):
"""Initialize the dictionary of Server options."""
super().__init__(kwargs)
for arg in args:
if type(arg) is str:
self[arg] = True
else:
raise TypeError()
def __getitem__(self, item):
"""Access options with square bracket notation.
Accessing unspecified options returns the boolean False.
"""
try:
return super().__getitem__(item)
except KeyError:
return False
def __setitem__(self, item, value):
"""Set and update options using square bracket notation."""
super().__setitem__(item, value)
def __getattr__(self, item):
"""Access options as attributes of the Options class."""
return self[item]
# Naomi from the SMART Space helped me understand how to use the method
# in terms of syntax
def __setattr__(self, item, value):
"""Set and update options using attribute notation."""
self[item] = value
# Naomi from the SMART Space helped me understand how to use the method
# in terms of syntax
def __delattr__(self, item):
"""Delete an attribute using square bracket/attribute notation."""
del self[item]
# Naomi from the SMART Space helped me understand how to use the method
# in terms of syntax
<file_sep>/Python/PycharmProjects_1718/Week 7 Programming Assignment/PasswordSaver_FirstDraft.py
import csv
import sys
#The password list - We start with it populated for testing purposes
entries = [["yahoo", "XqffoZeo"], ["google", "CoIushujSetu"]]
#The password file name to store the passwords to
password_file_name = "<PASSWORD>"
#The encryption key for the caesar cypher
encryption_key = 16
menu_text = """
What would you like to do:
1. Open password file
2. Lookup a password
3. Add a password
4. Save password file
5. Print the encrypted password list (for testing)
6. Quit program
Please enter a number (1-6)"""
def password_encrypt(unencrypted_message, key):
"""Returns an encrypted message using a caesar cypher
:param unencrypted_message (string)
:param key (int) The offset to be used for the caesar cypher
:return (string) The encrypted message
"""
#Fill in your code here.
# #If you can't get it working, you may want to put some temporary code here
# #While working on other parts of the program
result = ''
index = 0
while index < len(unencrypted_message):
ascii_val = ord(unencrypted_message[index]) - 32 + key
ascii_val = ascii_val % (126 - 32)
ascii_val += 32
result = result + chr(ascii_val)
index += 1
return result
# Placeholder for now, this is the Caesar Cipher example from class, going to try to write a simpler one
pass
def load_password_file(file_name):
"""Loads a password file. The file must be in the same directory as the .py file
:param file_name (string) The file to load. Must be a .csv file in the correct format
:return (list) The password entries
"""
with open(file_name, newline='') as csvfile:
password_reader = csv.reader(csvfile)
password_entries = list(password_reader)
return password_entries
def save_password_file(password_entries, file_name):
"""Saves a password file. The file will be created if it doesn't exist.
:param file_name (string) The file to save.
"""
with open(file_name, 'w+', newline='') as csvfile:
password_writer = csv.writer(csvfile)
password_writer.writerows(password_entries)
def add_entry(website, password):
"""Adds an entry with a website and password
Logic for function:
Step 1: Use the password_encrypt() function to encrypt the password.
The encryptionKey variable is defined already as 16, don't change this
Step 2: create a list of size 2, first item the website name and the second
item the password.
Step 3: append the list from Step 2 to the password list
:param website (string) The website for the entry
:param password (string) The unencrypted password for the entry
"""
#Fill in your code here
encrypt_password = password_encrypt(password, encryption_key)
entries.append([website, encrypt_password])
pass
def lookup_password(website):
"""Lookup the password for a given website
Logic for function:
1. Create a loop that goes through each item in the password list
You can consult the reading on lists in Week 5 for ways to loop through a list
2. Check if the name is found. To index a list of lists you use 2 square bracket sets
So passwords[0][1] would mean for the first item in the list get it's 2nd item (remember, lists start at 0)
So this would be 'XqffoZeo' in the password list given what is predefined at the top of the page.
If you created a loop using the syntax described in step 1, then i is your 'iterator' in the list so you
will want to use i in your first set of brackets.
3. If the name is found then decrypt it. Decrypting is that exact reverse operation from encrypting. Take a look at the
caesar cypher lecture as a reference. You do not need to write your own decryption function, you can reuse passwordEncrypt
Write the above one step at a time. By this I mean, write step 1... but in your loop print out every item in the list
for testing purposes. Then write step 2, and print out the password but not decrypted. Then write step 3. This way
you can test easily along the way.
:param website (string) The website for the entry to lookup
:return: Returns an unencrypted password. Returns None if no entry is found
"""
#Fill in your code here
for i in entries:
# NOT FINAL since not really a loop through the list
if website == 'yahoo':
password = entries[0][1]
password = password_encrypt(password, encryption_key)
return password
elif website == 'google':
password = entries[1][1]
password = password_encrypt(password, encryption_key)
return password
pass
while True:
print(menu_text)
choice = input()
if(choice == '1'): # Load the password list from a file
entries = load_password_file(password_file_name)
if(choice == '2'): # Lookup at password
print("Which website do you want to lookup the password for?")
for key_value in entries:
print(key_value[0])
website = input()
password = lookup_password(website)
if password:
print('The password is: ', password)
else:
print('Password not found')
if(choice == '3'):
print("What website is this password for?")
website = input()
print("What is the password?")
password = input()
add_entry(website, password)
if(choice == '4'): #Save the passwords to a file
save_password_file(entries, password_file_name)
if(choice == '5'): #print out the password list
for key_value in entries:
print(', '.join(key_value))
if(choice == '6'): #quit our program
sys.exit()<file_sep>/Python/PycharmProjects_1819/Week13_Lab/models.py
"""ORM Models for a patient database.
Also includes code to build the database if it doesn't exist.
Prof. <NAME>
Champlain College
CSI-260 -- Spring 2019
"""
import peewee
database = peewee.SqliteDatabase("patient_database.sqlite")
class BaseModel(peewee.Model):
"""Base ORM model."""
class Meta:
"""Common model configuration."""
database = database
def __str__(self):
"""Return string representation of record."""
pass
class Procedure(BaseModel):
"""ORM model of procedures table."""
name = peewee.CharField()
min_cost = peewee.DecimalField(default=None)
max_cost = peewee.DecimalField(default=None)
pre_procedure_checklist = peewee.TextField(default='')
class Meta:
"""Model configuration for procedures."""
table_name = 'procedures'
def __str__(self):
"""Return string representation of record."""
return f'Procedure: {self.name}; {self.min_cost} to {self.max_cost};' \
f' {self.pre_procedure_checklist}'
class Doctor(BaseModel):
"""ORM model of doctors table."""
first_name = peewee.CharField()
last_name = peewee.CharField()
primary_office = peewee.CharField(default='')
class Meta:
"""Model configuration for doctors."""
table_name = 'doctors'
def __str__(self):
"""Return string representation of record."""
return f'Dr. {self.first_name} {self.last_name}; {self.primary_office}'
class Patient(BaseModel):
"""ORM model of patients table."""
first_name = peewee.CharField()
last_name = peewee.CharField()
address = peewee.CharField(default='')
phone_number = peewee.CharField(default='')
emergency_contact = peewee.CharField(default='')
emergency_phone = peewee.CharField(default='')
primary_care_doctor = peewee.ForeignKeyField(Doctor, backref='patients',
null=True, default=None)
class Meta:
"""Model configuration for patients."""
table_name = 'patients'
def __str__(self):
"""Return string representation of record."""
return f'Patient: {self.first_name} {self.last_name}; {self.address};' \
f' {self.phone_number}; {self.primary_care_doctor}' \
f'Emergency Contact: {self.emergency_contact}; {self.phone_number}'
class PerformedProcedure(BaseModel):
"""ORM model of performed_procedures table."""
patient = peewee.ForeignKeyField(Patient, backref='procedure_history')
doctor = peewee.ForeignKeyField(Doctor, backref='procedure_history')
procedure = peewee.ForeignKeyField(Procedure, backref='procedure_history')
procedure_date = peewee.DateField(default=None)
notes = peewee.TextField(default='')
class Meta:
"""Model configuration for performed procedures."""
table_name = 'performed_procedures'
def __str__(self):
"""Return string representation of record."""
return f'Patient: {self.patient} Doctor: {self.doctor}' \
f'Procedure: {self.procedure}; {self.procedure_date}' \
f'Notes: {self.notes}'
if __name__ == "__main__":
try:
Procedure.create_table()
except peewee.OperationalError:
print("Procedure table already exists!")
try:
Doctor.create_table()
except peewee.OperationalError:
print("Doctor table already exists!")
try:
Patient.create_table()
except peewee.OperationalError:
print("Patient table already exists!")
try:
PerformedProcedure.create_table()
except peewee.OperationalError:
print("performed_procedures table already exists!")
<file_sep>/AutomationScripting/Bash/Week9/homework/secCheck.bash
#!/bin/bash
# Week 9 Assignment - Security Checks
# Create a script that performs local security checks.
function checks() {
# Check if set to one year
if [[ $3 != $2 ]]
then
# print if it is not compliant
echo -e "\e[1;31m$1 is not compliant. It should be: $2"
echo -e "The current value is: $3\e[0m"
echo ""
else
# print if it is compliant
echo -e "\e[1;32m$1 is compliant. The current value is: $3\e[0m"
echo ""
fi
} # closing checks function
# Get password policies
pass_check=$(egrep -i "^pass" /etc/login.defs)
# Get PASS_MAX_DAYS policy
pmax=$(echo "${pass_check}" | egrep -i "pass_max_days" | awk ' { print $2 } ')
# Get PASS_MIN_DAYS policy
pmin=$(echo "${pass_check}" | egrep -i "pass_min_days" | awk ' { print $2 } ')
# Get PASS_WARN_AGE policy
pwarn=$(echo "${pass_check}" | egrep -i "pass_warn_age" | awk ' { print $2 } ')
# Call our checks function
# $1 $2 $3
checks "PASSWORD MAX" "365" "${pmax}"
checks "PASSWORD MINIMUM" "14" "${pmin}"
checks "PASSWORD WARN AGE" "7" "${pwarn}"
# SSH Protocol check
chkSSHProto=$(egrep "^Protocol" /etc/ssh/sshd_config | awk ' { print $2 } ')
checks "The SSH Protocol" "2" "${chkSSHProto}"
# UsePAM setting check
chkUsePAM=$(egrep "^UsePAM" /etc/ssh/sshd_config | awk ' { print $2 } ')
checks "The UsePAM setting" "no" "${chkUsePAM}"
# PermitRootLogin setting check
chkPermitRootLogin=$(egrep "^PermitRootLogin" /etc/ssh/sshd_config | awk ' { print $2 } ')
checks "The PermitRootLogin setting" "prohibit-password" "${chkPermitRootLogin}"
# sftp_subsystem setting check
chkSFTP=$(egrep "^Subsystem" /etc/ssh/sshd_config | awk ' { print $3 } ')
checks "The SFTP Subsystem setting" "/usr/lib/openssh/sftp-server" "${chkSFTP}"
# Check direcotry Permissions
for eachDir in $(ls -l /home/ | grep '^d' | awk ' { print $3 } ')
do
# Check if the user is sys320
if [[ ${eachDir} == "sys320" ]]
then
# Don't check the directory
continue
fi
getDirPerms=$(ls -l /home/${eachDir} | awk ' { print $1 } ')
checks "The home directory for ${eachDir}" "drwx------" "${getDirPerms}"
done
<file_sep>/Python/PycharmProjects_1718/Loops_Assignment/exponent.py
num = 0
# set starting integer
for x in range(1, 101):
print(num)
# prints the current integer in the [num] variable
num = 2 ** x
# the cycle number in the range is set as the power of 2 and sets it in the [num] variable
<file_sep>/AutomationScripting/Bash/Week12/blockApache-skel.bash
#!/bin/bash
# Script to view Apache logs via a GUI and generate a block list for bad IPs.
function view_logs() {
# Present the apache access log screen
# Count the number of rules.
num_rules=$(echo ${block_ip} | awk -F"|" ' { print NF } ')
# If no rules are selected, the value of ${num_rules} will be 0.
if [[ ${num_rules} -eq 0 ]]
then
# Prompt for finding no IPs selected
# Get the value of the exit status, we set above with the buttons
no_ip=$?
# Allow the user to see the logs again
if [[ ${no_ip} -eq 10 ]]
then
view_logs
else
# Or exit if they select No.
exit 0
fi
else
# Get the IP address (field $2) from the yad output and format the results into an IPTables drop rule
# File save dialog will
# Save the IPs to the file specified.
echo "${the_rules}" |& tee ${save_ip}
# Prompt to view the logs again.
yad --text="Would you like to view the logs again?" \
--button="Yes":10 \
--button="No":20
# Get the value of the buttons (:10 or :20) from the bash environment
allDone=$?
# Process the buttons.
if [[ ${allDone} -eq 10 ]]
then
view_logs
else
exit 0
fi
fi
} # end view_logs function
# Display the main menu
view_logs
<file_sep>/Python/PycharmProjects_1819/Advanced_Python_Notes/week11_demo3.py
"""Demo of attr magic methods.
Prof. <NAME>
Champlain College
CSI-260 -- Spring 2019
"""
class Demo:
def __getattr__(self, item):
print("Calling __getattr__ ", item)
return 42
def __setattr__(self, key, value):
print("Calling __setattr__ ", key, value)
def __delattr__(self, item):
print("Calling __delattr__", item)
if __name__ == "__main__":
demo = Demo()
print(demo.something)
demo.something = 42
del demo.something
<file_sep>/Python/PycharmProjects_1718/Class Notes/Week6_Notes.py
# catNames = []
# while True:
# print('Enter the name of cat ' + str(len(catNames) + 1) + ' (Or enter nothing to stop.):')
# name = input()
# if name == '':
# break
# catNames = catNames + [name] # list concatenation
# print('The cat names are:')
# for name in catNames:
# print(' ' + name)
# method = any action we can take upon an object
# property = a characteristic/descriptor
# object = any thing that can be in memory
# products = [19.99, "Computer 1", 27]
# while True:
# price = (input("Enter the product price or press enter to continue: "))
# prod_desc = input("Enter the product name or press enter to continue: ")
# monitor = (input("Enter the product size or press enter to continue: "))
# if price == '' or prod_desc == '' or monitor == '':
# break
# products = products + [price] + [prod_desc] + [monitor]
# print(products)
names = ["John", "Betty", "Zak", "Mark", "Mary", "Kylie"]
# Returns the index value of an element in the list
# a = names.index('Zak')
# print(a)
# This is a ValueError message because 'Charles' is not in the list
# b = names.index("Charles")
# print(b)
# The append() will insert an element at the end of a list
names.append("Amos")
# print(names)
# The insert() method will allow the programmer to target a position in the list to insert a value
names.insert(3, "Steve")
# print(names)
names.remove("Mark")
# print(names)
# When performing a sort(), it will not work on a mixed list(ie. integers/alpha chars.)
names.sort()
# print(names)
# names.sort(reverse=True)
# print(names)
# userInput = input("Search for a name here: ")
# if userInput in names:
# print('The name of ' + userInput + ' was found and will be removed.')
# names.remove(userInput)
# elif userInput not in names:
# print('The name of ' + userInput + ' was not found.')
# or
# def findName():
# print('Here are the names in the list: ')
# print(names)
# j = 0
# my_name = input('What name do you want removed: ')
# for i in range(len(names)):
# if my_name in names:
# names.remove(my_name)
# j = 1
# else:
# continue
# if j == 1:
# print('The value of ' + my_name + ' was found and removed: ')
# print(names)
# else:
# print('The value of ' + my_name + ' was not found')
# findName()
# Nested loop is a loop in a loop
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
people = ["Andy", "Betsy", "Charles", "David", "George", "Harry", "Larry", "Mary", "Rose"]
for i in range(len(numbers)):
for j in range(len(people)):
# print("Person Num. " + str(numbers[i]) + ' is ' + people[j] + '.')
placeOfPeople = str(numbers[i]) + ". " + people[i]
print(placeOfPeople)
<file_sep>/Python/Python Assignments/Quiz 7.py
speed = int(input("Your speed in mph: "))
distance = float(input("Enter your distance in miles: "))
print("Enter your choice of format for time")
choice = input("decimal hours (D) or hours and minutes (M): ")
print()
if choice == "D" or choice == "d":
time = distance/speed
print("At", speed, "mph, it will take")
print(time, "hours to travel", distance, "miles.")
else:
time = distance/speed
hours = int(time)
minutes = int((time - hours)*60)
print("At", speed, "mph, it will take")
print(hours, "hours and", minutes, "minutes to travel",\
distance, "miles.")
input("\n\nPress the Enter key to exit")
<file_sep>/Python/Python Assignments/Quiz 7.2.py
scores = 1
while scores < 20:
scores = scores + 2
print(scores)
<file_sep>/Python/PycharmProjects_1819/Week 6 Programming Assignment/comma_code.py
userList = []
while True:
newWord = input("Enter a word to add to the list (press return to stop adding words): ")
if newWord == "":
break
else:
userList.append(newWord)
userList.insert(-1, "and")
print(*userList, sep=", ") # code influenced from source: https://www.geeksforgeeks.org/print-lists-in-python-4-different-ways/
# I was having trouble trying to show the whole list and was able to find a way to do so from the website
<file_sep>/Python/PycharmProjects_1718/Week4_Lab/week4.py
"""Menu as User Interface for medical.py classes.
Authors: <NAME>, <NAME>
Class: CSI-260-02
Assignment: Week 4 Lab
Due Date: February 12, 2019 11:59 PM
Certification of Authenticity:
I certify that this is entirely my own work, except where I have given
fully-documented references to the work of others. I understand the definition
and consequences of plagiarism and acknowledge that the assessor of this
assignment may, for the purpose of assessing this assignment:
- Reproduce this assignment and provide a copy to another member of academic
- staff; and/or Communicate a copy of this assignment to a plagiarism checking
- service (which may then retain a copy of this assignment on its database for
- the purpose of future plagiarism checking)
"""
import sys
import csv
from medical import Patient, Procedure
main_menu = "Patient Database Main Menu" \
"\n" \
"1. Search Patient Database by ID Number" \
"\n2. Add New Patient" \
"\n3. Quit" \
"\n"
patient_menu = "Patient Information Menu" \
"\n" \
"1. Modify Patient Information" \
"\n2. Delete Patient" \
"\n3. Add a Procedure" \
"\n"
modification_menu = "Modification Menu" \
"\n" \
"1. First Name" \
"\n2. Last Name" \
"\n3. Address" \
"\n4. Phone Number" \
"\n5. Emergency Contact First Name" \
"\n6. Emergency Contact Last Name" \
"\n7. Emergency Contact Phone Number" \
"\n"
def main():
"""Main Menu for Patient Information and commands associated with the menu options."""
# Patient.load_patients() # Load pickled dictionary from file
print(main_menu)
user_input = input("Enter Option: ")
if user_input == '1': # Search for Patient
patient_id = input("Enter Patient ID Number: ")
Patient.get_patient(patient_id)
if None:
print("Patient ID Not Found")
else:
print(patient_menu)
user_input = input("Enter Option: ")
if user_input == '1': # modify Patient attributes
print(modification_menu)
user_input = input("Enter Option: ")
if user_input == '1': # Modify Patient First Name
new_fname = input("Enter Modification Here: ")
Patient.first_name = new_fname
elif user_input == '2': # Modify Patient Last Name
new_lname = input("Enter Modification Here: ")
Patient.last_name = new_lname
elif user_input == '3': # Modify Patient Address
new_phone = input("Enter Modification Here: ")
Patient.phone_number = new_phone
elif user_input == '4': # Modify Patient Phone Number
new_address = input("Enter Modification Here: ")
Patient.address = new_address
elif user_input == '5': # Modify Emergency Contact First Name
new_emergency_fname = input("Enter Modification Here: ")
Patient.emergency_fname = new_emergency_fname
elif user_input == '6': # Modify Emergency Contact Last Name
new_emergency_lname = input("Enter Modification Here: ")
Patient.emergency_lname = new_emergency_lname
elif user_input == '7': # Modify Emergency Contact Phone Number
new_emergency_phone = input("Enter Modification Here: ")
Patient.emergency_phone = new_emergency_phone
elif user_input == '2': # delete Patient
confirmation = input("Re-enter Patient ID Number to Confirm: ")
if confirmation == patient_id:
Patient.delete_patient(patient_id)
else:
print("Patient ID - No Match")
elif user_input == '3': # add a procedure
Patient.add_procedure()
elif user_input == '2': # Add a Patient
first_name = input("Enter Patient's First Name: ")
last_name = input("Enter Patient's Last Name: ")
address = input("Enter Patient's Address: ")
phone_number = input("Enter Patient's Phone Number: ")
emergency_fname = input("Enter the Emergency Contact's First Name: ")
emergency_lname = input("Enter the Emergency Contact's Last Name: ")
emergency_phone = input("Enter the Emergency Contact's Phone Number: ")
patient = [Patient(first_name, last_name, address, phone_number, emergency_fname, emergency_lname,
emergency_phone).to_string()]
with open('database.csv', 'r') as csv_file:
csv_reader = csv.reader(csv_file)
for line in csv_reader:
if line[1] == first_name and line[2] == last_name and line[3] == address:
print("The Patient is already in the Database")
else:
break
with open('database.csv', 'a') as write_file:
writer = csv.writer(write_file)
writer.writerow(patient)
print("Patient added")
elif user_input == '3': # Save and Quit
# Patient.save_patients()
sys.exit()
if __name__ == '__main__':
main()
<file_sep>/Python/PycharmProjects_1718/Week 3 Programming Assignment/Functions.py
#Week 3 Programming Assignment - Functions
import math
def miles_to_kilometers(length_in_miles):
# This function converts a number from miles to kilometers
# Arguments:
# length_in_miles(float): The length to convert
# Returns:
# float: The length in kilometers
# Assumptions:
# Assumes that the length in miles is a float
return (length_in_miles * 1.609)
miles_input = float(input("Enter the length in Miles: "))
result_kilometer = miles_to_kilometers(miles_input)
print(result_kilometer)
def pounds_to_grams(weight_in_pounds):
# This function converts a number from pounds to pounds to grams
#
# Arguments:
# weight_in_pounds(float): The weight to convert
#
# Returns:
# float: The weight in grams
#
# Assumptions:
# Assumes that the weight in pounds is a float
return (weight_in_pounds * 453.592)
pounds_input = float(input("Enter the weight in Pounds: "))
result_grams = pounds_to_grams(pounds_input)
print(result_grams)
def britishGallon_to_americanGallon(volume_in_britishGallon):
# This function converts a number from British Gallons to U.S. Gallons
#
# Arguments:
# volume_in_britishGallon(float): The volume to convert
#
# Returns:
# float: The volume in U.S. Gallons
#
# Assumptions:
# Assumes that the volume in British Gallons is a float
return (volume_in_britishGallon * 1.201)
britishGallon_input = float(input("Enter the volume in British Gallons: "))
result_americanGallon = britishGallon_to_americanGallon(britishGallon_input)
print(result_americanGallon)
def power_formula(work, time):
# This function figures the amount of Power in Watts used by using two numerical inputs, Work and Time
# Power = Work / time
#
# Arguments:
# work (float): The force to be divided (in Joules)
# time (float): The amount of time to divide by (in seconds)
#
# Returns:
# float: The amount of Power in Joules per second
#
# Assumptions:
# Assumes the amount of Work is a float
# Assumes that the amount of Time is a float
return (work / time)
work_input = float(input("Enter the amount of Work in Joules: "))
time_input = float(input("Enter the amount of Time in seconds: "))
result_power = power_formula(work_input, time_input)
print(result_power)
<file_sep>/Python/PycharmProjects_1718/Class Notes/Week2_Notes.py
#Week 2 Class Notes
num1 = 1
num2 = 2
num_add = num1+num2
print(num_add)
fname = input("Please enter your first name:")
lname = input("Please enter your last name:")
age = int(input("What year were you born?"))
num = int(input("What is your favorite number?"))
lucky_num = age//num
print("Thank you for your input, " + fname + " " + lname + ". Your lucky number is: " + str(lucky_num) + ".")
#variable = a placeholder that holds 1 AND ONLY 1 value
#object = a thing in programming that consists of properties and actions (has characteristics)
#ex. = variable, group of variables (arrays)
#method = an action we can take
sentence = "I hope this example works at least once."
print(len(sentence))
<file_sep>/Python/PycharmProjects_1819/Week10_Lab/week10_tests.py
"""Tests for Week 10 Lab.
Prof. <NAME>
Champlain College
CSI-260 -- Spring 2019
"""
import unittest
from temperature_magic import Temperature
import sys
# define constants used by tests
STUDENT_CODE = ["temperature_magic.py"]
class TestWeek10(unittest.TestCase):
"""Main testing class for Week 10 Lab."""
def test_01_str(self):
"""Test if str conversion works as specified."""
message = "String conversion not correct"
self.assertEqual(str(Temperature(45)),"45°C", message)
self.assertEqual(str(Temperature(20.5)),"20.5°C", message)
self.assertEqual(str(Temperature(-11.1)),"-11.1°C", message)
def test_02_repr(self):
"""Test if repr conversion works as specified."""
message = "repr conversion not correct"
self.assertEqual(repr(Temperature(45)),"Temperature(45)", message)
self.assertEqual(repr(Temperature(20.5)),"Temperature(20.5)", message)
self.assertEqual(repr(Temperature(-11.1)),"Temperature(-11.1)", message)
def test_03_equality(self):
"""Test == and != comparisons."""
temperature = Temperature(20.5)
temperature2 = Temperature(13.1)
temperature3 = Temperature(20.5)
self.assertFalse(temperature == temperature2,
"== comparison not correct"
" when comparing two temperatures")
self.assertTrue(temperature == temperature3,
"== comparison not correct"
" when comparing two temperatures")
self.assertFalse(temperature == 11,
"== comparison not correct"
" when comparing temperature and number")
self.assertTrue(temperature == 20.5,
"== comparison not correct"
" when comparing temperature and number")
self.assertTrue(temperature != temperature2,
"!= comparison not correct"
" when comparing two temperatures")
self.assertFalse(temperature != temperature3,
"!= comparison not correct"
" when comparing two temperatures")
self.assertTrue(temperature != 11,
"!= comparison not correct"
" when comparing temperature and number")
self.assertFalse(temperature != 20.5,
"!= comparison not correct"
" when comparing temperature and number")
def test_04_strict_inequalities(self):
"""Test < and >."""
temperature = Temperature(20.5)
temperature2 = Temperature(13.1)
self.assertFalse(temperature < temperature2,
"< comparison not correct"
" when comparing two temperatures")
self.assertFalse(temperature < temperature,
"< comparison not correct"
" when comparing two temperatures")
self.assertFalse(temperature > temperature,
"> comparison not correct"
" when comparing two temperatures")
self.assertTrue(temperature > temperature2,
"> comparison not correct"
" when comparing two temperatures")
self.assertTrue(temperature < 25,
"< comparison not correct"
" when comparing temperature and number")
self.assertFalse(temperature > 25,
"> comparison not correct"
" when comparing temperature and number")
self.assertTrue(10 < temperature,
"< comparison not correct"
" when comparing temperature and number")
self.assertFalse(25 < temperature,
"> comparison not correct"
" when comparing temperature and number")
def test_05_inequalities(self):
"""Test <= and >=."""
temperature = Temperature(20.5)
self.assertTrue(temperature >= 10,
">= comparison not correct")
self.assertFalse(temperature <= 10,
"<= comparison not correct")
self.assertTrue(temperature <= 20.5,
"<= comparison not correct")
self.assertTrue(10 <= temperature,
"<= comparison not correct")
self.assertFalse(10 >= temperature,
">= comparison not correct")
self.assertTrue(20.5 >= temperature,
">= comparison not correct")
self.assertTrue(temperature >= Temperature(4),
">= comparison not correct")
def test_06_addition(self):
"""Test +."""
temperature = Temperature(20.5)
self.assertEqual((5 + temperature).celsius, 25.5,
"+ not correct")
self.assertEqual((temperature + 5).celsius, 25.5,
"+ not correct")
self.assertEqual((temperature + temperature).celsius, 41,
"+ not correct")
def test_07_subtraction(self):
"""Test -."""
temperature = Temperature(20.5)
self.assertEqual((temperature - 5).celsius, 15.5,
"- not correct")
self.assertEqual((5 - temperature).celsius, -15.5,
"- not correct")
self.assertEqual((temperature - temperature).celsius, 0,
"- not correct")
def test_08_inplace_addition(self):
"""Test +=."""
temperature = Temperature(20.5)
backup = temperature
temperature += 5
self.assertEqual(temperature.celsius, 25.5,
"+= not correct")
self.assertEqual(backup.celsius, 25.5,
"+= not correct")
temperature += Temperature(5)
self.assertEqual(temperature.celsius, 30.5,
"+= not correct")
self.assertEqual(backup.celsius, 30.5,
"+= not correct")
def test_09_inplace_subtraction(self):
"""Test +=."""
temperature = Temperature(20.5)
backup = temperature
temperature -= 5
self.assertEqual(temperature.celsius, 15.5,
"-= not correct")
self.assertEqual(backup.celsius, 15.5,
"-= not correct")
temperature -= Temperature(5)
self.assertEqual(temperature.celsius, 10.5,
"-= not correct")
self.assertEqual(backup.celsius, 10.5,
"-= not correct")
def test_10_hash(self):
"""Test hash."""
self.assertEqual(hash(Temperature(20.5)), hash(Temperature(20.5)),
"hash not correct")
self.assertNotEqual(hash(Temperature(20.5)), hash(Temperature(10.5)),
"hash not correct")
def test_11_style(self):
"""Run the linter and check that the header is there."""
try:
from flake8.api import legacy as flake8
# noqa on the following since just importing to test installed
import pep8ext_naming # noqa
import flake8_docstrings # noqa
print("\nLinting Code...\n" + "=" * 15)
style_guide = flake8.get_style_guide()
report = style_guide.check_files(STUDENT_CODE)
self.assertEqual(report.total_errors, 0,
"You should fix all linting errors "
"before submission in order to receive full "
"credit!")
for module in STUDENT_CODE:
self.check_header(module)
print("Passing linter tests!")
except ImportError:
print("""
### WARNING: Unable to import flake8 and/or extensions, so cannot \
properly lint your code. ###
Please install flake8, pep8-naming, and flake8-docstrings to auto-check \
whether you are adhering to proper style and docstring conventions.
To install, run:
pip install flake8 pep8-naming flake8-docstrings
""")
def check_header(self, module):
"""Check the header of the given module."""
docstring = sys.modules[module[:-3]].__doc__
for check in ['Author:', 'Class:', 'Assignment:',
'Certification of Authenticity:']:
self.assertIn(check, docstring,
"Missing '{}' in {}'s docstring".format(
check, module))
if __name__ == '__main__':
unittest.main(failfast=True)
<file_sep>/Python/PycharmProjects_1819/Loops_Assignment/multiplicationTable.py
for column in range(1, 11):
# the integer range for the column of the table
for row in range(1, 11):
# the integer range for the row of the table
mult_num = row * column
# create the multiplications from the integer range in the multiplication table
if mult_num < 10:
space = ' '
# for spacing purposes of single digit numbers
elif mult_num < 90:
space = ' '
# for spacing purposes of double digit numbers
print(space + str(mult_num), end=' ') # or [end = ' '] for a wider looking format
# for spacing purposes of how far apart each number is and create the format
print()
# inspiration sourced from: https://stackoverflow.com/questions/20415384/properly-formatted-multiplication-table
# for how to get the spacing right (also played around a bit too)(weird to see so many different ways to solve this)
# inspiration of format also sourced from previous python programming assignment from another class for similar question<file_sep>/AutomationScripting/Powershell/week5/class/ips-bad-iptables.bash
iptables -A INPUT -s1.189.85.14 -j DROP
iptables -A INPUT -s1.189.85.163 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s1.28.188.227 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s1172.16.17.32 -j DROP
iptables -A INPUT -s1192.168.127.12 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s12172.16.31.10 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s13192.168.127.12 -j DROP
iptables -A INPUT -s138.197.105.79 -j DROP
iptables -A INPUT -s138.197.180.16 -j DROP
iptables -A INPUT -s13172.16.31.10 -j DROP
iptables -A INPUT -s1172.16.58.3 -j DROP
iptables -A INPUT -s138.201.93.46 -j DROP
iptables -A INPUT -s13192.168.127.12 -j DROP
iptables -A INPUT -s13172.16.31.10 -j DROP
iptables -A INPUT -s138.68.20.158 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s13192.168.3.11 -j DROP
iptables -A INPUT -s13172.16.17.32 -j DROP
iptables -A INPUT -s139.59.147.0 -j DROP
iptables -A INPUT -s13172.16.58.3 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s13192.168.3.11 -j DROP
iptables -A INPUT -s1172.16.17.32 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s13172.16.31.10 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s14172.16.31.10 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s146.196.122.167 -j DROP
iptables -A INPUT -s14172.16.58.3 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s14172.16.58.3 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s149.167.86.174 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s14192.168.127.12 -j DROP
iptables -A INPUT -s14192.168.127.12 -j DROP
iptables -A INPUT -s14172.16.31.10 -j DROP
iptables -A INPUT -s14192.168.3.11 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s150.95.81.119 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s157.245.104.83 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s1192.168.3.11 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s164.132.40.47 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s1172.16.17.32 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s1192.168.3.11 -j DROP
iptables -A INPUT -s1172.16.31.10 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s1192.168.127.12 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s1172.16.17.32 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s1192.168.127.12 -j DROP
iptables -A INPUT -s181.164.8.25 -j DROP
iptables -A INPUT -s1192.168.127.12 -j DROP
iptables -A INPUT -s1172.16.31.10 -j DROP
iptables -A INPUT -s1192.168.3.11 -j DROP
iptables -A INPUT -s1192.168.127.12 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s18192.168.127.12 -j DROP
iptables -A INPUT -s1172.16.17.32 -j DROP
iptables -A INPUT -s1192.168.3.11 -j DROP
iptables -A INPUT -s18192.168.3.11 -j DROP
iptables -A INPUT -s181.81.143.108 -j DROP
iptables -A INPUT -s1172.16.17.32 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s1192.168.127.12 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s18192.168.3.11 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s18172.16.58.3 -j DROP
iptables -A INPUT -s18172.16.58.3 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s18172.16.31.10 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s18172.16.31.10 -j DROP
iptables -A INPUT -s1172.16.58.3 -j DROP
iptables -A INPUT -s1172.16.58.3 -j DROP
iptables -A INPUT -s183.98.48.152 -j DROP
iptables -A INPUT -s1172.16.58.3 -j DROP
iptables -A INPUT -s18172.16.31.10 -j DROP
iptables -A INPUT -s1172.16.58.3 -j DROP
iptables -A INPUT -s1172.16.31.10 -j DROP
iptables -A INPUT -s18192.168.3.11 -j DROP
iptables -A INPUT -s1192.168.127.12 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s18172.16.17.32 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s18172.16.58.3 -j DROP
iptables -A INPUT -s18192.168.3.11 -j DROP
iptables -A INPUT -s18192.168.127.12 -j DROP
iptables -A INPUT -s18192.168.127.12 -j DROP
iptables -A INPUT -s18192.168.3.11 -j DROP
iptables -A INPUT -s18172.16.31.10 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s185.117.215.9 -j DROP
iptables -A INPUT -s18192.168.127.12 -j DROP
iptables -A INPUT -s18172.16.17.32 -j DROP
iptables -A INPUT -s18172.16.31.10 -j DROP
iptables -A INPUT -s18192.168.3.11 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s1192.168.3.11 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s18192.168.127.12 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s18172.16.17.32 -j DROP
iptables -A INPUT -s18192.168.127.12 -j DROP
iptables -A INPUT -s18172.16.17.32 -j DROP
iptables -A INPUT -s1192.168.3.11 -j DROP
iptables -A INPUT -s18172.16.17.32 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s18172.16.17.32 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s1172.16.58.3 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s18172.16.58.3 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s1172.16.31.10 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s18172.16.17.32 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s18172.16.58.3 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s18192.168.127.12 -j DROP
iptables -A INPUT -s18172.16.31.10 -j DROP
iptables -A INPUT -s18172.16.17.32 -j DROP
iptables -A INPUT -s18172.16.17.32 -j DROP
iptables -A INPUT -s186.103.199.252 -j DROP
iptables -A INPUT -s18172.16.58.3 -j DROP
iptables -A INPUT -s18192.168.127.12 -j DROP
iptables -A INPUT -s18172.16.17.32 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s186.4.172.5 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s1172.16.31.10 -j DROP
iptables -A INPUT -s189.187.141.15 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s1192.168.127.12 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s195.123.247.27 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s198.199.88.162 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s198.98.62.43 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s199.76.38.81 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s203.15.33.222 -j DROP
iptables -A INPUT -s203.150.19.63 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s203.70.60.179 -j DROP
iptables -A INPUT -s204.17.56.42 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s205.185.113.88 -j DROP
iptables -A INPUT -s205.185.117.149 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s205.185.127.219 -j DROP
iptables -A INPUT -s205.186.154.130 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s206.189.134.83 -j DROP
iptables -A INPUT -s206.189.137.113 -j DROP
iptables -A INPUT -s206.189.142.71 -j DROP
iptables -A INPUT -s206.189.145.152 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s206.189.23.43 -j DROP
iptables -A INPUT -s206.189.55.53 -j DROP
iptables -A INPUT -s206.189.57.42 -j DROP
iptables -A INPUT -s206.189.65.11 -j DROP
iptables -A INPUT -s206.189.94.158 -j DROP
iptables -A INPUT -s206.81.19.12 -j DROP
iptables -A INPUT -s206.81.21.119 -j DROP
iptables -A INPUT -s207.180.208.175 -j DROP
iptables -A INPUT -s207.237.235.99 -j DROP
iptables -A INPUT -s207.244.97.230 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s208.100.26.251 -j DROP
iptables -A INPUT -s208.102.113.11 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s209.141.58.87 -j DROP
iptables -A INPUT -s209.95.51.11 -j DROP
iptables -A INPUT -s209.97.163.176 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s210.135.96.98 -j DROP
iptables -A INPUT -s210.178.94.230 -j DROP
iptables -A INPUT -s210.18.156.75 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s2192.168.3.11 -j DROP
iptables -A INPUT -s2172.16.31.10 -j DROP
iptables -A INPUT -s2192.168.127.12 -j DROP
iptables -A INPUT -s2192.168.127.12 -j DROP
iptables -A INPUT -s2172.16.31.10 -j DROP
iptables -A INPUT -s2172.16.17.32 -j DROP
iptables -A INPUT -s2192.168.3.11 -j DROP
iptables -A INPUT -s2172.16.58.3 -j DROP
iptables -A INPUT -s2172.16.31.10 -j DROP
iptables -A INPUT -s2192.168.3.11 -j DROP
iptables -A INPUT -s2192.168.127.12 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s213.136.64.147 -j DROP
iptables -A INPUT -s2192.168.3.11 -j DROP
iptables -A INPUT -s2192.168.3.11 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s213.32.66.16 -j DROP
iptables -A INPUT -s2172.16.17.32 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s2192.168.127.12 -j DROP
iptables -A INPUT -s216.127.187.29 -j DROP
iptables -A INPUT -s2192.168.3.11 -j DROP
iptables -A INPUT -s2172.16.17.32 -j DROP
iptables -A INPUT -s2172.16.17.32 -j DROP
iptables -A INPUT -s2172.16.31.10 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s2192.168.127.12 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s2192.168.127.12 -j DROP
iptables -A INPUT -s2172.16.17.32 -j DROP
iptables -A INPUT -s2172.16.17.32 -j DROP
iptables -A INPUT -s2172.16.58.3 -j DROP
iptables -A INPUT -s2172.16.58.3 -j DROP
iptables -A INPUT -s2172.16.17.32 -j DROP
iptables -A INPUT -s2192.168.3.11 -j DROP
iptables -A INPUT -s2192.168.3.11 -j DROP
iptables -A INPUT -s2172.16.58.3 -j DROP
iptables -A INPUT -s2172.16.58.3 -j DROP
iptables -A INPUT -s2192.168.127.12 -j DROP
iptables -A INPUT -s2172.16.17.32 -j DROP
iptables -A INPUT -s217.35.75.193 -j DROP
iptables -A INPUT -s2192.168.3.11 -j DROP
iptables -A INPUT -s2172.16.31.10 -j DROP
iptables -A INPUT -s2192.168.3.11 -j DROP
iptables -A INPUT -s2172.16.58.3 -j DROP
iptables -A INPUT -s2192.168.3.11 -j DROP
iptables -A INPUT -s2172.16.58.3 -j DROP
iptables -A INPUT -s218.98.26.167 -j DROP
iptables -A INPUT -s2172.16.31.10 -j DROP
iptables -A INPUT -s218.98.26.169 -j DROP
iptables -A INPUT -s218.98.26.172 -j DROP
iptables -A INPUT -s2192.168.127.12 -j DROP
iptables -A INPUT -s21192.168.127.12 -j DROP
iptables -A INPUT -s218.98.26.185 -j DROP
iptables -A INPUT -s2172.16.17.32 -j DROP
iptables -A INPUT -s2172.16.58.3 -j DROP
iptables -A INPUT -s2172.16.17.32 -j DROP
iptables -A INPUT -s218.98.40.147 -j DROP
iptables -A INPUT -s2172.16.31.10 -j DROP
iptables -A INPUT -s21192.168.3.11 -j DROP
iptables -A INPUT -s2172.16.31.10 -j DROP
iptables -A INPUT -s219.141.211.66 -j DROP
iptables -A INPUT -s2172.16.31.10 -j DROP
iptables -A INPUT -s21172.16.58.3 -j DROP
iptables -A INPUT -s219.84.203.57 -j DROP
iptables -A INPUT -s2192.168.127.12 -j DROP
iptables -A INPUT -s2172.16.31.10 -j DROP
iptables -A INPUT -s2172.16.17.32 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s2192.168.127.12 -j DROP
iptables -A INPUT -s2172.16.58.3 -j DROP
iptables -A INPUT -s2192.168.127.12 -j DROP
iptables -A INPUT -s2192.168.127.12 -j DROP
iptables -A INPUT -s2172.16.17.32 -j DROP
iptables -A INPUT -s2192.168.127.12 -j DROP
iptables -A INPUT -s2192.168.3.11 -j DROP
iptables -A INPUT -s2172.16.17.32 -j DROP
iptables -A INPUT -s22192.168.3.11 -j DROP
iptables -A INPUT -s22172.16.58.3 -j DROP
iptables -A INPUT -s2192.168.127.12 -j DROP
iptables -A INPUT -s2192.168.127.12 -j DROP
iptables -A INPUT -s22192.168.127.12 -j DROP
iptables -A INPUT -s22172.16.17.32 -j DROP
iptables -A INPUT -s2172.16.58.3 -j DROP
iptables -A INPUT -s22192.168.127.12 -j DROP
iptables -A INPUT -s22192.168.127.12 -j DROP
iptables -A INPUT -s2192.168.127.12 -j DROP
iptables -A INPUT -s2192.168.127.12 -j DROP
iptables -A INPUT -s2172.16.31.10 -j DROP
iptables -A INPUT -s22172.16.17.32 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s2172.16.58.3 -j DROP
iptables -A INPUT -s2192.168.3.11 -j DROP
iptables -A INPUT -s2172.16.31.10 -j DROP
iptables -A INPUT -s2172.16.58.3 -j DROP
iptables -A INPUT -s2192.168.127.12 -j DROP
iptables -A INPUT -s2172.16.58.3 -j DROP
iptables -A INPUT -s2172.16.17.32 -j DROP
iptables -A INPUT -s2172.16.31.10 -j DROP
iptables -A INPUT -s2192.168.3.11 -j DROP
iptables -A INPUT -s2172.16.31.10 -j DROP
iptables -A INPUT -s2172.16.31.10 -j DROP
iptables -A INPUT -s2172.16.31.10 -j DROP
iptables -A INPUT -s2192.168.127.12 -j DROP
iptables -A INPUT -s2192.168.127.12 -j DROP
iptables -A INPUT -s22172.16.17.32 -j DROP
iptables -A INPUT -s2172.16.31.10 -j DROP
iptables -A INPUT -s2192.168.3.11 -j DROP
iptables -A INPUT -s2172.16.31.10 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s2172.16.17.32 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.31.1001 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s2172.16.58.3 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s2172.16.31.10 -j DROP
iptables -A INPUT -s23.133.240.7 -j DROP
iptables -A INPUT -s23.94.184.124 -j DROP
iptables -A INPUT -s23.94.24.196 -j DROP
iptables -A INPUT -s23.95.214.138 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s2192.168.127.12 -j DROP
iptables -A INPUT -s2172.16.17.32 -j DROP
iptables -A INPUT -s2192.168.3.11 -j DROP
iptables -A INPUT -s2172.16.17.32 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s2192.168.127.12 -j DROP
iptables -A INPUT -s2172.16.17.32 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s2172.16.17.32 -j DROP
iptables -A INPUT -s2192.168.127.12 -j DROP
iptables -A INPUT -s2192.168.3.11 -j DROP
iptables -A INPUT -s31.12.67.62 -j DROP
iptables -A INPUT -s3172.16.58.3 -j DROP
iptables -A INPUT -s31.148.99.188 -j DROP
iptables -A INPUT -s3192.168.3.11 -j DROP
iptables -A INPUT -s3172.16.17.32 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s31.184.197.119 -j DROP
iptables -A INPUT -s31.184.197.126 -j DROP
iptables -A INPUT -s3192.168.127.12 -j DROP
iptables -A INPUT -s3172.16.31.10 -j DROP
iptables -A INPUT -s3172.16.17.32 -j DROP
iptables -A INPUT -s3172.16.17.32 -j DROP
iptables -A INPUT -s3172.16.31.10 -j DROP
iptables -A INPUT -s3192.168.127.12 -j DROP
iptables -A INPUT -s3192.168.3.11 -j DROP
iptables -A INPUT -s3172.16.31.10 -j DROP
iptables -A INPUT -s3172.16.58.3 -j DROP
iptables -A INPUT -s31.202.132.179 -j DROP
iptables -A INPUT -s31.41.44.130 -j DROP
iptables -A INPUT -s31.41.44.21 -j DROP
iptables -A INPUT -s31.41.44.246 -j DROP
iptables -A INPUT -s31.41.44.45 -j DROP
iptables -A INPUT -s31.41.47.37 -j DROP
iptables -A INPUT -s31.41.47.41 -j DROP
iptables -A INPUT -s31.41.47.50 -j DROP
iptables -A INPUT -s31.53.126.58 -j DROP
iptables -A INPUT -s3192.168.3.11 -j DROP
iptables -A INPUT -s34.68.102.89 -j DROP
iptables -A INPUT -s3172.16.17.32 -j DROP
iptables -A INPUT -s3192.168.3.11 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s3172.16.58.3 -j DROP
iptables -A INPUT -s3172.16.17.32 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s3172.16.17.32 -j DROP
iptables -A INPUT -s3172.16.58.3 -j DROP
iptables -A INPUT -s3192.168.3.11 -j DROP
iptables -A INPUT -s36.89.85.103 -j DROP
iptables -A INPUT -s3172.16.17.32 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s3172.16.31.10 -j DROP
iptables -A INPUT -s3172.16.17.32 -j DROP
iptables -A INPUT -s3192.168.3.11 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s3172.16.58.3 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s3172.16.31.10 -j DROP
iptables -A INPUT -s3172.16.31.10 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s3192.168.127.12 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s3192.168.3.11 -j DROP
iptables -A INPUT -s3172.16.31.10 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s3172.16.58.3 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s3192.168.127.12 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s4172.16.58.3 -j DROP
iptables -A INPUT -s4172.16.58.3 -j DROP
iptables -A INPUT -s4172.16.17.32 -j DROP
iptables -A INPUT -s4172.16.31.10 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s4172.16.58.3 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s4172.16.31.10 -j DROP
iptables -A INPUT -s4192.168.127.12 -j DROP
iptables -A INPUT -s4172.16.58.3 -j DROP
iptables -A INPUT -s4192.168.127.12 -j DROP
iptables -A INPUT -s4172.16.31.10 -j DROP
iptables -A INPUT -s4172.16.17.32 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s4172.16.31.10 -j DROP
iptables -A INPUT -s4172.16.58.3 -j DROP
iptables -A INPUT -s4192.168.3.11 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s4172.16.31.10 -j DROP
iptables -A INPUT -s4172.16.17.32 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s4172.16.31.10 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s4172.16.31.10 -j DROP
iptables -A INPUT -s4192.168.127.12 -j DROP
iptables -A INPUT -s4172.16.31.10 -j DROP
iptables -A INPUT -s4172.16.31.10 -j DROP
iptables -A INPUT -s4172.16.31.10 -j DROP
iptables -A INPUT -s4172.16.17.32 -j DROP
iptables -A INPUT -s4192.168.127.12 -j DROP
iptables -A INPUT -s4172.16.58.3 -j DROP
iptables -A INPUT -s4192.168.127.12 -j DROP
iptables -A INPUT -s4192.168.3.11 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s4192.168.3.11 -j DROP
iptables -A INPUT -s46.108.39.18 -j DROP
iptables -A INPUT -s46.148.20.46 -j DROP
iptables -A INPUT -s4172.16.17.32 -j DROP
iptables -A INPUT -s4172.16.31.10 -j DROP
iptables -A INPUT -s4192.168.3.11 -j DROP
iptables -A INPUT -s46.165.253.93 -j DROP
iptables -A INPUT -s4172.16.58.3 -j DROP
iptables -A INPUT -s4192.168.3.11 -j DROP
iptables -A INPUT -s46.17.40.234 -j DROP
iptables -A INPUT -s46.17.44.153 -j DROP
iptables -A INPUT -s46.182.106.190 -j DROP
iptables -A INPUT -s46.182.18.29 -j DROP
iptables -A INPUT -s46.182.19.219 -j DROP
iptables -A INPUT -s46.183.165.45 -j DROP
iptables -A INPUT -s46.20.35.112 -j DROP
iptables -A INPUT -s46.249.204.99 -j DROP
iptables -A INPUT -s46.30.41.229 -j DROP
iptables -A INPUT -s46.38.52.225 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s46.41.134.46 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s5.189.159.33 -j DROP
iptables -A INPUT -s5.189.166.57 -j DROP
iptables -A INPUT -s5.196.110.170 -j DROP
iptables -A INPUT -s5.196.200.229 -j DROP
iptables -A INPUT -s5.196.200.247 -j DROP
iptables -A INPUT -s5.196.99.239 -j DROP
iptables -A INPUT -s5.199.130.188 -j DROP
iptables -A INPUT -s5.230.147.179 -j DROP
iptables -A INPUT -s5.34.180.135 -j DROP
iptables -A INPUT -s5.34.183.136 -j DROP
iptables -A INPUT -s5.34.183.195 -j DROP
iptables -A INPUT -s5.34.183.21 -j DROP
iptables -A INPUT -s5.34.183.40 -j DROP
iptables -A INPUT -s5.39.76.12 -j DROP
iptables -A INPUT -s5.39.92.187 -j DROP
iptables -A INPUT -s5.53.124.55 -j DROP
iptables -A INPUT -s5.53.125.13 -j DROP
iptables -A INPUT -s5.67.96.120 -j DROP
iptables -A INPUT -s5.77.13.70 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s50.112.120.66 -j DROP
iptables -A INPUT -s50.115.168.103 -j DROP
iptables -A INPUT -s50.18.21.241 -j DROP
iptables -A INPUT -s50.209.215.142 -j DROP
iptables -A INPUT -s50.3.87.51 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s50.73.127.109 -j DROP
iptables -A INPUT -s50.99.193.144 -j DROP
iptables -A INPUT -s50.99.43.153 -j DROP
iptables -A INPUT -s5192.168.3.11 -j DROP
iptables -A INPUT -s5192.168.127.12 -j DROP
iptables -A INPUT -s5192.168.127.12 -j DROP
iptables -A INPUT -s5172.16.17.32 -j DROP
iptables -A INPUT -s5192.168.127.12 -j DROP
iptables -A INPUT -s51.15.76.60 -j DROP
iptables -A INPUT -s51.158.117.227 -j DROP
iptables -A INPUT -s5172.16.31.10 -j DROP
iptables -A INPUT -s5192.168.3.11 -j DROP
iptables -A INPUT -s51.159.6.199 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s51.254.240.45 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s5172.16.58.3 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s5172.16.58.3 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s5192.168.3.11 -j DROP
iptables -A INPUT -s5172.16.58.3 -j DROP
iptables -A INPUT -s5172.16.31.10 -j DROP
iptables -A INPUT -s5172.16.31.10 -j DROP
iptables -A INPUT -s5172.16.31.10 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s5172.16.17.32 -j DROP
iptables -A INPUT -s5192.168.3.11 -j DROP
iptables -A INPUT -s5192.168.3.11 -j DROP
iptables -A INPUT -s5192.168.127.12 -j DROP
iptables -A INPUT -s5172.16.31.10 -j DROP
iptables -A INPUT -s5172.16.17.32 -j DROP
iptables -A INPUT -s5192.168.127.12 -j DROP
iptables -A INPUT -s5172.16.58.3 -j DROP
iptables -A INPUT -s5192.168.3.11 -j DROP
iptables -A INPUT -s5172.16.17.32 -j DROP
iptables -A INPUT -s5172.16.58.3 -j DROP
iptables -A INPUT -s5172.16.58.3 -j DROP
iptables -A INPUT -s5192.168.3.11 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s5192.168.3.11 -j DROP
iptables -A INPUT -s54.37.90.210 -j DROP
iptables -A INPUT -s5192.168.127.12 -j DROP
iptables -A INPUT -s5192.168.3.11 -j DROP
iptables -A INPUT -s5172.16.58.3 -j DROP
iptables -A INPUT -s5192.168.3.11 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s5192.168.127.12 -j DROP
iptables -A INPUT -s54.39.18.237 -j DROP
iptables -A INPUT -s54.67.27.43 -j DROP
iptables -A INPUT -s5172.16.31.10 -j DROP
iptables -A INPUT -s5192.168.127.12 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s5172.16.31.10 -j DROP
iptables -A INPUT -s5192.168.3.11 -j DROP
iptables -A INPUT -s5172.16.58.3 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s5172.16.31.10 -j DROP
iptables -A INPUT -s5192.168.127.12 -j DROP
iptables -A INPUT -s5172.16.31.10 -j DROP
iptables -A INPUT -s5172.16.58.3 -j DROP
iptables -A INPUT -s5172.16.31.10 -j DROP
iptables -A INPUT -s59.60.180.163 -j DROP
iptables -A INPUT -s5172.16.31.10 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.17.32 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s60.186.77.230 -j DROP
iptables -A INPUT -s60.191.82.107 -j DROP
iptables -A INPUT -s60.250.232.158 -j DROP
iptables -A INPUT -s61.147.41.243 -j DROP
iptables -A INPUT -s61.147.42.60 -j DROP
iptables -A INPUT -s61.147.42.72 -j DROP
iptables -A INPUT -s61.147.50.178 -j DROP
iptables -A INPUT -s61.147.50.29 -j DROP
iptables -A INPUT -s61.147.59.111 -j DROP
iptables -A INPUT -s61.250.138.125 -j DROP
iptables -A INPUT -s61.250.144.195 -j DROP
iptables -A INPUT -s61.31.99.67 -j DROP
iptables -A INPUT -s62.102.148.68 -j DROP
iptables -A INPUT -s62.102.148.69 -j DROP
iptables -A INPUT -s62.152.5.151 -j DROP
iptables -A INPUT -s62.210.142.58 -j DROP
iptables -A INPUT -s62.210.37.15 -j DROP
iptables -A INPUT -s62.210.37.82 -j DROP
iptables -A INPUT -s62.210.75.89 -j DROP
iptables -A INPUT -s62.210.99.162 -j DROP
iptables -A INPUT -s62.4.3.37 -j DROP
iptables -A INPUT -s6172.16.58.3 -j DROP
iptables -A INPUT -s6192.168.127.12 -j DROP
iptables -A INPUT -s63.142.253.122 -j DROP
iptables -A INPUT -s64.113.32.29 -j DROP
iptables -A INPUT -s64.13.225.150 -j DROP
iptables -A INPUT -s64.18.139.82 -j DROP
iptables -A INPUT -s64.44.133.34 -j DROP
iptables -A INPUT -s64.44.51.126 -j DROP
iptables -A INPUT -s64.44.51.88 -j DROP
iptables -A INPUT -s64.64.4.158 -j DROP
iptables -A INPUT -s64.71.165.201 -j DROP
iptables -A INPUT -s64.85.169.114 -j DROP
iptables -A INPUT -s65.181.121.246 -j DROP
iptables -A INPUT -s65.19.178.15 -j DROP
iptables -A INPUT -s65.23.156.37 -j DROP
iptables -A INPUT -s65.23.157.127 -j DROP
iptables -A INPUT -s66.130.210.106 -j DROP
iptables -A INPUT -s66.154.121.231 -j DROP
iptables -A INPUT -s66.155.4.213 -j DROP
iptables -A INPUT -s66.55.71.11 -j DROP
iptables -A INPUT -s66.55.71.112 -j DROP
iptables -A INPUT -s66.55.71.15 -j DROP
iptables -A INPUT -s66.70.194.195 -j DROP
iptables -A INPUT -s66.85.156.66 -j DROP
iptables -A INPUT -s67.205.171.235 -j DROP
iptables -A INPUT -s67.205.181.63 -j DROP
iptables -A INPUT -s68.100.119.84 -j DROP
iptables -A INPUT -s68.168.123.85 -j DROP
iptables -A INPUT -s68.183.105.52 -j DROP
iptables -A INPUT -s68.183.156.156 -j DROP
iptables -A INPUT -s68.183.39.23 -j DROP
iptables -A INPUT -s6192.168.3.11 -j DROP
iptables -A INPUT -s68.33.118.31 -j DROP
iptables -A INPUT -s68.44.101.90 -j DROP
iptables -A INPUT -s6172.16.17.32 -j DROP
iptables -A INPUT -s68.96.59.60 -j DROP
iptables -A INPUT -s69.195.129.70 -j DROP
iptables -A INPUT -s69.49.68.227 -j DROP
iptables -A INPUT -s70.85.237.252 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s192.168.3.11 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s7172.16.31.10 -j DROP
iptables -A INPUT -s7192.168.127.12 -j DROP
iptables -A INPUT -s73.186.4.41 -j DROP
iptables -A INPUT -s7192.168.127.12 -j DROP
iptables -A INPUT -s7192.168.127.12 -j DROP
iptables -A INPUT -s7172.16.58.3 -j DROP
iptables -A INPUT -s75.127.14.170 -j DROP
iptables -A INPUT -s7172.16.31.10 -j DROP
iptables -A INPUT -s7192.168.127.12 -j DROP
iptables -A INPUT -s76.164.201.206 -j DROP
iptables -A INPUT -s76.227.182.38 -j DROP
iptables -A INPUT -s7192.168.3.11 -j DROP
iptables -A INPUT -s7172.16.58.3 -j DROP
iptables -A INPUT -s7172.16.31.10 -j DROP
iptables -A INPUT -s7172.16.31.10 -j DROP
iptables -A INPUT -s7172.16.31.10 -j DROP
iptables -A INPUT -s77.73.66.227 -j DROP
iptables -A INPUT -s7172.16.58.3 -j DROP
iptables -A INPUT -s7172.16.31.10 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s7172.16.17.32 -j DROP
iptables -A INPUT -s7172.16.17.32 -j DROP
iptables -A INPUT -s7172.16.31.10 -j DROP
iptables -A INPUT -s7172.16.17.32 -j DROP
iptables -A INPUT -s7172.16.17.32 -j DROP
iptables -A INPUT -s7172.16.58.3 -j DROP
iptables -A INPUT -s7172.16.58.3 -j DROP
iptables -A INPUT -s7192.168.3.11 -j DROP
iptables -A INPUT -s7192.168.3.11 -j DROP
iptables -A INPUT -s7192.168.3.11 -j DROP
iptables -A INPUT -s7172.16.58.3 -j DROP
iptables -A INPUT -s7172.16.31.10 -j DROP
iptables -A INPUT -s7192.168.127.12 -j DROP
iptables -A INPUT -s7192.168.3.11 -j DROP
iptables -A INPUT -s7172.16.17.32 -j DROP
iptables -A INPUT -s7192.168.3.11 -j DROP
iptables -A INPUT -s7192.168.3.11 -j DROP
iptables -A INPUT -s7172.16.31.10 -j DROP
iptables -A INPUT -s7192.168.127.12 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s172.16.58.3 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s192.168.127.12 -j DROP
iptables -A INPUT -s80.211.163.102 -j DROP
iptables -A INPUT -s80.249.176.206 -j DROP
iptables -A INPUT -s80.249.183.100 -j DROP
iptables -A INPUT -s80.67.172.162 -j DROP
iptables -A INPUT -s80.82.115.164 -j DROP
iptables -A INPUT -s80.87.196.55 -j DROP
iptables -A INPUT -s80.87.202.49 -j DROP
iptables -A INPUT -s81.12.159.146 -j DROP
iptables -A INPUT -s81.177.141.67 -j DROP
iptables -A INPUT -s81.177.181.164 -j DROP
iptables -A INPUT -s81.177.26.201 -j DROP
iptables -A INPUT -s81.177.27.222 -j DROP
iptables -A INPUT -s81.177.27.36 -j DROP
iptables -A INPUT -s81.177.6.144 -j DROP
iptables -A INPUT -s81.177.6.224 -j DROP
iptables -A INPUT -s81.213.182.115 -j DROP
iptables -A INPUT -s82.146.37.200 -j DROP
iptables -A INPUT -s82.196.6.154 -j DROP
iptables -A INPUT -s8192.168.3.11 -j DROP
iptables -A INPUT -s8192.168.127.12 -j DROP
iptables -A INPUT -s8172.16.17.32 -j DROP
iptables -A INPUT -s82.221.131.5 -j DROP
iptables -A INPUT -s82.221.131.71 -j DROP
iptables -A INPUT -s82.226.163.9 -j DROP
iptables -A INPUT -s82.251.46.69 -j DROP
iptables -A INPUT -s82.26.1.215 -j DROP
iptables -A INPUT -s82.64.126.39 -j DROP
iptables -A INPUT -s82.64.140.9 -j DROP
iptables -A INPUT -s82.97.16.22 -j DROP
iptables -A INPUT -s83.110.75.153 -j DROP
iptables -A INPUT -s83.217.11.191 -j DROP
iptables -A INPUT -s83.217.11.193 -j DROP
iptables -A INPUT -s83.217.25.239 -j DROP
iptables -A INPUT -s83.217.26.168 -j DROP
iptables -A INPUT -s83.217.8.127 -j DROP
iptables -A INPUT -s83.217.8.155 -j DROP
iptables -A INPUT -s83.217.8.234 -j DROP
iptables -A INPUT -s83.220.172.182 -j DROP
iptables -A INPUT -s83.68.16.198 -j DROP
iptables -A INPUT -s84.17.48.106 -j DROP
iptables -A INPUT -s84.19.170.244 -j DROP
iptables -A INPUT -s84.19.170.249 -j DROP
iptables -A INPUT -s84.209.63.124 -j DROP
iptables -A INPUT -s84.53.192.243 -j DROP
iptables -A INPUT -s8172.16.31.10 -j DROP
iptables -A INPUT -s85.106.1.166 -j DROP
iptables -A INPUT -s85.143.216.155 -j DROP
iptables -A INPUT -s85.143.221.0 -j DROP
iptables -A INPUT -s85.192.32.192 -j DROP
iptables -A INPUT -s85.192.32.45 -j DROP
iptables -A INPUT -s85.192.33.51 -j DROP
iptables -A INPUT -s85.217.171.98 -j DROP
iptables -A INPUT -s8172.16.17.32 -j DROP
iptables -A INPUT -s85.25.109.116 -j DROP
iptables -A INPUT -s85.25.138.187 -j DROP
iptables -A INPUT -s85.55.252.10 -j DROP
iptables -A INPUT -s85.93.218.204 -j DROP
iptables -A INPUT -s86.104.134.144 -j DROP
iptables -A INPUT -s86.205.224.234 -j DROP
iptables -A INPUT -s86.254.12.212 -j DROP
iptables -A INPUT -s86.98.25.30 -j DROP
iptables -A INPUT -s87.120.254.98 -j DROP
iptables -A INPUT -s87.120.36.157 -j DROP
iptables -A INPUT -s87.198.55.46 -j DROP
iptables -A INPUT -s88.156.97.210 -j DROP
iptables -A INPUT -s8172.16.17.32 -j DROP
iptables -A INPUT -s8172.16.31.10 -j DROP
iptables -A INPUT -s88.214.236.182 -j DROP
iptables -A INPUT -s8172.16.58.3 -j DROP
iptables -A INPUT -s8172.16.58.3 -j DROP
iptables -A INPUT -s8192.168.3.11 -j DROP
iptables -A INPUT -s88.91.198.228 -j DROP
iptables -A INPUT -s8172.16.17.32 -j DROP
iptables -A INPUT -s8172.16.58.3 -j DROP
iptables -A INPUT -s8192.168.3.11 -j DROP
iptables -A INPUT -s89.108.84.132 -j DROP
iptables -A INPUT -s89.108.84.155 -j DROP
iptables -A INPUT -s89.108.84.87 -j DROP
iptables -A INPUT -s89.108.85.163 -j DROP
iptables -A INPUT -s89.184.69.139 -j DROP
iptables -A INPUT -s89.188.124.145 -j DROP
iptables -A INPUT -s8192.168.127.12 -j DROP
iptables -A INPUT -s8172.16.31.10 -j DROP
iptables -A INPUT -s8192.168.127.12 -j DROP
iptables -A INPUT -s8172.16.31.10 -j DROP
iptables -A INPUT -s8172.16.17.32 -j DROP
iptables -A INPUT -s89.236.112.100 -j DROP
iptables -A INPUT -s89.236.112.99 -j DROP
iptables -A INPUT -s89.248.162.231 -j DROP
iptables -A INPUT -s89.248.174.219 -j DROP
iptables -A INPUT -s89.38.145.132 -j DROP
iptables -A INPUT -s89.38.145.227 -j DROP
iptables -A INPUT -s90.226.227.251 -j DROP
iptables -A INPUT -s91.121.146.118 -j DROP
iptables -A INPUT -s91.121.2.214 -j DROP
iptables -A INPUT -s91.121.67.157 -j DROP
iptables -A INPUT -s91.121.97.170 -j DROP
iptables -A INPUT -s91.132.139.170 -j DROP
iptables -A INPUT -s91.142.172.222 -j DROP
iptables -A INPUT -s91.142.90.46 -j DROP
iptables -A INPUT -s91.142.90.61 -j DROP
iptables -A INPUT -s91.191.184.158 -j DROP
iptables -A INPUT -s91.195.12.131 -j DROP
iptables -A INPUT -s91.195.12.143 -j DROP
iptables -A INPUT -s91.195.12.187 -j DROP
iptables -A INPUT -s91.200.14.109 -j DROP
iptables -A INPUT -s91.200.14.124 -j DROP
iptables -A INPUT -s91.200.14.139 -j DROP
iptables -A INPUT -s91.200.14.73 -j DROP
iptables -A INPUT -s91.201.202.12 -j DROP
iptables -A INPUT -s91.201.202.232 -j DROP
iptables -A INPUT -s91.201.41.91 -j DROP
iptables -A INPUT -s91.203.5.145 -j DROP
iptables -A INPUT -s91.203.5.181 -j DROP
iptables -A INPUT -s91.207.185.73 -j DROP
iptables -A INPUT -s91.209.77.86 -j DROP
iptables -A INPUT -s91.210.166.51 -j DROP
iptables -A INPUT -s91.211.119.71 -j DROP
iptables -A INPUT -s91.211.119.98 -j DROP
iptables -A INPUT -s91.211.210.47 -j DROP
iptables -A INPUT -s91.214.71.101 -j DROP
iptables -A INPUT -s91.219.28.231 -j DROP
iptables -A INPUT -s91.219.28.44 -j DROP
iptables -A INPUT -s91.219.29.106 -j DROP
iptables -A INPUT -s91.219.29.41 -j DROP
iptables -A INPUT -s91.219.29.48 -j DROP
iptables -A INPUT -s91.219.29.55 -j DROP
iptables -A INPUT -s91.219.29.64 -j DROP
iptables -A INPUT -s91.219.29.66 -j DROP
iptables -A INPUT -s91.219.29.81 -j DROP
iptables -A INPUT -s91.219.30.254 -j DROP
iptables -A INPUT -s91.219.31.14 -j DROP
iptables -A INPUT -s91.219.31.15 -j DROP
iptables -A INPUT -s91.219.31.18 -j DROP
iptables -A INPUT -s91.223.180.240 -j DROP
iptables -A INPUT -s91.223.88.205 -j DROP
iptables -A INPUT -s91.223.88.50 -j DROP
iptables -A INPUT -s91.226.116.69 -j DROP
iptables -A INPUT -s91.226.92.202 -j DROP
iptables -A INPUT -s91.226.92.204 -j DROP
iptables -A INPUT -s91.226.92.208 -j DROP
iptables -A INPUT -s91.226.93.113 -j DROP
iptables -A INPUT -s91.226.93.124 -j DROP
iptables -A INPUT -s91.228.239.216 -j DROP
iptables -A INPUT -s91.229.188.178 -j DROP
iptables -A INPUT -s91.230.211.103 -j DROP
iptables -A INPUT -s91.230.211.139 -j DROP
iptables -A INPUT -s91.230.211.187 -j DROP
iptables -A INPUT -s91.230.211.26 -j DROP
iptables -A INPUT -s91.234.32.192 -j DROP
iptables -A INPUT -s9172.16.31.10 -j DROP
iptables -A INPUT -s91.234.33.215 -j DROP
iptables -A INPUT -s91.234.34.98 -j DROP
iptables -A INPUT -s91.234.35.216 -j DROP
iptables -A INPUT -s9172.16.31.10 -j DROP
iptables -A INPUT -s91.236.239.228 -j DROP
iptables -A INPUT -s91.236.245.65 -j DROP
iptables -A INPUT -s9172.16.58.3 -j DROP
iptables -A INPUT -s91.239.235.130 -j DROP
iptables -A INPUT -s91.247.37.137 -j DROP
iptables -A INPUT -s91.250.242.12 -j DROP
iptables -A INPUT -s91.250.96.120 -j DROP
iptables -A INPUT -s91.67.11.42 -j DROP
iptables -A INPUT -s91.83.93.103 -j DROP
iptables -A INPUT -s91.92.109.43 -j DROP
iptables -A INPUT -s91.92.128.237 -j DROP
iptables -A INPUT -s91.92.191.134 -j DROP
iptables -A INPUT -s92.119.160.77 -j DROP
iptables -A INPUT -s92.12.145.57 -j DROP
iptables -A INPUT -s9172.16.58.3 -j DROP
iptables -A INPUT -s92.222.25.170 -j DROP
iptables -A INPUT -s172.16.31.10 -j DROP
iptables -A INPUT -s9192.168.3.11 -j DROP
iptables -A INPUT -s9172.16.17.32 -j DROP
iptables -A INPUT -s92.3.69.231 -j DROP
iptables -A INPUT -s9172.16.17.32 -j DROP
iptables -A INPUT -s9172.16.58.3 -j DROP
iptables -A INPUT -s9172.16.31.10 -j DROP
iptables -A INPUT -s92.51.129.249 -j DROP
iptables -A INPUT -s92.62.139.103 -j DROP
iptables -A INPUT -s92.63.102.210 -j DROP
iptables -A INPUT -s92.63.102.212 -j DROP
iptables -A INPUT -s92.63.87.106 -j DROP
iptables -A INPUT -s92.63.87.134 -j DROP
iptables -A INPUT -s92.63.87.48 -j DROP
iptables -A INPUT -s92.63.87.53 -j DROP
iptables -A INPUT -s93.115.241.194 -j DROP
iptables -A INPUT -s93.170.104.127 -j DROP
iptables -A INPUT -s93.170.123.119 -j DROP
iptables -A INPUT -s93.170.123.185 -j DROP
iptables -A INPUT -s93.170.123.60 -j DROP
iptables -A INPUT -s93.170.131.108 -j DROP
iptables -A INPUT -s93.170.169.52 -j DROP
iptables -A INPUT -s93.189.149.238 -j DROP
iptables -A INPUT -s93.189.42.21 -j DROP
iptables -A INPUT -s93.78.205.196 -j DROP
iptables -A INPUT -s94.102.51.78 -j DROP
iptables -A INPUT -s94.156.35.232 -j DROP
iptables -A INPUT -s94.203.254.248 -j DROP
iptables -A INPUT -s94.205.247.10 -j DROP
iptables -A INPUT -s94.23.10.157 -j DROP
iptables -A INPUT -s94.23.13.5 -j DROP
iptables -A INPUT -s94.23.157.150 -j DROP
iptables -A INPUT -s94.23.36.82 -j DROP
iptables -A INPUT -s94.242.57.45 -j DROP
iptables -A INPUT -s94.242.59.239 -j DROP
iptables -A INPUT -s94.247.179.149 -j DROP
iptables -A INPUT -s95.141.175.240 -j DROP
iptables -A INPUT -s95.163.107.41 -j DROP
iptables -A INPUT -s95.174.65.246 -j DROP
iptables -A INPUT -s95.178.241.254 -j DROP
iptables -A INPUT -s9192.168.3.11 -j DROP
iptables -A INPUT -s9172.16.58.3 -j DROP
iptables -A INPUT -s9192.168.127.12 -j DROP
iptables -A INPUT -s95.211.154.159 -j DROP
iptables -A INPUT -s9172.16.17.32 -j DROP
iptables -A INPUT -s9192.168.3.11 -j DROP
iptables -A INPUT -s95.213.184.10 -j DROP
iptables -A INPUT -s95.213.195.123 -j DROP
iptables -A INPUT -s9172.16.31.10 -j DROP
iptables -A INPUT -s95.217.33.61 -j DROP
iptables -A INPUT -s95.34.98.152 -j DROP
iptables -A INPUT -s95.37.176.63 -j DROP
iptables -A INPUT -s95.46.114.205 -j DROP
iptables -A INPUT -s95.46.114.80 -j DROP
iptables -A INPUT -s95.46.114.97 -j DROP
iptables -A INPUT -s95.85.19.195 -j DROP
iptables -A INPUT -s97.74.237.196 -j DROP
iptables -A INPUT -s98.11.32.74 -j DROP
iptables -A INPUT -s98.143.148.173 -j DROP
iptables -A INPUT -s98.210.48.44 -j DROP
iptables -A INPUT -s98.6.40.86 -j DROP
<file_sep>/Python/PycharmProjects_1718/Week 6 Programming Assignment/character_pic_grid.py
grid = [['.', '.', '.', '.', '.', '.'],
['.', 'O', 'O', '.', '.', '.'],
['O', 'O', 'O', 'O', '.', '.'],
['O', 'O', 'O', 'O', 'O', '.'],
['.', 'O', 'O', 'O', 'O', 'O'],
['O', 'O', 'O', 'O', 'O', '.'],
['O', 'O', 'O', 'O', '.', '.'],
['.', 'O', 'O', '.', '.', '.'],
['.', '.', '.', '.', '.', '.']]
for y in range(len(grid[0])): # [y] is the assigned y place in the list [grid], formerly the x place
for x in range(len(grid)): # [x] is the assigned x place in the list [grid], formerly the y place
print(grid[x][y], end="") # this flips them so the picture flips
print("") # helps shifts to a new line
<file_sep>/Python/PycharmProjects_1819/Week3_Lab/week3.py
"""Code for Week 3 Lab practicing creating a class.
Author: <NAME>
Class: CSI-260-02
Assignment: Week 3 Lab
Due Date: February 5, 2019 11:59 PM
Certification of Authenticity:
I certify that this is entirely my own work, except where I have given
fully-documented references to the work of others. I understand the definition
and consequences of plagiarism and acknowledge that the assessor of this
assignment may, for the purpose of assessing this assignment:
- Reproduce this assignment and provide a copy to another member of academic
- staff; and/or Communicate a copy of this assignment to a plagiarism checking
- service (which may then retain a copy of this assignment on its database for
- the purpose of future plagiarism checking)
"""
class Country:
"""A single country.
Attributes:
name: string
population: integer
area: integer
"""
def __init__(self, name, population, area):
"""Initialize the country information.
:param: name: a string to represent the name of the country
:param: population: an integer to represent the population of country
:param: area: an integer to represent the area of the country
"""
self.name = name
self.population = population
self.area = area
def is_larger(self, country):
"""Compare the area of another country object to self.
:return: Boolean
"""
if self.area > country.area:
return True
else:
return False
def population_density(self):
"""Return the population density (people per square kilometer) of the country.
:return: integer
"""
pop_density = self.population / self.area
return pop_density
def summary(self):
"""Return a summary representing the country.
:return: string
"""
summary = self.name+" has a population of " + \
str(self.population)+" people " \
"and is "+str(self.area)+" square km. " \
"It therefore has a population density of " \
+ str(f'{self.population_density():.4f}') + \
" people per square km."
return summary
<file_sep>/Python/PycharmProjects_1819/Class Notes/Week9_Notes.py
# Error Handling
'''
short_list = [1, 2, 3]
while True:
value = input('Position [q to quit]: ')
if value == 'q':
break
try:
position = int(value)
print(short_list[position])
except IndexError as err:
print('Bad Index:', position)
except Exception as other:
print('Something else broke:', other)
try:
f = open('username.txt')
except FileNotFoundError:
print("The file does not exist at this location.")
except NameError:
print("You are using an undefined variable.")
except Exception as e:
print(e)
else:
print(f.read())
f.close()
# Why run it here than in the try block?
# So that each potential error is caught
finally:
print("Code is executing the stuff in the 'finally' block.")
'''
import pprint # This will allow for cleaner printing. Can use the pprint() and the pformat functions()
courses = {'CIT 200': 'Relational Databases', 'CSI 300': 'Database Systems', 'SEC 250': 'Computer & Network Security',
'NET 215': 'TCP/IP'}
grade_avg = {'Exam 1': 90, 'Exam 2': 76, 'Exam 3': 82, 'Exam 4': 88}
while True:
print('Enter a name: (blank to quit)')
name = input()
if name == '':
break
if name in courses:
print(courses[name] + ' is known as ' + name)
else:
print('I do not have course information for ' + name)
print('What is the course?')
cname = input()
courses[name] = cname
print('Courses Database Updated')
for k in grade_avg.keys():
print(k)
for i in grade_avg.values():
print(i)
print("I want to take " + str(courses.get('NET 215', 0)))
print("I want to take " + str(courses.get('AI', 'a course that does not exist')))
message = 'You need to register for at least 4 or you will lose your full-time status'
msg_count = {}
for character in message:
msg_count.setdefault(character, 0)
msg_count[character] = msg_count[character] + 1
print(msg_count)
<file_sep>/Python/PycharmProjects_1718/Week 7 Programming Assignment/PasswordSaver_Refactoring.py
import csv
import sys
# The password list - We start with it populated for testing purposes
entries = {1: {'website': 'yahoo', 'username': 'jblumberg', 'password': '<PASSWORD>'},
2: {'website': 'google', 'username': 'jackieb', 'password': '<PASSWORD>'}}
# The password file name to store the passwords to
password_file_name = "<PASSWORD>"
# The encryption key for the caesar cypher
encryption_key = 16
menu_text = """
What would you like to do:
1. Open password file
2. Lookup a password
3. Add an entry
4. Save password file
5. Print the encrypted password list (for testing)
6. Quit program
Please enter a number (1-6)"""
def password_encrypt(unencrypted_message, key):
"""Returns an encrypted message using a caesar cypher
:param unencrypted_message (string)
:param key (int) The offset to be used for the caesar cypher
:return (string) The encrypted message
"""
# Fill in your code here.
# #If you can't get it working, you may want to put some temporary code here
# #While working on other parts of the program
result = ''
index = 0
while index < len(unencrypted_message):
ascii_val = ord(unencrypted_message[index]) - 32 + key
ascii_val = ascii_val % (126 - 32)
ascii_val += 32
result = result + chr(ascii_val)
index += 1
return result
# This is the Caesar Cipher example from class
pass
def load_password_file(file_name):
"""Loads a password file. The file must be in the same directory as the .py file
:param file_name (string) The file to load. Must be a .csv file in the correct format
:return (list) The password entries
"""
# Code influenced from website:
# https://stackoverflow.com/questions/8685809/writing-a-dictionary-to-a-csv-file-with-one-line-for-every-key-value
with open(file_name, newline='') as csvfile:
reader = csv.reader(csvfile)
entries_file = list(reader)
return entries_file
def save_password_file(entries_file, file_name):
"""Saves a password file. The file will be created if it doesn't exist.
:param file_name (string) The file to save.
"""
# Code influenced from website:
# https://stackoverflow.com/questions/8685809/writing-a-dictionary-to-a-csv-file-with-one-line-for-every-key-value
with open(file_name, 'w+', newline='') as csvfile:
writer = csv.writer(csvfile)
for key, value in entries.items():
writer.writerow([key, value])
def add_entry(website, username, password):
"""Adds an entry with a website and password
Logic for function:
Step 1: Use the password_encrypt() function to encrypt the password.
The encryptionKey variable is defined already as 16, don't change this
Step 2: create a list of size 2, first item the website name and the second
item the password.
Step 3: append the list from Step 2 to the password list
:param website (string) The website for the entry
:param password (string) The unencrypted password for the entry
"""
# Fill in your code here
count = len(entries) + 1
entries[count] = {}
encrypt_password = password_encrypt(password, encryption_key) # encrypts the password
entries[count]['website'] = website # adds website to the appropriate entry in the nested dictionary
entries[count]['username'] = username # adds username to the appropriate entry in the nested dictionary
entries[count]['password'] = encrypt_password # adds encrypted password to the appropriate entry in the nested list
# Code was influenced from website: https://www.programiz.com/python-programming/nested-dictionary
pass
def lookup_password(website):
"""Lookup the password for a given website
Logic for function:
1. Create a loop that goes through each item in the password list
You can consult the reading on lists in Week 5 for ways to loop through a list
2. Check if the name is found. To index a list of lists you use 2 square bracket sets
So passwords[0][1] would mean for the first item in the list get it's 2nd item (remember, lists start at 0)
So this would be 'XqffoZeo' in the password list given what is predefined at the top of the page.
If you created a loop using the syntax described in step 1, then i is your 'iterator' in the list so you
will want to use i in your first set of brackets.
3. If the name is found then decrypt it. Decrypting is that exact reverse operation from encrypting. Take a look at the
caesar cypher lecture as a reference. You do not need to write your own decryption function, you can reuse passwordEncrypt
Write the above one step at a time. By this I mean, write step 1... but in your loop print out every item in the list
for testing purposes. Then write step 2, and print out the password but not decrypted. Then write step 3. This way
you can test easily along the way.
:param website (string) The website for the entry to lookup
:return: Returns an unencrypted password. Returns None if no entry is found
"""
# Fill in your code here
# I got help for this part from:
# https://www.reddit.com/r/learnpython/comments/2ttuwa/python_27_searching_nested_dictionary/
for key, value in entries.items():
if entries[key]['website'] == website:
return password_encrypt(entries[key]['password'], -16)
pass
while True:
print(menu_text)
choice = input()
if(choice == '1'): # Load the password list from a file
try: # error handling
entries = load_password_file(password_file_name)
except FileNotFoundError:
print("The file was not found.")
if(choice == '2'): # Lookup at password
print("Which website do you want to lookup the password for?")
# for key in entries.items():
# print(entries.get('website', 0))
count = 1
while count <= len(entries):
print(entries[count]['website'])
count += 1
website = input()
password = lookup_password(website)
if password:
print('The password is: ', password)
else:
print('Password not found')
if(choice == '3'):
print("What website is this password for?")
website = input()
print("What is the username?")
username = input() # adds ability to add username for the add_entry function
print("What is the password?")
password = input()
while len(password) < 6: # Password must meet a requirement and loops until it is met
print("Password length must contain at least 6 characters. Please enter a new password: ")
password = input()
add_entry(website, username, password)
if(choice == '4'): # Save the passwords to a file
save_password_file(entries, password_file_name)
if(choice == '5'): # print out the entries dictionary
for e_id, e_info in entries.items():
print("\nEntry:", e_id)
for key in e_info:
print(key + ':', e_info[key])
# Code was influenced from website: https://www.programiz.com/python-programming/nested-dictionary
if(choice == '6'): # quit our program
sys.exit()
<file_sep>/Python/PycharmProjects_1819/Week10_Lab/temperature_magic.py
"""Tools for working with Temperatures.
Author: <NAME>
Class: CSI-260-02
Assignment: Week 8 Lab
Due Date: March 8, 2019 11:59 PM
Certification of Authenticity:
I certify that this is entirely my own work, except where I have given
fully-documented references to the work of others. I understand the definition
and consequences of plagiarism and acknowledge that the assessor of this
assignment may, for the purpose of assessing this assignment:
- Reproduce this assignment and provide a copy to another member of academic
- staff; and/or Communicate a copy of this assignment to a plagiarism checking
- service (which may then retain a copy of this assignment on its database for
- the purpose of future plagiarism checking)
"""
class Temperature:
"""Represents a temperature."""
def __init__(self, degrees=0):
"""Initialize temperature with specified degrees celsius.
Args:
degrees: number of degrees celsius
"""
self.celsius = degrees
self._celsius = degrees
def __str__(self):
"""Convert a Temperature instance to a string."""
return f'{self._celsius}°C'
def __repr__(self):
"""Convert a Temperature instance to an appropriate representation."""
return f'Temperature({self._celsius!r})'
def __eq__(self, other):
"""Compare two Temperature instances to see if they are equal."""
if self._celsius is other:
return True
elif self._celsius != other:
return False
else:
return True
def __lt__(self, other):
"""Compare two Temperature instances.
To see if one is less than another.
"""
if Temperature(self.celsius < other.celsius) is True:
return True
else:
return False
def __gt__(self, other):
"""Compare two Temperature instances.
To see is one is greater than another.
"""
if Temperature(self.celsius > other.celsius) is True:
return True
else:
return False
def __le__(self, other):
"""Compare two Temperature instances.
To see if one is less than or equal to another.
"""
if self._celsius <= other:
return True
elif self._celsius >= other:
return False
else:
return True
def __ge__(self, other):
"""Compare two Temperature instances.
To see if one is greater than or equal to another.
"""
if self._celsius >= other:
return True
elif self._celsius <= other:
return False
else:
return True
def __add__(self, other):
"""Add two Temperature instances|Temperature instance and a number.
The result must be a new Temperature instance.
"""
try:
return Temperature(self.celsius + other.celsius)
except AttributeError:
return Temperature(self.celsius + other)
def __radd__(self, other):
"""Add two Temperature instances|Temperature instance and a number.
The result must be a new Temperature instance.
"""
return self + other
def __sub__(self, other):
"""Subtract two Temperature instances|Temperature instance and a number.
The result must be a new Temperature instance.
"""
try:
return Temperature(self.celsius - other.celsius)
except AttributeError:
return Temperature(self.celsius - other)
def __rsub__(self, other):
"""Subtract two Temperature instances|Temperature instance and a number.
The result must be a new Temperature instance.
"""
return self + other
def __iadd__(self, other):
"""Create new instances of Temperature and overwriting the old variable.
The operation happens in-place.
"""
self.celsius += other
return self
def __isub__(self, other):
"""Create new instances of Temperature and overwriting the old variable.
The operation happens in-place.
"""
self.celsius -= other
return self
def __hash__(self):
"""Hashes the Temperature Object.
To be able to use Temperature objects as keys of a dictionary.
"""
return hash(self._celsius)
<file_sep>/Python/PycharmProjects_1819/Week11_Lab/week11_tests.py
"""Tests for Week 11 Lab.
Prof. <NAME>
Champlain College
CSI-260 -- Spring 2019
"""
import unittest
from options import Options
import sys
# define constants used by tests
STUDENT_CODE = ["options.py"]
class TestWeek11(unittest.TestCase):
"""Main testing class for Week 11 Lab."""
def test_01_initializer(self):
"""Test if initializer works as specified."""
# positional
options = Options("debug", "verbose")
message = "Option not initialized correctly from positional argument."
self.assertEqual(options["debug"], True, message)
self.assertEqual(options["verbose"], True, message)
# positional type
message = ("Must raise TypeError for any positional argument that is "
"not a string.")
with self.assertRaises(TypeError, msg=message):
options = Options(True)
with self.assertRaises(TypeError, msg=message):
options = Options(4.5)
# keywords
options = Options(log_file="logging.txt", port=80)
message = "Option not initialized correctly from keyword argument."
self.assertEqual(options["log_file"], "logging.txt", message)
self.assertEqual(options["port"], 80, message)
# combined
options = Options("debug", "verbose", log_file="logging.txt", port=80)
message = "Option not initialized using a combination of arguments."
self.assertEqual(options["debug"], True, message)
self.assertEqual(options["verbose"], True, message)
self.assertEqual(options["log_file"], "logging.txt", message)
self.assertEqual(options["port"], 80, message)
def test_02_getitem(self):
"""Test if getting items with []s works as specified."""
options = Options("debug", "verbose", log_file="logging.txt", port=80)
message = "Retrieving an unspecfied option must return False."
# no need to check specified options, since checked in previous test
self.assertEqual(options["fsdgjhgd"], False, message)
def test_03_getattr(self):
"""Test if getting items as attributesworks as specified."""
options = Options("debug", "verbose", log_file="logging.txt", port=80)
message = "Retrieving options as attributes not working correctly."
try:
self.assertEqual(options.debug, True, message)
self.assertEqual(options.verbose, True, message)
self.assertEqual(options.log_file, "logging.txt", message)
self.assertEqual(options.port, 80, message)
self.assertEqual(options["fsdgjhgd"], False,
"Retrieving an unspecfied option must "
"return False.")
except AttributeError:
self.fail("Accessing an option as an attribute should not raise"
" an AttributeError. Have you implemented __getattr__?")
def test_04_setitem(self):
"""Test if setting items with []s works as specified."""
options = Options()
options["test"] = "test_value"
message = ("It must be possible to set options with []s, e.g. "
'options["log_file"] = "new_logging.txt"')
self.assertEqual(options["test"], "test_value", message)
self.assertEqual(options.test, "test_value", message)
message = ("Must raise TypeError when attempting to set an option "
"with a name that is not a string.")
with self.assertRaises(TypeError, msg=message):
options = Options(True)
with self.assertRaises(TypeError, msg=message):
options = Options(4.5)
def test_05_setattr(self):
"""Test if setting attributes works as specified."""
options = Options()
options.test = "test_value"
message = ("It must be possible to set options with []s, e.g. "
'options["log_file"] = "new_logging.txt"')
self.assertEqual(options["test"], "test_value", message)
self.assertEqual(options.test, "test_value", message)
def test_06_delattr(self):
"""Test if deleting options works as specified."""
options = Options(test="test_value")
del options["test"]
self.assertEqual(options.test, False,
"Deleting options by deleting dict keys not working "
"as specified. You should not have needed to "
"override __delitem__")
options["test"] = "test_value"
del options.test
self.assertEqual(options.test, False,
"Deleting options by deleting attributes not working "
"as specified. Did you implement __delattr__?")
def test_07_style(self):
"""Run the linter and check that the header is there."""
try:
from flake8.api import legacy as flake8
# noqa on the following since just importing to test installed
import pep8ext_naming # noqa
import flake8_docstrings # noqa
print("\nLinting Code...\n" + "=" * 15)
style_guide = flake8.get_style_guide()
report = style_guide.check_files(STUDENT_CODE)
self.assertEqual(report.total_errors, 0,
"You should fix all linting errors "
"before submission in order to receive full "
"credit!")
for module in STUDENT_CODE:
self.check_header(module)
print("Passing linter tests!")
except ImportError:
print("""
### WARNING: Unable to import flake8 and/or extensions, so cannot \
properly lint your code. ###
Please install flake8, pep8-naming, and flake8-docstrings to auto-check \
whether you are adhering to proper style and docstring conventions.
To install, run:
pip install flake8 pep8-naming flake8-docstrings
""")
def check_header(self, module):
"""Check the header of the given module."""
docstring = sys.modules[module[:-3]].__doc__
for check in ['Author:', 'Class:', 'Assignment:',
'Certification of Authenticity:']:
self.assertIn(check, docstring,
"Missing '{}' in {}'s docstring".format(
check, module))
if __name__ == '__main__':
unittest.main(failfast=True)
<file_sep>/Python/PycharmProjects_1819/Class Notes/TempConversion_ClassProject_Enhanced.py
#Anything highlighted I changed or added
#I mostly just changed how some stuff was worded (or added) in relation to the Algorithm given to make things clearer.
def fahrenheit_to_celsius(temp_fahrenheit):
return ((5 / 9 * temp_fahrenheit) - 32)
def celsius_to_fahrenheit(temp_celsius):
return ((9 / 5 * temp_celsius) + 32)
f_to_c = "C"
c_to_f = "F"
exit = "exit"
end_yes = "yes"
end_no = "no"
print("Hello!")
start_action = input("Which conversion would you like to do. Enter 'C' to convert to Celsius, 'F' to convert to Fahrenheit, or 'exit' to exit the program.")
w hile start_action == f_to_c:
f_temp = int(input("Enter the temperature in Fahrenheit: "))
result_c = fahrenheit_to_celsius(f_temp)
print(result_c)
end_action = input("Would you like to perform another conversion? Type 'yes' to perform another one, or 'no' to exit the program.")
if end_action == end_yes:
start_action = input("Which conversion would you like to do. Enter 'C' to convert to Celsius, 'F' to convert to Fahrenheit, or 'exit' to exit the program.")
else:
print("Alright. Have a good day!")
break
while start_action == c_to_f:
c_temp = int(input("Enter the temperature in Celsius: "))
result_f = celsius_to_fahrenheit(c_temp)
print(result_f)
end_action = input("Would you like to perform another conversion? Type 'yes' to perform another one, or 'no' to exit the program.")
if end_action == end_yes:
start_action = input("Which conversion would you like to do. Enter 'C' to convert to Celsius, 'F' to convert to Fahrenheit, or 'exit' to exit the program.")
else:
print("Alright. Have a good day!")
break
while start_action == exit:
print("Alright. Have a good day!")
break
<file_sep>/Python/PycharmProjects_1819/Week 10 Programming Assignment/Part3.py
user_string = input("Submit text here: ")
stringFreq = {}
user_string = user_string.split()
# splits the sentence up by word and returns it back into the same variable
for word in user_string: # goes through the split string
stringFreq.setdefault(word, 0) # Sets each word counter to zero
stringFreq[word] = stringFreq[word] + 1 # if word in string is found, adds one to the counter
# Took inspiration from class examples from Week 9
print("\nTotal number of words in the given string: " + str(len(user_string)))
# This reads the length of the string (in words) and prints the output
stringFreq = sorted(stringFreq.items(), key=lambda kv: kv[1], reverse=True)
# This sorts the the words by the frequency from greatest to least and returns it back into the same variable
print("\nThe top 20 most frequently-used words in the given string:")
for key, value in stringFreq[:20]:
print("'" + key + "': " + str(value))
# Got help from website: (and realized I was using the wrong variable)
# https://stackoverflow.com/questions/20577840/python-dictionary-sorting-in-descending-order-based-on-values
freqPercentage = [(instance, count / len(user_string)) for instance, count in stringFreq]
# This calculates the percentage each word will occur by using the total length of the string
# and the frequency in which they occurred
print("\nThe chances that those words will occur again:")
for word, percentage in freqPercentage[:20]:
print("'%s': %.2f%%" % (word, percentage * 100))
# Got help from website:
# https://stackoverflow.com/questions/52871769/python-calculate-word-frequency-in-percentage
<file_sep>/Python/PycharmProjects_1819/Advanced_Python_Notes/Week6_Notes.py
""" Abstract Base Classes
abstract vs. concrete/tangible
abstract class contains at least 1 abstract method
CANNOT MAKE INSTANCES OF ABSTRACT CLASSES
Duck Typing and EAFP (easier to ask for forgiveness than permission) vs. LBYL (Look before you leap)"""
# shapes.py (review on multiple inheritances)
import abc
import math
class Shape(abc.ABC):
"""Shape abstract base class that other class will implement from."""
def __init__(self, color):
"""Create a shape of a specified color."""
self.color = color
@abc.abstractmethod
def get_area(self):
"""Return the area of this shape.
This must be implemented by all concrete subclasses.
"""
pass
class Circle(Shape):
"""Circle is a concrete extension of Shape.
:
"""
def __init__(self, color, radius):
"""Create a circle of specified color and radius."""
super().__init__(color)
self.radius = radius
def get_area(self):
"""Return the area of this circle."""
return math.pi * self.radius ** 2
class Rectangle(Shape):
""" """
def __init__(self, color, length, width):
super().__init__(color)
self.length = length
self.width = width
def get_area(self):
return self.length * self.width
def print_area(shape):
# LBYL
# if hasattr(shape, "get_area") and callable(shape.get_area):
# print(f"{shape.get_area():.2f}")
# else:
# print("Not a Shape!")
# EAFP
try:
print(f"{shape.get_area():.2f}")
except (TypeError, AttributeError):
print("Not a Shape!")
class NotAShape:
def __init__(self):
pass
def get_area(self, x):
return 42
# def get_area(self):
# return 42
if __name__ == "__main__":
circle = Circle("red", 2)
print_area(circle)
rectangle = Rectangle("blue", 3, 5)
print_area(rectangle)
not_a_shape = NotAShape()
print_area(not_a_shape)
<file_sep>/Python/PycharmProjects_1819/LibraryProject/library_system.py
"""The classes to implement the Library Collection system.
Author: <NAME>
Class: CSI-260-01
Assignment: Library Project
Due Date: 2/27/2019 11:59 PM
Certification of Authenticity:
I certify that this is entirely my own work, except where I have given
fully-documented references to the work of others. I understand the definition
and consequences of plagiarism and acknowledge that the assessor of this
assignment may, for the purpose of assessing this assignment:
- Reproduce this assignment and provide a copy to another member of academic
- staff; and/or Communicate a copy of this assignment to a plagiarism checking
- service (which may then retain a copy of this assignment on its database for
- the purpose of future plagiarism checking)
"""
import pickle
import abc
class LibraryItem(abc.ABC):
"""Base class for all items stored in a library catalog.
Provides a simple LibraryItem with only a few attributes.
"""
def __init__(self, name, isbn, tag_list=[]):
"""Initialize a LibraryItem.
:param name: (string) Name of item
:param isbn: (string) ISBN number for the item
"""
self.name = name
self.isbn = isbn
self.type = 'Generic' # This is the type of item being stored
self.tag_list = tag_list
@abc.abstractmethod
def match(self, filter_text):
"""Return whether the item is a match for the filter_text.
match should be case insensitive and should search all attributes of
the class. Depending on the attribute, match requires an exact match
or partial match.
match needs to be redefined for any subclasses. Please see the
note/notebook case study from Chapter 2 as an example of how match
is designed to work.
:param filter_text: (string) string to search for
:return: (boolean) whether the search_term is a match for this item
"""
return filter_text.lower() in self.name.lower() or \
filter_text.lower() == self.isbn.lower() or \
True if filter_text.lower in self.tag_list else False
@abc.abstractmethod
def __str__(self):
"""Return a well formatted string representation of the item.
All instance variables are included.
"""
return f'{self.name} {self.isbn} {self.type}'
def to_short_string(self):
"""Return a short string representation of the item.
String contains only the name of the item and the type of the item
"""
return f'{self.name} - {self.isbn}'
class BookRecord(LibraryItem):
"""Provides a Book Record for a Library Item."""
def __init__(self, name, isbn, genre, author, tag_list=[]):
"""Initialize a Book Record.
:param name: (string) Name of book
:param isbn: (string) ISBN number for the book
:param genre: (string) Genre of the book
:param author: (string) The author of the book
"""
super().__init__(name, isbn)
self.genre = genre
self.author = author
self.type = 'Book'
self.tag_list = tag_list
def match(self, filter_text):
"""Return whether the item is a match for the filter_text.
match should be case insensitive and should search all attributes of
the class. Depending on the attribute, match requires an exact match
or partial match.
:param filter_text: (string) string to search for
:return: (boolean) whether the search_term is a match for this item
"""
return filter_text.lower() in self.name.lower() or \
filter_text.lower() in self.author.lower() or \
filter_text.lower() == self.isbn.lower or \
filter_text.lower() in self.genre.lower() or \
filter_text.lower() in self.type.lower() or \
True if filter_text.lower in self.tag_list else False
def __str__(self):
"""Return a well formatted string representation of the book.
All instance variables are included.
"""
return \
f'{super().__str__()} \nAuthor: {self.author} ' \
f'\nGenre: {self.genre} \nCategory Tags: ' \
f'\n{self.tag_list}'
class MusicAlbumRecord(LibraryItem):
"""Provides a eBook Record for a Library Item."""
def __init__(self, name, isbn, genre, artist, label, tag_list=[]):
"""Initialize an eBook Record.
:param name: (string) Name of eBook
:param isbn: (string) ISBN number for the eBook
:param genre: (string) Genre of the eBook
:param artist: (string) The artist of the music album
:param label: (string) The record label of the music album
"""
super().__init__(name, isbn)
self.genre = genre
self.artist = artist
self.label = label
self.type = 'Music Album'
self.tag_list = tag_list
def match(self, filter_text):
"""Return whether the item is a match for the filter_text.
match should be case insensitive and should search all attributes of
the class. Depending on the attribute, match requires an exact match
or partial match.
:param filter_text: (string) string to search for
:return: (boolean) whether the search_term is a match for this item
"""
return filter_text.lower() in self.name.lower() or \
filter_text.lower() in self.artist.lower() or \
filter_text.lower() in self.label.lower() or \
filter_text.lower() == self.isbn.lower() or \
filter_text.lower() in self.genre.lower() or \
filter_text.lower() in self.type.lower() or \
True if filter_text.lower in self.tag_list else False
def __str__(self):
"""Return a well formatted string representation of the eBook.
All instance variables are included.
"""
return \
f'{super().__str__()} \nArtist: {self.artist} ' \
f'\nRecord Label: {self.label} \nGenre: {self.genre} ' \
f'\nCategory Tags: \n{self.tag_list}'
class DVDRecord(LibraryItem):
"""Provides a DVD Record for a Library Item."""
def __init__(self, name, isbn, genre, company, tag_list=[]):
"""Initialize a DVD Record.
:param name: (string) Name of DVD
:param genre: (string) Genre of the DVD
:param company: (string) The distributing company of the DVD
"""
super().__init__(name, isbn)
self.genre = genre
self.company = company
self.type = 'DVD'
self.tag_list = tag_list
def match(self, filter_text):
"""Return whether the item is a match for the filter_text.
match should be case insensitive and should search all attributes of
the class. Depending on the attribute, match requires an exact match
or partial match.
:param filter_text: (string) string to search for
:return: (boolean) whether the search_term is a match for this item
"""
return filter_text.lower() in self.name.lower() or \
filter_text.lower() == self.isbn.lower() or \
filter_text.lower() in self.company.lower() or \
filter_text.lower() in self.genre.lower() or \
filter_text.lower() in self.type.lower() or \
True if filter_text.lower in self.tag_list else False
def __str__(self):
"""Return a well formatted string representation of the DVD.
All instance variables are included.
"""
return \
f'{super().__str__()} \nDistributor: {self.company} ' \
f'\nGenre: {self.genre} \nCategory Tags: ' \
f'\n{self.tag_list}'
class Catalog:
"""Provides a 'private' list for holding a collection of LibraryItems."""
def __init__(self, name):
"""Initialize the name of catalog and the empty 'private' list.
:param name: the name of the 'private' list
"""
self.name = name
self._collection = []
def add_list(self, collection):
"""Give the ability to add a list of LibraryItems."""
for item in collection:
self._collection.append(item)
def remove_list(self, item):
"""Give the ability to remove a list of LibraryItems."""
try:
self._collection.remove(item)
except IndexError as e:
print("The item does not exist")
print(e)
def search(self, filter_text):
"""Give the ability to search for items.
Including the ability to filter the search by the type of item.
"""
return [search for search in
self._collection if search.match(filter_text)]
def save_catalog(self, collection):
"""Save the [_catalog] list to a pickle file.
:param collection: The collection that is being saved
"""
pickle.dump(collection, open("save_file.p", "wb"))
def load_catalog(self):
"""Load the [_catalog} list to the system."""
try:
self._collection = pickle.load(open("save_file.p", 'rb'))
except FileNotFoundError:
self._collection = []
class CategoryTag:
"""Provides a 'private' list for holding category tags."""
_category_tags = []
def __init__(self, name):
"""Initialize a Category Tag.
:param name: Name of Category Tag
"""
self.name = name
CategoryTag._category_tags.append(self.name)
def __str__(self):
"""Return a well formatted string representation of a category tag."""
return f'{self.name}'
@classmethod
def all_category_tags(cls):
"""Return a string representation of all category tags."""
print("All Category Tags:")
for tag in cls._category_tags:
print(f' - {tag}')
<file_sep>/Python/PycharmProjects_1718/Final_Project/Final_Project/venv/Lib/site-packages/pyad/adcontainer.py
from __future__ import absolute_import
from .adobject import *
from .aduser import ADUser
from .adcomputer import ADComputer
from .adgroup import ADGroup
from . import pyadconstants
class ADContainer(ADObject):
def get_children_iter(self, recursive=False, filter_=None):
for com_object in self._ldap_adsi_obj:
q = ADObject.from_com_object(com_object)
q.adjust_pyad_type()
if q.type == 'organizationalUnit' and recursive:
for c in q.get_children_iter(recursive=recursive):
if not filter_ or c.__class__ in filter_:
yield c
if not filter_ or q.__class__ in filter_:
yield q
def get_children(self, recursive=False, filter_=None):
"Iterate over the children objects in the container."
return list(self.get_children_iter(recursive=recursive, filter_=filter_))
def __create_object(self, type_, name):
prefix = 'ou' if type_ == 'organizationalUnit' else 'cn'
prefixed_name = '='.join((prefix,name))
return self._ldap_adsi_obj.Create(type_, prefixed_name)
def create_user(self, name, password=None, upn_suffix=None, enable=True,optional_attributes={}):
"""Create a new user object in the container"""
try:
if not upn_suffix:
upn_suffix = self.get_domain().get_default_upn()
upn = '@'.join((name, upn_suffix))
obj = self.__create_object('user', name)
obj.Put('sAMAccountName', optional_attributes.get('sAMAccountName', name))
obj.Put('userPrincipalName', upn)
obj.SetInfo()
pyadobj = ADUser.from_com_object(obj)
if enable:
pyadobj.enable()
if password:
pyadobj.set_password(password)
pyadobj.update_attributes(optional_attributes)
return pyadobj
except pywintypes.com_error as e:
pyadutils.pass_up_com_exception(e)
def create_group(self, name, security_enabled=True, scope='GLOBAL', optional_attributes={}):
"""Create a new group object in the container"""
try:
obj = self.__create_object('group', name)
obj.Put('sAMAccountName',name)
val = pyadconstants.ADS_GROUP_TYPE[scope]
if security_enabled:
val = val | pyadconstants.ADS_GROUP_TYPE['SECURITY_ENABLED']
obj.Put('groupType',val)
obj.SetInfo()
pyadobj = ADGroup.from_com_object(obj)
pyadobj.update_attributes(optional_attributes)
return pyadobj
except pywintypes.com_error as e:
pyadutils.pass_up_com_exception(e)
def create_container(self, name, optional_attributes={}):
"""Create a new organizational unit in the container"""
try:
obj = self.__create_object('organizationalUnit', name)
obj.SetInfo()
pyadobj = ADContainer.from_com_object(obj)
pyadobj.update_attributes(optional_attributes)
return pyadobj
except pywintypes.com_error as e:
pyadutils.pass_up_com_exception(e)
def create_computer(self, name, enable=True,optional_attributes={}):
"""Create a new computer object in the container"""
try:
obj = self.__create_object('computer', name)
obj.Put('sAMAccountName', name)
obj.SetInfo()
pyadobj = ADComputer.from_com_object(obj)
if enable:
pyadobj.enable()
pyadobj.update_attributes(optional_attributes)
return pyadobj
except pywintypes.com_error as e:
pyadutils.pass_up_com_exception(e)
def remove_child(self, child):
"""Rremoves the child object from the domain"""
self._ldap_adsi_obj.Delete(child.type, child.prefixed_cn)
ADObject._py_ad_object_mappings['organizationalUnit'] = ADContainer
ADObject._py_ad_object_mappings['container'] = ADContainer
<file_sep>/Python/PycharmProjects_1819/Advanced_Python_Notes/week11_demo1.py
"""Demo of additional magic methods.
Prof. <NAME>
Champlain College
CSI-260 -- Spring 2019
"""
class CustomInt(int):
"""A custom integer type for demoing magic methods."""
def __len__(self):
"""Called when the len operator is used."""
string_version = str(self)
return len(string_version)
def __getitem__(self, item):
"""Called when items are accessed via []s"""
string_version = str(self)
character = string_version[item]
return int(character)
def __setitem__(self, index, value):
"""Called when items are set via []s"""
print("calling __setitem__", index, value)
if __name__ == "__main__":
x = CustomInt(500)
print("len(x)", len(x)) # the same as print(x.__len__())
print("x[0]", x[0]) # the same as print(x.__getitem__(0))
x[1] = 9 # the same as x.__setitem__(0, 9)
<file_sep>/Python/PycharmProjects_1819/Advanced_Python_Notes/week11_demo4.py
"""More magic methods and extending built-ins.
Prof. <NAME>
Champlain College
CSI-260 -- Spring 2019
"""
class CustomList(list):
def __init__(self, *args):
super().__init__(args)
def __getitem__(self, item):
print("Calling __getitem__ with", item)
# don't do self[item], as this would keep calling this function
# repeatedly, instead:
return super().__getitem__(item)
def __setitem__(self, item, value):
print("Calling __setitem__ with", item, value)
super().__setitem__(item, value)
if __name__ == "__main__":
test = CustomList(1,2,3,4)
print(test)
print(test[0])
test[0] = 5<file_sep>/Python/PycharmProjects_1819/Class Notes/TempConversion_ClassProject.py
def fahrenheit_to_celsius(temp_fahrenheit):
return ((5 / 9 * temp_fahrenheit) - 32)
def celsius_to_fahrenheit(temp_celsius):
return ((9 / 5 * temp_celsius) + 32)
f_to_c = "F to C"
c_to_f = "C to F"
exit = "exit"
end_yes = "yes"
end_no = "no"
start_action = input("Which conversion would you like to do. Enter 'F to C' to convert to Celsius, 'C to F' to convert to Fahrenheit, or 'exit' to exit the program.")
while start_action == f_to_c:
f_temp = int(input("Enter the temperature in Fahrenheit: "))
result_c = fahrenheit_to_celsius(f_temp)
print(result_c)
end_action = input("Would you like to perform another conversion?")
if end_action == end_yes:
start_action = input("Which conversion would you like to do. Enter 'F to C' to convert to Celsius, 'C to F' to convert to Fahrenheit, or 'exit' to exit the program.")
else:
break
while start_action == c_to_f:
c_temp = int(input("Enter the temperature in Celsius: "))
result_f = celsius_to_fahrenheit(c_temp)
print(result_f)
end_action = input("Would you like to perform another conversion?")
if end_action == end_yes:
start_action = input("Which conversion would you like to do. Enter 'F to C' to convert to Celsius, 'C to F' to convert to Fahrenheit, or 'exit' to exit the program.")
else:
break
while start_action == exit:
break
<file_sep>/Python/PycharmProjects_1819/Advanced_Python_Notes/week11_demo2.py
"""Demo of advanced function usage.
Prof. <NAME>
Champlain College
CSI-260 -- Spring 2019
"""
def do_something(value1, value2, value3=3):
print(value1, value2, value3)
def do_something_else(a, b, *values, c=None, **kwargs):
print(values)
print(kwargs)
def add_10(x):
return x + 10
def use_function(function, value):
return function(value)
def create_add_x(x):
def add_x(value):
return value + x
return add_x
def wrap_tag(tag):
def wrapper(contents):
return f"<{tag}>{contents}</{tag}>"
return wrapper
if __name__ == "__main__":
values = [10, 20, 30]
do_something(*values) # the same as do_something(values[0], values[1], values[2])
values2 = [100, 200]
do_something(*values2)
do_something_else(1,2,3,4,5,"a", c=45, d=100, e=99)
add_30 = create_add_x(30)
print(add_30(20))
make_h1 = wrap_tag("h1")
print(make_h1("This is a header"))
print(make_h1("Another header"))
make_p = wrap_tag("p")
print(make_p("The first paragraph of my website."))
<file_sep>/Python/PycharmProjects_1819/Week 2 Programming Assignment/Conversation_Computer.py
#Conversation with a Computer - Week 2 Assignment
fname = input("Hello! What is your name?")
age = int(input("Hi " + fname + ". How old are you?"))
if age <= 38:
print("Wow, you're " + str(age) + ". You are so young.")#response that uses user input
if age > 38:
print("Wow, you're " + str(age) + ". Some people would call you old.")#response that uses user input
#I included the [fname] variable in the question of the input of the [age] variable to help reuse variables
#I also included if statements to help create responses from the user input
pizza_opinion = input("Do you like pizza?")
if pizza_opinion == "yes":
print("That's cool, so do I.")
pizza_choice = input("What kind of pizza do you like?")
print("You like " + pizza_choice + "? That's awesome, I like that too.")#response that uses user input
if pizza_opinion == "no":
print("Oh wow, you must be crazy.")
#just some yes or no questions to (again) easily create if statements to create responses from the user input
chocolate_opinion = input("Do you also like chocolate?")
if chocolate_opinion == "yes":
print("That's awesome.")
if chocolate_opinion == "no":
print("wait WHAT?!")
#again the same
tv_hours = int(input("How many hours do you usually watch TV in a week, " + fname + "?"))
music_hours = int(input("How many hours in a week do you also usually listen to music, " + fname + "?"))
computer_hours = int(input("...and on a computer?"))
total_hours = tv_hours + music_hours + computer_hours #an arithmetic operation that uses user input
hours_day = total_hours // 7 #another arithmetic operation that uses user input in a different way to create a different answer by using the output of [total_hours]
if total_hours < 40:
print("That's " + str(total_hours) + " hours a week.")#response that uses the sum of the user inputs
print("So that's about " + str(hours_day) + " hours a day.")#response that still uses the sum of the user input in a different algorithm
print("Oooo, that's not a lot of time with technology at all during the week.")
if total_hours >= 40:
print("That's " + str(total_hours) + " hours a week.")#response that uses the sum of the user inputs
print("So that's about " + str(hours_day) + " hours a day.")#response that still uses the sum of the user input in a different algorithm
print("Oh no, that's a lot of time with technology. You should go outside more often.")<file_sep>/Python/Python Assignments/tempConversion.py
tempF = input("Enter the temperature in degrees Fahrenheit: ")
tempC = (int(tempF)-32)*0.5556
print(tempC)
<file_sep>/Python/PycharmProjects_1718/Class Notes/Week7_Notes.py
# Nested Loops
for column in range(1, 11):
for row in range(1, 11):
mult_num = row * column
if mult_num < 10:
space = ' '
elif mult_num < 90:
space = ' '
print(space + str(mult_num), end = ' ')
print()
# or
for i in range(1, 11):
if(i < 10):
print("i = ", i, ":", end=" ")
else:
print("i =", i, ":", end=" ")
for j in range(1, 11):
print("{:0>3d}".format(i * j), end=" ")
print()
# Ciphers and Caesar Cipher
def password_encrypt (unencryptedMessage, key):
"""Returns an encrypted message using a caesar cypher
:param unencryptedMessage (string)
:param key (int) The offset to be used for the caesar cypher
:return (string) The encrypted message
1. Create a result string
2. Loop through each character of the unencryptedMessage
3. Convert to the ASCII Value
4. Subtract 32
5. Add the key
6. Modularly divide by (126 - 32) to shift back to a valid range
7. Add 32 back to the number
8. Convert back to a character
9. Append onto the end of the result string
10. Return the result string
"""
result = ''
index = 0
while index < len(unencryptedMessage):
ascii_val = ord(unencryptedMessage[index]) - 32 + key
ascii_val = ascii_val % (126 - 32)
ascii_val += 32
result = result + chr(ascii_val)
index += 1
return result
print(password_encrypt("Hi",5))
<file_sep>/Python/PycharmProjects_1718/Advanced_Python_Notes/Week3_Notes.py
# Playing Cards
import random
SUIT_NAMES = ['Clubs', 'Diamonds', 'Hearts', 'Spades']
RANK_NAMES = [None, 'Ace', '2', '3', '4', '5', '6', '7', '8', '9',
'10', 'Jack', 'Queen', 'King']
class Card:
"""A single playing card.
Attributes:
suit: integer 0-3
rank: integer 1-13
"""
def __init__(self, rank, suit):
"""Initialize the card.
:param rank: an integer 1-13 representing the rank
:param suit: an integer 0-3 representing the suit
"""
if rank < 1 or rank > 13:
raise ValueError("[ rank must be in range 1-13 ]")
if suit < 0 or suit > 3:
raise ValueError("[ suit must be in range 0-3 ]")
self.rank = rank
self.suit = suit
def to_string(self):
"""Return a human readable string representation of the card."""
return f'{RANK_NAMES[self.rank]} of {SUIT_NAMES[self.suit]}'
class Deck:
"""A deck of playing cards.
Attributes:
cards: list of playing cards
"""
def __init__(self):
"""Initialize a deck of playing cards.
Deck is not shuffled on initialization.
"""
self.cards = []
for suit in range(len(SUIT_NAMES)):
for rank in range(1, len(RANK_NAMES)):
card_to_add = Card(rank, suit)
self.cards.append(card_to_add)
def is_empty(self):
"""Return if the deck is empty or not.
:return Boolean
"""
if len(self.cards) == 0:
return True
else:
return False
def draw_card(self):
"""Remove and return the top of the deck.
:return Card
"""
return self.cards.pop()
def shuffle(self):
"""Shuffle the cards in the deck."""
random.shuffle(self.cards)
class Hand:
"""A player's hand.
Attributes:
cards: list of cards in the hand
"""
def __init__(self):
"""Initialize hand to be empty."""
self.cards = []
def draw_card(self):
"""Remove and return the top of the hand.
:return Card
"""
return self.cards.pop()
def shuffle(self):
"""Shuffle the cards in the hand."""
random.shuffle(self.cards)
def add_card(self, card):
"""Add a card to the top of the hand.
:param card: Card to add
"""
self.cards.append(card)
def is_empty(self):
"""Return if the hand is empty or not.
:return Boolean
"""
if len(self.cards) == 0:
return True
else:
return False
def main():
deck = Deck()
for card in deck.cards:
print(card.to_string())
if __name__ == "__main__":
main()
<file_sep>/Python/PycharmProjects_1819/Week 4 Programming Assignment/Grade_Percentage.py
grade_percentage = int(input("Please enter your grade percentage: "))
# A+'s don't exist at Champlain
if grade_percentage >= 93:
# if the grade is greater than or equal to 93
print("Your letter grade is an A.")
elif grade_percentage >= 90 and grade_percentage <= 92:
# if the grade is or between 90 and 92
print("Your letter grade is an A-.")
elif grade_percentage >= 87 and grade_percentage <= 89:
# if the grade is or between 87 and 89
print("Your letter grade is a B+.")
elif grade_percentage >= 83 and grade_percentage <= 86:
# if the grade is or between 83 and 86
print("Your letter grade is a B.")
elif grade_percentage >= 80 and grade_percentage <= 82:
# if the grade is or between 80 and 82
print("Your letter grade is a B-.")
elif grade_percentage >= 77 and grade_percentage <= 79:
# if the grade is or between 77 and 79
print("Your letter grade is a C+.")
elif grade_percentage >= 73 and grade_percentage <= 76:
# if the grade is or between 73 and 76
print("Your letter grade is a C.")
elif grade_percentage >= 70 and grade_percentage <= 72:
# if the grade is or between 70 and 72
print("Your letter grade is a C-.")
elif grade_percentage >= 67 and grade_percentage <= 69:
# if the grade is or between 67 and 69
print("Your letter grade is a D+.")
elif grade_percentage >= 63 and grade_percentage <= 66:
# if the grade is or between 63 and 66
print("Your letter grade is a D.")
elif grade_percentage >= 60 and grade_percentage <= 62:
# if the grade is or between 60 and 62
print("Your letter grade is a D-.")
elif grade_percentage < 60:
# if the grade is less than 60
# (Could have also made this statement just an 'else' statement)
print("Your letter grade is a F.")<file_sep>/Python/PycharmProjects_1819/Advanced_Python_Notes/Week11_Notes.py
class SillyLength:
def __len__(self):
return 42
class CustomInt(int):
def __len__(self):
return len(str(self))
def __getitem__(self, item):
return str(self)[item]
# or
# string_version = str(self)
# character = string_version[item]
# return int(character)
# if __name__ == "__main__":
# print(len("hello")) # string
# print(len((1, 2, 3, 4))) # tuple
#
# # dictionary
# my_dict = {"a": 24, "b": 42}
# print(len(my_dict))
# print(my_dict["a"])
#
# # list
# my_list = ([1, 2, 3, 4, 1, 2, 3])
# my_list.append(5)
# print(len(my_list))
# print(my_list)
#
# # set (for finding unique values)
# my_set = set([10, 1, 2, 3, 4, 1, 2, 3, 1, 1, 1, 1])
# my_set.add(5)
# print(len(my_set))
# print(my_set)
# print(5 in my_set)
# obj = SillyLength()
# print(len(obj))
#
# x = CustomInt(500)
# print(x)
# print(len(x))
# print(x[0]) # the same as print (x.__getitem__(0))
# --------------------------------------------------------
def do_something(value1, value2, value3=3):
print(value1, value2, value3)
def do_something_else(values_list):
print(*values_list)
if __name__ == "__main__":
values = [10, 20, 30]
# do_something(*values) # the same as do_something(values[0], values[1], values[2])
values2 = [100, 200]
# do_something(*values2)
do_something_else(values)
<file_sep>/Python/PycharmProjects_1819/Class Notes/Week8_Notes.py
"""
sequential search = start at the beginning
binary search = ordered list and a more faster/efficient way, calculates the midpoint, evaluate search item,determines direction, starts search
if you know the list is ordered use binary, other than that use sequential (may turn up errored results)
"""
'''
# Sequential Search Program
from random import randint
search_data = [i for i in range(1, 101)]
search_item = randint(1, 100)
finder = 0
for i in search_data:
if i
if finder == 0:
print("The value of " + str(search_item) + " is not in the list ")
else:
print("The value of " + str(search_item) + " is in the list.")
'''
# Binary Search Program
# Found in http://interactivepython.org/runestone/static/pythonds/SortSearch/TheBinarySearch.html
def binarySearch(alist, item):
# The function has two placeholders
first = 0 # to accept values when the function is called
last = len(alist)
found = False # assume the search criteria is not found
while first <= last and not found:
midpoint = (first + last) // 2
if alist[midpoint] == item:
found = True # If the search value is found then the variable 'found'
# has its value changed from 'False' to 'True'
else:
if item < alist[midpoint]:
last = midpoint - 1
else:
first = midpoint + 1
return found # This has the function return a 'false' or a value of 0
'''
find = 8
testlist = [0, 1, 2, 8, 13, 17, 19, 32, 42]
search = binarySearch(testlist, find)
# if
if search == True:
print("The value " + str(find) + " was found.")
else:
print("The value " + str(find) + " was found in the list.")
'''
# Example
finder = 0
letters = ['D', 'J', 'k', 'l', 'E', 'f', 'L', 'c', 'G', 'h', 'i']
ltr = 'd'
for i in letters:
if i == ltr:
finder = i
break
else:
continue
'''
if finder == 0:
print("The value of " + ltr + " was not found.")
else:
print("The value of " + ltr + " was in the list.")
order_letters = letters
order_letters.sort(key=str.lower)
'''
# Example
search_letters = [ord(i) for i in letters]
user_input = input("Enter a letter you wish to search dor in the list: ")
ascii_equiv = ord(user_input)
def binarySearch2(alist, item):
first = 0 # to accept values when the function is called
last = len(alist)
found = False # assume the search criteria is not found
while first <= last and not found:
midpoint = (first + last) // 2
if alist[midpoint] == item:
found = True # If the search value is found then the variable 'found'
# has its value changed from 'False' to 'True'
else:
if item < alist[midpoint]:
last = midpoint - 1
else:
first = midpoint + 1
return found # This has the function return a 'false' or a value of 0
searching = binarySearch2(search_letters, ascii_equiv)
if finder == 0:
print("The value of " + chr(ascii_equiv) + " was not found.")
else:
print("The value of " + chr(ascii_equiv) + " was in the list.")
<file_sep>/Python/PycharmProjects_1819/Loops_Assignment/countdown.py
# 'while' loop countdown
count = 10
while count >= 0:
print(count)
count -= 1
print(" ")
# Give space between the outputs of the different countdown loops
# 'for' loop countdown
for x in range(10, -1, -1):
print(x)
<file_sep>/Python/PycharmProjects_1819/Week13_Lab/user_interface.py
"""User Interface for medical database.
Prof. <NAME>
Champlain College
CSI-260 -- Spring 2019
"""
import models
def add_doctor():
"""User Interface for adding a new doctor to the database."""
params = dict()
params['first_name'] = input('First Name? ')
params['last_name'] = input('Last Name? ')
params['primary_office'] = input('Primary Office? ')
new_doc = models.Doctor(**params)
new_doc.save()
def add_patient():
"""User Interface for adding a new patient to the database."""
params = dict()
params['first_name'] = input('First Name? ')
params['last_name'] = input('Last Name? ')
params['address'] = input('Address? ')
params['phone_number'] = input('Phone Number? ')
params['emergency_contact'] = input('Emergency Contact? ')
params['emergency_phone'] = input('Emergency Phone? ')
response = input('Do you want to assign a primary care doctor (Y/N)? ')
if response.lower() in ('y', 'yes'):
params['primary_care_doctor'] = pick_primary_care_doctor()
new_patient = models.Patient(**params)
new_patient.save()
def pick_primary_care_doctor():
"""User Interface for selecting a primary care doctor.
Return: A Doctor object. Returns None if no doctor selected.
"""
doc_name = input('Identify a Doctor by last name or press enter to '
'display all doctors? ')
if doc_name:
docs = models.Doctor.select().where(models.Doctor.last_name
== doc_name)
else:
docs = models.Doctor.select()
if docs.count() > 1:
for i, doc in enumerate(docs):
print(f'{i}. Dr. {doc.first_name} {doc.last_name}')
while True:
doc_choice = input('Choose by number? ')
try:
return(docs[int(doc_choice)])
except (IndexError, ValueError):
print('Invalid choice')
elif docs.count() == 1:
print('Only one matching Doctor found')
print(f'Assigning Dr. {docs[0].first_name} '
f'{docs[0].last_name} to patient')
return docs[0]
else:
print('No doctor found with that name.')
response = input('Skip choosing primary care doctor (Y/N)')
if response.lower() in ('y', 'yes'):
return None
return pick_primary_care_doctor()
def add_procedure():
"""User interface for adding a procedure to the database."""
params = dict()
params['name'] = input('Procedure Name? ')
params['min_cost'] = input('Minimum Cost? ')
params['max_cost'] = input('Maximum Cost? ')
params['pre_procedure_checklist'] = input('Pre-Procedure Checklist? ')
new_procedure = models.Procedure(**params)
new_procedure.save()
def add_performed_procedures():
"""User interface to add performed procedures to database."""
params = dict()
params['patient'] = input('Patient? ')
params['doctor'] = input('Doctor? ')
params['procedure'] = input('Procedure Name? ')
params['procedure_date'] = input('Procedure Date? ')
params['notes'] = input("Notes? ")
new_performed_procedures = models.PerformedProcedure(**params)
new_performed_procedures.save()
if __name__ == "__main__":
DONE = "done"
menu_dict = {'1': add_doctor,
'2': add_patient,
'3': add_procedure(),
'4': add_performed_procedures(),
'5': None,
'6': None,
'7': None,
'8': DONE}
menu = """
1. Add Doctor
2. Add Patient
3. Add Procedure
4. Add Performed Procedure
5. Lookup a patient's medical records
6. Add a medication to the list of available prescriptions
7. Assign a medication to a patient
8. Quit
Choose:
"""
while True:
user_choice = input(menu)
if user_choice in menu_dict and menu_dict[user_choice]:
if menu_dict[user_choice] == DONE:
break
menu_dict[user_choice]()
else:
print('Not a valid choice')
<file_sep>/Python/PycharmProjects_1718/Week 4 Programming Assignment/Number_Sum.py
num_input1 = int(input("Enter a number: "))
num_input2 = int(input("Enter another number: "))
num_sum = num_input1 + num_input2
# sum of the two number inputs
if num_sum > 100:
# If the sum of the two number inputs is greater than 100
print("They add up to a big number.")
elif num_sum <= 100:
# If the sum of the two number inputs is less than or equal to 100
# (Could have also made this just an else statement)
print("They add up to " + str(num_sum) + ".")<file_sep>/AutomationScripting/Bash/Week10/menu.bash.save
#!/bin/bash
# Admin and Security admin menu.
# Admin Menu function
function admin_menu() {
# Clear the screen
clear
# Create menu options
echo "1. List Running Processes"
echo "2. Show Open Network Sockets"
echo "3. Check currently logged in users"
echo "[E]xit"
# Prompt for the menu option
echo -n "Please enter a value above"
#Read in the user input
read option
# Case statement to process options
case "${option}" in
1) ps -ef | less
;;
2)
lsof -i -n | less netstat -an --inet | less
;;
3) w | less
;;
"[Ee]") exit 0
;;
*) echo "| Invalid Option |"
sleep 3
admin_menu
;;
# Stops the case statement
esac
# Show admin menu
admin_menu
}
# Main Menu
# Clear the screen
# Create menu options
# Prompt for the menu option and read in the option
<file_sep>/Python/Python Assignments/squareEach.py
def squareEach(nums):
for ctr in range(len(nums)):
nums[ctr] **= 2
return nums
def squareEachNew(nums):
newList = []
for num in nums:
newList.append(num**2)
return newList
nums = [1,2,3,4,5]
print(squareEachNew(nums))
<file_sep>/Python/PycharmProjects_1819/Advanced_Python_Notes/Week12_Notes.py
# class MyClass:
# def __init__(self, value):
# self.value = value
#
# def __str__(self):
# return f"MyClass instance with value {self.value}"
#
# def __lt__(self, other):
# print("in __lt__")
# return self.value < other
# # or
# # return self.value > other # other.__gt__(self.value)
#
# def __gt__(self, other):
# print("in __gt__")
# return self.value > other
# # or
# # return self.value < other # other.__lt__(self.value)
#
#
# if __name__ == "__main__":
# obj1 = MyClass(15)
# obj2 = MyClass("hello")
# print(obj1 < obj2) # this is the same as print(obj1.__lt__(obj2)
# print(obj1 > obj2) # this is the same as print(obj1.__gt__(obj2)
# print(obj1 < 20)
# def print_repeatedly(thing, *args, n=1, **kwargs):
# for _ in range(n):
# print(thing, *args, **kwargs)
#
#
# if __name__ == "__main__":
# print_repeatedly('hello', 'world', 'ok', 'more words', n=10, sep="+", end="\n\n\n")
def print_count(*args):
print(len(args))
def do_repeatedly(function, *args, n=1, **kwargs):
for _ in range(n):
function(*args, **kwargs)
def square(x):
return x**2
def cube(x):
return x**3
def apply_to_all(function, values):
return [function(value) for value in values]
if __name__ == "__main__":
# do_repeatedly(print_count, 'hello', 'world', n=3)
print(apply_to_all(lambda x: x**2, [1, 2, 3]))
<file_sep>/Python/PycharmProjects_1819/Week3_Lab/week3_tests.py
"""Tests for Week 3 Lab.
Prof. <NAME>
Champlain College
CSI-260 -- Spring 2019
"""
import unittest
import sys
week3 = None
try:
import week3
except ImportError:
pass # swallow the error here, will be reported in test_1
STUDENT_CODE = ["week3.py"]
class TestWeek3(unittest.TestCase):
"""Main testing class for Week 3 Lab."""
def test_1_module_exists(self):
"""Test if the week3 module exists."""
self.assertIsNotNone(week3,
"Cannot import week3, make sure week3.py exists "
"in this directory.")
def test_2_class_exists(self):
"""Test if the week3 module contains a class Country."""
self.assertIn("Country", week3.__dict__,
"You must define a class called Country in week3.py.")
self.assertIsInstance(week3.Country, type, "Country is not a class!")
def _initializer_test_helper(self, args):
try:
country = week3.Country(args["name"], args["population"],
args["area"])
except TypeError:
country = None
self.assertIsNotNone(country,
"You must define an initializer on Country that "
"takes name, population, and area as arguments.")
for var in args:
self.assertIn(var, country.__dict__,
"The initializer for Country must initialize member "
f"variable {var}.")
self.assertEqual(country.__dict__[var], args[var],
f"The initializer for Country must initialize "
f"member variable {var} to the provided "
f"value.")
def test_3_initializer(self):
"""Test that the Country initializer functions properly."""
arg_sets = [{"name": "test country",
"population": 1000,
"area": 200001},
{"name": "another test country",
"population": 100234530,
"area": 200034501}]
for args in arg_sets:
self._initializer_test_helper(args)
def _init_countries(self):
return [week3.Country("Kingdom of Awesome", 10, 2),
week3.Country("Beautiful Land", 1, 10),
week3.Country("Chromeria", 1000, 1)]
def test_4_is_larger(self):
"""Test that the is_larger method functions properly."""
self.assertIn("is_larger", week3.Country.__dict__,
"Country must define a method 'is_larger'.")
countries = self._init_countries()
self.assertTrue(countries[0].is_larger(countries[2]),
"Country.is_larger must return True if the calling "
"Country is larger than the provided Country.")
self.assertFalse(countries[0].is_larger(countries[0]),
"Country.is_larger must return False if the calling "
"Country is not larger than the provided Country.")
self.assertFalse(countries[0].is_larger(countries[1]),
"Country.is_larger must return False if the calling "
"Country is not larger than the provided Country.")
def test_5_population_density(self):
"""Test that the population_density method functions properly."""
self.assertIn("population_density", week3.Country.__dict__,
"Country must define a method 'population_density'.")
countries = self._init_countries()
for country in countries:
self.assertEqual(country.population_density(),
country.population / country.area,
"Country.population_density must return the "
"population density of the calling Country.")
def test_6_summary(self):
"""Test the the summary method functions properly."""
countries = self._init_countries()
self.assertIn("summary", week3.Country.__dict__,
"Country must define a method 'summary'.")
expected_results = """\
Kingdom of Awesome has a population of 10 people and is 2 square km. \
It therefore has a population density of 5.0000 people per square km.
Beautiful Land has a population of 1 people and is 10 square km. \
It therefore has a population density of 0.1000 people per square km.
Chromeria has a population of 1000 people and is 1 square km. \
It therefore has a population density of 1000.0000 people per square km."""
for country, expected_result in zip(countries,
expected_results.split("\n")):
summary = country.summary()
self.assertEqual(summary, expected_result,
f"Calling summary on '{country.name}' returned "
f"'{summary}', but "
f"should return '{expected_result}')")
def test_7_style(self):
"""Run the linter and check that the header is there."""
try:
from flake8.api import legacy as flake8
# noqa on the following since just importing to test installed
import pep8ext_naming # noqa
import flake8_docstrings # noqa
print("\nLinting Code...\n" + "=" * 15)
style_guide = flake8.get_style_guide()
report = style_guide.check_files(STUDENT_CODE)
self.assertEqual(report.total_errors, 0,
"You should fix all linting errors "
"before submission in order to receive full "
"credit!")
for module in STUDENT_CODE:
self.check_header(module)
print("Passing linter tests!")
except ImportError:
print("""
### WARNING: Unable to import flake8 and/or extensions, so cannot \
properly lint your code. ###
Please install flake8, pep8-naming, and flake8-docstrings to auto-check \
whether you are adhering to proper style and docstring conventions.
To install, run:
pip install flake8 pep8-naming flake8-docstrings
""")
def check_header(self, module):
"""Check the header of the given module."""
docstring = sys.modules[module[:-3]].__doc__
for check in ['Author:', 'Class:', 'Assignment:',
'Certification of Authenticity:']:
self.assertIn(check, docstring,
"Missing '{}' in {}'s docstring".format(
check, module))
if __name__ == '__main__':
unittest.main(failfast=True)
<file_sep>/Python/PycharmProjects_1819/Week 4 Programming Assignment/Random_Num.py
# from random import randint
# # import [random] module
# random_num = randint(0, 9)
#
# while True:
# guess = int(input("Guess a number between 0 and 9: "))
#
# if random_num == guess:
# # If the random number chosen by the module is the same as the guess input from the user
# print("You guessed right!")
# else:
# # If the random number chosen by the module is NOT the same as the guess input from the user
# print("Oops, you guessed wrong.")
#
# try_again = input("Would you like to try again? Enter 'YES' or 'NO'")
# if try_again == 'YES':
# True
# else:
# break
# or
from random import randint
random_num = randint(0, 10)
for x in range(3):
guess = int(input("Guess a number between 0 and 10: "))
if random_num == guess:
print("You guessed right!")
try_again = input("Would you like to try again? Enter 'YES' or 'NO'")
if try_again == 'YES':
True
else:
break
elif random_num < guess:
print("Oops, you guessed too high.")
elif random_num > guess:
print("Oops, you guessed too low.")
print("Oops, you ran out of guesses.")<file_sep>/Python/PycharmProjects_1819/Advanced_Python_Notes/Week4_Notes.py
class Employee:
num_employees = 0
raise_amount = 1.05
def __init__(self, first_name, last_name, salary):
"""Initialize an Employee with given names and salary."""
self.first_name = first_name
self.last_name = last_name
self.salary = salary
Employee.num_employees += 1 # it would be global.-- if variable was outside class
self.id = Employee.num_employees
def apply_raise(self):
self.salary = self.salary * self.raise_amount
@classmethod
def increase_raise_amount(cls, percentage):
cls.raise_amount += percentage # if @staticmethod, have to hard code Employee.raise_amount
def main():
john = Employee("John", "Smith", 45000)
jane = Employee("Jane", "Doe", 60000)
jane.raise_amount = 1.1
jane.apply_raise()
print(john.__dict__)
print(jane.__dict__)
if __name__ == "__main__":
main()
<file_sep>/AutomationScripting/Bash/Week14/apache-parse.bash
#!/bin/bash
# Parse an apache web Log
# Read in the file from the commandline
# Arguments using the position. Arguments start at $1.
APACHE_LOG="$1"
# check if the logfile exists
if [[ ! -f ${APACHE_LOG} ]]
then
echo "Please specify the path to a log file."
exit 1
fi
# Parse iptables Log
sed -e "s/\[//g" -e "s/\"//g" ${APACHE_LOG} | \
awk ' BEGIN { format = "%-16s %-25s %-8s %-8s %-9s %-50s %-50s \n"
printf format, "IP", "Date", "Method", "Status", "Size", "URI", "UA"
printf format, "---------------", "---------------", "-------", "-------", "-----", "------", "------"}
{
if ($12 == "-") {
# print the results
printf format, $1, $4, $6, $9, $10, $7, "No User Agent"
} else {
# Start at field $12
start = 12
# Initialize an empty variable which is a placeholder for $12 (called msg)
# Start at field $12 using the "start" variable
# Count the number of fields left in the line
msg = ""; for (i = start; i <= NF; i++)
# Start the user agent formatting
# Print from field $12 until the end of the line
msg = msg " " $i;
# print the results with the user agent
printf format, $1, $4, $6, $9, $10, $7, msg
}
}'
<file_sep>/Python/PycharmProjects_1819/Week8_Lab/temperature.py
"""Classes for working with Temperatures of different values.
Author: <NAME>
Class: CSI-260-02
Assignment: Week 8 Lab
Due Date: March 17, 2019 11:59 PM
Certification of Authenticity:
I certify that this is entirely my own work, except where I have given
fully-documented references to the work of others. I understand the definition
and consequences of plagiarism and acknowledge that the assessor of this
assignment may, for the purpose of assessing this assignment:
- Reproduce this assignment and provide a copy to another member of academic
- staff; and/or Communicate a copy of this assignment to a plagiarism checking
- service (which may then retain a copy of this assignment on its database for
- the purpose of future plagiarism checking)
"""
NUMBERS = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0']
LETTERS = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd',
'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x',
'y', 'z']
class TemperatureError(Exception):
"""Raises Error if degrees is not one of the specified forms."""
def __init__(self, degrees):
"""Initialize exception with given username.
Can optionally provide a user instance as well.
"""
super().__init__(degrees)
self.degrees = degrees
def __str__(self):
"""Provide a string representation of the error."""
return f'Invalid Value: {self.degrees}'
class Temperature:
"""Represents a temperature.
Temperatures are expressable in degrees Fahrenheit, degrees Celsius,
or Kelvins.
"""
def __init__(self, degrees=0):
"""Initialize temperature with specified degrees.
Args:
degrees, which can be one of the following:
(1) a number, or a string containing a number
in which case it is interpreted as degrees Celsius
(2) a string containing a number followed by one of the
following symbols:
C, in which case it is interpreted as degrees Celsius
F, in which case it is interpreted as degrees Fahrenheit
K, in which case it is interpreted as Kelvins
Raises:
InvalidTemperatureError: if degrees is not one of the specified
forms
"""
if type(degrees) is int or type(degrees) is float:
self._celsius = float(degrees)
elif type(degrees) is str:
if degrees[-1] == 'C' and degrees[-2] != 'C':
self._celsius = float(degrees[:-1])
elif degrees[-1] == 'F':
fahrenheit = float(degrees[:-1])
self._celsius = ((fahrenheit - 32) * (5/9))
elif degrees[-1] == 'K':
kelvin = float(degrees[:-1])
self._celsius = (kelvin - 273.15)
elif degrees in NUMBERS:
self._celsius = float(degrees)
elif degrees[0] == '-':
self._celsius = float(degrees)
elif (degrees[0] in LETTERS) or (degrees[-1] != 'C') or \
(degrees[-1] != 'F') or (degrees[-1] != 'K'):
raise TemperatureError(degrees)
elif type(degrees) is not str or int:
raise TemperatureError(degrees)
self._degrees = degrees
@property
def celsius(self):
"""Degrees Celsius Property."""
return self._celsius
@celsius.setter
def celsius(self, celsius):
self._degrees = celsius
@property
def fahrenheit(self):
"""Degrees Fahrenheit Property to convert Celsius to Fahrenheit."""
return (self._celsius * (9/5)) + 32
@fahrenheit.setter
def fahrenheit(self, fahrenheit):
self._degrees = fahrenheit
@property
def kelvin(self):
"""Degrees Kelvin Property to convert Celsius to Kelvin."""
return self._celsius + 273.15
@kelvin.setter
def kelvin(self, kelvin):
self._degrees = kelvin
@classmethod
def average(cls, temperatures):
"""Compute the average of a list of temperatures.
Args:
temperatures: a list of Temperature objects
Returns:
a Temperature object with average (mean) of the given temperatures
"""
total = 0
for temp in temperatures:
temp = Temperature(temp).celsius
total = total + temp
return total / len(temperatures)
<file_sep>/Python/Python Assignments/Area.py
def rectangle():
length = input("Enter the length of the rectangle: ")
width = input("Enter the width of the rectangle: ")
area = int(length)*int(width)
print('The area of the rectangle is ', area)
rectangle()
<file_sep>/Python/PycharmProjects_1819/Advanced_Python_Notes/Week10_Notes.py
# shapes.py (review on multiple inheritances)
import abc
import math
class Shape(abc.ABC):
"""Shape abstract base class that other class will implement from."""
def __init__(self, color):
"""Create a shape of a specified color."""
self.color = color
@abc.abstractmethod
def get_area(self):
"""Return the area of this shape.
This must be implemented by all concrete subclasses.
"""
pass
class Circle(Shape):
"""Circle is a concrete extension of Shape.
attributes:
color: string
radius: number
"""
def __init__(self, color, radius):
"""Create a circle of specified color and radius."""
super().__init__(color)
self.radius = radius
@property
def get_area(self):
"""Return the area of this circle."""
return math.pi * self.radius ** 2
def __str__(self):
return f"A {self.color} circle with radius {self.radius} and area {self.get_area}"
# code representation of string (python readable)
def __repr__(self):
return f"Circle({self.color!r}, {self.radius})"
def __add__(self, other):
try:
return Circle(self.color + "-" + other.color, self.radius + other.radius)
except AttributeError:
return Circle(self.color, self.radius + other)
def __radd__(self, other):
return self + other
if __name__ == "__main__":
circle = Circle("red", 5)
circle2 = Circle("green", 9)
print(f'circle: {circle}')
print(f'repr: {circle!r}')
circle3 = circle + circle2 # same as circle3 = circle.__add__(circle2)
print(circle3)
circle4 = circle + 10 # same as circle4 = circle.__add__(10
print(circle4)
circle5 = circle2 + circle
print(circle5)
circle6 = 10 + circle5
# __eq__ = equality
# __lt__ = less than
# __le__ = less than or equal to
# __gt__ = greater than
# __ge__ + greater than or equal to
<file_sep>/Python/PycharmProjects_1819/Week 10 Programming Assignment/Part1.py
import string
user_string = input("Submit text here: ")
user_string = user_string.lower() # changes all uppercase letter to lowercase
user_string = user_string.replace(' ', '') # deletes all the whitespace by replacing the spaces with non-spaces
for x in string.punctuation:
user_string = user_string.replace(x, '')
# this loop goes through each punctuation character and removes it from the string
# by replacing it with nothing (the empty quotations)
print(user_string)
<file_sep>/Python/PycharmProjects_1718/Class Notes/Week11_Notes.py
import csv
import sys
menu_text = "" \
"\nWhat would you like to do:" \
"\n(1) Find a customer" \
"\n(2) Remove a duplicate record" \
"\n(3) Add a customer" \
"\n(4) Quit the program" \
""
def search_customer(cfn, cln):
with open('customer_data.csv', 'r') as csv_file: # Open the file in 'read' mode
csv_reader = csv.reader(csv_file) # Create a variable 'csv_reader', pass file contents to it
counter = 0
for line in csv_reader: # reading EVERY line of data in the file
if line[1] == cfn and line[2] == cln: # Once the first and last name in the variables match a line
# in the file, we get the email address of that customer
print("E-mail Address of " + cfn + " " + cln + ": " + line[3]) # email address is shown here
counter += 1
if counter > 1:
print("\nThe customer " + cfn + " " + cln + " appears " + str(counter) + " times in the file.")
def delete_customer():
'''
cfn = input("\nPlease enter the customer's first name: ")
cln = input("Please enter the customer's last name: ")
with open('customer_data.csv', 'r') as csv_file: # Open the file in 'read' mode
csv_reader = csv.reader(csv_file) # Create a variable 'csv_reader', pass file contents to it
counter = 0
for line in csv_reader: # reading EVERY line of data in the file
if line[1] == cfn and line[2] == cln: # Once the first and last name in the variables match a line
# in the file, we get the email address of that customer
if counter == 0:
print("E-mail Address of " + cfn + " " + cln + ": " + line[3]) # email address is shown here
counter += 1
elif counter > 1:
with open('customer_delete.csv', 'w') as bye_data: # Open the file in 'write' mode
csv_writer = csv.writer(bye_data)
csv_writer.writerow(line)
'''
cfn = input("\nPlease enter the customer's first name: ")
cln = input("Please enter the customer's last name: ")
cem = input("Please enter the customer's e-mail address: ")
with open('customer_data.csv', 'r') as bye_data, open('customer_delete.csv', 'w') as data_out:
writer = csv.writer(data_out)
counter = 0
for row in csv.reader(bye_data):
if row[1] == cfn and row[2] == cln and row[3] == cem and counter == 0:
counter += 1
elif row[1] == cfn and row[2] == cln and row[3] == cem and counter == 1:
writer.writerow(row)
else:
print("| System Failure | Please Try Again |")
def add_customer():
cid = input("\nCustomer ID: ")
cfn = input("Customer's first name: ")
cln = input("Customer's last name: ")
cem = input("Customer's e-mail address: ")
file_data = [cid, cfn, cln, cem]
with open('customer_data.csv', 'r') as csv_file: # Open the file in 'read' mode
csv_reader = csv.reader(csv_file) # create a variable 'csv_reader', pass the file contents to it
for line in csv_reader: # reading every line of data in the file
if line[0] == cid and line[1] == cfn and line[2] == cln and line[3] == cem:
print("| The Customer is Already in the Database |")
else:
break
with open('customer_data.csv', 'a') as write_file:
writer = csv.writer(write_file)
writer.writerow(file_data)
print("| Customer Added |")
def user_input(): # This function will allow a user to identify a customer for search
cfn = input("\nPlease enter the customer's first name: ")
cln = input("Please enter the customer's last name: ")
return search_customer(cfn, cln) # Pass the values of the user's input to a function call
# Return the results variable
while True:
print(menu_text)
choice = input("Please enter an option: ")
if choice == '1':
user_input()
elif choice == '2':
delete_customer()
elif choice == '3':
add_customer()
elif choice == '4':
sys.exit()
else:
print("\n| Please re-enter an option |")
<file_sep>/AutomationScripting/Bash/Week11/apacheParse.bash
#!/bin/bash
# Parse log
# 192.168.3.11 - - [24/Oct/2017:04:11:14 -0500] "GET / HTTP/1.1" 200 225 "-"
# "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko)
# Chrome/27.0.1453.94 Safari/537.36"
#Read in file
#Arguments using the position, they start at $1
APACHE_LOG="$1"
#check if file exists
if [[ ! -f ${APACHE_LOG} ]]
then
echo "Please specify the path to a log file."
exit 1
fi
# Use sed to remove the extraneous characters [ and "
sed -e "s/\[//g" -e "s/\"//g" ${APACHE_LOG}
# Then search for known bad stuff in our log file
# Then use awk to create a header for columns
# Then create a purdy report.
<file_sep>/Python/PycharmProjects_1718/Advanced_Python_Notes/Week5_PracticeProblems.py
class Shape:
def __init__(self, color):
self.color = color
def get_area(self):
return None
class Circle:
def __init__(self, radius, color):
super().__init__(color)
self.radius = radius
class Rectangle:
def __init__(self, length, width, color):
super().__init__(color)
self.length = length
self.width = width
def main():
"""Simple tests for Shape, Circle, and Rectangle classes."""
shape = Shape("blue")
circle = Circle(2.5, "red")
rectangle = Rectangle(3.5, 10.0, "green")
print(f"A {shape.color} generic shape has area {shape.get_area()}")
print(f"A {circle.color} circle with radius {circle.radius} "
f" has area {circle.get_area():.4f}")
print(f"A {rectangle.color} rectangle with length {rectangle.length} and "
f"width {rectangle.width} has area {rectangle.get_area():.4f}")
if __name__ == "__main__":
main()
<file_sep>/Python/PycharmProjects_1819/Advanced_Python_Notes/Week1_PracticeProblems.py
# Practice 1
'''
values = [i for i in range(1, 1001) if i % 7 == 0]
# or
# for i in range(0, 1001):
# if i % 7 == 0:
# values.append(i)
print(values)
'''
# Practice 2
'''
values = [i for i in range(1, 1001) if '3' in str(i)]
print(values)
'''
# Practice 3
'''
VOWELS = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
statement = input("Enter a sentence: ")
no_vowel = ''.join([letter for letter in statement if letter not in VOWELS])
print(no_vowel)
'''
# Practice 4
'''
statement = input("Enter a sentence: ")
words = statement.split(" ")
list_words = [word for word in words if len(word) < 4]
print(list_words)
'''
# Practice 5
statement = input("Enter a sentence: ")
words = statement.split(" ")
stuff = {word: len(word) for word in words}
print(stuff)
<file_sep>/AutomationScripting/Powershell/week5/ips-bad-iptables.bash
access-list deny host 172.16.58.3
access-list deny host 192.168.127.12
access-list deny host 192.168.3.11
access-list deny host 192.168.127.12
access-list deny host 172.16.58.3
access-list deny host 172.16.17.32
access-list deny host 192.168.127.12
access-list deny host 172.16.31.10
access-list deny host 172.16.17.32
access-list deny host 172.16.17.32
access-list deny host 172.16.31.10
access-list deny host 172.16.31.10
access-list deny host 172.16.58.3
access-list deny host 192.168.127.12
access-list deny host 192.168.3.11
access-list deny host 172.16.17.32
access-list deny host 172.16.17.32
access-list deny host 192.168.3.11
access-list deny host 172.16.58.3
access-list deny host 192.168.3.11
access-list deny host 192.168.127.12
access-list deny host 192.168.127.12
access-list deny host 172.16.17.32
access-list deny host 172.16.58.3
access-list deny host 172.16.31.10
access-list deny host 192.168.3.11
access-list deny host 192.168.127.12
access-list deny host 172.16.58.3
access-list deny host 192.168.127.12
access-list deny host 192.168.3.11
access-list deny host 192.168.3.11
access-list deny host 172.16.31.10
access-list deny host 172.16.17.32
access-list deny host 192.168.127.12
access-list deny host 192.168.3.11
access-list deny host 172.16.58.3
access-list deny host 172.16.31.10
access-list deny host 172.16.17.32
access-list deny host 192.168.3.11
access-list deny host 172.16.17.32
access-list deny host 172.16.58.3
access-list deny host 172.16.58.3
access-list deny host 172.16.31.10
access-list deny host 172.16.17.32
access-list deny host 192.168.3.11
access-list deny host 192.168.127.12
access-list deny host 192.168.127.12
access-list deny host 192.168.127.12
access-list deny host 172.16.17.32
access-list deny host 172.16.58.3
access-list deny host 192.168.3.11
access-list deny host 192.168.3.11
access-list deny host 172.16.58.3
access-list deny host 192.168.3.11
access-list deny host 172.16.31.10
access-list deny host 172.16.31.10
access-list deny host 172.16.17.32
access-list deny host 192.168.127.12
access-list deny host 172.16.17.32
access-list deny host 172.16.17.32
access-list deny host 172.16.58.3
access-list deny host 192.168.3.11
access-list deny host 172.16.17.32
access-list deny host 192.168.3.11
access-list deny host 192.168.3.11
access-list deny host 172.16.17.32
access-list deny host 172.16.31.10
access-list deny host 192.168.3.11
access-list deny host 172.16.31.10
access-list deny host 192.168.127.12
access-list deny host 172.16.17.32
access-list deny host 172.16.17.32
access-list deny host 192.168.127.12
access-list deny host 172.16.58.3
access-list deny host 172.16.17.32
access-list deny host 192.168.3.11
access-list deny host 192.168.3.11
access-list deny host 192.168.3.11
access-list deny host 172.16.58.3
access-list deny host 172.16.17.32
access-list deny host 192.168.127.12
access-list deny host 192.168.127.12
access-list deny host 172.16.58.3
access-list deny host 172.16.31.10
access-list deny host 172.16.17.32
access-list deny host 172.16.31.10
access-list deny host 192.168.3.11
access-list deny host 172.16.31.10
access-list deny host 172.16.17.32
access-list deny host 172.16.17.32
access-list deny host 192.168.3.11
access-list deny host 192.168.127.12
access-list deny host 172.16.58.3
access-list deny host 192.168.127.12
access-list deny host 172.16.58.3
access-list deny host 172.16.58.3
access-list deny host 172.16.17.32
access-list deny host 172.16.17.32
access-list deny host 172.16.17.32
access-list deny host 172.16.17.32
access-list deny host 172.16.17.32
access-list deny host 192.168.3.11
access-list deny host 192.168.3.11
access-list deny host 172.16.31.10
access-list deny host 192.168.127.12
access-list deny host 172.16.58.3
access-list deny host 172.16.58.3
access-list deny host 172.16.31.10
access-list deny host 172.16.31.10
access-list deny host 192.168.3.11
access-list deny host 192.168.127.12
access-list deny host 192.168.3.11
access-list deny host 172.16.31.10
access-list deny host 172.16.31.10
access-list deny host 192.168.3.11
access-list deny host 172.16.31.10
access-list deny host 172.16.58.3
access-list deny host 172.16.58.3
access-list deny host 172.16.58.3
access-list deny host 192.168.3.11
access-list deny host 172.16.17.32
access-list deny host 172.16.58.3
access-list deny host 172.16.17.32
access-list deny host 192.168.3.11
access-list deny host 172.16.17.32
access-list deny host 172.16.58.3
access-list deny host 172.16.31.10
access-list deny host 172.16.17.32
access-list deny host 172.16.31.10
access-list deny host 172.16.31.10
access-list deny host 172.16.58.3
access-list deny host 192.168.127.12
access-list deny host 192.168.3.11
access-list deny host 172.16.31.10
access-list deny host 192.168.127.12
access-list deny host 172.16.58.3
access-list deny host 172.16.17.32
access-list deny host 172.16.58.3
access-list deny host 172.16.17.32
access-list deny host 172.16.31.10
access-list deny host 192.168.127.12
access-list deny host 192.168.127.12
access-list deny host 172.16.31.10
access-list deny host 172.16.17.32
access-list deny host 172.16.17.32
access-list deny host 172.16.17.32
access-list deny host 172.16.31.10
access-list deny host 172.16.17.32
access-list deny host 192.168.3.11
access-list deny host 172.16.58.3
access-list deny host 172.16.31.10
access-list deny host 172.16.17.32
access-list deny host 192.168.127.12
access-list deny host 192.168.127.12
access-list deny host 172.16.31.10
access-list deny host 192.168.3.11
access-list deny host 192.168.127.12
access-list deny host 172.16.17.32
access-list deny host 172.16.31.10
access-list deny host 192.168.127.12
access-list deny host 192.168.127.12
access-list deny host 192.168.3.11
access-list deny host 172.16.58.3
access-list deny host 172.16.17.32
access-list deny host 172.16.17.32
access-list deny host 172.16.17.32
access-list deny host 192.168.3.11
access-list deny host 192.168.127.12
access-list deny host 172.16.17.32
access-list deny host 172.16.17.32
access-list deny host 172.16.58.3
access-list deny host 192.168.3.11
access-list deny host 192.168.127.12
access-list deny host 172.16.58.3
access-list deny host 172.16.58.3
access-list deny host 172.16.58.3
access-list deny host 172.16.58.3
access-list deny host 172.16.17.32
access-list deny host 192.168.127.12
access-list deny host 172.16.31.10
access-list deny host 172.16.17.32
access-list deny host 172.16.58.3
access-list deny host 192.168.127.12
access-list deny host 192.168.127.12
access-list deny host 192.168.3.11
access-list deny host 172.16.58.3
access-list deny host 172.16.31.10
access-list deny host 172.16.31.10
access-list deny host 172.16.58.3
access-list deny host 172.16.31.10
access-list deny host 172.16.31.10
access-list deny host 172.16.58.3
access-list deny host 192.168.127.12
access-list deny host 172.16.31.10
access-list deny host 192.168.3.11
access-list deny host 192.168.127.12
access-list deny host 172.16.31.10
access-list deny host 172.16.58.3
access-list deny host 192.168.127.12
access-list deny host 172.16.31.10
access-list deny host 192.168.3.11
access-list deny host 172.16.31.10
access-list deny host 192.168.127.12
access-list deny host 192.168.3.11
access-list deny host 172.16.17.32
access-list deny host 172.16.31.10
access-list deny host 192.168.3.11
access-list deny host 172.16.58.3
access-list deny host 192.168.127.12
access-list deny host 172.16.58.3
access-list deny host 192.168.127.12
access-list deny host 172.16.58.3
access-list deny host 172.16.17.32
access-list deny host 172.16.58.3
access-list deny host 192.168.127.12
access-list deny host 192.168.3.11
access-list deny host 172.16.58.3
access-list deny host 192.168.127.12
access-list deny host 192.168.127.12
access-list deny host 192.168.127.12
access-list deny host 192.168.127.12
access-list deny host 192.168.127.12
access-list deny host 192.168.3.11
access-list deny host 172.16.17.32
access-list deny host 192.168.3.11
access-list deny host 172.16.31.10
access-list deny host 192.168.127.12
access-list deny host 172.16.58.3
access-list deny host 172.16.17.32
access-list deny host 192.168.3.11
access-list deny host 172.16.58.3
access-list deny host 172.16.31.10
access-list deny host 192.168.127.12
access-list deny host 172.16.17.32
access-list deny host 172.16.58.3
access-list deny host 192.168.3.11
access-list deny host 172.16.58.3
access-list deny host 172.16.58.3
access-list deny host 172.16.17.32
access-list deny host 172.16.17.32
access-list deny host 192.168.127.12
access-list deny host 192.168.127.12
access-list deny host 192.168.3.11
access-list deny host 192.168.3.11
access-list deny host 192.168.127.12
access-list deny host 192.168.3.11
access-list deny host 172.16.17.32
access-list deny host 172.16.17.32
access-list deny host 172.16.31.10
access-list deny host 172.16.31.10
access-list deny host 172.16.31.10
access-list deny host 172.16.17.32
access-list deny host 172.16.31.10
access-list deny host 192.168.127.12
access-list deny host 192.168.127.12
access-list deny host 172.16.58.3
access-list deny host 192.168.127.12
access-list deny host 192.168.3.11
access-list deny host 192.168.3.11
access-list deny host 172.16.31.10
access-list deny host 172.16.31.10
access-list deny host 172.16.31.10
access-list deny host 172.16.58.3
access-list deny host 192.168.127.12
access-list deny host 192.168.3.11
access-list deny host 172.16.58.3
access-list deny host 192.168.127.12
access-list deny host 192.168.3.11
access-list deny host 192.168.127.12
access-list deny host 172.16.58.3
access-list deny host 192.168.127.12
access-list deny host 172.16.58.3
access-list deny host 192.168.127.12
access-list deny host 172.16.17.32
access-list deny host 172.16.17.32
access-list deny host 172.16.17.32
access-list deny host 172.16.58.3
access-list deny host 192.168.127.12
access-list deny host 192.168.3.11
access-list deny host 172.16.17.32
access-list deny host 172.16.58.3
access-list deny host 172.16.58.3
access-list deny host 172.16.31.10
access-list deny host 172.16.31.10
access-list deny host 192.168.3.11
access-list deny host 192.168.127.12
access-list deny host 172.16.17.32
access-list deny host 192.168.3.11
access-list deny host 172.16.31.10
access-list deny host 192.168.3.11
access-list deny host 172.16.58.3
access-list deny host 172.16.17.32
access-list deny host 172.16.58.3
access-list deny host 172.16.17.32
access-list deny host 192.168.127.12
access-list deny host 192.168.127.12
access-list deny host 172.16.17.32
access-list deny host 192.168.127.12
access-list deny host 172.16.17.32
access-list deny host 172.16.31.10
access-list deny host 172.16.31.10
access-list deny host 192.168.127.12
access-list deny host 172.16.17.32
access-list deny host 192.168.3.11
access-list deny host 172.16.31.10
access-list deny host 172.16.31.10
access-list deny host 192.168.127.12
access-list deny host 192.168.127.12
access-list deny host 192.168.127.12
access-list deny host 172.16.58.3
access-list deny host 172.16.31.10
access-list deny host 192.168.3.11
access-list deny host 172.16.17.32
access-list deny host 192.168.127.12
access-list deny host 192.168.3.11
access-list deny host 172.16.31.10
access-list deny host 172.16.31.10
access-list deny host 172.16.17.32
access-list deny host 172.16.58.3
access-list deny host 192.168.127.12
access-list deny host 192.168.127.12
access-list deny host 172.16.31.10
access-list deny host 172.16.17.32
access-list deny host 172.16.17.32
access-list deny host 172.16.58.3
access-list deny host 172.16.17.32
access-list deny host 172.16.31.10
access-list deny host 172.16.58.3
access-list deny host 192.168.3.11
access-list deny host 192.168.127.12
access-list deny host 172.16.17.32
access-list deny host 192.168.3.11
access-list deny host 192.168.3.11
access-list deny host 172.16.31.10
access-list deny host 192.168.3.11
access-list deny host 192.168.127.12
access-list deny host 172.16.58.3
access-list deny host 192.168.3.11
access-list deny host 192.168.3.11
access-list deny host 172.16.58.3
access-list deny host 172.16.31.10
access-list deny host 172.16.17.32
access-list deny host 192.168.3.11
access-list deny host 172.16.31.10
access-list deny host 172.16.31.10
access-list deny host 172.16.58.3
access-list deny host 192.168.3.11
access-list deny host 192.168.127.12
access-list deny host 192.168.127.12
access-list deny host 192.168.127.12
access-list deny host 192.168.127.12
access-list deny host 172.16.17.32
access-list deny host 172.16.58.3
access-list deny host 172.16.58.3
access-list deny host 172.16.31.10
access-list deny host 192.168.127.12
access-list deny host 192.168.127.12
access-list deny host 172.16.17.32
access-list deny host 172.16.31.10
access-list deny host 192.168.127.12
access-list deny host 172.16.31.10
access-list deny host 172.16.17.32
access-list deny host 172.16.31.10
access-list deny host 192.168.3.11
access-list deny host 172.16.31.10
access-list deny host 192.168.3.11
access-list deny host 172.16.31.10
access-list deny host 192.168.3.11
access-list deny host 172.16.31.10
access-list deny host 172.16.31.10
access-list deny host 192.168.127.12
access-list deny host 172.16.17.32
access-list deny host 172.16.31.10
access-list deny host 192.168.3.11
access-list deny host 172.16.58.3
access-list deny host 172.16.31.10
access-list deny host 192.168.127.12
access-list deny host 192.168.3.11
access-list deny host 172.16.17.32
access-list deny host 192.168.3.11
access-list deny host 172.16.17.32
access-list deny host 172.16.58.3
access-list deny host 192.168.3.11
access-list deny host 172.16.31.10
access-list deny host 172.16.31.10
access-list deny host 172.16.31.10
access-list deny host 172.16.31.10
access-list deny host 172.16.17.32
access-list deny host 172.16.31.10
access-list deny host 172.16.58.3
access-list deny host 192.168.3.11
access-list deny host 172.16.58.3
access-list deny host 192.168.127.12
access-list deny host 172.16.17.32
access-list deny host 172.16.31.10
access-list deny host 172.16.17.32
access-list deny host 192.168.127.12
access-list deny host 192.168.127.12
access-list deny host 192.168.3.11
access-list deny host 172.16.17.32
access-list deny host 192.168.127.12
access-list deny host 172.16.31.10
access-list deny host 172.16.58.3
access-list deny host 172.16.31.10
access-list deny host 172.16.17.32
access-list deny host 172.16.58.3
access-list deny host 192.168.127.12
access-list deny host 172.16.31.10
access-list deny host 172.16.17.32
access-list deny host 192.168.127.12
access-list deny host 192.168.3.11
access-list deny host 172.16.17.32
access-list deny host 172.16.31.10
access-list deny host 172.16.17.32
access-list deny host 172.16.58.3
access-list deny host 192.168.127.12
access-list deny host 192.168.127.12
access-list deny host 172.16.31.10
access-list deny host 192.168.3.11
access-list deny host 192.168.127.12
access-list deny host 172.16.58.3
access-list deny host 192.168.127.12
access-list deny host 172.16.17.32
access-list deny host 192.168.127.12
access-list deny host 172.16.17.32
access-list deny host 192.168.3.11
access-list deny host 172.16.58.3
access-list deny host 192.168.127.12
access-list deny host 172.16.58.3
access-list deny host 192.168.127.12
access-list deny host 172.16.17.32
access-list deny host 172.16.31.10
access-list deny host 192.168.3.11
access-list deny host 192.168.3.11
access-list deny host 192.168.3.11
access-list deny host 172.16.17.32
access-list deny host 172.16.17.32
access-list deny host 172.16.31.10
access-list deny host 172.16.17.32
access-list deny host 172.16.17.32
access-list deny host 172.16.58.3
access-list deny host 172.16.17.32
access-list deny host 192.168.3.11
access-list deny host 172.16.31.10
access-list deny host 192.168.127.12
access-list deny host 192.168.3.11
access-list deny host 172.16.58.3
access-list deny host 192.168.127.12
access-list deny host 172.16.58.3
access-list deny host 192.168.3.11
access-list deny host 172.16.58.3
access-list deny host 172.16.17.32
access-list deny host 192.168.3.11
access-list deny host 172.16.31.10
access-list deny host 172.16.17.32
access-list deny host 192.168.3.11
access-list deny host 172.16.58.3
access-list deny host 172.16.31.10
access-list deny host 172.16.17.32
access-list deny host 192.168.127.12
access-list deny host 172.16.17.32
access-list deny host 172.16.17.32
access-list deny host 172.16.31.10
access-list deny host 172.16.58.3
access-list deny host 172.16.31.10
access-list deny host 172.16.58.3
access-list deny host 172.16.17.32
access-list deny host 192.168.127.12
access-list deny host 172.16.31.10
access-list deny host 192.168.3.11
access-list deny host 172.16.17.32
access-list deny host 172.16.58.3
access-list deny host 192.168.127.12
access-list deny host 172.16.17.32
access-list deny host 172.16.31.10
access-list deny host 172.16.17.32
access-list deny host 192.168.3.11
access-list deny host 192.168.127.12
access-list deny host 192.168.127.12
access-list deny host 192.168.3.11
access-list deny host 192.168.127.12
access-list deny host 192.168.3.11
access-list deny host 172.16.17.32
access-list deny host 192.168.3.11
access-list deny host 172.16.58.3
access-list deny host 172.16.58.3
access-list deny host 172.16.31.10
access-list deny host 192.168.3.11
access-list deny host 192.168.3.11
access-list deny host 192.168.127.12
access-list deny host 192.168.3.11
access-list deny host 172.16.31.10
access-list deny host 172.16.17.32
access-list deny host 172.16.17.32
access-list deny host 192.168.127.12
access-list deny host 192.168.3.11
access-list deny host 192.168.127.12
access-list deny host 192.168.3.11
access-list deny host 172.16.17.32
access-list deny host 172.16.17.32
access-list deny host 172.16.31.10
access-list deny host 192.168.3.11
access-list deny host 192.168.3.11
access-list deny host 172.16.17.32
access-list deny host 172.16.17.32
access-list deny host 192.168.127.12
access-list deny host 192.168.127.12
access-list deny host 172.16.31.10
access-list deny host 172.16.31.10
access-list deny host 172.16.58.3
access-list deny host 192.168.127.12
access-list deny host 172.16.58.3
access-list deny host 172.16.17.32
access-list deny host 172.16.17.32
access-list deny host 172.16.31.10
access-list deny host 192.168.127.12
access-list deny host 172.16.58.3
access-list deny host 192.168.127.12
access-list deny host 192.168.127.12
access-list deny host 192.168.127.12
access-list deny host 172.16.58.3
access-list deny host 172.16.31.10
access-list deny host 172.16.58.3
access-list deny host 192.168.127.12
access-list deny host 192.168.127.12
access-list deny host 192.168.3.11
access-list deny host 192.168.3.11
access-list deny host 192.168.127.12
access-list deny host 192.168.3.11
access-list deny host 172.16.31.10
access-list deny host 192.168.127.12
access-list deny host 172.16.58.3
access-list deny host 172.16.31.10
access-list deny host 192.168.127.12
access-list deny host 192.168.127.12
access-list deny host 172.16.58.3
access-list deny host 192.168.3.11
access-list deny host 172.16.58.3
access-list deny host 172.16.31.10
access-list deny host 192.168.3.11
access-list deny host 172.16.31.10
access-list deny host 172.16.17.32
access-list deny host 192.168.127.12
access-list deny host 172.16.58.3
access-list deny host 172.16.58.3
access-list deny host 172.16.58.3
access-list deny host 192.168.3.11
access-list deny host 192.168.3.11
access-list deny host 192.168.3.11
access-list deny host 172.16.31.10
access-list deny host 172.16.17.32
access-list deny host 172.16.31.10
access-list deny host 172.16.17.32
access-list deny host 172.16.31.10
access-list deny host 192.168.127.12
access-list deny host 172.16.17.32
access-list deny host 192.168.3.11
access-list deny host 172.16.17.32
access-list deny host 192.168.127.12
access-list deny host 192.168.3.11
access-list deny host 172.16.31.10
access-list deny host 172.16.17.32
access-list deny host 192.168.127.12
access-list deny host 172.16.58.3
access-list deny host 172.16.58.3
access-list deny host 172.16.58.3
access-list deny host 172.16.31.10
access-list deny host 172.16.31.10
access-list deny host 192.168.3.11
access-list deny host 172.16.31.10
access-list deny host 172.16.17.32
access-list deny host 172.16.17.32
access-list deny host 192.168.127.12
access-list deny host 172.16.31.10
access-list deny host 172.16.31.10
access-list deny host 192.168.3.11
access-list deny host 172.16.58.3
access-list deny host 172.16.31.10
access-list deny host 172.16.58.3
access-list deny host 192.168.3.11
access-list deny host 192.168.3.11
access-list deny host 192.168.127.12
access-list deny host 192.168.127.12
access-list deny host 172.16.17.32
access-list deny host 172.16.58.3
access-list deny host 172.16.58.3
access-list deny host 172.16.58.3
access-list deny host 172.16.17.32
access-list deny host 192.168.3.11
access-list deny host 192.168.127.12
access-list deny host 192.168.127.12
access-list deny host 172.16.17.32
access-list deny host 192.168.127.12
access-list deny host 172.16.31.10
access-list deny host 172.16.58.3
access-list deny host 172.16.31.10
access-list deny host 172.16.58.3
access-list deny host 172.16.58.3
access-list deny host 192.168.3.11
access-list deny host 172.16.31.10
access-list deny host 172.16.17.32
access-list deny host 172.16.17.32
access-list deny host 172.16.58.3
access-list deny host 192.168.127.12
access-list deny host 192.168.127.12
access-list deny host 172.16.58.3
access-list deny host 172.16.31.10
access-list deny host 192.168.3.11
access-list deny host 172.16.17.32
access-list deny host 172.16.31.10
access-list deny host 192.168.3.11
access-list deny host 192.168.3.11
access-list deny host 172.16.31.10
access-list deny host 172.16.31.10
access-list deny host 172.16.58.3
access-list deny host 172.16.17.32
access-list deny host 172.16.17.32
access-list deny host 172.16.58.3
access-list deny host 172.16.17.32
access-list deny host 172.16.17.32
access-list deny host 172.16.58.3
access-list deny host 172.16.31.10
access-list deny host 172.16.17.32
access-list deny host 172.16.31.10
access-list deny host 192.168.3.11
access-list deny host 192.168.127.12
access-list deny host 172.16.17.32
access-list deny host 172.16.58.3
access-list deny host 172.16.17.32
access-list deny host 192.168.127.12
access-list deny host 192.168.127.12
access-list deny host 192.168.3.11
access-list deny host 192.168.3.11
access-list deny host 192.168.3.11
access-list deny host 172.16.17.32
access-list deny host 192.168.127.12
access-list deny host 172.16.58.3
access-list deny host 172.16.17.32
access-list deny host 172.16.31.10
access-list deny host 192.168.127.12
access-list deny host 172.16.31.10
access-list deny host 192.168.127.12
access-list deny host 192.168.127.12
access-list deny host 192.168.127.12
access-list deny host 192.168.3.11
access-list deny host 192.168.127.12
access-list deny host 192.168.3.11
access-list deny host 172.16.17.32
access-list deny host 192.168.127.12
access-list deny host 172.16.17.32
access-list deny host 172.16.31.10
access-list deny host 172.16.17.32
access-list deny host 172.16.17.32
access-list deny host 172.16.17.32
access-list deny host 192.168.127.12
access-list deny host 192.168.3.11
access-list deny host 192.168.3.11
access-list deny host 192.168.127.12
access-list deny host 172.16.17.32
access-list deny host 172.16.58.3
access-list deny host 192.168.3.11
access-list deny host 192.168.3.11
access-list deny host 172.16.17.32
access-list deny host 172.16.31.10
access-list deny host 172.16.58.3
access-list deny host 192.168.3.11
access-list deny host 192.168.3.11
access-list deny host 172.16.58.3
access-list deny host 192.168.127.12
access-list deny host 192.168.127.12
access-list deny host 172.16.58.3
access-list deny host 172.16.58.3
access-list deny host 172.16.31.10
access-list deny host 172.16.58.3
access-list deny host 192.168.3.11
access-list deny host 172.16.17.32
access-list deny host 172.16.31.10
access-list deny host 192.168.127.12
access-list deny host 172.16.17.32
access-list deny host 192.168.127.12
access-list deny host 172.16.58.3
access-list deny host 172.16.31.10
access-list deny host 172.16.31.10
access-list deny host 172.16.58.3
access-list deny host 192.168.127.12
access-list deny host 172.16.31.10
access-list deny host 172.16.58.3
access-list deny host 192.168.127.12
access-list deny host 172.16.17.32
access-list deny host 192.168.127.12
access-list deny host 192.168.127.12
access-list deny host 192.168.3.11
access-list deny host 192.168.3.11
access-list deny host 172.16.31.10
access-list deny host 172.16.58.3
access-list deny host 172.16.17.32
access-list deny host 172.16.17.32
access-list deny host 192.168.3.11
access-list deny host 192.168.127.12
access-list deny host 172.16.58.3
access-list deny host 172.16.58.3
access-list deny host 172.16.31.10
access-list deny host 192.168.127.12
access-list deny host 172.16.17.32
access-list deny host 192.168.3.11
access-list deny host 172.16.17.32
access-list deny host 172.16.17.32
access-list deny host 192.168.3.11
access-list deny host 172.16.58.3
access-list deny host 172.16.31.10
access-list deny host 172.16.31.10
access-list deny host 192.168.127.12
access-list deny host 192.168.127.12
access-list deny host 192.168.127.12
access-list deny host 172.16.58.3
access-list deny host 172.16.58.3
access-list deny host 192.168.3.11
access-list deny host 172.16.17.32
access-list deny host 172.16.31.10
access-list deny host 172.16.17.32
access-list deny host 172.16.31.10
access-list deny host 192.168.127.12
access-list deny host 172.16.17.32
access-list deny host 172.16.58.3
access-list deny host 172.16.58.3
access-list deny host 172.16.31.10
access-list deny host 192.168.127.12
access-list deny host 172.16.31.10
access-list deny host 192.168.3.11
access-list deny host 172.16.58.3
access-list deny host 172.16.31.10
access-list deny host 192.168.127.12
access-list deny host 172.16.17.32
access-list deny host 172.16.31.10
access-list deny host 192.168.3.11
access-list deny host 172.16.17.32
access-list deny host 192.168.3.11
access-list deny host 192.168.3.11
access-list deny host 172.16.17.32
access-list deny host 172.16.31.10
access-list deny host 172.16.58.3
access-list deny host 192.168.3.11
access-list deny host 192.168.127.12
access-list deny host 172.16.58.3
access-list deny host 172.16.31.10
access-list deny host 172.16.17.32
access-list deny host 172.16.31.10
access-list deny host 192.168.127.12
access-list deny host 192.168.3.11
access-list deny host 172.16.31.10
access-list deny host 172.16.17.32
access-list deny host 192.168.127.12
access-list deny host 172.16.17.32
access-list deny host 192.168.127.12
access-list deny host 172.16.58.3
access-list deny host 172.16.31.10
access-list deny host 172.16.31.10
access-list deny host 172.16.17.32
access-list deny host 172.16.58.3
access-list deny host 172.16.58.3
access-list deny host 172.16.58.3
access-list deny host 172.16.17.32
access-list deny host 172.16.17.32
access-list deny host 172.16.58.3
access-list deny host 172.16.58.3
access-list deny host 192.168.127.12
access-list deny host 172.16.58.3
access-list deny host 172.16.31.10
access-list deny host 172.16.17.32
access-list deny host 172.16.17.32
access-list deny host 172.16.17.32
access-list deny host 192.168.3.11
access-list deny host 192.168.127.12
access-list deny host 192.168.127.12
access-list deny host 192.168.127.12
access-list deny host 172.16.58.3
access-list deny host 172.16.58.3
access-list deny host 172.16.58.3
access-list deny host 172.16.58.3
access-list deny host 172.16.31.10
access-list deny host 192.168.3.11
access-list deny host 172.16.58.3
access-list deny host 192.168.3.11
access-list deny host 192.168.3.11
access-list deny host 192.168.127.12
access-list deny host 192.168.3.11
access-list deny host 172.16.31.10
access-list deny host 192.168.127.12
access-list deny host 172.16.31.10
access-list deny host 172.16.58.3
access-list deny host 172.16.58.3
access-list deny host 172.16.17.32
access-list deny host 172.16.17.32
access-list deny host 172.16.17.32
access-list deny host 172.16.58.3
access-list deny host 172.16.17.32
access-list deny host 192.168.127.12
access-list deny host 172.16.31.10
access-list deny host 192.168.3.11
access-list deny host 192.168.3.11
access-list deny host 192.168.3.11
access-list deny host 172.16.58.3
access-list deny host 172.16.58.3
access-list deny host 172.16.31.10
access-list deny host 172.16.31.10
access-list deny host 172.16.31.10
access-list deny host 172.16.31.10
access-list deny host 172.16.31.10
access-list deny host 172.16.31.10
access-list deny host 172.16.58.3
access-list deny host 172.16.58.3
access-list deny host 172.16.31.10
access-list deny host 172.16.58.3
access-list deny host 172.16.58.3
access-list deny host 172.16.31.10
access-list deny host 192.168.3.11
access-list deny host 192.168.3.11
access-list deny host 192.168.127.12
access-list deny host 172.16.58.3
access-list deny host 172.16.58.3
access-list deny host 172.16.58.3
access-list deny host 192.168.3.11
access-list deny host 172.16.58.3
access-list deny host 192.168.127.12
access-list deny host 172.16.58.3
access-list deny host 172.16.31.10
access-list deny host 192.168.3.11
access-list deny host 172.16.31.10
access-list deny host 172.16.17.32
access-list deny host 192.168.3.11
access-list deny host 172.16.17.32
access-list deny host 192.168.127.12
access-list deny host 172.16.17.32
access-list deny host 192.168.127.12
access-list deny host 192.168.127.12
access-list deny host 172.16.31.10
access-list deny host 192.168.3.11
access-list deny host 192.168.3.11
access-list deny host 192.168.127.12
access-list deny host 172.16.58.3
access-list deny host 172.16.58.3
access-list deny host 192.168.3.11
access-list deny host 172.16.31.10
access-list deny host 192.168.3.11
access-list deny host 192.168.3.11
access-list deny host 192.168.3.11
access-list deny host 172.16.31.10
access-list deny host 192.168.3.11
access-list deny host 192.168.127.12
access-list deny host 172.16.58.3
access-list deny host 172.16.58.3
access-list deny host 172.16.58.3
access-list deny host 172.16.58.3
access-list deny host 172.16.17.32
access-list deny host 172.16.58.3
access-list deny host 172.16.58.3
access-list deny host 192.168.3.11
access-list deny host 172.16.31.10
access-list deny host 172.16.31.10
access-list deny host 172.16.58.3
access-list deny host 192.168.127.12
access-list deny host 172.16.58.3
access-list deny host 172.16.17.32
access-list deny host 192.168.127.12
access-list deny host 192.168.127.12
access-list deny host 172.16.31.10
access-list deny host 192.168.3.11
access-list deny host 192.168.3.11
access-list deny host 172.16.58.3
access-list deny host 192.168.127.12
access-list deny host 172.16.58.3
access-list deny host 172.16.17.32
access-list deny host 192.168.127.12
access-list deny host 192.168.3.11
access-list deny host 172.16.58.3
access-list deny host 172.16.58.3
access-list deny host 172.16.17.32
access-list deny host 172.16.31.10
access-list deny host 172.16.31.10
access-list deny host 172.16.58.3
access-list deny host 172.16.17.32
access-list deny host 172.16.58.3
access-list deny host 172.16.17.32
access-list deny host 172.16.31.10
access-list deny host 172.16.17.32
access-list deny host 172.16.31.10
access-list deny host 172.16.17.32
access-list deny host 192.168.127.12
access-list deny host 172.16.17.32
access-list deny host 172.16.58.3
access-list deny host 172.16.31.10
access-list deny host 192.168.127.12
access-list deny host 172.16.17.32
access-list deny host 172.16.31.10
access-list deny host 172.16.58.3
access-list deny host 192.168.3.11
access-list deny host 192.168.127.12
access-list deny host 192.168.3.11
access-list deny host 192.168.127.12
access-list deny host 192.168.127.12
access-list deny host 172.16.58.3
access-list deny host 192.168.3.11
access-list deny host 192.168.127.12
access-list deny host 172.16.58.3
access-list deny host 192.168.127.12
access-list deny host 172.16.31.10
access-list deny host 172.16.17.32
access-list deny host 192.168.3.11
access-list deny host 172.16.31.10
access-list deny host 192.168.127.12
access-list deny host 172.16.58.3
access-list deny host 172.16.31.10
access-list deny host 172.16.31.10
access-list deny host 172.16.17.32
access-list deny host 192.168.3.11
access-list deny host 172.16.58.3
access-list deny host 192.168.127.12
access-list deny host 192.168.3.11
access-list deny host 192.168.3.11
access-list deny host 172.16.31.10
access-list deny host 172.16.58.3
access-list deny host 192.168.3.11
access-list deny host 192.168.127.12
access-list deny host 192.168.127.12
access-list deny host 172.16.31.10
access-list deny host 172.16.31.10
access-list deny host 172.16.31.10
access-list deny host 172.16.58.3
access-list deny host 172.16.31.10
access-list deny host 192.168.3.11
access-list deny host 192.168.127.12
access-list deny host 172.16.58.3
access-list deny host 192.168.127.12
access-list deny host 192.168.3.11
access-list deny host 192.168.127.12
access-list deny host 172.16.17.32
access-list deny host 172.16.17.32
access-list deny host 172.16.17.32
access-list deny host 172.16.17.32
access-list deny host 172.16.58.3
access-list deny host 172.16.58.3
access-list deny host 172.16.17.32
access-list deny host 172.16.31.10
access-list deny host 172.16.17.32
access-list deny host 172.16.17.32
access-list deny host 192.168.3.11
access-list deny host 172.16.31.10
access-list deny host 192.168.127.12
access-list deny host 172.16.58.3
access-list deny host 192.168.3.11
access-list deny host 192.168.127.12
access-list deny host 192.168.3.11
access-list deny host 192.168.3.11
access-list deny host 192.168.127.12
access-list deny host 172.16.17.32
access-list deny host 172.16.17.32
access-list deny host 172.16.58.3
access-list deny host 192.168.3.11
access-list deny host 172.16.31.10
access-list deny host 172.16.17.32
access-list deny host 172.16.31.10
access-list deny host 172.16.31.10
access-list deny host 192.168.127.12
access-list deny host 172.16.31.10
access-list deny host 172.16.31.10
access-list deny host 172.16.17.32
access-list deny host 172.16.31.10
access-list deny host 172.16.17.32
access-list deny host 172.16.31.10
access-list deny host 192.168.127.12
access-list deny host 192.168.3.11
access-list deny host 172.16.31.10
access-list deny host 192.168.127.12
access-list deny host 172.16.17.32
access-list deny host 192.168.3.11
access-list deny host 192.168.127.12
access-list deny host 192.168.127.12
access-list deny host 192.168.127.12
access-list deny host 192.168.3.11
access-list deny host 192.168.127.12
access-list deny host 172.16.17.32
access-list deny host 172.16.17.32
access-list deny host 192.168.127.12
access-list deny host 192.168.127.12
access-list deny host 192.168.127.12
access-list deny host 192.168.3.11
access-list deny host 172.16.17.32
access-list deny host 172.16.58.3
access-list deny host 172.16.31.10
access-list deny host 172.16.17.32
access-list deny host 192.168.3.11
access-list deny host 172.16.31.10
access-list deny host 172.16.58.3
access-list deny host 172.16.58.3
access-list deny host 172.16.17.32
access-list deny host 192.168.3.11
access-list deny host 192.168.127.12
access-list deny host 172.16.58.3
access-list deny host 172.16.31.10
access-list deny host 192.168.3.11
access-list deny host 192.168.3.11
access-list deny host 172.16.31.10
access-list deny host 192.168.3.11
access-list deny host 172.16.17.32
access-list deny host 172.16.31.10
access-list deny host 192.168.127.12
access-list deny host 192.168.127.12
access-list deny host 172.16.58.3
access-list deny host 172.16.58.3
access-list deny host 172.16.17.32
access-list deny host 172.16.17.32
access-list deny host 172.16.58.3
access-list deny host 172.16.58.3
access-list deny host 172.16.58.3
access-list deny host 192.168.3.11
access-list deny host 172.16.31.10
access-list deny host 172.16.17.32
access-list deny host 172.16.17.32
access-list deny host 192.168.127.12
access-list deny host 172.16.17.32
access-list deny host 172.16.17.32
access-list deny host 172.16.17.32
access-list deny host 172.16.58.3
access-list deny host 172.16.31.10
access-list deny host 172.16.17.32
access-list deny host 192.168.127.12
access-list deny host 172.16.58.3
access-list deny host 192.168.127.12
access-list deny host 172.16.31.10
access-list deny host 172.16.58.3
access-list deny host 192.168.3.11
access-list deny host 172.16.58.3
access-list deny host 172.16.17.32
access-list deny host 172.16.58.3
access-list deny host 192.168.127.12
access-list deny host 192.168.127.12
access-list deny host 172.16.17.32
access-list deny host 192.168.3.11
access-list deny host 192.168.3.11
access-list deny host 172.16.31.10
access-list deny host 172.16.31.10
access-list deny host 172.16.31.10
access-list deny host 172.16.31.10
access-list deny host 192.168.127.12
access-list deny host 172.16.31.10
access-list deny host 172.16.31.10
access-list deny host 172.16.58.3
access-list deny host 172.16.58.3
access-list deny host 192.168.127.12
access-list deny host 172.16.31.10
access-list deny host 172.16.31.10
access-list deny host 192.168.3.11
access-list deny host 192.168.127.12
access-list deny host 172.16.58.3
access-list deny host 172.16.58.3
access-list deny host 172.16.17.32
access-list deny host 172.16.58.3
access-list deny host 172.16.17.32
access-list deny host 172.16.17.32
access-list deny host 192.168.127.12
access-list deny host 192.168.3.11
access-list deny host 192.168.127.12
access-list deny host 192.168.127.12
access-list deny host 172.16.58.3
access-list deny host 192.168.3.11
access-list deny host 192.168.3.11
access-list deny host 172.16.31.10
access-list deny host 172.16.17.32
access-list deny host 192.168.3.11
access-list deny host 192.168.127.12
access-list deny host 172.16.58.3
access-list deny host 192.168.3.11
access-list deny host 172.16.58.3
access-list deny host 172.16.17.32
access-list deny host 192.168.3.11
access-list deny host 192.168.127.12
access-list deny host 172.16.17.32
access-list deny host 192.168.3.11
access-list deny host 172.16.17.32
access-list deny host 172.16.17.32
access-list deny host 172.16.58.3
access-list deny host 192.168.3.11
access-list deny host 172.16.31.10
access-list deny host 192.168.3.11
access-list deny host 192.168.3.11
access-list deny host 172.16.17.32
access-list deny host 192.168.3.11
access-list deny host 192.168.127.12
access-list deny host 192.168.127.12
access-list deny host 192.168.127.12
access-list deny host 192.168.3.11
access-list deny host 172.16.31.10
access-list deny host 192.168.127.12
access-list deny host 192.168.3.11
access-list deny host 192.168.127.12
access-list deny host 192.168.127.12
access-list deny host 192.168.3.11
access-list deny host 172.16.17.32
access-list deny host 172.16.31.10
access-list deny host 192.168.127.12
access-list deny host 172.16.31.10
access-list deny host 172.16.31.10
access-list deny host 172.16.58.3
access-list deny host 172.16.31.10
access-list deny host 192.168.3.11
access-list deny host 172.16.31.10
access-list deny host 192.168.3.11
access-list deny host 172.16.31.10
access-list deny host 172.16.31.10
access-list deny host 172.16.58.3
access-list deny host 192.168.127.12
access-list deny host 172.16.58.3
access-list deny host 172.16.58.3
access-list deny host 172.16.31.10
access-list deny host 172.16.58.3
access-list deny host 192.168.3.11
access-list deny host 172.16.17.32
access-list deny host 192.168.127.12
access-list deny host 192.168.3.11
access-list deny host 172.16.31.10
access-list deny host 172.16.31.10
access-list deny host 172.16.31.10
access-list deny host 192.168.127.12
access-list deny host 172.16.31.10
access-list deny host 192.168.3.11
access-list deny host 172.16.17.32
access-list deny host 192.168.3.11
access-list deny host 172.16.58.3
access-list deny host 172.16.31.10
access-list deny host 192.168.3.11
access-list deny host 172.16.17.32
access-list deny host 172.16.58.3
access-list deny host 192.168.3.11
access-list deny host 172.16.58.3
access-list deny host 172.16.31.10
access-list deny host 172.16.17.32
access-list deny host 192.168.3.11
access-list deny host 172.16.17.32
access-list deny host 192.168.127.12
access-list deny host 172.16.58.3
access-list deny host 172.16.17.32
access-list deny host 192.168.3.11
access-list deny host 172.16.58.3
access-list deny host 192.168.3.11
access-list deny host 172.16.58.3
access-list deny host 172.16.17.32
access-list deny host 192.168.127.12
access-list deny host 192.168.3.11
access-list deny host 172.16.58.3
access-list deny host 172.16.31.10
access-list deny host 172.16.58.3
access-list deny host 172.16.58.3
access-list deny host 172.16.31.10
access-list deny host 172.16.17.32
access-list deny host 192.168.3.11
access-list deny host 172.16.31.10
access-list deny host 172.16.17.32
access-list deny host 172.16.31.10
access-list deny host 172.16.31.10
access-list deny host 172.16.58.3
access-list deny host 192.168.3.11
access-list deny host 172.16.58.3
access-list deny host 192.168.3.11
access-list deny host 172.16.58.3
access-list deny host 192.168.3.11
access-list deny host 192.168.3.11
access-list deny host 172.16.31.10
access-list deny host 172.16.58.3
access-list deny host 192.168.3.11
access-list deny host 172.16.31.10
access-list deny host 172.16.31.10
access-list deny host 192.168.127.12
access-list deny host 172.16.17.32
access-list deny host 192.168.3.11
access-list deny host 192.168.127.12
access-list deny host 172.16.17.32
access-list deny host 172.16.17.32
access-list deny host 172.16.17.32
access-list deny host 172.16.17.32
access-list deny host 172.16.31.10
access-list deny host 172.16.58.3
access-list deny host 192.168.127.12
access-list deny host 192.168.3.11
access-list deny host 192.168.127.12
access-list deny host 192.168.3.11
access-list deny host 172.16.17.32
access-list deny host 172.16.31.10
access-list deny host 192.168.3.11
access-list deny host 172.16.31.10
access-list deny host 172.16.17.32
access-list deny host 172.16.17.32
access-list deny host 172.16.31.10
access-list deny host 172.16.58.3
access-list deny host 192.168.127.12
access-list deny host 172.16.58.3
access-list deny host 172.16.31.10
access-list deny host 172.16.17.32
access-list deny host 172.16.31.10
access-list deny host 192.168.3.11
access-list deny host 172.16.58.3
access-list deny host 172.16.58.3
access-list deny host 192.168.3.11
access-list deny host 192.168.3.11
access-list deny host 172.16.31.10
access-list deny host 172.16.58.3
access-list deny host 172.16.17.32
access-list deny host 172.16.58.3
access-list deny host 172.16.31.10
access-list deny host 172.16.58.3
access-list deny host 172.16.17.32
access-list deny host 172.16.17.32
access-list deny host 192.168.3.11
access-list deny host 172.16.17.32
access-list deny host 192.168.127.12
access-list deny host 172.16.17.32
access-list deny host 172.16.31.10
access-list deny host 172.16.17.32
access-list deny host 192.168.3.11
access-list deny host 192.168.127.12
access-list deny host 172.16.17.32
access-list deny host 192.168.3.11
access-list deny host 192.168.127.12
access-list deny host 192.168.3.11
access-list deny host 172.16.31.10
access-list deny host 192.168.3.11
access-list deny host 172.16.58.3
access-list deny host 172.16.58.3
access-list deny host 172.16.17.32
access-list deny host 172.16.58.3
access-list deny host 192.168.127.12
access-list deny host 192.168.127.12
access-list deny host 192.168.3.11
access-list deny host 192.168.3.11
access-list deny host 172.16.17.32
access-list deny host 172.16.17.32
access-list deny host 192.168.127.12
access-list deny host 172.16.58.3
access-list deny host 172.16.58.3
access-list deny host 192.168.127.12
access-list deny host 172.16.58.3
access-list deny host 192.168.127.12
access-list deny host 172.16.58.3
access-list deny host 192.168.3.11
access-list deny host 172.16.17.32
access-list deny host 172.16.31.10
access-list deny host 172.16.17.32
access-list deny host 192.168.3.11
access-list deny host 192.168.3.11
access-list deny host 192.168.127.12
access-list deny host 172.16.17.32
access-list deny host 192.168.3.11
access-list deny host 192.168.3.11
access-list deny host 172.16.31.10
access-list deny host 192.168.127.12
access-list deny host 172.16.58.3
access-list deny host 172.16.31.10
access-list deny host 192.168.3.11
access-list deny host 172.16.17.32
access-list deny host 192.168.127.12
access-list deny host 192.168.127.12
access-list deny host 192.168.127.12
access-list deny host 172.16.31.10
access-list deny host 192.168.127.12
access-list deny host 172.16.17.32
access-list deny host 172.16.58.3
access-list deny host 172.16.31.10
access-list deny host 172.16.31.10
access-list deny host 172.16.58.3
access-list deny host 172.16.58.3
access-list deny host 172.16.58.3
access-list deny host 172.16.31.10
access-list deny host 172.16.58.3
access-list deny host 192.168.127.12
access-list deny host 192.168.127.12
access-list deny host 172.16.31.10
access-list deny host 172.16.31.10
access-list deny host 172.16.17.32
access-list deny host 172.16.58.3
access-list deny host 172.16.17.32
access-list deny host 172.16.17.32
access-list deny host 172.16.17.32
access-list deny host 192.168.3.11
access-list deny host 192.168.3.11
access-list deny host 192.168.3.11
access-list deny host 192.168.127.12
access-list deny host 172.16.17.32
access-list deny host 172.16.17.32
access-list deny host 172.16.31.10
access-list deny host 192.168.127.12
access-list deny host 172.16.31.10
access-list deny host 172.16.31.10
access-list deny host 192.168.3.11
access-list deny host 192.168.3.11
access-list deny host 192.168.3.11
access-list deny host 192.168.127.12
access-list deny host 172.16.58.3
access-list deny host 192.168.3.11
access-list deny host 172.16.17.32
access-list deny host 172.16.31.10
access-list deny host 172.16.58.3
access-list deny host 192.168.3.11
access-list deny host 192.168.3.11
access-list deny host 172.16.31.10
access-list deny host 192.168.127.12
access-list deny host 172.16.17.32
access-list deny host 172.16.31.10
access-list deny host 172.16.17.32
access-list deny host 172.16.17.32
access-list deny host 172.16.17.32
access-list deny host 192.168.127.12
access-list deny host 172.16.17.32
access-list deny host 192.168.127.12
access-list deny host 172.16.58.3
access-list deny host 172.16.17.32
access-list deny host 172.16.17.32
access-list deny host 172.16.17.32
access-list deny host 172.16.17.32
access-list deny host 172.16.58.3
access-list deny host 192.168.3.11
access-list deny host 172.16.17.32
access-list deny host 172.16.31.10
access-list deny host 172.16.31.10
access-list deny host 172.16.58.3
access-list deny host 192.168.3.11
access-list deny host 172.16.58.3
access-list deny host 172.16.17.32
access-list deny host 192.168.3.11
access-list deny host 46.165.254.160
access-list deny host 192.168.127.12
access-list deny host 192.168.3.11
access-list deny host 172.16.17.32
access-list deny host 172.16.31.10
access-list deny host 172.16.58.3
access-list deny host 192.168.127.12
access-list deny host 172.16.58.3
access-list deny host 192.168.3.11
access-list deny host 192.168.127.12
access-list deny host 172.16.58.3
access-list deny host 192.168.3.11
access-list deny host 172.16.31.10
access-list deny host 192.168.127.12
access-list deny host 192.168.127.12
access-list deny host 192.168.127.12
access-list deny host 172.16.31.10
access-list deny host 172.16.17.32
access-list deny host 172.16.31.10
access-list deny host 172.16.58.3
access-list deny host 192.168.127.12
access-list deny host 192.168.3.11
access-list deny host 192.168.127.12
access-list deny host 172.16.17.32
access-list deny host 192.168.3.11
access-list deny host 172.16.31.10
access-list deny host 192.168.127.12
access-list deny host 172.16.58.3
access-list deny host 192.168.3.11
access-list deny host 172.16.31.10
access-list deny host 172.16.58.3
access-list deny host 192.168.127.12
access-list deny host 172.16.31.10
access-list deny host 192.168.127.12
access-list deny host 192.168.3.11
access-list deny host 192.168.3.11
access-list deny host 192.168.3.11
access-list deny host 172.16.31.10
access-list deny host 192.168.3.11
access-list deny host 192.168.127.12
access-list deny host 192.168.3.11
access-list deny host 192.168.127.12
access-list deny host 172.16.58.3
access-list deny host 172.16.58.3
access-list deny host 192.168.127.12
access-list deny host 192.168.3.11
access-list deny host 172.16.17.32
access-list deny host 172.16.58.3
access-list deny host 192.168.127.12
access-list deny host 172.16.31.10
access-list deny host 172.16.31.10
access-list deny host 172.16.58.3
access-list deny host 192.168.3.11
access-list deny host 192.168.127.12
access-list deny host 5.187.5.171
access-list deny host 172.16.31.10
access-list deny host 172.16.17.32
access-list deny host 172.16.58.3
access-list deny host 192.168.3.11
access-list deny host 172.16.58.3
access-list deny host 172.16.58.3
access-list deny host 172.16.58.3
access-list deny host 192.168.127.12
access-list deny host 172.16.31.10
access-list deny host 192.168.3.11
access-list deny host 192.168.3.11
access-list deny host 172.16.17.32
access-list deny host 192.168.127.12
access-list deny host 172.16.17.32
access-list deny host 192.168.127.12
access-list deny host 192.168.3.11
access-list deny host 172.16.58.3
access-list deny host 172.16.58.3
access-list deny host 192.168.127.12
access-list deny host 172.16.58.3
access-list deny host 172.16.58.3
access-list deny host 172.16.58.3
access-list deny host 172.16.31.10
access-list deny host 192.168.3.11
access-list deny host 172.16.31.10
access-list deny host 192.168.3.11
access-list deny host 172.16.17.32
access-list deny host 192.168.3.11
access-list deny host 192.168.3.11
access-list deny host 192.168.127.12
access-list deny host 172.16.58.3
access-list deny host 172.16.31.10
access-list deny host 172.16.17.32
access-list deny host 172.16.17.32
access-list deny host 192.168.127.12
access-list deny host 192.168.3.11
access-list deny host 172.16.58.3
access-list deny host 192.168.3.11
access-list deny host 172.16.17.32
access-list deny host 172.16.31.10
access-list deny host 172.16.58.3
access-list deny host 172.16.17.32
access-list deny host 172.16.17.32
access-list deny host 172.16.31.10
access-list deny host 192.168.3.11
access-list deny host 172.16.31.10
access-list deny host 172.16.58.3
access-list deny host 172.16.58.3
access-list deny host 192.168.3.11
access-list deny host 172.16.31.10
access-list deny host 172.16.17.32
access-list deny host 192.168.3.11
access-list deny host 172.16.31.10
access-list deny host 172.16.31.10
access-list deny host 172.16.31.10
access-list deny host 172.16.58.3
access-list deny host 172.16.17.32
access-list deny host 172.16.17.32
access-list deny host 192.168.127.12
access-list deny host 172.16.31.10
access-list deny host 172.16.31.10
access-list deny host 172.16.17.32
access-list deny host 172.16.31.10
access-list deny host 172.16.31.10
access-list deny host 192.168.127.12
access-list deny host 192.168.127.12
access-list deny host 192.168.127.12
access-list deny host 192.168.127.12
access-list deny host 172.16.31.10
access-list deny host 172.16.31.10
access-list deny host 172.16.17.32
access-list deny host 172.16.58.3
access-list deny host 192.168.127.12
access-list deny host 172.16.58.3
access-list deny host 172.16.58.3
access-list deny host 192.168.3.11
access-list deny host 192.168.3.11
access-list deny host 192.168.3.11
access-list deny host 192.168.3.11
access-list deny host 172.16.58.3
access-list deny host 172.16.17.32
access-list deny host 172.16.58.3
access-list deny host 172.16.58.3
access-list deny host 192.168.127.12
access-list deny host 172.16.58.3
access-list deny host 172.16.17.32
access-list deny host 192.168.3.11
access-list deny host 172.16.58.3
access-list deny host 192.168.127.12
access-list deny host 172.16.31.10
access-list deny host 192.168.127.12
access-list deny host 172.16.31.10
access-list deny host 192.168.127.12
access-list deny host 192.168.127.12
access-list deny host 172.16.31.10
access-list deny host 192.168.3.11
access-list deny host 192.168.127.12
access-list deny host 172.16.17.32
access-list deny host 172.16.58.3
access-list deny host 192.168.3.11
access-list deny host 192.168.3.11
access-list deny host 172.16.31.10
access-list deny host 192.168.3.11
access-list deny host 192.168.3.11
access-list deny host 192.168.127.12
access-list deny host 192.168.127.12
access-list deny host 172.16.31.10
access-list deny host 172.16.31.10
access-list deny host 192.168.127.12
access-list deny host 172.16.58.3
access-list deny host 172.16.58.3
access-list deny host 172.16.58.3
access-list deny host 172.16.17.32
access-list deny host 172.16.17.32
access-list deny host 192.168.3.11
access-list deny host 172.16.31.10
access-list deny host 172.16.31.10
access-list deny host 172.16.58.3
access-list deny host 172.16.17.32
access-list deny host 172.16.31.10
access-list deny host 172.16.17.32
access-list deny host 192.168.127.12
access-list deny host 192.168.127.12
access-list deny host 192.168.3.11
access-list deny host 172.16.58.3
access-list deny host 172.16.17.32
access-list deny host 192.168.127.12
access-list deny host 172.16.58.3
access-list deny host 192.168.3.11
access-list deny host 172.16.17.32
access-list deny host 172.16.17.32
access-list deny host 172.16.58.3
access-list deny host 172.16.58.3
access-list deny host 172.16.17.32
access-list deny host 192.168.3.11
access-list deny host 192.168.3.11
access-list deny host 192.168.3.11
access-list deny host 192.168.127.12
access-list deny host 192.168.127.12
access-list deny host 172.16.58.3
access-list deny host 172.16.17.32
access-list deny host 172.16.58.3
access-list deny host 192.168.127.12
access-list deny host 192.168.127.12
access-list deny host 172.16.17.32
access-list deny host 172.16.17.32
access-list deny host 172.16.58.3
access-list deny host 172.16.58.3
access-list deny host 192.168.3.11
access-list deny host 172.16.17.32
access-list deny host 192.168.3.11
access-list deny host 192.168.3.11
access-list deny host 172.16.58.3
access-list deny host 172.16.31.10
access-list deny host 172.16.58.3
access-list deny host 192.168.127.12
access-list deny host 172.16.58.3
access-list deny host 172.16.58.3
access-list deny host 172.16.58.3
access-list deny host 172.16.58.3
access-list deny host 192.168.127.12
access-list deny host 172.16.58.3
access-list deny host 192.168.3.11
access-list deny host 172.16.17.32
access-list deny host 192.168.3.11
access-list deny host 172.16.58.3
access-list deny host 192.168.127.12
access-list deny host 172.16.31.10
access-list deny host 192.168.3.11
access-list deny host 172.16.31.10
access-list deny host 172.16.31.10
access-list deny host 192.168.3.11
access-list deny host 192.168.127.12
access-list deny host 192.168.127.12
access-list deny host 172.16.58.3
access-list deny host 192.168.127.12
access-list deny host 172.16.58.3
access-list deny host 192.168.3.11
access-list deny host 172.16.17.32
access-list deny host 172.16.31.10
access-list deny host 192.168.3.11
access-list deny host 192.168.3.11
access-list deny host 192.168.127.12
access-list deny host 172.16.31.10
access-list deny host 172.16.58.3
access-list deny host 172.16.17.32
access-list deny host 172.16.31.10
access-list deny host 172.16.31.10
access-list deny host 192.168.3.11
access-list deny host 192.168.127.12
access-list deny host 172.16.17.32
access-list deny host 192.168.127.12
access-list deny host 172.16.17.32
access-list deny host 192.168.3.11
access-list deny host 172.16.58.3
access-list deny host 172.16.58.3
access-list deny host 192.168.3.11
access-list deny host 172.16.31.10
access-list deny host 192.168.3.11
access-list deny host 172.16.31.10
access-list deny host 172.16.58.3
access-list deny host 172.16.17.32
access-list deny host 192.168.127.12
access-list deny host 192.168.3.11
access-list deny host 172.16.58.3
access-list deny host 172.16.31.10
access-list deny host 192.168.3.11
access-list deny host 172.16.58.3
access-list deny host 172.16.31.10
access-list deny host 192.168.127.12
access-list deny host 192.168.127.12
access-list deny host 172.16.17.32
access-list deny host 172.16.58.3
access-list deny host 172.16.31.10
access-list deny host 192.168.3.11
access-list deny host 172.16.17.32
access-list deny host 192.168.3.11
access-list deny host 172.16.17.32
access-list deny host 192.168.127.12
access-list deny host 172.16.31.10
access-list deny host 172.16.58.3
access-list deny host 192.168.3.11
access-list deny host 172.16.58.3
access-list deny host 172.16.58.3
access-list deny host 172.16.58.3
access-list deny host 172.16.31.10
access-list deny host 192.168.127.12
access-list deny host 172.16.17.32
access-list deny host 192.168.127.12
access-list deny host 172.16.31.10
access-list deny host 192.168.3.11
access-list deny host 172.16.17.32
access-list deny host 172.16.31.10
access-list deny host 172.16.58.3
access-list deny host 172.16.17.32
access-list deny host 172.16.31.10
access-list deny host 172.16.31.10
access-list deny host 192.168.127.12
access-list deny host 172.16.58.3
access-list deny host 172.16.58.3
access-list deny host 172.16.58.3
access-list deny host 192.168.3.11
access-list deny host 172.16.17.32
access-list deny host 172.16.17.32
access-list deny host 192.168.127.12
access-list deny host 192.168.3.11
access-list deny host 192.168.127.12
access-list deny host 172.16.17.32
access-list deny host 172.16.58.3
access-list deny host 192.168.127.12
access-list deny host 192.168.3.11
access-list deny host 192.168.127.12
access-list deny host 172.16.58.3
access-list deny host 172.16.31.10
access-list deny host 172.16.31.10
access-list deny host 172.16.31.10
access-list deny host 192.168.3.11
access-list deny host 192.168.3.11
access-list deny host 172.16.17.32
access-list deny host 192.168.3.11
access-list deny host 172.16.17.32
access-list deny host 172.16.58.3
access-list deny host 172.16.58.3
access-list deny host 172.16.31.10
access-list deny host 192.168.3.11
access-list deny host 192.168.127.12
access-list deny host 192.168.127.12
access-list deny host 172.16.58.3
access-list deny host 192.168.127.12
access-list deny host 192.168.127.12
access-list deny host 172.16.31.10
access-list deny host 172.16.31.10
access-list deny host 172.16.31.10
access-list deny host 192.168.3.11
access-list deny host 172.16.31.10
access-list deny host 172.16.17.32
access-list deny host 172.16.17.32
access-list deny host 172.16.58.3
access-list deny host 192.168.3.11
access-list deny host 192.168.3.11
access-list deny host 192.168.3.11
access-list deny host 192.168.3.11
access-list deny host 172.16.58.3
access-list deny host 172.16.58.3
access-list deny host 172.16.31.10
access-list deny host 192.168.127.12
access-list deny host 192.168.3.11
access-list deny host 172.16.58.3
access-list deny host 172.16.58.3
access-list deny host 192.168.127.12
access-list deny host 172.16.31.10
access-list deny host 192.168.127.12
access-list deny host 192.168.3.11
access-list deny host 172.16.17.32
access-list deny host 192.168.127.12
access-list deny host 172.16.58.3
access-list deny host 192.168.127.12
access-list deny host 192.168.3.11
access-list deny host 192.168.127.12
access-list deny host 192.168.127.12
access-list deny host 172.16.17.32
access-list deny host 172.16.31.10
access-list deny host 172.16.17.32
access-list deny host 172.16.31.10
access-list deny host 172.16.58.3
access-list deny host 192.168.3.11
access-list deny host 192.168.3.11
access-list deny host 192.168.3.11
access-list deny host 172.16.58.3
access-list deny host 192.168.127.12
access-list deny host 192.168.3.11
access-list deny host 192.168.127.12
access-list deny host 192.168.127.12
access-list deny host 172.16.58.3
access-list deny host 172.16.17.32
access-list deny host 192.168.127.12
access-list deny host 172.16.31.10
access-list deny host 192.168.3.11
access-list deny host 172.16.58.3
access-list deny host 192.168.3.11
access-list deny host 192.168.3.11
access-list deny host 192.168.3.11
access-list deny host 172.16.17.32
access-list deny host 172.16.58.3
access-list deny host 172.16.31.10
access-list deny host 192.168.127.12
access-list deny host 172.16.58.3
access-list deny host 172.16.31.10
access-list deny host 192.168.127.12
access-list deny host 172.16.31.10
access-list deny host 192.168.3.11
access-list deny host 172.16.31.10
access-list deny host 192.168.3.11
access-list deny host 172.16.58.3
access-list deny host 192.168.3.11
access-list deny host 192.168.127.12
access-list deny host 172.16.58.3
access-list deny host 192.168.3.11
access-list deny host 192.168.127.12
access-list deny host 192.168.3.11
access-list deny host 192.168.3.11
access-list deny host 172.16.58.3
access-list deny host 172.16.31.10
access-list deny host 192.168.3.11
access-list deny host 192.168.127.12
access-list deny host 172.16.31.10
access-list deny host 192.168.127.12
access-list deny host 172.16.31.10
access-list deny host 192.168.3.11
access-list deny host 172.16.58.3
access-list deny host 192.168.127.12
access-list deny host 172.16.31.10
access-list deny host 192.168.3.11
access-list deny host 172.16.31.10
access-list deny host 172.16.31.10
access-list deny host 172.16.31.10
access-list deny host 192.168.3.11
access-list deny host 172.16.31.10
access-list deny host 172.16.58.3
access-list deny host 192.168.127.12
access-list deny host 192.168.127.12
access-list deny host 172.16.17.32
access-list deny host 172.16.58.3
access-list deny host 192.168.3.11
access-list deny host 172.16.17.32
access-list deny host 172.16.58.3
access-list deny host 172.16.31.10
access-list deny host 172.16.58.3
access-list deny host 192.168.3.11
access-list deny host 172.16.58.3
access-list deny host 192.168.127.12
access-list deny host 192.168.127.12
access-list deny host 172.16.58.3
access-list deny host 192.168.127.12
access-list deny host 172.16.17.32
access-list deny host 172.16.17.32
access-list deny host 172.16.31.10
access-list deny host 172.16.31.10
access-list deny host 172.16.17.32
access-list deny host 192.168.3.11
access-list deny host 192.168.3.11
access-list deny host 172.16.58.3
access-list deny host 172.16.31.10
access-list deny host 172.16.17.32
access-list deny host 192.168.3.11
access-list deny host 172.16.31.10
access-list deny host 192.168.3.11
access-list deny host 172.16.58.3
access-list deny host 192.168.3.11
access-list deny host 172.16.58.3
access-list deny host 192.168.3.11
access-list deny host 172.16.58.3
access-list deny host 172.16.58.3
access-list deny host 172.16.17.32
access-list deny host 172.16.17.32
access-list deny host 192.168.3.11
access-list deny host 172.16.58.3
access-list deny host 192.168.127.12
access-list deny host 172.16.58.3
access-list deny host 172.16.58.3
access-list deny host 172.16.31.10
access-list deny host 192.168.3.11
access-list deny host 172.16.58.3
access-list deny host 172.16.17.32
access-list deny host 192.168.127.12
access-list deny host 192.168.3.11
access-list deny host 172.16.58.3
access-list deny host 192.168.127.12
access-list deny host 172.16.17.32
access-list deny host 172.16.58.3
access-list deny host 172.16.58.3
access-list deny host 172.16.58.3
access-list deny host 192.168.127.12
access-list deny host 192.168.3.11
access-list deny host 172.16.58.3
access-list deny host 192.168.127.12
access-list deny host 172.16.31.10
access-list deny host 172.16.58.3
access-list deny host 172.16.58.3
access-list deny host 172.16.31.10
access-list deny host 172.16.17.32
access-list deny host 172.16.58.3
access-list deny host 192.168.3.11
access-list deny host 172.16.31.10
access-list deny host 172.16.31.10
access-list deny host 172.16.58.3
access-list deny host 172.16.17.32
access-list deny host 192.168.127.12
access-list deny host 192.168.127.12
access-list deny host 172.16.58.3
access-list deny host 192.168.3.11
access-list deny host 192.168.3.11
access-list deny host 172.16.58.3
access-list deny host 172.16.31.10
access-list deny host 192.168.3.11
access-list deny host 172.16.17.32
access-list deny host 172.16.17.32
access-list deny host 172.16.31.10
access-list deny host 192.168.127.12
access-list deny host 192.168.127.12
access-list deny host 172.16.31.10
access-list deny host 192.168.127.12
access-list deny host 172.16.17.32
access-list deny host 172.16.17.32
access-list deny host 172.16.31.10
access-list deny host 172.16.17.32
access-list deny host 172.16.58.3
access-list deny host 172.16.58.3
access-list deny host 192.168.127.12
access-list deny host 192.168.127.12
access-list deny host 172.16.17.32
access-list deny host 172.16.17.32
access-list deny host 192.168.3.11
access-list deny host 172.16.31.10
<file_sep>/LinuxSSH/centos7/secure-ssh.sh
#SECURE-SSH.SH
#AUTHOR TURTLE0910
#!/bin/bash
#Creates a new ssh user called $l
read l
sudo useradd $l
sudo usermod -aG wheel $l
sudo mkdir /home/$l/.ssh
#Adds a public key to that users authorized key file
sudo cp linux/public-keys/SYS265.pub /home/$l/.ssh/authorized_keys
#Removes roots ablility to ssh in
sudo chmod 700 /home/$l/.ssh
sudo chmod 644 /home/$l/.ssh/authorized_keys
sudo chown -R $l:$l /home/$l/.ssh
echo "testing 123"
<file_sep>/Python/PycharmProjects_1718/Week4_Lab/medical.py
"""Management of Patient and Procedure Information.
Authors: <NAME>, <NAME>
Class: CSI-260-02
Assignment: Week 4 Lab
Due Date: February 12, 2019 11:59 PM
Certification of Authenticity:
I certify that this is entirely my own work, except where I have given
fully-documented references to the work of others. I understand the definition
and consequences of plagiarism and acknowledge that the assessor of this
assignment may, for the purpose of assessing this assignment:
- Reproduce this assignment and provide a copy to another member of academic
- staff; and/or Communicate a copy of this assignment to a plagiarism checking
- service (which may then retain a copy of this assignment on its database for
- the purpose of future plagiarism checking)
"""
import pickle
import csv
class Patient:
"""A patient's personal information.
Attributes:
first_name: string
last_name: string
address: string
phone_number: integer
emergency_fname: string
emergency_lname: string
emergency_phone: integer
id_num: integer
"""
_next_id = 0
#_all_patients = {}
def __init__(self, first_name, last_name, address, phone_number, emergency_fname, emergency_lname, emergency_phone):
"""Initializes Patient information
:param first_name: a patient's first name
:param last_name: a patient's last name
:param address: a patient's address
:param phone_number: a patient's phone number
:param emergency_fname: emergency contact's first name
:param emergency_lname: emergency contact's last name
:param emergency_phone: emergency contact's phone number
"""
self.first_name = first_name
self.last_name = last_name
self.address = address
self.phone_number = phone_number
self.emergency_fname = emergency_fname
self.emergency_lname = emergency_lname
self.emergency_phone = emergency_phone
self.id_num = Patient._next_id
Patient._next_id += 1
#_all_patients[self.id_nums] = self
def to_string(self):
string = f"Patient ID Number: {self.id_num}" \
f"\nPatient: {self.first_name} {self.last_name} " \
f"\nAddress: {self.address} " \
f"\nPhone Number: {self.phone_number} " \
f"\nEmergency Contact: {self.emergency_fname} {self.emergency_lname} " \
f"\nEmergency Phone Number: {self.emergency_phone}"
print(string)
@classmethod
def get_patient(cls, id_num):
"""Takes the ID number of a patient and returns the Patient information if the entry exists.
:return None or Patient Information
"""
# for Patient.id in Patient._all_patients:
# if id_num == Patient.id in Patient._all_patients:
# return Patient._all_patients[Patient.id].to_string()
# else:
# return None
with open('database.csv', 'r') as csv_file:
csv_reader = csv.reader(csv_file)
for line in csv_reader:
if line[0] == id_num:
Patient(line[0], line[1], line[2], line[3], line[4], line[5], line[6]).to_string()
else:
return None
@classmethod
def delete_patient(cls, id_num):
"""Takes the ID number of a patient and deletes the entry from the [_all_patients] dictionary."""
# for Patient.id in Patient._all_patients:
# if id_num == Patient.id in Patient._all_patients:
# return Patient.id
# else:
# return None
with open('database.csv', 'r') as bye_data, open('database_delete.csv', 'w') as data_out:
writer = csv.writer(data_out)
for row in csv.reader(bye_data):
if row[0] == id_num:
writer.writerow(row)
else:
return None
# @classmethod
# def save_patients(cls):
# """Saves the [_all_patients] dictionary to a file."""
# pickle.dump(Patient._all_patients, open("pickle.txt", 'wb'))
#
# @classmethod
# def load_patients(cls):
# """Loads the dictionary from a file, and then appropriately sets the next
# available ids for patients and procedures so that newly added
# patients will still get a unique id."""
# infile = open("pickle.txt", 'rb')
# Patient._all_patients = pickle.load(infile)
# infile.close()
# return Patient._all_patients
# @classmethod
# def save_patients(cls):
# with open('database.csv', 'r') as csv_file:
# csv_reader = csv.reader(csv_file)
# for line in csv.reader(csv_file):
# if line[0] == Patient.id_num
#
# @classmethod
# def load_patients(cls):
#
@classmethod
def add_procedure(cls):
name = input("Enter Name of Procedure: ")
date = input("Enter Date of Procedure: ")
med_practitioner = input("Enter Medical Practitioner: ")
cost = input("Enter Cost of Procedure: ")
Procedure(name, date, med_practitioner, cost).to_string()
class Procedure:
"""A Patient's procedure information.
Attributes:
name: string
date: string
med_practitioner: string
cost: integer
id_num : integer
"""
_num_procedures = 0
def __init__(self, name, date, med_practitioner, cost):
"""Initializes a Patient's procedure information.
:param name: a procedures name
:param date: the date of the procedure
:param med_practitioner: the medical practitioner performing the procedure
:param cost: the procedures cost
"""
self.name = name
self.date = date
self.med_practitioner = med_practitioner
self.cost = cost
Procedure._num_procedures += 1
self.id_num = Procedure._num_procedures
def to_string(self):
string = f"Procedure ID Number: {self.id_num}" \
f"\nProcedure Name: {self.name}" \
f"\nProcedure Date: {self.date}" \
f"\nMedical Practitioner: {self.med_practitioner} " \
f"\nCost of Procedure: {self.cost}"
print(string)
<file_sep>/Python/PycharmProjects_1819/Class Notes/Week4_Notes.py
# a = 1
# b = 1
# b = 1
#
# not_a = 0
# not_b = 0
# not_c = 0
#
# # Use this set up#
# a = "true"
# b = "true"
# c = "true"
#
# if (((a or b) and c) or [(a or not c) and not b]):
# print("true")
# else:
# print("false")
#
# x = 1
# y = 2
# z = 4
# if (x > y) or (z > x):
# print("The 'if' condition was met.")
# elif (x < y) and (z > x):
# print("The 'elif' statement returned a true.")
# else:
# print("All conditions failed.")
# y = 1,2,3,4,5
# for x in y:
# print(x)
#
# for x in range(0,11,2):
# print("The value in this range equals: ", x)
x = 0
while x < 10:
print("The value of x is", x)
break<file_sep>/Python/PycharmProjects_1819/Advanced_Python_Notes/Week1_Notes.py
# Error Handling
'''
while True:
try:
x = int(input("Enter a number: "))
print(x ** 2)
break
except ValueError: # only executed when that particular error comes up in the code
print("That was not a valid integer, please try again.")
finally: # always going to be executed
print("In finally block")
'''
'''
# Comprehension
values = list(range(10))
print(values)
squares = []
squares_dictionary = {}
for value in values:
if value % 2 == 0:
squares.append(value ** 2)
squares_dictionary[value] = value ** 2
print(squares)
print(squares_dictionary)
def square_value(x): # Not an Important example
return x ** 2
squares2 = list(map(square_value, values))
print(squares2)
squares3 = [value ** 2 for value in values if value % 2 == 0]
print(squares3)
squares_dictionary2 = {value: value ** 2 for value in values}
print(squares_dictionary2)
'''
# finding values (enumerate, zip)
values = ['hello', 'world', 'cool']
for index, value in enumerate(values):
print(index, value)
other_values = [34, 45, 78]
for value, other in zip(values, other_values):
print(value, other)
<file_sep>/AutomationScripting/Bash/Week10/menu.bash.save.1
#!/bin/bash
# Admin and Security admin menu.
# Admin Menu function
function admin_menu() {
# Clear the screen
clear
# Create menu options
echo "| System Administration Menu |"
echo ""
echo "1. List Running Processes"
echo "2. Show Open Network Sockets"
echo "3. Check Logged in Users"
echo "4. Show current username and groups"
echo "5. Show last users logged on"
echo "9. Return to Main Menu"
echo ""
echo "[E]xit"
# Prompt for the menu option
echo ""
echo -n "Please enter an option: "
# Read in the user input
read option
# Case statement to process options
case ${option} in
1) ps -ef | less
;;
2) netstat -an --inet | less
# lsof -i -n | less
;;
3) w | less
;;
4) id | less
# Print real and effective user id (uid) and group id (gid),
#prints identity information about the given user
# This is a good command as is gives current identity information about the user
#to make sure they are in the right account and such
;;
5) last -a | less
# Prints the last users who logged on
# This is a good command as if an issue with the system arose
#the administrator can check who was last logged on and
#investigate their actions
;;
6) lsusb | less
;;
7) lscpu | less
;;
8) lshw | less
;;
9) main_menu
;;
[Ee]) exit 0
;;
*) echo "| Invalid input |"
sleep 3
admin_menu
;;
# Stops the case statement
esac
# Call admin_menu
admin_menu
} # End admin_menu function
#Security Menu
function security_menu() {
# Clear the screen
clear
# Create menu options
echo "| Security Administration Menu |"
echo ""
echo "1. Show last logged in users"
echo "2. Check installed packages"
echo "3. Check all users and their ID"
echo "4. Return to Main Menu"
echo ""
echo "[E]xit"
# Prompt for the menu option
echo ""
echo -n "Please enter an option: "
# Read in the user input
read option
# Case statement to process options
case ${option} in
1) last -adx | less
;;
2) dpkg -l | less
;;
3) cut -d: -f1,3 /etc/passwd
;;
4) main_menu
;;
[Ee]) exit 0
;;
*) echo "| Invalid input |"
sleep 3
admin_menu
;;
# Stops the case statement
esac
# Call security menu
security_menu
} # End security_menu function
# Main Menu
function main_menu() {
# Clear the screen
clear
# Create menu options
echo "| Administration |"
echo ""
echo "1. System Admin Menu"
echo "2. Security Admin Menu"
echo ""
echo "[E]xit"
# Prompt for the menu option and read in the option
echo ""
echo -n "Please select a menu: "
read menuOption
if [[ ${menuOption} -eq 1 ]]
then
# Call the admin_menu function
admin_menu
elif [[ ${menuOption} -eq 2 ]]
then
# Call the security_menu function
security_menu
else
# Exit the program
exit 0
fi
} # End main_menu function
# Call main_menu function
main_menu
| c2584c3fbace76b253db1dfbc4fb435b1bbd1717 | [
"Python",
"Shell"
] | 80 | Python | absentee-neptune/Personal-Projects | 5cb7649093fd420c5a6882051aa82f4c947dd667 | 9c17e9112eca20a02ae8875c5790116db5170c45 |
refs/heads/master | <file_sep># TodoList
The repository includes the TodoList Application with use Nodejs-Electron-Mysql
<file_sep>const electron=require("electron");
const{ipcRenderer}=electron;
checkTodoCount();
//ilk penceredeki ekle butonunu aktif etme
const todoValue=document.querySelector("#todoValue");
//db den gelen verileri ana sayfada gosterme islemi
ipcRenderer.on("initApp",(e,todos)=>{
todos.forEach(todo=>{
drawRow(todo)
})
})
todoValue.addEventListener("keypress",(e)=>{
if(e.keyCode==13){
ipcRenderer.send("newToDoModal:save",
{ref: "main", todoValue: e.target.value
});
e.target.value="";
}
})
document.querySelector("#addBtn").addEventListener("click",()=>{
ipcRenderer.send("newToDoModal:save",{ ref: "main", todoValue: todoValue.value});
todoValue.value="";
})
document.querySelector("#closeBtn").addEventListener("click",()=>{
if(confirm("Çıkmak istiyor musunuz?")){
ipcRenderer.send("todo:close")
}
})
//db den gelen verilere anasayfada gosterme islemi
ipcRenderer.on("todo:addItem",(e,todo)=>{
drawRow(todo);
ipcRenderer.send("remove:todo",e.target.getAttribute("data-id"))
checkTodoCount()
})
//todo sayılarını kontrol edip eğer aktif todo yoksa uyarı mesajı verir
function checkTodoCount(){
const container = document.querySelector(".todo-container")
const alertContainer = document.querySelector(".alert-container")
//toplam kayıt sayısı alıp .total-count-container clasının textine yazdırır
document.querySelector(".total-count-container").innerText=
container.children.length;
if(container.children.length !==0){
alertContainer.style.display="none"
}
else{
alertContainer.style.display="block"
}
}
function drawRow(todo){
//container
const container = document.querySelector(".todo-container")
//row
//div den bir element üret
const row=document.createElement("div")
row.className="row"
//col
const col=document.createElement("div")
col.className="p-2 mb-3 text-light bg-dark col-md-12 shadow card d-flex justify-content-center flex-row align-items-center"
col.style.backgroundColor="yellow"
//p
const p =document.createElement("p")
p.className="m-0 w-100"
p.innerText=todo.text
//sil btn
const deleteBtn =document.createElement("button")
deleteBtn.className="btn btn-sm btn-outline-danger flex-shrink-1"
deleteBtn.innerText="X"
deleteBtn.setAttribute("data-id",todo.id)
deleteBtn.addEventListener("click",(e)=>{
if(confirm("bu kaydı silmek istedipinizden emin misiniz?")){
e.target.parentNode.parentNode.remove()
//silinen veririn id si alınıyor
ipcRenderer.send("remove:todo",e.target.getAttribute("data-id"))
checkTodoCount()
}
})
//içeriden dışarıya doğru todo listleri ekledik
col.appendChild(p);
col.appendChild(deleteBtn);
row.appendChild(col);
container.appendChild(row);
checkTodoCount();
}
<file_sep>const electron = require("electron");
const url = require("url");
const path = require("path");
const db = require("./lib/connection").db;
const mssql = require("mssql");
//const express = require("express");
const { app, BrowserWindow, Menu, ipcMain, MenuItem } = electron;
const dialog = electron.dialog;
const globalShortCut = electron.globalShortcut;
let mainWindow, addWindow;
var dbconfig = {
database: "sema",
server: "localhost",
port: "1433"
};
function getRecord() {
var conn = new mssql.ConnectionPool(dbconfig);
conn.connect(function(err) {
if (err) throw err;
var req = new mssql.Request(conn);
req.query("select * from sema.todos", function(e, recordset) {
if (e) throw e;
else console.log(recordset);
conn.close();
});
});
}
app.on("ready", () => {
mainWindow = new BrowserWindow({
webPreferences: {
nodeIntegration: true
}
});
mainWindow.setResizable(false);
//pencerenin oluşturulması
mainWindow.loadURL(
url.format({
pathname: path.join(__dirname, "mainWindow.html"),
protocol: "file:",
slashes: true,
frame: false //kapatma,aşağı indrime ve buyutme butonları kaldırıldı.
})
);
//menunun olusturulması
const mainMenu = Menu.buildFromTemplate(mainMenuTemplate);
Menu.setApplicationMenu(mainMenu);
ipcMain.on("todo:close", () => {
app.quit();
addWindow = null;
});
//new todo penceresi eventleri
ipcMain.on("newToDoModal:close", () => {
addWindow.close();
addWindow = null();
});
ipcMain.on("newToDoModal:save", (err, data) => {
if (data) {
db.query(
"INSERT INTO sema.todos SET text = ?",
data.todoValue,
(error, result, fields) => {
console.log(data);
console.log(error);
console.log(result);
if (result.insertId > 0) {
mainWindow.webContents.send("todo:addItem", {
id: result.insertId,
text: data.todoValue
});
}
}
);
//text deki kaydedilen değeri ekrana yazdırır
//console.log(todoList);
//mainWindow.webContents.send("todo:addItem",todo);
if (data.ref == "new") {
addWindow.close();
addWindow = null;
}
}
});
//context menu dizaynı
const contextMenu = new Menu();
contextMenu.append(new MenuItem({ label: "Kes", role: "cut" }));
contextMenu.append(new MenuItem({ label: "Kopyala", role: "copy" }));
contextMenu.append(new MenuItem({ label: "Yapıştır", role: "paste" }));
contextMenu.append(new MenuItem({ label: "Sil", role: "delete" }));
contextMenu.append(new MenuItem({ label: "Tümünü Seç", role: "selectAll" }));
mainWindow.webContents.on("context-menu", function(e, params) {
contextMenu.popup(mainWindow, params.x, params.y);
});
//veriler hazır olduğunda verş tabanı işlemlerini yapıyoruz
//ana pencerenin verileri geldiyse ->
mainWindow.webContents.once("dom-ready", () => {
db.query("SELECT * FROM sema.todos", (error, results, fields) => {
console.log(results);
mainWindow.webContents.send("initApp", results);
});
});
ipcMain.on("remove:todo", (e, id) => {
db.query(
"delete from sema.todos where id = ?",
id,
(error, result, fields) => {
//console.log(result)
if (result.affectedRows > 0) {
console.log("silme işlemi başarılı bir şekilde gerçekleşti...");
}
}
);
});
});
//manu template yapısı
const mainMenuTemplate = [
{
label: "Dosya",
submenu: [
{
label: "Yeni Todo Ekle",
accelerator: "CmdorCtrl + T",
click() {
createWindow();
}
},
{ type: "separator" },
{
label: "Çıkış",
accelerator: process.platform == "darwin" ? "Command+Q" : "Ctrl+Q", //kısayol oluşturur
role: "quit"
}
]
},
{
label: "Yardım",
submenu: [
{
label: "About Electron",
click: function() {
electron.shell.openExternal("https://electron.atom.io");
},
accelerator: "CmdorCtrl + H"
}
]
}
];
function createWindow() {
addWindow = new BrowserWindow({
width: 500,
height: 300,
webPreferences: {
nodeIntegration: true
}
// title="Yeni Bir Pencere"
//frame:false //kapatma,aşağı indrime ve buyutme butonları kaldırıldı.
});
addWindow.setResizable(false);
addWindow.loadURL(
url.format({
pathname: path.join(__dirname, "newToDoModal.html"),
protocol: "file:",
slashes: true
})
);
addWindow.on("close", () => {
addWindow = null;
});
}
| d548766a30c20b1fceeaaa05cf03033ab1df2993 | [
"Markdown",
"JavaScript"
] | 3 | Markdown | isayldrm/TodoList | ddd786bd01186a6c6b762528abdf7b7e228bfde1 | 1dc51ce3a0649229e429aa8c3764196c756c614d |
refs/heads/master | <file_sep><?php session_start();?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="Description" content="Application web de gestion des etudiants de l'université IST Anosy">
<meta name="Auteur" content="<NAME>">
<meta name="Contact" content="0344848963">
<title>IST | Anosy</title>
<link href="bootstrap/css/bootstrap.css" rel="stylesheet">
<link href="css/ist_anosy.css" rel="stylesheet">
<link href="css/template.css" rel="stylesheet">
<link rel="icon" href="ist_anosy.png">
<script src="bootstrap/js/jquery.min.js"></script>
<script src="bootstrap/js/bootstrap.js"></script>
<script src="js/main.js"></script>
</head>
<body>
<div class="container-fluid">
<!-- Second navbar for sign in -->
<nav class="navbar navbar-default ">
<div class="container">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar-collapse-2">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#"><?php if(isset($_SESSION['pseudo'])){
echo $_SESSION['pseudo'];
}else{
echo "IST | ANOSY";
} ?></a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="navbar-collapse-2">
<ul class="nav navbar-nav navbar-right">
<li><a href="/ist_anosy"><span class="glyphicon glyphicon-home" aria-hidden="true"></span> Accueil</a></li>
<li><a href="/ist_anosy/pages/admin.php"><span class="glyphicon glyphicon-wrench" aria-hidden="true"></span> Admin</a></li>
<li><a href="/ist_anosy/pages/A_propos.php">A propos</a></li>
<li>
<?php if(isset($_SESSION['utilisateur'])){
?>
<a class="btn btn-danger btn-outline btn-circle collapsed" data-toggle="collapse" href="#" aria-expanded="false" aria-controls="nav-collapse2">Deconnexion</a>
<?php
}
else{
?>
<a class="btn btn-default btn-outline btn-circle collapsed" data-toggle="collapse" href="#nav-collapse2" aria-expanded="false" aria-controls="nav-collapse2">Compte</a>
<?php
}?>
</li>
</ul>
<div class="collapse nav navbar-nav nav-collapse slide-down" id="nav-collapse2">
<?php
if(!(isset($_SESSION['utilisateur']))){
?>
<form action="crud/login.php" method="POST" class="navbar-form navbar-right form-inline" role="form">
<div class="form-group">
<label class="sr-only" for="nom">Nom</label>
<input type="email" name="nom" class="form-control" id="nom" placeholder="Nom" autofocus required />
</div>
<div class="form-group">
<label class="sr-only" for="Password">Mot de passe</label>
<input type="<PASSWORD>" name="password" class="form-control" id="Password" placeholder="<PASSWORD>" required />
</div>
<button type="submit" class="btn btn-primary">Connexion</button>
</form>
<?php
}else{
?>
<form action="crud/login.php" method="POST" class="navbar-form navbar-right form-inline logout" role="form">
<button type="submit" class="btn btn-danger">Deconnexion</button>
</form>
<?php
}
?>
</div>
</div><!-- /.navbar-collapse -->
</div><!-- /.container -->
</nav><!-- /.navbar -->
</div><!-- /.container-fluid -->
<div class="container">
<div class="row">
<div class="col-md-1"></div>
<div class="col-md-10 recherche">
<div id="custom-search-input">
<div class="input-group col-md-12">
<input id="recherche" type="text" class="form-control input-lg" placeholder="Rechercher..." />
<span class="input-group-btn">
<button class="btn btn-info btn-lg" type="button">
<i class="glyphicon glyphicon-search"></i>
</button>
</span>
</div>
</div>
</div>
<div class="col-md-1"></div>
</div>
<div class="row">
<div class="col-md-1"></div>
<div class="col-md-10">
<div id="resultat" class="row "></div>
</div>
<div class="col-md-1"></div>
</div>
</div>
<script type="text/javascript">
$("#creer_compte").click(function(){
window.location.href = "http://localhost/ist_anosy/template/inscription.php";
});
</script>
<!-- gap -->
<div class="gap"></div>
<!-- /gap -->
<?php include_once 'template/footer.php'; ?>
</body>
</html><file_sep>$(document).ready(function () {
$("#recherche").keyup(function(){
if($(this).val()!=""){
console.log("OK!");
var requete="requete="+$(this).val();
$.ajax({
type:"GET",
url:"crud/get_etudiant.php",
data:requete,
success:function(server_response){
$("#resultat").html(server_response).show();
}
});
}else{
$("#resultat").html("").show();
}
});
});<file_sep><?php
if(VerifieData()){
include_once 'connexion_bdd.php';
$requete = $connexion->prepare('INSERT INTO penalite (motif,annee,date,etudiant_id,administrateur) VALUES(?, 0,now(),?,?)');
$requete->execute(array($_POST['motif'], $_POST['etudiant_id'], $_POST['administrateur']));
// echo $_POST['etudiant_id'];
header('Location: ../pages/etudiant.php?id='.$_POST['etudiant_id']);
}
function VerifieData(){
if(isset($_POST['motif'])&&isset($_POST['etudiant_id'])&&isset($_POST['administrateur'])){
return true;
}
else
echo "misy tsy mety";
}
?><file_sep><?php
if(VerifieData()){
include_once 'connexion_bdd.php';
$requete = $connexion->prepare('INSERT INTO payement (montant,annee,date,etudiant_id,administrateur) VALUES(?, 0,now(),?,?)');
$requete->execute(array($_POST['montant'], $_POST['etudiant_id'], $_POST['administrateur']));
// echo $_POST['etudiant_id'];
header('Location: ../pages/etudiant.php?id='.$_POST['etudiant_id']);
}
function VerifieData(){
if(isset($_POST['montant'])&&isset($_POST['etudiant_id'])&&isset($_POST['administrateur'])){
return true;
}
else
echo "misy tsy mety";
}
?><file_sep><?php
if(VerifieData()){
include_once 'connexion_bdd.php';
$requete = $connexion->prepare('INSERT INTO filiere (nom_filiere) VALUES(?)');
$requete->execute(array($_POST['nom_filiere']));
// echo $_POST['etudiant_id'];
header('Location: ../pages/admin.php');
}
function VerifieData(){
if(isset($_POST['nom_filiere'])){
return true;
}
else
echo "misy tsy mety";
}
?><file_sep><!DOCTYPE html>
<html>
<head>
<title>IST | Anosy</title>
<link rel="icon" href="../ist_anosy.png">
<link href="/ist_anosy/bootstrap/css/bootstrap.css" rel="stylesheet">
<link href="/ist_anosy/css/template.css" rel="stylesheet">
<link href="/ist_anosy/css/admin.css" rel="stylesheet">
<meta charset="utf-8" />
</head>
<body>
<?php include_once '../template/header.php'; ?>
<div class="container">
<div class="row deca-haut-b">
<div class="col-md-12 well">
Ce page d'admin vous permet d'ajouter et de supprimer des items tel que les ecolages ou les filieres
</div>
</div>
<div class="row bloc-admin">
<h4 class="text-center">Admnistrer filiere</h4>
<div class="col-md-12">
<table class="table table-hover">
<tbody>
<tr>
<th class="">id</th>
<th class="">Nom filiere</th>
<th class="text-center">Operation</th>
</tr>
<?php
include_once '../crud/get_filiere.php';
while ($filiere=$listeFiliere->fetch()) {
?>
<tr>
<td class="col-md-6"><em><?php echo $filiere['id']; ?></em></td>
<td class="col-md-3"><?php echo $filiere['nom_filiere']; ?></td>
<td class="col-md-1 text-center"> <span class="glyphicon glyphicon-trash active-hand" data-toggle="modal" data-target=<?php echo "\"#confirmation".$filiere['id']."\""; ?>></span></td>
</tr>
<!-- modalConfirm -->
<div class="modal" id=<?php echo "\"confirmation".$filiere['id']."\""; ?> role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<strong> <span class="glyphicon glyphicon-alert"></span> Confirmation</strong>
</div>
<div class="modal-body">
<p> Supprimer le filiere <?php echo $filiere['nom_filiere'] ?>?</p>
<button class="btn btn-succes">Annuler</button> <a class="text-noir" href=<?php echo "../crud/delete_filiere.php?id=".$filiere['id']; ?>><button class="btn btn-danger">Supprimer </button></a>
</div>
</div>
</div>
</div>
<!-- /modalConfirm -->
<?php } ?>
</tbody>
</table>
<div class="row gap">
<form action="../crud/add_filiere.php" method="POST">
<div class="col-md-6"><input name="nom_filiere" class="form-control" placeholder="Nom filiere" type="text" required> </div>
<div class="col-md-2"><button class="btn btn-primary">Ajouter filiere</button></div>
</form>
</div>
</div>
</div>
<!-- gap -->
<div class="gap2"></div>
<!-- /gap -->
<!-- -->
<div class="row bloc-admin">
<h4 class="text-center">Admnistrer écolage</h4>
<div class="col-md-12">
<table class="table table-hover">
<tbody>
<tr>
<th class="">Niveau(Année)</th>
<th class="">Montant Ecolage(Ar)</th>
<th class="text-center">Operation</th>
</tr>
<?php
include_once '../crud/get_ecolage.php';
while ($ecolage=$listeEcolage->fetch()) {
?>
<form action="../crud/update_ecolage.php" method="POST">
<tr>
<td class="col-md-6"><?php echo $ecolage['niveau']; ?></td>
<td class="col-md-3"><input name="montant" class="form-control" value=<?php echo $ecolage['montant']; ?> placeholder="Niveau" type="text" required></td>
<input name="id" class="form-control" value=<?php echo $ecolage['id']; ?> type="hidden">
<td class="col-md-1 text-center"> <button class="btn"><span class="glyphicon glyphicon-floppy-save active-hand" data-toggle="modal" data-target=<?php echo "\"#confirmation2".$ecolage['id']."\""; ?>></span></button></td>
</tr>
</form>
<?php } ?>
</tbody>
</table>
</div>
</div>
<!-- / -->
<!-- gap -->
<div class="gap2"></div>
<!-- /gap -->
<!-- -->
<div class="row bloc-admin text-center">
<h4 class="text-center">Ajouter D'autres étudiants</h4>
<p>Si vous voulez ajouter de nouvelle etudiant cliquer sur le lien ci dessous</p>
<p><a href="new_etudiant.php">Ajouter?</a></p>
</div>
<!-- / -->
</div>
<!-- gap -->
<div class="gap"></div>
<!-- /gap -->
<?php include_once '../template/footer.php'; ?>
<script src="/ist_anosy/bootstrap/js/jquery.min.js"></script>
<script src="/ist_anosy/bootstrap/js/bootstrap.js"></script>
</body>
</html><file_sep><?php
include_once 'connexion_bdd.php';
//echo "OK";
if(isset($_GET['requete'])){
$requete=$_GET['requete'];
$tableau_requete=array('requete'=>$requete."%" );
$requete_SQL="SELECT * FROM etudiant WHERE nom LIKE :requete OR prenom LIKE :requete";
$resultat=$connexion->prepare($requete_SQL);
$resultat->execute($tableau_requete);
$count=$resultat->rowCount($requete_SQL);
if($count>=1){
while($row = $resultat->fetch()){
?>
<a class="bloc-user" href= <?php echo "/ist_anosy/pages/etudiant.php?id=".$row['id'] ; ?> >
<div class="col-md-4 single-user">
<div class="well well-sm single-user-well">
<div class="row">
<div class="col-sm-6 col-md-4">
<img src=<?php echo "img/".$row['photo']; ?> alt="" class="img-rounded img-responsive" />
</div>
<div class="col-sm-6 col-md-8">
<h4>
<?php echo $row["nom"]." ".$row['prenom']; ?></h4>
<small><cite title="San Francisco, USA" class="addresse"><?php echo $row['adresse']; ?> <i class="glyphicon glyphicon-map-marker">
</i></cite></small>
<p>
N°:<?php echo $row['num_insc']; ?>
<br />
</i><?php if($row['niveau']==1){echo "Niveau:".$row['niveau']."ère Année";}else{echo "Niveau:".$row['niveau']."ème Année";} ?>
<br />
Filiere:<?php
$requete_SQL2="SELECT * FROM filiere WHERE id=".$row['filiere'];
$resultat2=$connexion->prepare($requete_SQL2);
$resultat2->execute();
$row2 = $resultat2->fetch();
echo $row2['nom_filiere'];
?></p>
</div>
</div>
</div>
</div>
</a>
<?php
}
}else{
echo "pas de resultat";
}
}
?><file_sep><?php
if(VerifieData()){
include_once 'connexion_bdd.php';
$requete = $connexion->prepare('DELETE FROM `abscence` WHERE id=? ');
$requete->execute(array($_GET['id']));
header('Location: ../pages/etudiant.php?id='.$_GET['eid']);
}
function VerifieData(){
if(isset($_GET['id'])&&isset($_GET['eid'])){
return true;
}
else
echo "misy tsy mety";
}
?><file_sep><?php
include_once 'connexion_bdd.php';
$requete_filiere="SELECT * FROM filiere";
$listeFiliere=$connexion->prepare($requete_filiere);
$listeFiliere->execute();<file_sep># ist_anosy
Cette application web est destiné a l'administration des université notament de l'etablissement ist_anosy Fort-dauphin
pour pouvoir l'adapter a votre besoin effacer les fichiers dans le repertoire "img/" et installer la base de donnée app.sql et enfin finissez votre configuration dans le fichier "crud/connexion_bdd.php"
<file_sep> <div class="navbar navbar-default navbar-fixed-bottom">
<div class="container">
<p class="navbar-text pull-left">Copyright © <?php echo date('Y') ?> - IST Anosy
</p>
</div>
</div><file_sep><?php
if(VerifieData()){
include_once 'connexion_bdd.php';
$requete = $connexion->prepare('UPDATE ecolage SET montant=? WHERE id=?');
$requete ->execute(array($_POST['montant'],$_POST['id']));
header('Location: ../pages/admin.php');
}
function VerifieData(){
if(isset($_POST['montant'])&&isset($_POST['id'])){
return true;
}
else
return false;
}
?><file_sep><?php
try
{
$pdo_options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
$connexion = new PDO('mysql:host=localhost;dbname=ist_anosy', 'root','',$pdo_options);
}
catch(Exception $e)
{
die('Erreur : '.$e->getMessage());
}
?><file_sep><?php
if(VerifieData()){
$path='';
include_once 'connexion_bdd.php';
$requete = $connexion->prepare('UPDATE etudiant SET num_insc=?, nom=?,prenom=?,sexe=?,date_naissance=?,niveau=?,cin=?,adresse=?,tel=?,nom_pere=?,nom_mere=?,adresse_parent=?,tel_parent=?,email=?,filiere=?,photo=? WHERE id=?');
//======================
if (isset($_FILES['photo']) AND $_FILES['photo']['error']==0){
if ($_FILES['photo']['size'] <= 4000000)
{
$infosfichier=pathinfo($_FILES['photo']['name']);
$extension_upload = $infosfichier['extension'];
$extensions_autorisees = array('jpg','png','gif');
if (in_array($extension_upload,$extensions_autorisees)){
$path=time().rand(1111, 9999).".".$infosfichier['extension'];
move_uploaded_file($_FILES['photo']['tmp_name'], '../img/'.$path);
}
}
}
//======================
if($path==''){
$path=$_POST['photo'];
}
$requete ->execute(array($_POST['num_insc'],$_POST['nom'], $_POST['prenom'], $_POST['sexe'],date('Y-m-d',strtotime($_POST['date_naissance'])),$_POST['niveau'],$_POST['cin'],$_POST['adresse'],$_POST['tel'],$_POST['nom_pere'],$_POST['nom_mere'],$_POST['adresse_parent'],$_POST['tel_parent'],$_POST['email'],$_POST['filiere'],$path,$_POST['etudiant_id']));
header('Location: ../pages/etudiant.php?id='.$_POST['etudiant_id']);
}
function VerifieData(){
if(isset($_POST['num_insc'])&&isset($_POST['nom'])&&isset($_POST['prenom'])&&isset($_POST['sexe'])&&isset($_POST['date_naissance'])&&isset($_POST['niveau'])&&isset($_POST['cin'])&&isset($_POST['adresse'])&&isset($_POST['tel'])&&isset($_POST['nom_pere'])&&isset($_POST['nom_mere'])&&isset($_POST['adresse_parent'])&&isset($_POST['tel_parent'])&&isset($_POST['email'])&&isset($_POST['filiere'])&&isset($_FILES['photo'])&&isset($_POST['etudiant_id'])){
return true;
}
else
return false;
}
?><file_sep><!DOCTYPE html>
<html>
<head>
<title>IST | Anosy</title>
<link rel="icon" href="../ist_anosy.png">
<link href="/ist_anosy/bootstrap/css/bootstrap.css" rel="stylesheet">
<link href="/ist_anosy/css/etudiant.css" rel="stylesheet">
<link href="/ist_anosy/css/template.css" rel="stylesheet">
<meta charset="utf-8" />
</head>
<body>
<?php
include_once '../crud/connexion_bdd.php';
include_once '../template/header.php';
//echo "OK";
if(isset($_GET['id'])){
$requete=$_GET['id'];
$requete_SQL="SELECT * FROM etudiant WHERE id=".$_GET['id'];
$resultat=$connexion->prepare($requete_SQL);
$resultat->execute();
$etudiant = $resultat->fetch();
?>
<div class="container">
<div class="row">
<div class="col-md-12" >
<div class="panel panel-default">
<div class="panel-heading">
<h1 class="panel-title">Fiche de l'etudiant</h1>
</div>
<div class="panel-body">
<div class="row">
<div class="col-md-3 col-lg-3 " align="center"> <img alt="User Pic" src=<?php echo "../img/".$etudiant['photo']; ?> class="img-responsive"> </div>
<!--<div class="col-xs-10 col-sm-10 hidden-md hidden-lg"> <br>
<dl>
<dt>DEPARTMENT:</dt>
<dd>Administrator</dd>
<dt>HIRE DATE</dt>
<dd>11/12/2013</dd>
<dt>DATE OF BIRTH</dt>
<dd>11/12/2013</dd>
<dt>GENDER</dt>
<dd>Male</dd>
</dl>
</div>-->
<form action="/ist_anosy/crud/update_etudiant.php" method="POST" class="form" role="form" enctype="multipart/form-data">
<div class=" col-md-9 col-lg-9 ">
<table class="table table-user-information">
<tbody>
<tr>
<td>Nom et Prenom</td>
<td><input name="nom" class="form-control" value=<?php echo "'".$etudiant['nom']."'"; ?> placeholder="Nom de l'etudiant" type="text" required></td>
<td><input name="prenom" class="form-control" value=<?php echo "'".$etudiant['prenom']."'"; ?> placeholder="Prenom de l'etudiant" type="text" required></td>
</tr>
<tr>
<td>CIN et N° Inscription</td>
<td><input class="form-control" name="cin" value=<?php echo "'".$etudiant['cin']."'"; ?> placeholder="Numero CIN" type="text" required></td>
<td><input class="form-control" name="num_insc" value=<?php echo "'".$etudiant['num_insc']."'"; ?> placeholder="Numero inscription" type="text" required></td>
</tr>
<tr>
<td>Filiere et Année</td>
<td>
<select name="filiere" class="form-control">
<?php
$requete_SQL2="SELECT * FROM filiere";
$resultat2=$connexion->prepare($requete_SQL2);
$resultat2->execute();
while($filiere = $resultat2->fetch()){
?>
<option <?php if($filiere['id']==$etudiant['filiere']){ echo "value=\"".$filiere['id']."\" selected";}else{echo "value=\"".$filiere['id']."\"";} ?>><?php echo $filiere['nom_filiere']; ?></option>
<?php } ?>
</select>
</td>
<td><select name="niveau" class="form-control">
<?php
for ($i=1; $i <=4 ; $i++) {
$etat="";
if ($i==$etudiant['niveau']) {
# code...
$etat="selected";
}
?>
<option <?php echo "value=".$i." ".$etat ?> ><?php echo $i; ?></option>
<?php
}
?>
</select></td>
</tr>
<tr>
<tr>
<td>Date de naissance et Sêxe</td>
<td><select name="sexe" class="form-control">
<?php
if ($etudiant['sexe']==1) {
?>
<option value="1" selected>Masculin</option>
<option value="0">Feminin</option>
<?php
}
else{
?>
<option value="1">Masculin</option>
<option value="0" selected>Feminin</option>
<?php
}
?>
</select></td>
<td>
<div data-date-format="dd-mm-yyyy" data-date="12-02-2012" id="dp3" class="input-append date">
<input name="date_naissance" type="text" value=<?php echo date('d-m-Y',strtotime($etudiant['date_naissance'])); ?> class="span2">
<span class="add-on"><span class="glyphicon glyphicon-calendar active-hand"></span></span>
</div>
</td>
</tr>
<tr>
<td>Photo</td>
<td>
<div class="input-group image-preview">
<input type="text" class="form-control image-preview-filename" disabled="disabled"> <!-- don't give a name === doesn't send on POST/GET -->
<span class="input-group-btn">
<!-- image-preview-clear button -->
<button type="button" class="btn btn-default image-preview-clear" style="display:none;">
<span class="glyphicon glyphicon-remove"></span> Annuler
</button>
<!-- image-preview-input -->
<div class="btn btn-default image-preview-input">
<span class="glyphicon glyphicon-folder-open"></span>
<span class="image-preview-input-title">Choisir</span>
<input type="file" accept="image/png, image/jpeg, image/gif" name="photo"/> <!-- rename it -->
</div>
</span>
</div>
</td>
</tr>
<tr>
<td>Adresse</td>
<td><input name="adresse" class="form-control" value=<?php echo "'".$etudiant['adresse']."'"; ?> placeholder="Adresse Etudiant" type="text" required></td>
<td><input name="adresse_parent" class="form-control" value=<?php echo "'".$etudiant['adresse_parent']."'"; ?> placeholder="Adresse Parent" type="text" required></td>
</tr>
<tr>
<td>Parent</td>
<td><input name="nom_pere" class="form-control" value=<?php echo "'".$etudiant['nom_pere']."'"; ?> placeholder="Nom Père" type="text" required></td>
<td><input name="nom_mere" class="form-control" value=<?php echo "'".$etudiant['nom_mere']."'"; ?> placeholder="Nom Mère" type="text" required></td>
</tr>
<tr>
<td>Email</td>
<td><input name="email" class="form-control" value=<?php echo $etudiant['email']; ?> placeholder="Email" type="email" required></td>
</tr>
<tr>
<td>Telephone</td>
<td><input name="tel" class="form-control" value=<?php echo $etudiant['tel']; ?> placeholder="Tel etudiant" type="text" required></td><td><input name="tel_parent" class="form-control" value=<?php echo $etudiant['tel_parent']; ?> placeholder="Tel Parent" type="text" required>
</td>
</tr>
</tbody>
</table>
<a href="#" class="btn btn-primary" data-toggle="modal" data-target="#myModal">Etat Payement Ecolage</a>
<a href="#" class="btn btn-danger" data-toggle="modal" data-target="#myModal2">Etat Abscence</a>
<a href="#" class="btn btn-danger" data-toggle="modal" data-target="#myModal3">Etat Penalité</a>
<input type="hidden" name="etudiant_id" value=<?php echo $etudiant['id']; ?> />
<input type="hidden" name="photo" value=<?php echo $etudiant['photo']; ?> />
<span class="pull-right"><button class="btn btn-primary">Enregistrer <span class="glyphicon glyphicon-floppy-save"></span></button></span>
</div>
</form>
</div>
</div>
<div class="panel-footer">
<div class="row">
</div>
</div>
</div>
</div>
</div>
<!-- gap -->
<div class="gap"></div>
<!-- /gap -->
<?php include_once '../template/footer.php'; ?>
</div>
<?php } ?>
<script src="/ist_anosy/bootstrap/js/jquery.min.js"></script>
<script src="/ist_anosy/bootstrap/js/bootstrap.js"></script>
<script src="/ist_anosy/js/date.js"></script>
<script src="/ist_anosy/js/photo.js"></script>
<!-- modal -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="centerize"> <i class="glyphicon glyphicon-calendar"></i> Gerer payement écolage</h4>
</div>
<div class="modal-body well ">
<div class="row">
<div class="col-md-12">
<div class="row">
<div class="text-center">
<h3>Reçu</h3>
</div>
<table class="table table-hover">
<tbody>
<tr>
<th>Nom de l'administrateur</th>
<th class="text-center">Montant(Ar)</th>
<th class="text-center">date</th>
<th class="text-center">operation</th>
</tr>
<?php
$requete_payement="SELECT * FROM payement WHERE etudiant_id=".$etudiant['id']." AND annee=0";
$resultat_requete_payment=$connexion->prepare($requete_payement);
$resultat_requete_payment->execute();
$totale_payement=0;
while ($payement=$resultat_requete_payment->fetch()) {
$totale_payement+=$payement['montant'];
?>
<tr>
<td class="col-md-9"><em><?php echo $payement['administrateur']; ?></em></td>
<td class="col-md-1 text-center"><?php echo $payement['montant']; ?></td>
<td class="col-md-1 text-center"><?php echo date('d-m-Y',strtotime($payement['date'])); ?></td>
<td class="col-md-1 text-center"> <span class="glyphicon glyphicon-trash active-hand" data-toggle="modal" data-target=<?php echo "\"#confirmation".$payement['id']."\""; ?>></span></td>
</tr>
<!-- modalConfirm -->
<div class="modal" role="dialog" id=<?php echo "\"confirmation".$payement['id']."\""; ?>>
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<strong> <span class="glyphicon glyphicon-alert"></span> Confirmation</strong>
</div>
<div class="modal-body">
<p> Supprimer le payement de <?php echo $payement['montant']."Ar du date ".date('d-m-Y',strtotime($payement['date'])) ; ?>?</p>
<button class="btn btn-succes">Annuler</button> <a class="text-noir" href=<?php echo "\"../crud/delete_payement.php?id=".$payement['id']."&eid=".$etudiant['id']."\""; ?>><button class="btn btn-danger">Supprimer </button></a>
</div>
</div>
</div>
</div>
<!-- /modalConfirm -->
<?php
} ?>
</tbody>
</table>
<div class="row totale-payement">
<?php
$requete_ecolage="SELECT * FROM ecolage WHERE niveau=".$etudiant['niveau'];
$resultat_requete_ecolage=$connexion->prepare($requete_ecolage);
$resultat_requete_ecolage->execute();
$ecolage=$resultat_requete_ecolage->fetch();
?>
<div class="col-md-offset-6 col-md-6">
<p><strong>Totale payement: <?php echo $totale_payement."Ar"; ?></strong></p>
<p><strong>Ecolage: <?php echo $ecolage['montant']."Ar"; ?></strong></p>
<p><strong>Reste à payer: <?php echo ($ecolage['montant']-$totale_payement)."Ar"; ?></strong></p>
</div>
</div>
</div>
</div>
</div>
<hr>
<div class="modal-body">
<button type="button" class="btn btn-primary btn-sm btn-block" onclick="$('#target').toggle();">
Ajouter payement <span class=" glyphicon glyphicon-plus-sign"></span>
</button>
<div id="target" style="display: none">
<div class="row">
<div class="col-md-12">
<form action="../crud/add_payement.php" method="POST">
<input class="form-control deca-haut" name="montant" placeholder="Montant(Ar)" type="text" required>
<input type="hidden" name="administrateur" value="Clara" />
<input type="hidden" name="etudiant_id" value=<?php echo $etudiant['id']; ?> />
<input type="submit" class="btn btn-default btn-block btn-sm deca-haut" value="Enregistrer payement" />
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- /modal -->
<!-- modal2 -->
<div class="modal fade" id="myModal2" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="centerize"> <i class="glyphicon glyphicon-info-sign"></i> Gerer abscence</h4>
</div>
<div class="modal-body well ">
<div class="row">
<div class="col-md-12">
<div class="row">
<div class="text-center">
<h3>Nombre d'abscence</h3>
</div>
<table class="table table-hover">
<tbody>
<tr>
<th>Motif</th>
<th class="text-center">Nombre de jours</th>
<th class="text-center">date</th>
<th class="text-center">operation</th>
</tr>
<?php
$requete_abscence="SELECT * FROM abscence WHERE etudiant_id=".$etudiant['id']." AND annee=0";
$resultat_requete_payment=$connexion->prepare($requete_abscence);
$resultat_requete_payment->execute();
$i=0;
$totale_abcsence=0;
while ($abscence=$resultat_requete_payment->fetch()) {
$i++;
$totale_abcsence+=$abscence['nombre_jour'];
?>
<tr>
<td class="col-md-6"><em><?php echo $abscence['motif']; ?></em></td>
<td class="col-md-3 text-center"><?php echo $abscence['nombre_jour']; ?></td>
<td class="col-md-2 text-center"><?php echo date('d-m-Y',strtotime($abscence['date'])); ?></td>
<td class="col-md-1 text-center"> <span class="glyphicon glyphicon-trash active-hand" data-toggle="modal" data-target=<?php echo "\"#confirmation2".$abscence['id']."\""; ?>></span></td>
</tr>
<!-- modalConfirm -->
<div class="modal" id=<?php echo "\"confirmation2".$abscence['id']."\""; ?> role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<strong> <span class="glyphicon glyphicon-alert"></span> Confirmation</strong>
</div>
<div class="modal-body">
<p> Supprimer l'abscence du date <?php echo date('d-m-Y',strtotime($abscence['date'])) ; ?>?</p>
<button class="btn btn-succes">Annuler</button> <a class="text-noir" href=<?php echo "../crud/delete_abscence.php?id=".$abscence['id']."&eid=".$etudiant['id']; ?>><button class="btn btn-danger">Supprimer </button></a>
</div>
</div>
</div>
</div>
<!-- /modalConfirm -->
<?php } ?>
</tbody>
</table>
<div class="row totale-payement">
<div class="col-md-offset-6 col-md-6">
<p><strong>Nombre d'abscence: <?php echo $i; ?></strong></p>
<p><strong>Totale nombre de jour d'abscence: <?php echo $totale_abcsence; ?></strong></p>
</div>
</div>
</div>
</div>
</div>
<hr>
<div class="modal-body">
<button type="button" class="btn btn-primary btn-sm btn-block" onclick="$('#target2').toggle();">Ajouter Abcence <span class=" glyphicon glyphicon-plus-sign"></span>
</button>
<div id="target2" style="display: none">
<div class="row">
<div class="col-md-12">
<form action="../crud/add_abscence.php" method="POST">
<input class="form-control deca-haut" name="motif" placeholder="Motif d'abscence" type="text" required>
<input class="form-control deca-haut" name="nombre_jour" placeholder="Nombre de jours" type="text" required>
<input type="hidden" name="administrateur" value="Clara clara" />
<input type="hidden" name="etudiant_id" value=<?php echo $etudiant['id']; ?> />
<input type="submit" class="deca-haut btn btn-default btn-block btn-sm" value="Enregistrer abscence" />
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- /modal2 -->
<!-- modal3 -->
<div class="modal fade" id="myModal3" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="centerize"> <i class="glyphicon glyphicon-info-sign"></i> Gerer penalité</h4>
</div>
<div class="modal-body well ">
<div class="row">
<div class="col-md-12">
<div class="row">
<div class="text-center">
<h3>Nombre de penalité</h3>
</div>
<table class="table table-hover">
<tbody>
<tr>
<th>Motif</th>
<th class="text-center">date</th>
<th class="text-center">operation</th>
</tr>
<?php
$requete_penalite="SELECT * FROM penalite WHERE etudiant_id=".$etudiant['id']." AND annee=0";
$resultat_requete_penalite=$connexion->prepare($requete_penalite);
$resultat_requete_penalite->execute();
$j=0;
while ($penalite=$resultat_requete_penalite->fetch()) {
$j++;
?>
<tr>
<td class="col-md-8"><em><?php echo $penalite['motif']; ?></em></td>
<td class="col-md-3 text-center"><?php echo date('d-m-Y',strtotime($penalite['date'])); ?></td>
<td class="col-md-1 text-center"> <span class="glyphicon glyphicon-trash active-hand" data-toggle="modal" data-target=<?php echo "\"#confirmation3".$penalite['id']."\""; ?>></span></td>
</tr>
<!-- modalConfirm -->
<div class="modal" id=<?php echo "\"confirmation3".$penalite['id']."\""; ?> role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<strong> <span class="glyphicon glyphicon-alert"></span> Confirmation</strong>
</div>
<div class="modal-body">
<p> Supprimer la penalité du date <?php echo date('d-m-Y',strtotime($penalite['date'])) ; ?>?</p>
<button class="btn btn-succes">Annuler</button> <a class="text-noir" href=<?php echo "../crud/delete_penalite.php?id=".$penalite['id']."&eid=".$etudiant['id']; ?>><button class="btn btn-danger">Supprimer </button></a>
</div>
</div>
</div>
</div>
<!-- /modalConfirm -->
<?php } ?>
</tbody>
</table>
<div class="row totale-payement">
<div class="col-md-offset-6 col-md-6">
<p><strong>Nombre de penalité: <?php echo $j; ?></strong></p>
</div>
</div>
</div>
</div>
</div>
<hr>
<div class="modal-body">
<button type="button" class="btn btn-primary btn-sm btn-block" onclick="$('#target3').toggle();">Ajouter Abcence <span class=" glyphicon glyphicon-plus-sign"></span>
</button>
<div id="target3" style="display: none">
<div class="row">
<div class="col-md-12">
<form action="../crud/add_penalite.php" method="POST">
<input class="form-control deca-haut" name="motif" placeholder="Motif de la penalité" type="text" required>
<input type="hidden" name="administrateur" value="Clara clara" />
<input type="hidden" name="etudiant_id" value=<?php echo $etudiant['id']; ?> />
<input type="submit" class="deca-haut btn btn-default btn-block btn-sm" value="Enregistrer penalité" />
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- /modal3 -->
</body>
</html><file_sep><!DOCTYPE html>
<html>
<head>
<title>IST | Anosy</title>
<link rel="icon" href="../ist_anosy.png">
<link href="/ist_anosy/bootstrap/css/bootstrap.css" rel="stylesheet">
<link href="/ist_anosy/css/etudiant.css" rel="stylesheet">
<link href="/ist_anosy/css/template.css" rel="stylesheet">
<meta charset="utf-8" />
</head>
<body>
<?php
include_once '../crud/connexion_bdd.php';
include_once '../template/header.php';
?>
<div class="container">
<div class="row">
<div class="col-md-12" >
<div class="panel panel-default">
<div class="panel-heading">
<h1 class="panel-title">Ajout etudiant</h1>
</div>
<div class="panel-body">
<div class="row">
<div class="col-md-3 col-lg-3 " align="center"> <img alt="User Pic" src="../img/autocollant.png" class="img-responsive"> </div>
<!--<div class="col-xs-10 col-sm-10 hidden-md hidden-lg"> <br>
<dl>
<dt>DEPARTMENT:</dt>
<dd>Administrator</dd>
<dt>HIRE DATE</dt>
<dd>11/12/2013</dd>
<dt>DATE OF BIRTH</dt>
<dd>11/12/2013</dd>
<dt>GENDER</dt>
<dd>Male</dd>
</dl>
</div>-->
<form action="/ist_anosy/crud/add_etudiant.php" method="POST" class="form" role="form" enctype="multipart/form-data">
<div class=" col-md-9 col-lg-9 ">
<table class="table table-user-information">
<tbody>
<tr>
<td>Nom et Prenom</td>
<td><input name="nom" class="form-control" placeholder="Nom de l'etudiant" type="text" required></td>
<td><input name="prenom" class="form-control" placeholder="Prenom de l'etudiant" type="text" required></td>
</tr>
<tr>
<td>CIN et N° Inscription</td>
<td><input class="form-control" name="cin" placeholder="Numero CIN" type="text" required></td>
<td><input class="form-control" name="num_insc" placeholder="Numero inscription" type="text" required></td>
</tr>
<tr>
<td>Filiere et Année</td>
<td>
<select name="filiere" class="form-control">
<?php
$requete_SQL2="SELECT * FROM filiere";
$resultat2=$connexion->prepare($requete_SQL2);
$resultat2->execute();
while($filiere = $resultat2->fetch()){
?>
<option><?php echo $filiere['nom_filiere']; ?></option>
<?php } ?>
</select>
</td>
<td>
<select name="niveau" class="form-control">
<?php
for ($i=1; $i <=4 ; $i++) {
?>
<option <?php echo "value=".$i; ?> ><?php echo $i; ?></option>
<?php
}
?>
</select>
</td>
</tr>
<tr>
<tr>
<td>Date de naissance et Sêxe</td>
<td><select name="sexe" class="form-control">
<option value="1">Masculin</option>
<option value="0">Feminin</option>
</select></td>
<td>
<div data-date-format="dd-mm-yyyy" data-date="12-02-2012" id="dp3" class="input-append date">
<input name="date_naissance" type="text" class="span2">
<span class="add-on"><span class="glyphicon glyphicon-calendar active-hand"></span></span>
</div>
</td>
</tr>
<tr>
<td>Photo</td>
<td>
<div class="input-group image-preview">
<input type="text" class="form-control image-preview-filename" disabled="disabled"> <!-- don't give a name === doesn't send on POST/GET -->
<span class="input-group-btn">
<!-- image-preview-clear button -->
<button type="button" class="btn btn-default image-preview-clear" style="display:none;">
<span class="glyphicon glyphicon-remove"></span> Annuler
</button>
<!-- image-preview-input -->
<div class="btn btn-default image-preview-input">
<span class="glyphicon glyphicon-folder-open"></span>
<span class="image-preview-input-title">Choisir</span>
<input type="file" accept="image/png, image/jpeg, image/gif" name="photo"/> <!-- rename it -->
</div>
</span>
</div>
</td>
</tr>
<tr>
<td>Adresse</td>
<td><input name="adresse" class="form-control" placeholder="Adresse Etudiant" type="text" required></td>
<td><input name="adresse_parent" class="form-control" placeholder="Adresse Parent" type="text" required></td>
</tr>
<tr>
<td>Parent</td>
<td><input name="nom_pere" class="form-control" placeholder="Nom Père" type="text" required></td>
<td><input name="nom_mere" class="form-control" placeholder="<NAME>" type="text" required></td>
</tr>
<tr>
<td>Email</td>
<td><input name="email" class="form-control" placeholder="Email" type="email" required></td>
</tr>
<tr>
<td>Telephone</td>
<td><input name="tel" class="form-control" placeholder="Tel étudiant" type="text" required></td><td><input name="tel_parent" class="form-control" placeholder="Tel parent" type="text" required>
</td>
</tr>
</tbody>
</table>
<input type="hidden" name="photo" value=<?php echo "" ?> />
<span class="pull-right"><button class="btn btn-primary">Enregistrer <span class="glyphicon glyphicon-floppy-save"></span></button></span>
</div>
</form>
</div>
</div>
<div class="panel-footer">
<div class="row">
</div>
</div>
</div>
</div>
</div>
<!-- gap -->
<div class="gap"></div>
<!-- /gap -->
<?php include_once '../template/footer.php'; ?>
</div>
<script src="/ist_anosy/bootstrap/js/jquery.min.js"></script>
<script src="/ist_anosy/bootstrap/js/bootstrap.js"></script>
<script src="/ist_anosy/js/date.js"></script>
<script src="/ist_anosy/js/photo.js"></script>
</body>
</html><file_sep><!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>IST | Anosy</title>
<link rel="icon" href="../ist_anosy.png">
<link href="/ist_anosy/bootstrap/css/bootstrap.css" rel="stylesheet">
<link href="/ist_anosy/css/template.css" rel="stylesheet">
<link href="/ist_anosy/css/admin.css" rel="stylesheet">
<link href="/ist_anosy/css/style.css" rel="stylesheet">
<meta charset="utf-8" />
</head>
<body>
<?php include_once '../template/header.php'; ?>
<div class="container">
<!-- gap -->
<div class="gap"></div>
<!-- /gap -->
<div class="row">
<div class="col-lg-8 col-lg-offset-2 text-center">
<img src="../img/autocollant.png" alt="IST Anosy">
<h1>A propos de l'application!</h1>
<p>Hello everybody. I'm Stanley, a free handsome bootstrap theme coded by BlackTie.co. A really simple theme for those wanting to showcase their work with a cute & clean style.</p>
<p>Please, consider to register to <a href="http://eepurl.com/IcgkX">our newsletter</a> to be updated with our latest themes and freebies. Like always, you can use this theme in any project freely. Share it with your friends.</p>
</div><!-- /col-lg-8 -->
</div><!-- /row -->
</div>
<?php include_once '../template/footer.php'; ?>
<script src="/ist_anosy/bootstrap/js/jquery.min.js"></script>
<script src="/ist_anosy/bootstrap/js/bootstrap.js"></script>
</body>
</html>
<file_sep><?php
include_once 'connexion_bdd.php';
$requete_ecolage="SELECT * FROM ecolage";
$listeEcolage=$connexion->prepare($requete_ecolage);
$listeEcolage->execute();<file_sep><?php
if(VerifieData()){
$path='';
include_once 'connexion_bdd.php';
$requete = $connexion->prepare('INSERT INTO etudiant (num_insc, nom,prenom,sexe,date_naissance,niveau,cin,adresse,tel,nom_pere,nom_mere,adresse_parent,tel_parent,email,filiere,photo) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)');
//======================
if (isset($_FILES['photo']) AND $_FILES['photo']['error']==0){
if ($_FILES['photo']['size'] <= 4000000)
{
$infosfichier=pathinfo($_FILES['photo']['name']);
$extension_upload = $infosfichier['extension'];
$extensions_autorisees = array('jpg','png','gif');
if (in_array($extension_upload,$extensions_autorisees)){
$path=time().rand(1111, 9999).".".$infosfichier['extension'];
move_uploaded_file($_FILES['photo']['tmp_name'], '../img/'.$path);
}
}
}
//======================
if($path==''){
$path=$_POST['photo'];
}
$requete ->execute(array($_POST['num_insc'],$_POST['nom'], $_POST['prenom'], $_POST['sexe'],date('Y-m-d',strtotime($_POST['date_naissance'])),$_POST['niveau'],$_POST['cin'],$_POST['adresse'],$_POST['tel'],$_POST['nom_pere'],$_POST['nom_mere'],$_POST['adresse_parent'],$_POST['tel_parent'],$_POST['email'],$_POST['filiere'],$path));
header('Location: ../pages/admin.php');
}
function VerifieData(){
if(isset($_POST['num_insc'])&&isset($_POST['nom'])&&isset($_POST['prenom'])&&isset($_POST['sexe'])&&isset($_POST['date_naissance'])&&isset($_POST['niveau'])&&isset($_POST['cin'])&&isset($_POST['adresse'])&&isset($_POST['tel'])&&isset($_POST['nom_pere'])&&isset($_POST['nom_mere'])&&isset($_POST['adresse_parent'])&&isset($_POST['tel_parent'])&&isset($_POST['email'])&&isset($_POST['filiere'])&&isset($_FILES['photo'])){
return true;
}
else
echo "misy tsy mety";
}
?><file_sep><?php
if(VerifieData()){
include_once 'connexion_bdd.php';
$requete = $connexion->prepare('DELETE FROM `filiere` WHERE id=? ');
$requete->execute(array($_GET['id']));
header('Location: ../pages/admin.php');
}
function VerifieData(){
if(isset($_GET['id'])){
return true;
}
else
echo "misy tsy mety";
}
?><file_sep><?php
session_start();
include_once 'connexion_bdd.php';
$requete_SQL="SELECT * FROM utilisateur WHERE email='".$_POST['email']."' AND password='".$_POST['password']."'";
$resultat=$connexion->prepare($requete_SQL);
$resultat->execute();
$row = $resultat->fetch();
$_SESSION['pseudo']=$row['nom'];
$_SESSION['utilisateur']=$row;
header('Location: ../');
?> | 90a33fe81130842660981dc02c0e47f6c85fe3f9 | [
"JavaScript",
"Markdown",
"PHP"
] | 21 | PHP | ramasy/ist_anosy | e595f1896699bc97cd26394dd17352da0c91884d | 08e17bdfd374c90b251bf8db9c77147ee161594f |
refs/heads/master | <file_sep>/**
* Created by macbook on 2016-09-28.
*/
//test client input;
var input = "A*2 B C#*3 D Ab B";
var parseSong = function (string) {
var eachNote = string.split(" ");
var newNote=[];
for (var i = 0; i < eachNote.length; i++) {
var arr = eachNote[i].split("*");
if(!arr[1]){
arr[1]=1;
}
//arr[0]=pitch
//arr[1]=beats
var obj={};
obj["pitch"]=arr[0];
obj["beats"]=parseInt(arr[1]);
newNote.push(obj);
}
return newNote;
}
console.log(parseSong(input));
<file_sep>/**
* Created by macbook on 2016-09-29.
*/
//C#*2 C#*2 C#*2 C#*2 C#*2
// D#*2 D#*2 D#*2 D#*2 D#*2
var play_begining = function () {
$('#play').html('playing....');
$('#play').prop('disabled', true);
$('#play').attr('disabled', true);
$('#play').slideUp();
};
var play_finishing = function () {
$('#play').slideDown();
$('#play').html('play');
$('#play').attr('disabled', false);
$('#songName').html("Enter a song to play");
//clear the Ul>li name
//beacse the li is appedning afterward, so has to use delegate
// $('ul').on('click','li',function () {
// $(this).remove();
// })
};
$(document).ready(function () {
var notes_arr = [];
//just for test
// var notes_arr = [['a', 'C#*2 C#*2 C#*2 C#*2 C#*2'], ['b', 'D#*2 D#*2 D#*2 D#*2 D#*2', 'E#*2 E#*2 E#*2 E#*2 E#*2']];
$("form").on("submit", function (evt) {
//get the val from input text
var input_note = $('input[id=note]').val();
var input_name = $('input[id=name]').val();
//create a li inside ul
// $('ul').append('<li>Song name ' + input_name + ' ' + input_note + '</li>');
$('ul').append('<li>Song name ' + input_name);
//fade in your note when your mouse over the li
$("ul").on("mouseenter", "li", function () {
//get the index of li insode the ul
var index = $(this).index();
//fetch the li's note
$('#show-note').html(notes_arr[index][1]).fadeIn(1000);
});
//fade out note when mouse moves out
$("ul").on("mouseleave", "li", function () {
$('#show-note').fadeOut(1000);
});
//clear the input arear
$('input[id=note]').val("");
$('input[id=name]').val("");
//push note into a array
notes_arr.push([input_name, input_note]);
//not jump to a new page, stay in the same page
evt.preventDefault();
});
$('#play').on('click', function () {
play_begining();
// var input = prompt("give me your song");
console.log(notes_arr);
// playSong(parseSong(notes_arr[0]), 400, playSong(parseSong(notes_arr[1]),400));
//notes_arr[0][0] the first 0 is the first song, the second 0 is the 0 argument
//show the song's name when playing
$('#songName').html('Now playing ' + notes_arr[0][0]);
playSong(parseSong(notes_arr[0][1]), 400, playNext);
var i = 0;
function playNext() {
i++;
//play the next song
if (i < notes_arr.length) {
//show the next song's name
$('#songName').html("Now playing " + notes_arr[i][0]);
//play the song
playSong(parseSong(notes_arr[i][1]), 400, playNext);
} else {
//if n=notes_arr.length
play_finishing();
}
}
});
});
| 469a544e6c34c939249b9f95cdc66413400cc56f | [
"JavaScript"
] | 2 | JavaScript | zhuliangyu/judebox | 65a6ef54ec61fbfaf6fa56c3ed5ba3186d413bfa | 6302af86457187eb6f60fbb836911b27f98f3c81 |
refs/heads/master | <repo_name>Augustojf98/Expendedora<file_sep>/Expendedora.Consola/Clases/Maquina.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Expendedora.Consola.Clases
{
class Maquina
{
private List<Lata> _latas;
private string _proveedor;
private int _capacidad;
private double _dinero;
public bool _encendida;
public void AgregarLata(Lata lata)
{
try
{
this._latas.Add(lata);
}
catch
{
}
}
//public Lata ExtraerLata(string codigo, double dinero)
//{
// return this._latas.Equals().;
//}
public string GetBalance()
{
return "Dinero: " + "$" + this._dinero + ", Latas: " + this._latas.Count();
}
public int GetCapacidadRestante()
{
return this._capacidad - this._latas.Count();
}
public void EncenderMaquina()
{
this._encendida = true;
Console.WriteLine("La máquina fue encendida");
}
public bool EstaVacia()
{
return this._latas.Count() == 0;
}
}
}
<file_sep>/Expendedora.Consola/Clases/Lata.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Expendedora.Consola.Clases
{
class Lata
{
private string _codigo;
private string _nombre;
private string _sabor;
private double _precio;
private double _volumen;
public string Codigo
{
get
{
return _codigo;
}
set
{
this._codigo = value;
}
}
public string Nombre
{
get
{
return this._nombre;
}
set
{
this._nombre = value;
}
}
public string Sabor
{
get
{
return this._sabor;
}
set
{
this._sabor = value;
}
}
public double Precio
{
get
{
return this._precio;
}
set
{
this._precio = value;
}
}
public double Volumen
{
get
{
return this._volumen;
}
set
{
this._volumen = value;
}
}
public string GetDatosTotales()
{
return _nombre + " - " + _precio.ToString() + " $" + _precio + " / $/L" + this.GetPrecioPorLitro().ToString();
}
private double GetPrecioPorLitro()
{
return this._precio * 1000 / _volumen;
}
}
}
<file_sep>/Expendedora.Consola/Program.cs
using Expendedora.Consola.Clases;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Expendedora.Consola
{
class Program
{
static void Main(string[] args)
{
Maquina maquina = new Maquina();
Console.WriteLine("Presione 1 para encender la máquina");
var codIngresado = Console.ReadLine();
Console.Clear();
if (codIngresado.ToString() != "1")
{
throw new Exception(Exceptions.CodigoInvalido);
}
else{
maquina.EncenderMaquina();
Console.WriteLine("");
Console.WriteLine("-o-o-o-o-o-o-o-o-o-o-o-o-o-o-o-");
Console.WriteLine("");
Console.WriteLine("Presione 1 para ver el listado de latas");
Console.WriteLine("Presione 2 para agregar una lata");
Console.WriteLine("Presione 3 para extraer una lata");
Console.WriteLine("Presione 4 para obtener el balance");
Console.WriteLine("Presione 5 para mostrar el stock");
var accionSolicitada = Console.ReadLine();
if (int.Parse(accionSolicitada) == 1)
{
int cantidad = GetListadoLatas().Count();
Console.Clear();
Console.WriteLine("");
Console.WriteLine("Ingrese el código de la lata a agregar: ");
for (int i = 0; i < cantidad; ++i)
{
Console.WriteLine("");
Console.WriteLine("- " + GetListadoLatas()[i].Codigo);
}
}
else if (int.Parse(accionSolicitada) == 2)
{
int cantidad = GetListadoLatas().Count();
Console.Clear();
Console.WriteLine("");
for (int i = 0; i < cantidad; ++i)
{
Console.WriteLine(GetListadoLatas()[i].Codigo);
}
}
else if (int.Parse(accionSolicitada) == 3)
{
int cantidad = GetListadoLatas().Count();
Console.Clear();
Console.WriteLine("");
for (int i = 0; i < cantidad; ++i)
{
Console.WriteLine(GetListadoLatas()[i]);
}
}
else if (int.Parse(accionSolicitada) == 4)
{
int cantidad = GetListadoLatas().Count();
Console.Clear();
Console.WriteLine("");
for (int i = 0; i < cantidad; ++i)
{
Console.WriteLine(GetListadoLatas()[i]);
}
}
else if (int.Parse(accionSolicitada) == 5)
{
int cantidad = GetListadoLatas().Count();
Console.Clear();
Console.WriteLine("");
Console.WriteLine("La cantidad de latas en stock es: " + cantidad + " unidades");
for (int i = 0; i < cantidad; ++i)
{
Console.WriteLine("- " + GetListadoLatas().Find(f => f.Codigo == GetListadoLatas()[i].Codigo) + " " + GetListadoLatas()[i].Nombre + " " + GetListadoLatas()[i].Sabor);
}
}
}
Console.Read();
}
private static List<Lata> GetListadoLatas()
{
var listado = new List<Lata>();
Lata l1 = new Lata();
l1.Codigo = "CO1";
l1.Nombre = "Coca Cola";
l1.Sabor = "Regular";
Lata l2 = new Lata();
l2.Codigo = "CO2";
l2.Nombre = "Coca Cola";
l2.Sabor = "Zero";
Lata l3 = new Lata();
l3.Codigo = "SP1";
l3.Nombre = "Sprite";
l3.Sabor = "Regular";
Lata l4 = new Lata();
l4.Codigo = "SP2";
l4.Nombre = "Sprite";
l4.Sabor = "Zero";
Lata l5 = new Lata();
l5.Codigo = "FA1";
l5.Nombre = "Fanta";
l5.Sabor = "Regular";
Lata l6 = new Lata();
l6.Codigo = "FA2";
l6.Nombre = "Fanta";
l6.Sabor = "Zero";
listado.Add(l1);
listado.Add(l2);
listado.Add(l3);
listado.Add(l4);
listado.Add(l5);
listado.Add(l6);
return listado;
}
private static bool CodigosValidos(string codIngresado)
{
var listado = new List<string>();
listado.Add("CO1");
listado.Add("CO2");
listado.Add("SP1");
listado.Add("SP2");
listado.Add("FA1");
listado.Add("FA2");
int cantidad = listado.Count();
var listado2 = new List<bool>();
for (int i=0; i < cantidad; ++i)
{
listado2.Add(listado[i].Equals(codIngresado));
}
if (listado2.Find(f => f.Equals(true)))
{
return true;
}
else
{
throw new Exception(Exceptions.CodigoInvalido);
}
}
}
}
<file_sep>/Expendedora.Consola/Clases/Exceptions.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Expendedora.Consola.Clases
{
static class Exceptions
{
private static string _capacidadInexistenteException;
public static string CapacidadInexistente
{
get
{
return _capacidadInexistenteException = "La máquina no tiene más capacidad.";
}
}
private static string _dineroInsuficienteException;
public static string DineroInsuficiente
{
get
{
return _dineroInsuficienteException = "No se ingresó suficiente dinero.";
}
}
private static string _sinStockException;
public static string SinStock
{
get
{
return _sinStockException = "La máquina no tiene más stock.";
}
}
private static string _codigoInvalidoException;
public static string CodigoInvalido
{
get
{
return _codigoInvalidoException = "El código ingresado es inválido.";
}
}
}
}
| d91a8e763295ca4b2ce37b0528dd9afa16e3e57c | [
"C#"
] | 4 | C# | Augustojf98/Expendedora | 910e32b2c2a6a45a8af2ad0f135a2adf1df279a4 | 484feb4acc0aa1a81544c7bc44042d7051ecdd72 |
refs/heads/master | <repo_name>huxiaodi/Anything<file_sep>/src/main/java/com/test/framework/exception/AnyException.java
package com.test.framework.exception;
import com.test.framework.enums.ApiCodeEnum;
public class AnyException extends RuntimeException {
private Integer code;
public AnyException(ApiCodeEnum apiCodeEnum) {
super(apiCodeEnum.getMessage());
this.code = apiCodeEnum.getCode();
}
public AnyException(String message) {
super(message);
this.code = ApiCodeEnum.FAILURE.getCode();
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
}
<file_sep>/src/main/java/com/test/manage/model/generator/Role.java
package com.test.manage.model.generator;
import java.util.Date;
/**
* 角色
* role
* @mbg.generated do_not_delete_during_merge
*/
public class Role {
/**
* role.role_id
* @mbg.generated
*/
private String roleId;
/**
* 父级
* role.parent_role_id
* @mbg.generated
*/
private String parentRoleId;
/**
* 企业ID
* role.role_company_id
* @mbg.generated
*/
private String roleCompanyId;
/**
* 角色名称
* role.role_name
* @mbg.generated
*/
private String roleName;
/**
* 角色英文名称
* role.role_en_name
* @mbg.generated
*/
private String roleEnName;
/**
* 角色类型 1、前台 2、后台
* role.role_type
* @mbg.generated
*/
private Integer roleType;
/**
* 角色排序
* role.role_index
* @mbg.generated
*/
private Integer roleIndex;
/**
* 创建时间
* role.role_create_time
* @mbg.generated
*/
private Date roleCreateTime;
/**
* 创建人
* role.role_create_user_id
* @mbg.generated
*/
private String roleCreateUserId;
/**
* 修改时间
* role.role_update_time
* @mbg.generated
*/
private Date roleUpdateTime;
/**
* 修改人
* role.role_update_user_id
* @mbg.generated
*/
private String roleUpdateUserId;
/**
* 是否删除
* role.role_is_delete
* @mbg.generated
*/
private Boolean roleIsDelete;
/**
* @return the value of role.role_id
* @mbg.generated
*/
public String getRoleId() {
return roleId;
}
/**
* @param roleId the value for role.role_id
* @mbg.generated
*/
public void setRoleId(String roleId) {
this.roleId = roleId == null ? null : roleId.trim();
}
/**
* 父级
* @return the value of role.parent_role_id
* @mbg.generated
*/
public String getParentRoleId() {
return parentRoleId;
}
/**
* 父级
* @param parentRoleId the value for role.parent_role_id
* @mbg.generated
*/
public void setParentRoleId(String parentRoleId) {
this.parentRoleId = parentRoleId == null ? null : parentRoleId.trim();
}
/**
* 企业ID
* @return the value of role.role_company_id
* @mbg.generated
*/
public String getRoleCompanyId() {
return roleCompanyId;
}
/**
* 企业ID
* @param roleCompanyId the value for role.role_company_id
* @mbg.generated
*/
public void setRoleCompanyId(String roleCompanyId) {
this.roleCompanyId = roleCompanyId == null ? null : roleCompanyId.trim();
}
/**
* 角色名称
* @return the value of role.role_name
* @mbg.generated
*/
public String getRoleName() {
return roleName;
}
/**
* 角色名称
* @param roleName the value for role.role_name
* @mbg.generated
*/
public void setRoleName(String roleName) {
this.roleName = roleName == null ? null : roleName.trim();
}
/**
* 角色英文名称
* @return the value of role.role_en_name
* @mbg.generated
*/
public String getRoleEnName() {
return roleEnName;
}
/**
* 角色英文名称
* @param roleEnName the value for role.role_en_name
* @mbg.generated
*/
public void setRoleEnName(String roleEnName) {
this.roleEnName = roleEnName == null ? null : roleEnName.trim();
}
/**
* 角色类型 1、前台 2、后台
* @return the value of role.role_type
* @mbg.generated
*/
public Integer getRoleType() {
return roleType;
}
/**
* 角色类型 1、前台 2、后台
* @param roleType the value for role.role_type
* @mbg.generated
*/
public void setRoleType(Integer roleType) {
this.roleType = roleType;
}
/**
* 角色排序
* @return the value of role.role_index
* @mbg.generated
*/
public Integer getRoleIndex() {
return roleIndex;
}
/**
* 角色排序
* @param roleIndex the value for role.role_index
* @mbg.generated
*/
public void setRoleIndex(Integer roleIndex) {
this.roleIndex = roleIndex;
}
/**
* 创建时间
* @return the value of role.role_create_time
* @mbg.generated
*/
public Date getRoleCreateTime() {
return roleCreateTime;
}
/**
* 创建时间
* @param roleCreateTime the value for role.role_create_time
* @mbg.generated
*/
public void setRoleCreateTime(Date roleCreateTime) {
this.roleCreateTime = roleCreateTime;
}
/**
* 创建人
* @return the value of role.role_create_user_id
* @mbg.generated
*/
public String getRoleCreateUserId() {
return roleCreateUserId;
}
/**
* 创建人
* @param roleCreateUserId the value for role.role_create_user_id
* @mbg.generated
*/
public void setRoleCreateUserId(String roleCreateUserId) {
this.roleCreateUserId = roleCreateUserId == null ? null : roleCreateUserId.trim();
}
/**
* 修改时间
* @return the value of role.role_update_time
* @mbg.generated
*/
public Date getRoleUpdateTime() {
return roleUpdateTime;
}
/**
* 修改时间
* @param roleUpdateTime the value for role.role_update_time
* @mbg.generated
*/
public void setRoleUpdateTime(Date roleUpdateTime) {
this.roleUpdateTime = roleUpdateTime;
}
/**
* 修改人
* @return the value of role.role_update_user_id
* @mbg.generated
*/
public String getRoleUpdateUserId() {
return roleUpdateUserId;
}
/**
* 修改人
* @param roleUpdateUserId the value for role.role_update_user_id
* @mbg.generated
*/
public void setRoleUpdateUserId(String roleUpdateUserId) {
this.roleUpdateUserId = roleUpdateUserId == null ? null : roleUpdateUserId.trim();
}
/**
* 是否删除
* @return the value of role.role_is_delete
* @mbg.generated
*/
public Boolean getRoleIsDelete() {
return roleIsDelete;
}
/**
* 是否删除
* @param roleIsDelete the value for role.role_is_delete
* @mbg.generated
*/
public void setRoleIsDelete(Boolean roleIsDelete) {
this.roleIsDelete = roleIsDelete;
}
}<file_sep>/src/main/java/com/test/framework/security/AuthInterceptor.java
package com.test.framework.security;
import com.test.framework.enums.ApiCodeEnum;
import com.test.framework.exception.AnyException;
import com.test.framework.model.AuthUser;
import com.test.framework.utils.RedisUtils;
import com.google.common.base.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;
public class AuthInterceptor extends HandlerInterceptorAdapter {
@Autowired
private Auth auth;
@Autowired
private RedisUtils redisUtils;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
auth.setCurrentUser(null);
String token = request.getHeader("token");
if(Strings.isNullOrEmpty(token)){
throw new AnyException(ApiCodeEnum.TOKEN_INVALID);
}
Boolean hasKey = redisUtils.hasKey(token);
if(!hasKey){
throw new AnyException(ApiCodeEnum.TOKEN_INVALID);
}else{
// token 有效期 15分钟
redisUtils.expire(token,15L,TimeUnit.MINUTES);
}
AuthUser user = Auth.parseJWToken(token);
auth.setCurrentUser(user);
return true;
}
}<file_sep>/src/main/java/com/test/framework/enums/AuthEnum.java
package com.test.framework.enums;
public enum AuthEnum {
AUTH_USER("auth_user"),
MENUS("menus"),
;
private String value;
AuthEnum(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
<file_sep>/src/main/java/com/test/manage/model/dto/JsTreeStateDto.java
package com.test.manage.model.dto;
public class JsTreeStateDto {
private Boolean opened;
//private Boolean checked;
private Boolean selected = false;
public Boolean getSelected() {
return selected;
}
public void setSelected(Boolean selected) {
this.selected = selected;
}
// public Boolean getChecked() {
// return checked;
// }
//
// public void setChecked(Boolean checked) {
// this.checked = checked;
// }
public Boolean getOpened() {
return opened;
}
public void setOpened(Boolean opened) {
this.opened = opened;
}
public JsTreeStateDto(Boolean opened) {
this.opened = opened;
}
}
<file_sep>/src/main/java/com/test/manage/dao/custom/OrderCuMapper.java
package com.test.manage.dao.custom;
import com.test.manage.model.dto.OrderDto;
import com.test.manage.model.request.QueryParams;
import java.util.List;
public interface OrderCuMapper {
List<OrderDto> getOrderList(QueryParams queryParams);
List<OrderDto> getReceiveOrderList(QueryParams queryParams);
OrderDto getOrderInfo(String orderId);
}
<file_sep>/dlebvue/src/utils/tableUtil.js
import _ from 'lodash'
const objectToQueryString = (object) => {
let str = ''
_.forIn(object, (value, key) => {
console.log(key)
console.log(value)
if (_.isDate(value)) {
str += key + '=' + value + '&'
} else {
str += key + '=' + value + '&'
}
})
str = _.trimEnd(str, '&')
console.log(str)
return str
}
export default {
objectToQueryString
}
<file_sep>/dlebvue/src/mock/data/user.js
import Mock from 'mockjs'
const LoginUsers = [
{
id: 1,
userame: 'hugo',
password: '123',
name: ''
}
]
const Users = []
for (let i = 0; i < 100; i++) {
Users.push({
id: Mock.Random.guid(),
name: Mock.Random.cname(),
birth: Mock.Random.date()
})
}
export { LoginUsers, Users }
<file_sep>/src/main/java/com/test/manage/model/generator/Notice.java
package com.test.manage.model.generator;
import java.util.Date;
/**
* sys_notice
* @mbg.generated do_not_delete_during_merge
*/
public class Notice {
/**
* id
* sys_notice.sys_notice_id
* @mbg.generated
*/
private String sysNoticeId;
/**
* 标题
* sys_notice.sys_notice_title
* @mbg.generated
*/
private String sysNoticeTitle;
/**
* 内容
* sys_notice.sys_notice_content
* @mbg.generated
*/
private String sysNoticeContent;
/**
* 发布时间
* sys_notice.sys_notice_issue_time
* @mbg.generated
*/
private Date sysNoticeIssueTime;
/**
* 结束时间
* sys_notice.sys_notice_end_time
* @mbg.generated
*/
private Date sysNoticeEndTime;
/**
* 发布人
* sys_notice.sys_notice_create_user_id
* @mbg.generated
*/
private String sysNoticeCreateUserId;
/**
* 创建时间
* sys_notice.sys_notice_create_time
* @mbg.generated
*/
private Date sysNoticeCreateTime;
/**
* 是否删除 0-否,1-是
* sys_notice.sys_notice_is_delete
* @mbg.generated
*/
private Boolean sysNoticeIsDelete;
/**
* id
* @return the value of sys_notice.sys_notice_id
* @mbg.generated
*/
public String getSysNoticeId() {
return sysNoticeId;
}
/**
* id
* @param sysNoticeId the value for sys_notice.sys_notice_id
* @mbg.generated
*/
public void setSysNoticeId(String sysNoticeId) {
this.sysNoticeId = sysNoticeId == null ? null : sysNoticeId.trim();
}
/**
* 标题
* @return the value of sys_notice.sys_notice_title
* @mbg.generated
*/
public String getSysNoticeTitle() {
return sysNoticeTitle;
}
/**
* 标题
* @param sysNoticeTitle the value for sys_notice.sys_notice_title
* @mbg.generated
*/
public void setSysNoticeTitle(String sysNoticeTitle) {
this.sysNoticeTitle = sysNoticeTitle == null ? null : sysNoticeTitle.trim();
}
/**
* 内容
* @return the value of sys_notice.sys_notice_content
* @mbg.generated
*/
public String getSysNoticeContent() {
return sysNoticeContent;
}
/**
* 内容
* @param sysNoticeContent the value for sys_notice.sys_notice_content
* @mbg.generated
*/
public void setSysNoticeContent(String sysNoticeContent) {
this.sysNoticeContent = sysNoticeContent == null ? null : sysNoticeContent.trim();
}
/**
* 发布时间
* @return the value of sys_notice.sys_notice_issue_time
* @mbg.generated
*/
public Date getSysNoticeIssueTime() {
return sysNoticeIssueTime;
}
/**
* 发布时间
* @param sysNoticeIssueTime the value for sys_notice.sys_notice_issue_time
* @mbg.generated
*/
public void setSysNoticeIssueTime(Date sysNoticeIssueTime) {
this.sysNoticeIssueTime = sysNoticeIssueTime;
}
/**
* 结束时间
* @return the value of sys_notice.sys_notice_end_time
* @mbg.generated
*/
public Date getSysNoticeEndTime() {
return sysNoticeEndTime;
}
/**
* 结束时间
* @param sysNoticeEndTime the value for sys_notice.sys_notice_end_time
* @mbg.generated
*/
public void setSysNoticeEndTime(Date sysNoticeEndTime) {
this.sysNoticeEndTime = sysNoticeEndTime;
}
/**
* 发布人
* @return the value of sys_notice.sys_notice_create_user_id
* @mbg.generated
*/
public String getSysNoticeCreateUserId() {
return sysNoticeCreateUserId;
}
/**
* 发布人
* @param sysNoticeCreateUserId the value for sys_notice.sys_notice_create_user_id
* @mbg.generated
*/
public void setSysNoticeCreateUserId(String sysNoticeCreateUserId) {
this.sysNoticeCreateUserId = sysNoticeCreateUserId == null ? null : sysNoticeCreateUserId.trim();
}
/**
* 创建时间
* @return the value of sys_notice.sys_notice_create_time
* @mbg.generated
*/
public Date getSysNoticeCreateTime() {
return sysNoticeCreateTime;
}
/**
* 创建时间
* @param sysNoticeCreateTime the value for sys_notice.sys_notice_create_time
* @mbg.generated
*/
public void setSysNoticeCreateTime(Date sysNoticeCreateTime) {
this.sysNoticeCreateTime = sysNoticeCreateTime;
}
/**
* 是否删除 0-否,1-是
* @return the value of sys_notice.sys_notice_is_delete
* @mbg.generated
*/
public Boolean getSysNoticeIsDelete() {
return sysNoticeIsDelete;
}
/**
* 是否删除 0-否,1-是
* @param sysNoticeIsDelete the value for sys_notice.sys_notice_is_delete
* @mbg.generated
*/
public void setSysNoticeIsDelete(Boolean sysNoticeIsDelete) {
this.sysNoticeIsDelete = sysNoticeIsDelete;
}
}<file_sep>/src/main/java/com/test/configurer/MyWebMvcConfigurer.java
package com.test.configurer;
import com.test.framework.security.AuthInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
public class MyWebMvcConfigurer extends WebMvcConfigurerAdapter {
@Bean
public AuthInterceptor authInterceptor() {
return new AuthInterceptor();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(authInterceptor())
// 排除配置
.excludePathPatterns("/api/**")
.excludePathPatterns("/callback/**")
.excludePathPatterns("/user/login/**")
.excludePathPatterns("/user/register/**")
.excludePathPatterns("/home/**")
.excludePathPatterns("/bind/**")
//.excludePathPatterns("/pabank/**")
.excludePathPatterns("/openapi*/**") //对于开放式API暂时放开认证,提供给TMS使用
.excludePathPatterns("/swagger*/**")
.excludePathPatterns("/api/pay/**")// 业务平台发起的支付相关接口
.excludePathPatterns("/accountSub/accountSubController/returnBack")
.excludePathPatterns("/trade/accountSubTrade/**")
.excludePathPatterns("/pay/getPayInfoForBusiness")
.excludePathPatterns("/pay/returnbackForBusiness")
.excludePathPatterns("/pay/returnback")
.excludePathPatterns("/pay/queryStatus")
.excludePathPatterns("/refund/applicationfordrawback")
.excludePathPatterns("/invoiceManage/generateXml")
.excludePathPatterns("/testApi/show")
//.excludePathPatterns("/admin/**")
// .excludePathPatterns("/admin/dictionaryManage/**")
// 拦截配置
.addPathPatterns("/**");
}
}
<file_sep>/src/main/java/com/test/framework/configurer/JwtProperties.java
package com.test.framework.configurer;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
@Configuration
@ConfigurationProperties(prefix = "awesome.jwt")
@EnableConfigurationProperties(JwtProperties.class)
public class JwtProperties {
private String base64EncodedSecretKey;
private String issuer;
public String getBase64EncodedSecretKey() {
return base64EncodedSecretKey;
}
public void setBase64EncodedSecretKey(String base64EncodedSecretKey) {
this.base64EncodedSecretKey = base64EncodedSecretKey;
}
public String getIssuer() {
return issuer;
}
public void setIssuer(String issuer) {
this.issuer = issuer;
}
}
<file_sep>/src/main/java/com/test/manage/web/admin/RoleManageController.java
package com.test.manage.web.admin;
import com.test.manage.model.generator.User;
import com.test.manage.model.request.RolePageParams;
import com.test.manage.model.request.RoleParams;
import com.test.manage.service.role.RoleService;
import com.test.framework.controller.BaseController;
import com.test.framework.model.ApiResult;
import com.test.framework.model.AuthUser;
import com.test.framework.security.Auth;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
/**
* 角色管理
*/
@RestController
@RequestMapping("admin/roleManage")
public class RoleManageController extends BaseController {
@Autowired
private RoleService roleService;
@Autowired
private Auth auth;
/**
* 角色列表
*/
@PostMapping("/roleList")
public ApiResult roleList(@RequestBody RolePageParams rolePageParams) {
rolePageParams.startPage();
List<Map<String, Object>> role = roleService.manageList(rolePageParams);
return success(new PageInfo<>(role));
}
/**
* 角色列表
*/
@PostMapping("/roleListFront")
public ApiResult roleListFront(@RequestBody RolePageParams rolePageParams) {
rolePageParams.startPage();
List<Map<String, Object>> role = roleService.manageListFront(rolePageParams);
return success(new PageInfo<>(role));
}
/**
* 所有权限资源
*/
@GetMapping("/allRoleResources")
public ApiResult allRoleResources() {
return success(roleService.allRoleResources());
}
@GetMapping("/frontRoleResources")
public ApiResult frontRoleResources() {
return success(roleService.frontRoleResources());
}
/**
* 删除角色
*/
@PostMapping("/deleteRole")
public ApiResult deleteRole(@RequestBody RoleParams roleParams) {
try {
roleService.deleteRole(roleParams.getRoleId());
return success("角色删除成功");
} catch (Exception e) {
return error("角色删除失败");
}
}
/**
* 新增角色
*/
@PostMapping("/addRole")
public ApiResult addRole(@RequestBody RoleParams roleParams) {
try {
roleService.addRole(roleParams);
return success("角色新增成功");
} catch (Exception e) {
return error("角色新增失败");
}
}
@PostMapping("/addRoleFront")
public ApiResult addRoleFront(@RequestBody RoleParams roleParams) {
try {
roleService.addRoleFront(roleParams);
return success("角色新增成功");
} catch (Exception e) {
return error("角色新增失败");
}
}
/**
* 修改角色
*/
@PostMapping("/updateRole")
public ApiResult updateRole(@RequestBody RoleParams roleParams) {
try {
roleService.updateRole(roleParams);
return success("角色修改成功");
} catch (Exception e) {
return error("角色修改失败");
}
}
}
<file_sep>/src/main/java/com/test/framework/configurer/DateJsonDeserializer.java
package com.test.framework.configurer;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.boot.jackson.JsonComponent;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import java.util.TimeZone;
@JsonComponent
public class DateJsonDeserializer extends JsonDeserializer<Date> {
protected static final Logger logger = LogManager.getLogger(DateJsonDeserializer.class);
private final Set<String> patterns;
public DateJsonDeserializer() {
patterns = new HashSet<>();
patterns.add("yyyy-MM-dd EEE aa hh:mm:ss");
patterns.add("yyyy-MM-dd EEE HH:mm:ss");
patterns.add("yyyy-MM-dd HH:mm:ss");
patterns.add("yyyy-MM-dd HH:mm");
patterns.add("yyyy-MM-dd");
patterns.add("yyyy/MM/dd EEE aa hh:mm:ss");//2016/12/14 星期三 下午 3:52:49
patterns.add("yyyy/MM/dd EEE HH:mm:ss");
patterns.add("yyyy/MM/dd HH:mm:ss");
patterns.add("yyyy/MM/dd HH:mm");
patterns.add("yyyy/MM/dd");
}
@Override
public Date deserialize(JsonParser jsonparser, DeserializationContext deserializationcontext)
throws IOException {
try {
String date = jsonparser.getText();
if (StringUtils.isBlank(date)) {
return null;
}
String utcFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
if( date.length() == ( utcFormat.length()-4 ) ){
SimpleDateFormat sdf = new SimpleDateFormat(utcFormat);
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
try {
Date parse = sdf.parse(date);
return parse;
}catch (ParseException e){
logger.error(e);
}
}
return DateUtils.parseDate(date, patterns.toArray(new String[]{}));
} catch (ParseException e) {
logger.error(e);
return new Date();
}
}
}
<file_sep>/src/main/java/com/test/manage/web/admin/ResourceController.java
package com.test.manage.web.admin;
import com.test.manage.dao.custom.ResourceCuMapper;
import com.test.manage.model.dto.Menu;
import com.test.manage.model.dto.ResourceDto;
import com.test.manage.model.generator.Resource;
import com.test.manage.service.resource.ResourceService;
import com.test.framework.controller.BaseController;
import com.test.framework.model.ApiResult;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/basic")
public class ResourceController extends BaseController {
@Autowired
private ResourceService resourceService;
@Autowired
private ResourceCuMapper resourceCuMapper;
/***
*
* @author hugo
* @Description: 获取资源
* @param
* @return
* @throws
*/
@RequestMapping(value = "/resource", method = RequestMethod.GET)
public ApiResult menus() {
List<Resource> list = resourceService.grid();
List<ResourceDto> listDto = new ArrayList<ResourceDto>(list.size());
for(int i = 0;i<list.size();i++ ){
Resource resource = list.get(i);
ResourceDto resourceDto = new ResourceDto();
BeanUtils.copyProperties(resource, resourceDto);
int hasIndex = 0;
for(int j = 0 ;j<list.size();j++){
if(resource.getResourceId().equals(list.get(j).getParentResourceId())){
hasIndex++;
}
}
resourceDto.setChildNum(hasIndex);
listDto.add(resourceDto);
}
return success(listDto);
}
/***
*
* @author hugo
* @Description: 添加资源
* @param resource
* @return
* @throws
*/
@RequestMapping(value = "/resource", method = RequestMethod.POST)
public ApiResult add(@RequestBody Resource resource) {
resourceService.add(resource);
return success("资源添加成功");
}
/***
*
* @author hugo
* @Description: 修改资源
* @param resource
* @return
* @throws
*/
@RequestMapping(value = "/resource", method = RequestMethod.PUT)
public ApiResult update(@RequestBody Resource resource) {
resourceService.modify(resource);
return success("资源修改成功");
}
/***
*
* @author hugo
* @Description: 删除资源
* @param id
* @return
* @throws
*/
@RequestMapping(value = "/resource/{id}", method = RequestMethod.DELETE)
public ApiResult delete(@PathVariable String id) {
resourceService.delete(id);
return success("资源删除成功");
}
/***
*
* @author hugo
* @Description: 获取全部资源
* @return
* @throws
*/
@GetMapping("/getResouceTreeData")
public ApiResult getResouceTreeData() {
return success(resourceService.getResouceTreeData());
}
@GetMapping("/getFrontResouceTreeData")
public ApiResult getFrontResouceTreeData() {
List<Menu> frontMenu = resourceService.getFrontMenu("2");
List<String> frontButton = resourceService.getFrontButton();
Map<String, Object> map = new HashMap<>();
map.put("frontMenu",frontMenu);
map.put("frontButton",frontButton);
return success(map);
}
}
<file_sep>/src/main/java/com/test/framework/utils/RedisUtils.java
package com.test.framework.utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
@Component
public class RedisUtils {
@Autowired
private RedisTemplate redisTemplate;
@Autowired
private StringRedisTemplate stringRedisTemplate;
public String get(String key) {
return stringRedisTemplate.opsForValue().get(key);
}
public void set(String key, String value) {
stringRedisTemplate.opsForValue().set(key, value);
}
public void expire(String key, Long timeout, TimeUnit timeUnit) {
stringRedisTemplate.expire(key, timeout, timeUnit);
}
public void del(String key) {
stringRedisTemplate.delete(key);
}
public void hset(String h, Object hk, Object hv) {
stringRedisTemplate.opsForHash().put(h, hk, hv);
}
public Object hget(String h, Object hk) {
return stringRedisTemplate.opsForHash().get(h, hk);
}
public Object hdel(String h, Object hk) {
return stringRedisTemplate.opsForHash().delete(h, hk);
}
public void hmset(String h, Map map) {
stringRedisTemplate.opsForHash().putAll(h, map);
}
public Set keys(String key) {
return stringRedisTemplate.keys(key);
}
public Boolean hasKey(String key) {
return stringRedisTemplate.hasKey(key);
}
}<file_sep>/src/main/java/com/test/manage/service/user/impl/UserServiceImpl.java
package com.test.manage.service.user.impl;
import com.test.common.CommonUtil;
import com.test.manage.configurer.EbpayProperties;
import com.test.manage.dao.custom.RoleCuMapper;
import com.test.manage.dao.custom.UserCuMapper;
import com.test.manage.dao.generator.CompanyMapper;
import com.test.manage.dao.generator.UserMapper;
import com.test.manage.dao.generator.userRoleMapper;
import com.test.manage.model.form.UserForm;
import com.test.manage.model.generator.*;
import com.test.manage.model.request.LoginRequest;
import com.test.manage.model.request.QueryParams;
import com.test.manage.model.request.UserRequest;
import com.test.manage.service.role.RoleService;
import com.test.manage.service.user.UserService;
import com.test.framework.enums.AuthEnum;
import com.test.framework.exception.AnyException;
import com.test.framework.model.ApiResult;
import com.test.framework.model.AuthUser;
import com.test.framework.security.Auth;
import com.test.framework.utils.*;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import static com.test.framework.utils.ApiResultUtil.error;
import static com.test.framework.utils.ApiResultUtil.success;
@Service
@Transactional
public class UserServiceImpl implements UserService {
@Autowired
private Auth auth;
@Autowired
private UserMapper userMapper;
@Autowired
private UserCuMapper userCuMapper;
@Autowired
private CompanyMapper companyMapper;
@Autowired
private EbpayProperties ebpayProperties;
@Autowired
private RoleCuMapper roleCuMapper;
@Autowired
private userRoleMapper userRoleMapper;
@Autowired
private RoleService roleService;
@Autowired
private RedisUtils redisUtils;
private String passwordReg = "^(?=[^A-Z\\u4e00-\\u9fa5]*[0-9])(?=[^A-Z\\u4e00-\\u9fa5]*[a-z])[^A-Z\\u4e00-\\u9fa5]{8,50}$";
@Override
public ApiResult login(LoginRequest loginRequest) {
String userName = loginRequest.getUserName();
String password = loginRequest.getUserPassword();
Integer userType = loginRequest.getUserType();
UserExample userExample = new UserExample();
UserExample.Criteria criteria = userExample.createCriteria();
if (userType != null && userType == 0) {
criteria.andUserNameEqualTo(userName).andUserTypeEqualTo(userType);
} else {
criteria.andUserNameEqualTo(userName).andUserTypeNotEqualTo(0);
}
User user = userMapper.selectByExample(userExample).stream().findFirst().orElse(null);
if (user == null) {
throw new AnyException("账号不存在");
}
if (user.getUserStatus() == 0) {
throw new AnyException("此用户已禁用");
}
if (!user.getPassword().equals(SecurityUtils.encrypt(password))) {
throw new AnyException("密码错误");
}
AuthUser authUser = new AuthUser();
authUser.setUserId(user.getUserId());
authUser.setUserName(user.getUserName());
authUser.setUserType(user.getUserType());
authUser.setUserCompanyId(user.getUserCompanyId());
authUser.setUserHeadImg(user.getUserHeadImg());
authUser.setUserCnName(user.getUserCnName());
if (user.getUserType().equals(2) || user.getUserType().equals(3) ) { // 企业用户
Company company = companyMapper.selectByPrimaryKey(user.getUserCompanyId());
authUser.setUserCompanyName(company.getCompanyName());
authUser.setUserCompanyId(company.getCompanyId());
} else if (user.getUserType().equals(1)) {//个人用户
}
String token = auth.createJWToken(authUser);
redisUtils.hset(token, AuthEnum.AUTH_USER.getValue(), JsonUtils.toJSONString(authUser));
// token 有效期 15分钟
redisUtils.expire(token, 15L, TimeUnit.MINUTES);
authUser.setUserToken(token);
return ApiResultUtil.success(authUser);
}
@Override
public ApiResult save(User user, Company company, String mobile) throws Exception {
String userId = CommonUtil.uuid();
String companyId = CommonUtil.uuid();
user.setUserId(userId);
user.setPassword(SecurityUtils.encrypt(user.getPassword()));
user.setUserStatus(1);
user.setUserMobile(mobile);
user.setUserCreateTime(new Date());
user.setUserIsDelete(false);
user.setUserCompanyId(companyId);
userMapper.insertSelective(user);
company.setCompanyId(companyId);
company.setCompanyStatus(1);
company.setCompanyCreateTime(new Date());
company.setCompanyIsDelete(false);
companyMapper.insertSelective(company);
roleService.addFrontUserRole(user);
return success("注册成功");
}
/**
* 管理端 用户列表
*/
@Override
public List manageList(QueryParams queryParams) {
return userCuMapper.manageList(queryParams);
}
@Override
public Boolean checkMobile(String mobile) {
UserExample userExample = new UserExample();
userExample.createCriteria().andUserMobileEqualTo(mobile);
List<User> users = userMapper.selectByExample(userExample);
CompanyExample companyExample = new CompanyExample();
companyExample.createCriteria().andCompanyContactTelEqualTo(mobile);
List<Company> companies = companyMapper.selectByExample(companyExample);
if (users.isEmpty() && companies.isEmpty()) {
return true;
}
throw new AnyException("手机号已注册");
}
@Override
public User checkUser(String userName) {
UserExample userExample = new UserExample();
userExample.createCriteria().andUserNameEqualTo(userName);
return userMapper.selectByExample(userExample).stream().findFirst().orElse(null);
}
@Override
public ApiResult resetPassword(UserRequest userRequest) {
String userName = userRequest.getUserName();
User user = checkUser(userName);
if (user == null) {
throw new AnyException("账号不存在");
}
String password = userRequest.getNewPassword();
if (password.matches(passwordReg)) {
user.setPassword(SecurityUtils.encrypt(password));
userMapper.updateByPrimaryKeySelective(user);
return success("成功重置密码");
} else {
return error("密码格式错误");
}
}
@Override
public boolean checkMobile(UserRequest userRequest) {
User user = checkUser(userRequest.getUserName());
Integer userType = user.getUserType();
String mobile = userRequest.getMobile();
String reserveMobile = user.getUserMobile();
if (userType == 2) {
reserveMobile = companyMapper.selectByPrimaryKey(user.getUserCompanyId()).getCompanyContactTel();
}
return mobile.equals(reserveMobile);
}
@Override
public ApiResult changePassword(UserRequest userRequest) {
String userPassword = SecurityUtils.encrypt(userRequest.getUserPassword());
String newPassword = SecurityUtils.encrypt(userRequest.getNewPassword());
AuthUser authUser = auth.getCurrentUser();
UserExample example = new UserExample();
example.createCriteria().andUserIdEqualTo(authUser.getUserId()).andPasswordEqualTo(userPassword);
User user = userMapper.selectByExample(example).stream().findFirst().orElse(null);
if (user == null) {
throw new AnyException("旧密码错误");
}
if (userPassword.equals(newPassword)) {
throw new AnyException("新旧密码相同");
}
if (newPassword.matches(passwordReg)) {
user.setPassword(newPassword);
userMapper.updateByPrimaryKeySelective(user);
return success("您的密码已修改成功");
} else {
return error("密码格式错误");
}
}
@Override
public Integer changeMobile(UserRequest userRequest) {
String mobile = userRequest.getNewMobile();
AuthUser authUser = auth.getCurrentUser();
Company company = new Company();
company.setCompanyId(authUser.getUserCompanyId());
company.setCompanyContactTel(mobile);
Integer i = companyMapper.updateByPrimaryKeySelective(company);
User user = new User();
user.setUserId(authUser.getUserId());
user.setUserMobile(mobile);
Integer j = userMapper.updateByPrimaryKeySelective(user);
return i + j;
}
@Override
public Company getCompanyInformation(String userCompanyId) {
return companyMapper.selectByPrimaryKey(userCompanyId);
}
@Override
public void upload(Company company) {
companyMapper.updateByPrimaryKeySelective(company);
}
@Override
public void changeCompanyInformation(Company company) {
companyMapper.updateByPrimaryKeySelective(company);
}
@Override
public User getPersonalInformation(String userId) {
return userMapper.selectByPrimaryKey(userId);
}
@Override
public void changePersonalInformation(User user) {
userMapper.updateByPrimaryKeySelective(user);
}
@Override
public void upload(User user) {
userMapper.updateByPrimaryKeySelective(user);
}
public User selectByPrimaryKey(String id) {
return userMapper.selectByPrimaryKey(id);
}
public void updateByPrimaryKeySelective(User user) {
userMapper.updateByPrimaryKeySelective(user);
}
@Override
public Boolean checkUserName(User user) {
UserExample userExample = new UserExample();
userExample.createCriteria().andUserNameEqualTo(user.getUserName());
List<User> list = userMapper.selectByExample(userExample);
if (list.size() == 0) {
return true;
} else {
return false;
}
}
@Override
public List<Map<String, Object>> getUserMemberList(UserForm userForm) {
AuthUser authUser = auth.getCurrentUser();
Integer userType = authUser.getUserType();
userForm.setUserType(userType);
// 类型,0-后台用户,1-个人,2-企业
if (userType == 2) {
userForm.setUserCompanyId(authUser.getUserCompanyId());
}
PageHelper.startPage(userForm);
List<Map<String, Object>> list = userCuMapper.getUserMemberList(userForm);
for (Map map : list) {
String userId = (String) map.get("userId");
List<Role> roles = roleCuMapper.getRoleByUserId(userId);
String roleNames = roles.stream().map(Role::getRoleName).collect(Collectors.joining(","));
List<String> roleIds = roles.stream().map(Role::getRoleId).collect(Collectors.toList());
map.put("roleNames", roleNames);
map.put("roleIds", roleIds);
}
return list;
}
@Override
public void addUser(UserRequest userRequest) {
String userName = userRequest.getUserName();
UserExample userExample = new UserExample();
userExample.createCriteria().andUserNameEqualTo(userName);
User user = userMapper.selectByExample(userExample).stream().findFirst().orElse(null);
if (user != null) {
throw new AnyException("用户名已存在");
}
AuthUser authUser = auth.getCurrentUser();
String userId = CommonUtil.uuid();
user = new User();
user.setUserId(userId);
user.setUserCompanyId(authUser.getUserCompanyId());
user.setUserType(authUser.getUserType());
user.setUserName(userRequest.getUserName());
user.setPassword(SecurityUtils.encrypt(userRequest.getUserPassword()));
user.setUserMobile(userRequest.getMobile());
user.setUserCreateUserId(authUser.getUserId());
user.setUserCreateTime(new Date());
user.setUserIsDelete(false);
user.setUserStatus(1);
userMapper.insertSelective(user);
userRequest.setUserId(userId);
updateRolesAndTeams(userRequest);
}
@Override
public void modify(UserRequest userRequest) {
AuthUser authUser = auth.getCurrentUser();
User user = new User();
user.setUserId(userRequest.getUserId());
user.setUserMobile(userRequest.getMobile());
user.setUserCnName(userRequest.getUserCnName());
user.setUserUpdateUserId(authUser.getUserId());
user.setUserUpdateTime(new Date());
userMapper.updateByPrimaryKeySelective(user);
updateRolesAndTeams(userRequest);
}
@Override
public List<Resource> getResource(String userId) {
return userCuMapper.getResource(userId);
}
@Override
public void loginOut(String token) {
AuthUser authUser = auth.getCurrentUser();
AuthUser user = Auth.parseJWToken(token);
if (!StringUtils.equals(user.getUserName(), authUser.getUserName())) {
throw new AnyException("登出失败");
}
redisUtils.del(token);
}
//更新用户的角色和分组
public void updateRolesAndTeams(UserRequest userRequest) {
String authUserId = auth.getCurrentUser().getUserId();
String userId = userRequest.getUserId();
// 更新用户的角色
userRoleExample example = new userRoleExample();
example.createCriteria().andUserRoleUserIdEqualTo(userId);
userRoleMapper.deleteByExample(example);
if (userRequest.getRoleIds() != null) {
userRequest.getRoleIds().forEach(roleId -> {
userRole userRole = new userRole();
userRole.setUserRoleUserId(userId);
userRole.setUserRoleRoleId(roleId);
userRole.setUserRoleCreateUserId(authUserId);
userRole.setUserRoleCreateTime(new Date());
userRoleMapper.insertSelective(userRole);
});
}
}
}
<file_sep>/dlebvue/src/router/index.js
import Vue from 'vue'
import Router from 'vue-router'
// 管理端页面导入
import Loyout from '@/layout/Loyout'
import NotFound from '@/views/404'
import Home from '@/views/Home'
import AdminLogin from '@/views/AdminLogin'
import NoticeManageList from '@/views/NoticeManageList'
import UserMemberList from '@/views/UserMemberList'
import UserCreate from '@/views/UserCreate'
import BusinessMemberList from '@/views/BusinessMemberList'
import BusinessMemberEdit from '@/views/BusinessMemberEdit'
import BusinessMemberDetails from '@/views/BusinessMemberDetails'
import OrderManageList from '@/views/OrderManageList'
import orderDetail from '@/views/orderDetail'
import PersonalCenter from '@/views/PersonalCenter'
import PasswordSetting from '@/views/PasswordSetting'
import PasswordEdit from '@/views/PasswordEdit'
// 用户端页面导入
import Login from '@/views-front/Login'
import FrontLoyout from '@/layout-front/FrontLoyout'
import AccountCentral from '@/views-front/AccountCentral'
import ChangePassword from '@/views-front/ChangePassword'
import IssueGoods from '@/views-front/IssueGoods'
import IssueGoodsDetail from '@/views-front/IssueGoodsDetail'
import IssueGoodsModify from '@/views-front/IssueGoodsModify'
import IssueManager from '@/views-front/IssueManager'
import OrderManager from '@/views-front/OrderManager'
import Register from '@/views-front/Register'
import _ from "lodash";
Vue.use(Router)
export const FrontViews = [
{path: '/AccountCentral', component: AccountCentral, name: '账户中心', meta: {keepAlive: true, cname: AccountCentral.name}},
{path: '/IssueGoods', component: IssueGoods, name: '发布', meta: {keepAlive: true, cname: IssueGoods.name}},
{path: '/IssueGoodsDetail/:id', component: IssueGoodsDetail, name: '发布详情', meta: {keepAlive: true, cname: IssueGoodsDetail.name}},
{path: '/IssueGoodsModify/:id', component: IssueGoodsModify, name: '发布修改', meta: {keepAlive: true, cname: IssueGoodsModify.name}},
{path: '/IssueManager', component: IssueManager, name: '发布管理', meta: {keepAlive: true, cname: IssueManager.name}},
{path: '/OrderManager', component: OrderManager, name: '订单管理', meta: {keepAlive: true, cname: OrderManager.name}},
{path: '/ChangePassword/:mobile', component: ChangePassword, name: '修改登录密码', meta: {keepAlive: true, cname: ChangePassword.name}},
]
export const AdminViews = [
{path: '/home', component: Home, name: '首页', meta: {keepAlive: true, cname: Home.name}},
{path: '/BusinessMemberList', component: BusinessMemberList, name: '会员管理', meta: {keepAlive: true, cname: BusinessMemberList.name, show: false}},
{path: '/BusinessMemberEdit', component: BusinessMemberEdit, name: '会员修改', meta: {keepAlive: true, cname: BusinessMemberEdit.name, show: false}},
{path: '/BusinessMemberDetails', component: BusinessMemberDetails, name: '会员详情', meta: {keepAlive: true, cname: BusinessMemberDetails.name, show: false}},
{path: '/NoticeManageList', component: NoticeManageList, name: '公告管理', meta: {keepAlive: true, cname: NoticeManageList.name, show: false}},
{path: '/OrderManageList', component: OrderManageList, name: '物流管理', meta: {keepAlive: true, cname: OrderManageList.name, show: false}},
{path: '/orderDetail/:id', component: orderDetail, name: '物流详情', meta: {keepAlive: true, cname: orderDetail.name, show: false}},
{path: '/UserMemberList', component: UserMemberList, name: '用户管理', meta: {keepAlive: true, cname: UserMemberList.name, show: false}},
{path: '/UserCreate', component: UserCreate, name: '创建用户', meta: {keepAlive: true, cname: UserCreate.name, show: false}},
{path: '/PersonalCenter', component: PersonalCenter, name: '个人中心', meta: {keepAlive: true, cname: PersonalCenter.name, show: false}},
{path: '/PasswordSetting', component: PasswordSetting, name: '密码设置', meta: {keepAlive: true, cname: PasswordSetting.name, show: false}},
{path: '/PasswordEdit', component: PasswordEdit, name: '密码修改', meta: {keepAlive: true, cname: PasswordEdit.name, show: false}}
]
const router = new Router({
mode: 'history',
routes: [
{
path: '/',
name: 'FrontLoyout',
component: FrontLoyout,
redirect: '/AccountCentral',
children: FrontViews
},
{
path: '/admin',
name: 'Loyout',
component: Loyout,
redirect: '/home',
children: AdminViews
},
{
path: '/login',
name: 'Login',
component: Login
},
{
path: '/AdminLogin',
name: 'AdminLogin',
component: AdminLogin
},
{
path: '/Register',
name: 'Register',
component: Register
},
{
path: '/404',
name: 'NotFound',
component: NotFound
},
{
path: '*',
redirect: '/404'
}
]
})
export function isFrontPath(path) {
let isFront = true
_.forEach(AdminViews, (item) => {
if (_.startsWith(path, item.path)) {
isFront = false
return false
}
})
return isFront
}
export function getLoginPath(path) {
return isFrontPath(path) ? '/login' : '/AdminLogin'
}
export default router
<file_sep>/src/main/java/com/test/manage/dao/custom/UserLogCuMapper.java
package com.test.manage.dao.custom;
import com.test.manage.dao.generator.UserMapper;
import com.test.manage.model.form.UserLogForm;
import com.test.manage.model.generator.UserLog;
import java.util.List;
import java.util.Map;
public interface UserLogCuMapper extends UserMapper {
List<Map<String, Object>> getLogList(UserLogForm userLogForm);
List<Map<String, Object>> getUserLogList(UserLogForm userLogForm);
void addLog(UserLog userLog);
}
<file_sep>/src/main/java/com/test/framework/utils/ApiResultUtil.java
package com.test.framework.utils;
import com.test.framework.enums.ApiCodeEnum;
import com.test.framework.model.ApiResult;
public class ApiResultUtil {
public static <T> ApiResult<T> success(T data) {
return new ApiResult<T>(ApiCodeEnum.SUCCESS.getCode(), ApiCodeEnum.SUCCESS.getMessage(), data);
}
public static <T> ApiResult<T> error(String msg) {
return new ApiResult<T>(ApiCodeEnum.FAILURE.getCode(), msg);
}
}
<file_sep>/src/main/java/com/test/framework/model/AuthUser.java
package com.test.framework.model;
public class AuthUser {
private String userToken;//会员号
private String userId;//用户ID
private String userName;//用户名
private String userCnName;//用户名
private Integer userType;//用户类型
private String userCompanyId;//企业ID
private String userCompanyName;//企业名称
private String accountSubNo;//子账户账号
private String userHeadImg; // 用户头像
public String getUserCnName() { return userCnName; }
public void setUserCnName(String userCnName) { this.userCnName = userCnName; }
public String getUserHeadImg() { return userHeadImg; }
public void setUserHeadImg(String userHeadImg) { this.userHeadImg = userHeadImg; }
public String getAccountSubNo() {
return accountSubNo;
}
public void setAccountSubNo(String accountSubNo) {
this.accountSubNo = accountSubNo;
}
public String getUserCompanyName() { return userCompanyName; }
public void setUserCompanyName(String userCompanyName) { this.userCompanyName = userCompanyName; }
public String getUserCompanyId() {
return userCompanyId;
}
public void setUserCompanyId(String userCompanyId) {
this.userCompanyId = userCompanyId;
}
public Integer getUserType() {
return userType;
}
public void setUserType(Integer userType) {
this.userType = userType;
}
public String getUserToken() {
return userToken;
}
public void setUserToken(String userToken) {
this.userToken = userToken;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
<file_sep>/dlebvue/README.md
# 前端
http://localhost:8091
常用命令
```
#修改源
yarn config set registry https://registry.npm.taobao.org
#安装依赖,需要安装yarn
yarn
#启动
npm run dev
#打包
npm run build
```
<file_sep>/Dockerfile
FROM openjdk:8-jdk-alpine
VOLUME /tmp
# 替换aliyun镜像,设置时区
RUN echo "https://mirrors.aliyun.com/alpine/latest-stable/main" > /etc/apk/repositories \
&& echo "https://mirrors.aliyun.com/alpine/latest-stable/community" >> /etc/apk/repositories \
&& apk update \
&& apk add --no-cache tzdata \
&& cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime \
&& echo "Asia/Shanghai" > /etc/timezone \
&& apk del tzdata
ADD target/ebpay.jar app.jar
ADD conf /conf
ENV JAVA_OPTS=""
EXPOSE 8092
ENTRYPOINT exec java $JAVA_OPTS -Djava.security.egd=file:/dev/./urandom -jar /app.jar
<file_sep>/src/main/java/com/test/manage/service/order/OrderService.java
package com.test.manage.service.order;
import com.test.manage.model.dto.OrderDto;
import com.test.manage.model.form.OrderForm;
import com.test.manage.model.generator.Order;
import com.test.manage.model.request.QueryParams;
import java.util.List;
public interface OrderService {
void assignOrder(OrderForm orderForm);
List<OrderDto> getOrderList(QueryParams queryParams);
List<OrderDto> getIssueOrderList(QueryParams queryParams);
List<OrderDto> getReceiveOrderList(QueryParams queryParams);
void deleteIssueOrder(String orderId);
OrderDto getOrderInfo(String orderId);
void modifyOrderStatus(OrderDto orderDto ,Integer status);
}
<file_sep>/dlebvue/src/api/fetch.js
import axios from 'axios'
import {MessageError} from '../utils/messageUtil'
import {getLoginPath} from '../router/index'
const instance = axios.create({
baseURL: process.env.BASE_API
})
// Add a request interceptor
instance.interceptors.request.use(config => {
// Do something before request is sent
let token = sessionStorage.getItem('dleb_token')
config.headers['token'] = token
return config
}, error => {
// Do something with request error
console.log('err' + error)
return Promise.reject(error)
})
// Add a response interceptor
instance.interceptors.response.use(response => {
// Do something with response data
if (response.data) {
// console.log(response.data)
if (response.data.code === 103) {
sessionStorage.removeItem('dleb_token');
let pathname = location.pathname
location.href = getLoginPath(pathname)
}
}
return response
}, error => {
// Do something with response error
console.log('err' + error)
MessageError(error.message)
return Promise.reject(error)
})
export default instance
<file_sep>/src/main/java/com/test/manage/web/OrderController.java
package com.test.manage.web;
import com.github.pagehelper.PageInfo;
import com.test.common.CommonUtil;
import com.test.framework.controller.BaseController;
import com.test.framework.exception.AnyException;
import com.test.framework.model.ApiResult;
import com.test.framework.model.AuthUser;
import com.test.framework.security.Auth;
import com.test.manage.dao.generator.CompanyMapper;
import com.test.manage.dao.generator.OrderMapper;
import com.test.manage.dao.generator.OrderTraceMapper;
import com.test.manage.dao.generator.UserMapper;
import com.test.manage.model.dto.OrderDto;
import com.test.manage.model.form.OrderForm;
import com.test.manage.model.generator.CompanyExample;
import com.test.manage.model.generator.Order;
import com.test.manage.model.generator.OrderTrace;
import com.test.manage.model.generator.UserExample;
import com.test.manage.model.request.QueryParams;
import com.test.manage.service.order.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
@RequestMapping("/order")
@RestController
public class OrderController extends BaseController {
@Autowired
private OrderTraceMapper orderTraceMapper;
@Autowired
private CompanyMapper companyMapper;
@Autowired
private OrderService orderService;
@Autowired
private OrderMapper orderMapper;
@Autowired
private UserMapper userMapper;
@Autowired
private Auth auth;
/**
* 发布单据
* @param orderForm
* @return
*/
@PostMapping("/assignOrder")
public ApiResult assignOrder(@RequestBody OrderForm orderForm){
orderService.assignOrder(orderForm);
return success();
}
/**
* 获取单据列表
* @param queryParams
* @return
*/
@PostMapping("/getOrderList")
public ApiResult getOrderList(@RequestBody QueryParams queryParams){
return success(new PageInfo<>(orderService.getOrderList(queryParams)));
}
/**
* 获取接单列表
* @param queryParams
* @return
*/
@PostMapping("/getReceiveOrderList")
public ApiResult getReceiveOrderList(@RequestBody QueryParams queryParams){
return success(new PageInfo<>(orderService.getReceiveOrderList(queryParams)));
}
/**
* 获取发布方单据列表
* @param queryParams
* @return
*/
@PostMapping("/getIssueOrderList")
public ApiResult getIssueOrderList(@RequestBody QueryParams queryParams){
return success(new PageInfo<>(orderService.getIssueOrderList(queryParams)));
}
@PostMapping("/deleteIssueOrder")
public ApiResult deleteIssueOrder(@RequestParam String orderId){
orderService.deleteIssueOrder(orderId);
return success();
}
@GetMapping("/getOrderInfo")
public ApiResult getOrderInfo(@RequestParam String orderId){
return success(orderService.getOrderInfo(orderId));
}
@PostMapping("/modifyOrder")
public ApiResult modifyOrder(@RequestBody OrderDto orderDto,@RequestParam Integer status){
orderService.modifyOrderStatus(orderDto, status);
return success();
}
@GetMapping("/getReceiveUserList")
public ApiResult getReceiveUserList(){
UserExample userExample = new UserExample();
userExample.createCriteria().andUserTypeEqualTo(3).andUserIsDeleteEqualTo(false);
List<String> companyIds = userMapper.selectByExample(userExample).stream().map(item -> item.getUserCompanyId()).collect(Collectors.toList());
CompanyExample companyExample = new CompanyExample();
companyExample.createCriteria().andCompanyIdIn(companyIds);
return success(companyMapper.selectByExample(companyExample));
}
}
<file_sep>/src/main/java/com/test/manage/model/generator/NoticeExample.java
package com.test.manage.model.generator;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class NoticeExample {
/**
* This field was generated by MyBatis Generator, do not modify.
* This field corresponds to the database table sys_notice
* @mbg.generated
*/
protected String orderByClause;
/**
* This field was generated by MyBatis Generator, do not modify.
* This field corresponds to the database table sys_notice
* @mbg.generated
*/
protected boolean distinct;
/**
* This field was generated by MyBatis Generator, do not modify.
* This field corresponds to the database table sys_notice
* @mbg.generated
*/
protected List<Criteria> oredCriteria;
/**
* This method was generated by MyBatis Generator, do not modify.
* @mbg.generated
*/
public NoticeExample() {
oredCriteria = new ArrayList<Criteria>();
}
/**
* This method was generated by MyBatis Generator, do not modify.
* @mbg.generated
*/
public void setOrderByClause(String orderByClause) {
this.orderByClause = orderByClause;
}
/**
* This method was generated by MyBatis Generator, do not modify.
* @mbg.generated
*/
public String getOrderByClause() {
return orderByClause;
}
/**
* This method was generated by MyBatis Generator, do not modify.
* @mbg.generated
*/
public void setDistinct(boolean distinct) {
this.distinct = distinct;
}
/**
* This method was generated by MyBatis Generator, do not modify.
* @mbg.generated
*/
public boolean isDistinct() {
return distinct;
}
/**
* This method was generated by MyBatis Generator, do not modify.
* @mbg.generated
*/
public List<Criteria> getOredCriteria() {
return oredCriteria;
}
/**
* This method was generated by MyBatis Generator, do not modify.
* @mbg.generated
*/
public void or(Criteria criteria) {
oredCriteria.add(criteria);
}
/**
* This method was generated by MyBatis Generator, do not modify.
* @mbg.generated
*/
public Criteria or() {
Criteria criteria = createCriteriaInternal();
oredCriteria.add(criteria);
return criteria;
}
/**
* This method was generated by MyBatis Generator, do not modify.
* @mbg.generated
*/
public Criteria createCriteria() {
Criteria criteria = createCriteriaInternal();
if (oredCriteria.size() == 0) {
oredCriteria.add(criteria);
}
return criteria;
}
/**
* This method was generated by MyBatis Generator, do not modify.
* @mbg.generated
*/
protected Criteria createCriteriaInternal() {
Criteria criteria = new Criteria();
return criteria;
}
/**
* This method was generated by MyBatis Generator, do not modify.
* @mbg.generated
*/
public void clear() {
oredCriteria.clear();
orderByClause = null;
distinct = false;
}
/**
* sys_notice
* @mbg.generated
*/
protected abstract static class GeneratedCriteria {
protected List<Criterion> criteria;
protected GeneratedCriteria() {
super();
criteria = new ArrayList<Criterion>();
}
public boolean isValid() {
return criteria.size() > 0;
}
public List<Criterion> getAllCriteria() {
return criteria;
}
public List<Criterion> getCriteria() {
return criteria;
}
protected void addCriterion(String condition) {
if (condition == null) {
throw new RuntimeException("Value for condition cannot be null");
}
criteria.add(new Criterion(condition));
}
protected void addCriterion(String condition, Object value, String property) {
if (value == null) {
throw new RuntimeException("Value for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value));
}
protected void addCriterion(String condition, Object value1, Object value2, String property) {
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value1, value2));
}
public Criteria andSysNoticeIdIsNull() {
addCriterion("sys_notice_id is null");
return (Criteria) this;
}
public Criteria andSysNoticeIdIsNotNull() {
addCriterion("sys_notice_id is not null");
return (Criteria) this;
}
public Criteria andSysNoticeIdEqualTo(String value) {
addCriterion("sys_notice_id =", value, "sysNoticeId");
return (Criteria) this;
}
public Criteria andSysNoticeIdNotEqualTo(String value) {
addCriterion("sys_notice_id <>", value, "sysNoticeId");
return (Criteria) this;
}
public Criteria andSysNoticeIdGreaterThan(String value) {
addCriterion("sys_notice_id >", value, "sysNoticeId");
return (Criteria) this;
}
public Criteria andSysNoticeIdGreaterThanOrEqualTo(String value) {
addCriterion("sys_notice_id >=", value, "sysNoticeId");
return (Criteria) this;
}
public Criteria andSysNoticeIdLessThan(String value) {
addCriterion("sys_notice_id <", value, "sysNoticeId");
return (Criteria) this;
}
public Criteria andSysNoticeIdLessThanOrEqualTo(String value) {
addCriterion("sys_notice_id <=", value, "sysNoticeId");
return (Criteria) this;
}
public Criteria andSysNoticeIdLike(String value) {
addCriterion("sys_notice_id like", value, "sysNoticeId");
return (Criteria) this;
}
public Criteria andSysNoticeIdNotLike(String value) {
addCriterion("sys_notice_id not like", value, "sysNoticeId");
return (Criteria) this;
}
public Criteria andSysNoticeIdIn(List<String> values) {
addCriterion("sys_notice_id in", values, "sysNoticeId");
return (Criteria) this;
}
public Criteria andSysNoticeIdNotIn(List<String> values) {
addCriterion("sys_notice_id not in", values, "sysNoticeId");
return (Criteria) this;
}
public Criteria andSysNoticeIdBetween(String value1, String value2) {
addCriterion("sys_notice_id between", value1, value2, "sysNoticeId");
return (Criteria) this;
}
public Criteria andSysNoticeIdNotBetween(String value1, String value2) {
addCriterion("sys_notice_id not between", value1, value2, "sysNoticeId");
return (Criteria) this;
}
public Criteria andSysNoticeTitleIsNull() {
addCriterion("sys_notice_title is null");
return (Criteria) this;
}
public Criteria andSysNoticeTitleIsNotNull() {
addCriterion("sys_notice_title is not null");
return (Criteria) this;
}
public Criteria andSysNoticeTitleEqualTo(String value) {
addCriterion("sys_notice_title =", value, "sysNoticeTitle");
return (Criteria) this;
}
public Criteria andSysNoticeTitleNotEqualTo(String value) {
addCriterion("sys_notice_title <>", value, "sysNoticeTitle");
return (Criteria) this;
}
public Criteria andSysNoticeTitleGreaterThan(String value) {
addCriterion("sys_notice_title >", value, "sysNoticeTitle");
return (Criteria) this;
}
public Criteria andSysNoticeTitleGreaterThanOrEqualTo(String value) {
addCriterion("sys_notice_title >=", value, "sysNoticeTitle");
return (Criteria) this;
}
public Criteria andSysNoticeTitleLessThan(String value) {
addCriterion("sys_notice_title <", value, "sysNoticeTitle");
return (Criteria) this;
}
public Criteria andSysNoticeTitleLessThanOrEqualTo(String value) {
addCriterion("sys_notice_title <=", value, "sysNoticeTitle");
return (Criteria) this;
}
public Criteria andSysNoticeTitleLike(String value) {
addCriterion("sys_notice_title like", value, "sysNoticeTitle");
return (Criteria) this;
}
public Criteria andSysNoticeTitleNotLike(String value) {
addCriterion("sys_notice_title not like", value, "sysNoticeTitle");
return (Criteria) this;
}
public Criteria andSysNoticeTitleIn(List<String> values) {
addCriterion("sys_notice_title in", values, "sysNoticeTitle");
return (Criteria) this;
}
public Criteria andSysNoticeTitleNotIn(List<String> values) {
addCriterion("sys_notice_title not in", values, "sysNoticeTitle");
return (Criteria) this;
}
public Criteria andSysNoticeTitleBetween(String value1, String value2) {
addCriterion("sys_notice_title between", value1, value2, "sysNoticeTitle");
return (Criteria) this;
}
public Criteria andSysNoticeTitleNotBetween(String value1, String value2) {
addCriterion("sys_notice_title not between", value1, value2, "sysNoticeTitle");
return (Criteria) this;
}
public Criteria andSysNoticeContentIsNull() {
addCriterion("sys_notice_content is null");
return (Criteria) this;
}
public Criteria andSysNoticeContentIsNotNull() {
addCriterion("sys_notice_content is not null");
return (Criteria) this;
}
public Criteria andSysNoticeContentEqualTo(String value) {
addCriterion("sys_notice_content =", value, "sysNoticeContent");
return (Criteria) this;
}
public Criteria andSysNoticeContentNotEqualTo(String value) {
addCriterion("sys_notice_content <>", value, "sysNoticeContent");
return (Criteria) this;
}
public Criteria andSysNoticeContentGreaterThan(String value) {
addCriterion("sys_notice_content >", value, "sysNoticeContent");
return (Criteria) this;
}
public Criteria andSysNoticeContentGreaterThanOrEqualTo(String value) {
addCriterion("sys_notice_content >=", value, "sysNoticeContent");
return (Criteria) this;
}
public Criteria andSysNoticeContentLessThan(String value) {
addCriterion("sys_notice_content <", value, "sysNoticeContent");
return (Criteria) this;
}
public Criteria andSysNoticeContentLessThanOrEqualTo(String value) {
addCriterion("sys_notice_content <=", value, "sysNoticeContent");
return (Criteria) this;
}
public Criteria andSysNoticeContentLike(String value) {
addCriterion("sys_notice_content like", value, "sysNoticeContent");
return (Criteria) this;
}
public Criteria andSysNoticeContentNotLike(String value) {
addCriterion("sys_notice_content not like", value, "sysNoticeContent");
return (Criteria) this;
}
public Criteria andSysNoticeContentIn(List<String> values) {
addCriterion("sys_notice_content in", values, "sysNoticeContent");
return (Criteria) this;
}
public Criteria andSysNoticeContentNotIn(List<String> values) {
addCriterion("sys_notice_content not in", values, "sysNoticeContent");
return (Criteria) this;
}
public Criteria andSysNoticeContentBetween(String value1, String value2) {
addCriterion("sys_notice_content between", value1, value2, "sysNoticeContent");
return (Criteria) this;
}
public Criteria andSysNoticeContentNotBetween(String value1, String value2) {
addCriterion("sys_notice_content not between", value1, value2, "sysNoticeContent");
return (Criteria) this;
}
public Criteria andSysNoticeIssueTimeIsNull() {
addCriterion("sys_notice_issue_time is null");
return (Criteria) this;
}
public Criteria andSysNoticeIssueTimeIsNotNull() {
addCriterion("sys_notice_issue_time is not null");
return (Criteria) this;
}
public Criteria andSysNoticeIssueTimeEqualTo(Date value) {
addCriterion("sys_notice_issue_time =", value, "sysNoticeIssueTime");
return (Criteria) this;
}
public Criteria andSysNoticeIssueTimeNotEqualTo(Date value) {
addCriterion("sys_notice_issue_time <>", value, "sysNoticeIssueTime");
return (Criteria) this;
}
public Criteria andSysNoticeIssueTimeGreaterThan(Date value) {
addCriterion("sys_notice_issue_time >", value, "sysNoticeIssueTime");
return (Criteria) this;
}
public Criteria andSysNoticeIssueTimeGreaterThanOrEqualTo(Date value) {
addCriterion("sys_notice_issue_time >=", value, "sysNoticeIssueTime");
return (Criteria) this;
}
public Criteria andSysNoticeIssueTimeLessThan(Date value) {
addCriterion("sys_notice_issue_time <", value, "sysNoticeIssueTime");
return (Criteria) this;
}
public Criteria andSysNoticeIssueTimeLessThanOrEqualTo(Date value) {
addCriterion("sys_notice_issue_time <=", value, "sysNoticeIssueTime");
return (Criteria) this;
}
public Criteria andSysNoticeIssueTimeIn(List<Date> values) {
addCriterion("sys_notice_issue_time in", values, "sysNoticeIssueTime");
return (Criteria) this;
}
public Criteria andSysNoticeIssueTimeNotIn(List<Date> values) {
addCriterion("sys_notice_issue_time not in", values, "sysNoticeIssueTime");
return (Criteria) this;
}
public Criteria andSysNoticeIssueTimeBetween(Date value1, Date value2) {
addCriterion("sys_notice_issue_time between", value1, value2, "sysNoticeIssueTime");
return (Criteria) this;
}
public Criteria andSysNoticeIssueTimeNotBetween(Date value1, Date value2) {
addCriterion("sys_notice_issue_time not between", value1, value2, "sysNoticeIssueTime");
return (Criteria) this;
}
public Criteria andSysNoticeEndTimeIsNull() {
addCriterion("sys_notice_end_time is null");
return (Criteria) this;
}
public Criteria andSysNoticeEndTimeIsNotNull() {
addCriterion("sys_notice_end_time is not null");
return (Criteria) this;
}
public Criteria andSysNoticeEndTimeEqualTo(Date value) {
addCriterion("sys_notice_end_time =", value, "sysNoticeEndTime");
return (Criteria) this;
}
public Criteria andSysNoticeEndTimeNotEqualTo(Date value) {
addCriterion("sys_notice_end_time <>", value, "sysNoticeEndTime");
return (Criteria) this;
}
public Criteria andSysNoticeEndTimeGreaterThan(Date value) {
addCriterion("sys_notice_end_time >", value, "sysNoticeEndTime");
return (Criteria) this;
}
public Criteria andSysNoticeEndTimeGreaterThanOrEqualTo(Date value) {
addCriterion("sys_notice_end_time >=", value, "sysNoticeEndTime");
return (Criteria) this;
}
public Criteria andSysNoticeEndTimeLessThan(Date value) {
addCriterion("sys_notice_end_time <", value, "sysNoticeEndTime");
return (Criteria) this;
}
public Criteria andSysNoticeEndTimeLessThanOrEqualTo(Date value) {
addCriterion("sys_notice_end_time <=", value, "sysNoticeEndTime");
return (Criteria) this;
}
public Criteria andSysNoticeEndTimeIn(List<Date> values) {
addCriterion("sys_notice_end_time in", values, "sysNoticeEndTime");
return (Criteria) this;
}
public Criteria andSysNoticeEndTimeNotIn(List<Date> values) {
addCriterion("sys_notice_end_time not in", values, "sysNoticeEndTime");
return (Criteria) this;
}
public Criteria andSysNoticeEndTimeBetween(Date value1, Date value2) {
addCriterion("sys_notice_end_time between", value1, value2, "sysNoticeEndTime");
return (Criteria) this;
}
public Criteria andSysNoticeEndTimeNotBetween(Date value1, Date value2) {
addCriterion("sys_notice_end_time not between", value1, value2, "sysNoticeEndTime");
return (Criteria) this;
}
public Criteria andSysNoticeCreateUserIdIsNull() {
addCriterion("sys_notice_create_user_id is null");
return (Criteria) this;
}
public Criteria andSysNoticeCreateUserIdIsNotNull() {
addCriterion("sys_notice_create_user_id is not null");
return (Criteria) this;
}
public Criteria andSysNoticeCreateUserIdEqualTo(String value) {
addCriterion("sys_notice_create_user_id =", value, "sysNoticeCreateUserId");
return (Criteria) this;
}
public Criteria andSysNoticeCreateUserIdNotEqualTo(String value) {
addCriterion("sys_notice_create_user_id <>", value, "sysNoticeCreateUserId");
return (Criteria) this;
}
public Criteria andSysNoticeCreateUserIdGreaterThan(String value) {
addCriterion("sys_notice_create_user_id >", value, "sysNoticeCreateUserId");
return (Criteria) this;
}
public Criteria andSysNoticeCreateUserIdGreaterThanOrEqualTo(String value) {
addCriterion("sys_notice_create_user_id >=", value, "sysNoticeCreateUserId");
return (Criteria) this;
}
public Criteria andSysNoticeCreateUserIdLessThan(String value) {
addCriterion("sys_notice_create_user_id <", value, "sysNoticeCreateUserId");
return (Criteria) this;
}
public Criteria andSysNoticeCreateUserIdLessThanOrEqualTo(String value) {
addCriterion("sys_notice_create_user_id <=", value, "sysNoticeCreateUserId");
return (Criteria) this;
}
public Criteria andSysNoticeCreateUserIdLike(String value) {
addCriterion("sys_notice_create_user_id like", value, "sysNoticeCreateUserId");
return (Criteria) this;
}
public Criteria andSysNoticeCreateUserIdNotLike(String value) {
addCriterion("sys_notice_create_user_id not like", value, "sysNoticeCreateUserId");
return (Criteria) this;
}
public Criteria andSysNoticeCreateUserIdIn(List<String> values) {
addCriterion("sys_notice_create_user_id in", values, "sysNoticeCreateUserId");
return (Criteria) this;
}
public Criteria andSysNoticeCreateUserIdNotIn(List<String> values) {
addCriterion("sys_notice_create_user_id not in", values, "sysNoticeCreateUserId");
return (Criteria) this;
}
public Criteria andSysNoticeCreateUserIdBetween(String value1, String value2) {
addCriterion("sys_notice_create_user_id between", value1, value2, "sysNoticeCreateUserId");
return (Criteria) this;
}
public Criteria andSysNoticeCreateUserIdNotBetween(String value1, String value2) {
addCriterion("sys_notice_create_user_id not between", value1, value2, "sysNoticeCreateUserId");
return (Criteria) this;
}
public Criteria andSysNoticeCreateTimeIsNull() {
addCriterion("sys_notice_create_time is null");
return (Criteria) this;
}
public Criteria andSysNoticeCreateTimeIsNotNull() {
addCriterion("sys_notice_create_time is not null");
return (Criteria) this;
}
public Criteria andSysNoticeCreateTimeEqualTo(Date value) {
addCriterion("sys_notice_create_time =", value, "sysNoticeCreateTime");
return (Criteria) this;
}
public Criteria andSysNoticeCreateTimeNotEqualTo(Date value) {
addCriterion("sys_notice_create_time <>", value, "sysNoticeCreateTime");
return (Criteria) this;
}
public Criteria andSysNoticeCreateTimeGreaterThan(Date value) {
addCriterion("sys_notice_create_time >", value, "sysNoticeCreateTime");
return (Criteria) this;
}
public Criteria andSysNoticeCreateTimeGreaterThanOrEqualTo(Date value) {
addCriterion("sys_notice_create_time >=", value, "sysNoticeCreateTime");
return (Criteria) this;
}
public Criteria andSysNoticeCreateTimeLessThan(Date value) {
addCriterion("sys_notice_create_time <", value, "sysNoticeCreateTime");
return (Criteria) this;
}
public Criteria andSysNoticeCreateTimeLessThanOrEqualTo(Date value) {
addCriterion("sys_notice_create_time <=", value, "sysNoticeCreateTime");
return (Criteria) this;
}
public Criteria andSysNoticeCreateTimeIn(List<Date> values) {
addCriterion("sys_notice_create_time in", values, "sysNoticeCreateTime");
return (Criteria) this;
}
public Criteria andSysNoticeCreateTimeNotIn(List<Date> values) {
addCriterion("sys_notice_create_time not in", values, "sysNoticeCreateTime");
return (Criteria) this;
}
public Criteria andSysNoticeCreateTimeBetween(Date value1, Date value2) {
addCriterion("sys_notice_create_time between", value1, value2, "sysNoticeCreateTime");
return (Criteria) this;
}
public Criteria andSysNoticeCreateTimeNotBetween(Date value1, Date value2) {
addCriterion("sys_notice_create_time not between", value1, value2, "sysNoticeCreateTime");
return (Criteria) this;
}
public Criteria andSysNoticeIsDeleteIsNull() {
addCriterion("sys_notice_is_delete is null");
return (Criteria) this;
}
public Criteria andSysNoticeIsDeleteIsNotNull() {
addCriterion("sys_notice_is_delete is not null");
return (Criteria) this;
}
public Criteria andSysNoticeIsDeleteEqualTo(Boolean value) {
addCriterion("sys_notice_is_delete =", value, "sysNoticeIsDelete");
return (Criteria) this;
}
public Criteria andSysNoticeIsDeleteNotEqualTo(Boolean value) {
addCriterion("sys_notice_is_delete <>", value, "sysNoticeIsDelete");
return (Criteria) this;
}
public Criteria andSysNoticeIsDeleteGreaterThan(Boolean value) {
addCriterion("sys_notice_is_delete >", value, "sysNoticeIsDelete");
return (Criteria) this;
}
public Criteria andSysNoticeIsDeleteGreaterThanOrEqualTo(Boolean value) {
addCriterion("sys_notice_is_delete >=", value, "sysNoticeIsDelete");
return (Criteria) this;
}
public Criteria andSysNoticeIsDeleteLessThan(Boolean value) {
addCriterion("sys_notice_is_delete <", value, "sysNoticeIsDelete");
return (Criteria) this;
}
public Criteria andSysNoticeIsDeleteLessThanOrEqualTo(Boolean value) {
addCriterion("sys_notice_is_delete <=", value, "sysNoticeIsDelete");
return (Criteria) this;
}
public Criteria andSysNoticeIsDeleteIn(List<Boolean> values) {
addCriterion("sys_notice_is_delete in", values, "sysNoticeIsDelete");
return (Criteria) this;
}
public Criteria andSysNoticeIsDeleteNotIn(List<Boolean> values) {
addCriterion("sys_notice_is_delete not in", values, "sysNoticeIsDelete");
return (Criteria) this;
}
public Criteria andSysNoticeIsDeleteBetween(Boolean value1, Boolean value2) {
addCriterion("sys_notice_is_delete between", value1, value2, "sysNoticeIsDelete");
return (Criteria) this;
}
public Criteria andSysNoticeIsDeleteNotBetween(Boolean value1, Boolean value2) {
addCriterion("sys_notice_is_delete not between", value1, value2, "sysNoticeIsDelete");
return (Criteria) this;
}
}
/**
* This class was generated by MyBatis Generator, do not modify.
* sys_notice
* @mbg.generated do_not_delete_during_merge
*/
public static class Criteria extends GeneratedCriteria {
protected Criteria() {
super();
}
}
/**
* sys_notice
* @mbg.generated
*/
public static class Criterion {
private String condition;
private Object value;
private Object secondValue;
private boolean noValue;
private boolean singleValue;
private boolean betweenValue;
private boolean listValue;
private String typeHandler;
public String getCondition() {
return condition;
}
public Object getValue() {
return value;
}
public Object getSecondValue() {
return secondValue;
}
public boolean isNoValue() {
return noValue;
}
public boolean isSingleValue() {
return singleValue;
}
public boolean isBetweenValue() {
return betweenValue;
}
public boolean isListValue() {
return listValue;
}
public String getTypeHandler() {
return typeHandler;
}
protected Criterion(String condition) {
super();
this.condition = condition;
this.typeHandler = null;
this.noValue = true;
}
protected Criterion(String condition, Object value, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.typeHandler = typeHandler;
if (value instanceof List<?>) {
this.listValue = true;
} else {
this.singleValue = true;
}
}
protected Criterion(String condition, Object value) {
this(condition, value, null);
}
protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.secondValue = secondValue;
this.typeHandler = typeHandler;
this.betweenValue = true;
}
protected Criterion(String condition, Object value, Object secondValue) {
this(condition, value, secondValue, null);
}
}
}<file_sep>/src/main/java/com/test/framework/handle/ExceptionHandle.java
package com.test.framework.handle;
import com.test.framework.enums.ApiCodeEnum;
import com.test.framework.exception.AnyException;
import com.test.framework.model.ApiResult;
import io.jsonwebtoken.ExpiredJwtException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.ConversionNotSupportedException;
import org.springframework.beans.TypeMismatchException;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.HttpMediaTypeNotAcceptableException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingPathVariableException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.async.AsyncRequestTimeoutException;
import org.springframework.web.multipart.support.MissingServletRequestPartException;
import org.springframework.web.servlet.NoHandlerFoundException;
import org.springframework.web.servlet.mvc.multiaction.NoSuchRequestHandlingMethodException;
import javax.validation.ConstraintViolationException;
@RestControllerAdvice
public class ExceptionHandle {
private final static Logger logger = LoggerFactory.getLogger(ExceptionHandle.class);
@ExceptionHandler(Exception.class)
public ApiResult handle(Exception ex) {
try {
if (ex instanceof AnyException) {
AnyException anyException = (AnyException) ex;
if (anyException.getCode().equals(ApiCodeEnum.UNKONW_ERROR.getCode())) {
logger.error(anyException.getMessage(), ex);
}
return new ApiResult(anyException);
} else if (ex instanceof ExpiredJwtException) {
return new ApiResult(ApiCodeEnum.TOKEN_INVALID);
} else if (ex instanceof NoSuchRequestHandlingMethodException) {
return new ApiResult(ApiCodeEnum.NOT_FOUND);
} else if (ex instanceof HttpRequestMethodNotSupportedException) {
return new ApiResult(ApiCodeEnum.METHOD_NOT_ALLOWED);
} else if (ex instanceof HttpMediaTypeNotSupportedException) {
return new ApiResult(ApiCodeEnum.UNSUPPORTED_MEDIA_TYPE);
} else if (ex instanceof HttpMediaTypeNotAcceptableException) {
return new ApiResult(ApiCodeEnum.NOT_ACCEPTABLE);
} else if (ex instanceof MissingPathVariableException) {
return new ApiResult(ApiCodeEnum.INTERNAL_SERVER_ERROR);
} else if (ex instanceof MissingServletRequestParameterException) {
return new ApiResult(ApiCodeEnum.BAD_REQUEST);
} else if (ex instanceof ServletRequestBindingException) {
return new ApiResult(ApiCodeEnum.BAD_REQUEST);
} else if (ex instanceof ConversionNotSupportedException) {
return new ApiResult(ApiCodeEnum.INTERNAL_SERVER_ERROR);
} else if (ex instanceof TypeMismatchException) {
return new ApiResult(ApiCodeEnum.BAD_REQUEST);
} else if (ex instanceof HttpMessageNotReadableException) {
return new ApiResult(ApiCodeEnum.BAD_REQUEST);
} else if (ex instanceof HttpMessageNotWritableException) {
return new ApiResult(ApiCodeEnum.INTERNAL_SERVER_ERROR);
} else if (ex instanceof MethodArgumentNotValidException) {
MethodArgumentNotValidException exception = (MethodArgumentNotValidException) ex;
String result = dealBindingResult(exception.getBindingResult());
return new ApiResult(ApiCodeEnum.BAD_REQUEST.getCode(), result);
} else if (ex instanceof MissingServletRequestPartException) {
return new ApiResult(ApiCodeEnum.BAD_REQUEST);
} else if (ex instanceof BindException) {
BindException exception = (BindException) ex;
String result = dealBindingResult(exception.getBindingResult());
return new ApiResult(ApiCodeEnum.BAD_REQUEST.getCode(), result);
} else if (ex instanceof NoHandlerFoundException) {
return new ApiResult(ApiCodeEnum.NOT_FOUND);
} else if (ex instanceof AsyncRequestTimeoutException) {
return new ApiResult(ApiCodeEnum.SERVICE_UNAVAILABLE);
} else if(ex instanceof ConstraintViolationException){
throw ex;
}else{
if (logger.isWarnEnabled()) {
logger.warn("Unknown exception type: " + ex.getClass().getName());
}
logger.error(ex.getMessage(), ex);
return new ApiResult(ApiCodeEnum.INTERNAL_SERVER_ERROR);
}
} catch (Exception e) {
logger.error(ex.getMessage(), ex);
return new ApiResult(ApiCodeEnum.UNKONW_ERROR);
}
}
private String dealBindingResult(BindingResult bindingResult) {
StringBuilder sb = new StringBuilder();
bindingResult.getFieldErrors().forEach(fieldError -> {
sb.append(fieldError.getField())
.append(":")
.append(fieldError.getDefaultMessage())
.append(";");
});
return sb.toString();
}
}
<file_sep>/src/main/java/com/test/manage/model/generator/userRoleKey.java
package com.test.manage.model.generator;
/**
* 用户和角色关系表
* user_role
* @mbg.generated do_not_delete_during_merge
*/
public class userRoleKey {
/**
* user_role.user_role_user_id
* @mbg.generated
*/
private String userRoleUserId;
/**
* user_role.user_role_role_id
* @mbg.generated
*/
private String userRoleRoleId;
/**
* @return the value of user_role.user_role_user_id
* @mbg.generated
*/
public String getUserRoleUserId() {
return userRoleUserId;
}
/**
* @param userRoleUserId the value for user_role.user_role_user_id
* @mbg.generated
*/
public void setUserRoleUserId(String userRoleUserId) {
this.userRoleUserId = userRoleUserId == null ? null : userRoleUserId.trim();
}
/**
* @return the value of user_role.user_role_role_id
* @mbg.generated
*/
public String getUserRoleRoleId() {
return userRoleRoleId;
}
/**
* @param userRoleRoleId the value for user_role.user_role_role_id
* @mbg.generated
*/
public void setUserRoleRoleId(String userRoleRoleId) {
this.userRoleRoleId = userRoleRoleId == null ? null : userRoleRoleId.trim();
}
}<file_sep>/src/main/java/com/test/manage/model/generator/Area.java
package com.test.manage.model.generator;
/**
* 省市区
* area
* @mbg.generated do_not_delete_during_merge
*/
public class Area {
/**
* 地区编码
* area.area_id
* @mbg.generated
*/
private String areaId;
/**
* 区域名称
* area.area_name
* @mbg.generated
*/
private String areaName;
/**
* 父节点id
* area.area_parent_id
* @mbg.generated
*/
private String areaParentId;
/**
* 当前层级,省-1,市-2,区-3
* area.area_level
* @mbg.generated
*/
private String areaLevel;
/**
* 地区编码
* @return the value of area.area_id
* @mbg.generated
*/
public String getAreaId() {
return areaId;
}
/**
* 地区编码
* @param areaId the value for area.area_id
* @mbg.generated
*/
public void setAreaId(String areaId) {
this.areaId = areaId == null ? null : areaId.trim();
}
/**
* 区域名称
* @return the value of area.area_name
* @mbg.generated
*/
public String getAreaName() {
return areaName;
}
/**
* 区域名称
* @param areaName the value for area.area_name
* @mbg.generated
*/
public void setAreaName(String areaName) {
this.areaName = areaName == null ? null : areaName.trim();
}
/**
* 父节点id
* @return the value of area.area_parent_id
* @mbg.generated
*/
public String getAreaParentId() {
return areaParentId;
}
/**
* 父节点id
* @param areaParentId the value for area.area_parent_id
* @mbg.generated
*/
public void setAreaParentId(String areaParentId) {
this.areaParentId = areaParentId == null ? null : areaParentId.trim();
}
/**
* 当前层级,省-1,市-2,区-3
* @return the value of area.area_level
* @mbg.generated
*/
public String getAreaLevel() {
return areaLevel;
}
/**
* 当前层级,省-1,市-2,区-3
* @param areaLevel the value for area.area_level
* @mbg.generated
*/
public void setAreaLevel(String areaLevel) {
this.areaLevel = areaLevel == null ? null : areaLevel.trim();
}
}<file_sep>/src/main/java/com/test/manage/model/generator/Order.java
package com.test.manage.model.generator;
import java.math.BigDecimal;
import java.util.Date;
/**
* 订单表
* goods_order
* @mbg.generated do_not_delete_during_merge
*/
public class Order {
/**
* 订单ID
* goods_order.order_id
* @mbg.generated
*/
private String orderId;
/**
* goods_order.order_no
* @mbg.generated
*/
private String orderNo;
/**
* 下单方id
* goods_order.order_company_id
* @mbg.generated
*/
private String orderCompanyId;
/**
* 接单方id
* goods_order.order_receive_company_id
* @mbg.generated
*/
private String orderReceiveCompanyId;
/**
* 0:不指定 1:指定
* goods_order.order_assign
* @mbg.generated
*/
private Boolean orderAssign;
/**
* 1:已下单 2:已接单3:已提货 4:已发货 5:已签收
* goods_order.order_status
* @mbg.generated
*/
private Integer orderStatus;
/**
* 物流单号
* goods_order.order_logistics_no
* @mbg.generated
*/
private String orderLogisticsNo;
/**
* 货物名称
* goods_order.order_goods_name
* @mbg.generated
*/
private String orderGoodsName;
/**
* 货物重量
* goods_order.order_goods_weight
* @mbg.generated
*/
private BigDecimal orderGoodsWeight;
/**
* 货物体积
* goods_order.order_goods_cube
* @mbg.generated
*/
private BigDecimal orderGoodsCube;
/**
* 费用
* goods_order.order_money
* @mbg.generated
*/
private BigDecimal orderMoney;
/**
* 发布时间
* goods_order.order_issue_time
* @mbg.generated
*/
private Date orderIssueTime;
/**
* 预计提货时间
* goods_order.order_pickup_time
* @mbg.generated
*/
private Date orderPickupTime;
/**
* 实际提货时间
* goods_order.order_final_pickup_time
* @mbg.generated
*/
private Date orderFinalPickupTime;
/**
* 到货时间
* goods_order.order_receive_time
* @mbg.generated
*/
private Date orderReceiveTime;
/**
* 发货地省份
* goods_order.order_pickup_province
* @mbg.generated
*/
private String orderPickupProvince;
/**
* 发货地城市
* goods_order.order_pickup_city
* @mbg.generated
*/
private String orderPickupCity;
/**
* 发货地区县
* goods_order.order_pickup_district
* @mbg.generated
*/
private String orderPickupDistrict;
/**
* 发货地区县
* goods_order.order_pickup_address
* @mbg.generated
*/
private String orderPickupAddress;
/**
* 收货地省份
* goods_order.order_receive_province
* @mbg.generated
*/
private String orderReceiveProvince;
/**
* 收货地城市
* goods_order.order_receive_city
* @mbg.generated
*/
private String orderReceiveCity;
/**
* 收货地区县
* goods_order.order_receive_district
* @mbg.generated
*/
private String orderReceiveDistrict;
/**
* 收货地区县
* goods_order.order_receive_address
* @mbg.generated
*/
private String orderReceiveAddress;
/**
* 备注
* goods_order.order_remark
* @mbg.generated
*/
private String orderRemark;
/**
* 下单人id
* goods_order.order_create_user_id
* @mbg.generated
*/
private String orderCreateUserId;
/**
* 接单人Id
* goods_order.order_receive_user_id
* @mbg.generated
*/
private String orderReceiveUserId;
/**
* 是否删除 0-否,1-是
* goods_order.order_is_delete
* @mbg.generated
*/
private Boolean orderIsDelete;
/**
* 订单创建时间
* goods_order.order_create_time
* @mbg.generated
*/
private Date orderCreateTime;
/**
* 订单ID
* @return the value of goods_order.order_id
* @mbg.generated
*/
public String getOrderId() {
return orderId;
}
/**
* 订单ID
* @param orderId the value for goods_order.order_id
* @mbg.generated
*/
public void setOrderId(String orderId) {
this.orderId = orderId == null ? null : orderId.trim();
}
/**
* @return the value of goods_order.order_no
* @mbg.generated
*/
public String getOrderNo() {
return orderNo;
}
/**
* @param orderNo the value for goods_order.order_no
* @mbg.generated
*/
public void setOrderNo(String orderNo) {
this.orderNo = orderNo == null ? null : orderNo.trim();
}
/**
* 下单方id
* @return the value of goods_order.order_company_id
* @mbg.generated
*/
public String getOrderCompanyId() {
return orderCompanyId;
}
/**
* 下单方id
* @param orderCompanyId the value for goods_order.order_company_id
* @mbg.generated
*/
public void setOrderCompanyId(String orderCompanyId) {
this.orderCompanyId = orderCompanyId == null ? null : orderCompanyId.trim();
}
/**
* 接单方id
* @return the value of goods_order.order_receive_company_id
* @mbg.generated
*/
public String getOrderReceiveCompanyId() {
return orderReceiveCompanyId;
}
/**
* 接单方id
* @param orderReceiveCompanyId the value for goods_order.order_receive_company_id
* @mbg.generated
*/
public void setOrderReceiveCompanyId(String orderReceiveCompanyId) {
this.orderReceiveCompanyId = orderReceiveCompanyId == null ? null : orderReceiveCompanyId.trim();
}
/**
* 0:不指定 1:指定
* @return the value of goods_order.order_assign
* @mbg.generated
*/
public Boolean getOrderAssign() {
return orderAssign;
}
/**
* 0:不指定 1:指定
* @param orderAssign the value for goods_order.order_assign
* @mbg.generated
*/
public void setOrderAssign(Boolean orderAssign) {
this.orderAssign = orderAssign;
}
/**
* 1:已下单 2:已接单3:已提货 4:已发货 5:已签收
* @return the value of goods_order.order_status
* @mbg.generated
*/
public Integer getOrderStatus() {
return orderStatus;
}
/**
* 1:已下单 2:已接单3:已提货 4:已发货 5:已签收
* @param orderStatus the value for goods_order.order_status
* @mbg.generated
*/
public void setOrderStatus(Integer orderStatus) {
this.orderStatus = orderStatus;
}
/**
* 物流单号
* @return the value of goods_order.order_logistics_no
* @mbg.generated
*/
public String getOrderLogisticsNo() {
return orderLogisticsNo;
}
/**
* 物流单号
* @param orderLogisticsNo the value for goods_order.order_logistics_no
* @mbg.generated
*/
public void setOrderLogisticsNo(String orderLogisticsNo) {
this.orderLogisticsNo = orderLogisticsNo == null ? null : orderLogisticsNo.trim();
}
/**
* 货物名称
* @return the value of goods_order.order_goods_name
* @mbg.generated
*/
public String getOrderGoodsName() {
return orderGoodsName;
}
/**
* 货物名称
* @param orderGoodsName the value for goods_order.order_goods_name
* @mbg.generated
*/
public void setOrderGoodsName(String orderGoodsName) {
this.orderGoodsName = orderGoodsName == null ? null : orderGoodsName.trim();
}
/**
* 货物重量
* @return the value of goods_order.order_goods_weight
* @mbg.generated
*/
public BigDecimal getOrderGoodsWeight() {
return orderGoodsWeight;
}
/**
* 货物重量
* @param orderGoodsWeight the value for goods_order.order_goods_weight
* @mbg.generated
*/
public void setOrderGoodsWeight(BigDecimal orderGoodsWeight) {
this.orderGoodsWeight = orderGoodsWeight;
}
/**
* 货物体积
* @return the value of goods_order.order_goods_cube
* @mbg.generated
*/
public BigDecimal getOrderGoodsCube() {
return orderGoodsCube;
}
/**
* 货物体积
* @param orderGoodsCube the value for goods_order.order_goods_cube
* @mbg.generated
*/
public void setOrderGoodsCube(BigDecimal orderGoodsCube) {
this.orderGoodsCube = orderGoodsCube;
}
/**
* 费用
* @return the value of goods_order.order_money
* @mbg.generated
*/
public BigDecimal getOrderMoney() {
return orderMoney;
}
/**
* 费用
* @param orderMoney the value for goods_order.order_money
* @mbg.generated
*/
public void setOrderMoney(BigDecimal orderMoney) {
this.orderMoney = orderMoney;
}
/**
* 发布时间
* @return the value of goods_order.order_issue_time
* @mbg.generated
*/
public Date getOrderIssueTime() {
return orderIssueTime;
}
/**
* 发布时间
* @param orderIssueTime the value for goods_order.order_issue_time
* @mbg.generated
*/
public void setOrderIssueTime(Date orderIssueTime) {
this.orderIssueTime = orderIssueTime;
}
/**
* 预计提货时间
* @return the value of goods_order.order_pickup_time
* @mbg.generated
*/
public Date getOrderPickupTime() {
return orderPickupTime;
}
/**
* 预计提货时间
* @param orderPickupTime the value for goods_order.order_pickup_time
* @mbg.generated
*/
public void setOrderPickupTime(Date orderPickupTime) {
this.orderPickupTime = orderPickupTime;
}
/**
* 实际提货时间
* @return the value of goods_order.order_final_pickup_time
* @mbg.generated
*/
public Date getOrderFinalPickupTime() {
return orderFinalPickupTime;
}
/**
* 实际提货时间
* @param orderFinalPickupTime the value for goods_order.order_final_pickup_time
* @mbg.generated
*/
public void setOrderFinalPickupTime(Date orderFinalPickupTime) {
this.orderFinalPickupTime = orderFinalPickupTime;
}
/**
* 到货时间
* @return the value of goods_order.order_receive_time
* @mbg.generated
*/
public Date getOrderReceiveTime() {
return orderReceiveTime;
}
/**
* 到货时间
* @param orderReceiveTime the value for goods_order.order_receive_time
* @mbg.generated
*/
public void setOrderReceiveTime(Date orderReceiveTime) {
this.orderReceiveTime = orderReceiveTime;
}
/**
* 发货地省份
* @return the value of goods_order.order_pickup_province
* @mbg.generated
*/
public String getOrderPickupProvince() {
return orderPickupProvince;
}
/**
* 发货地省份
* @param orderPickupProvince the value for goods_order.order_pickup_province
* @mbg.generated
*/
public void setOrderPickupProvince(String orderPickupProvince) {
this.orderPickupProvince = orderPickupProvince == null ? null : orderPickupProvince.trim();
}
/**
* 发货地城市
* @return the value of goods_order.order_pickup_city
* @mbg.generated
*/
public String getOrderPickupCity() {
return orderPickupCity;
}
/**
* 发货地城市
* @param orderPickupCity the value for goods_order.order_pickup_city
* @mbg.generated
*/
public void setOrderPickupCity(String orderPickupCity) {
this.orderPickupCity = orderPickupCity == null ? null : orderPickupCity.trim();
}
/**
* 发货地区县
* @return the value of goods_order.order_pickup_district
* @mbg.generated
*/
public String getOrderPickupDistrict() {
return orderPickupDistrict;
}
/**
* 发货地区县
* @param orderPickupDistrict the value for goods_order.order_pickup_district
* @mbg.generated
*/
public void setOrderPickupDistrict(String orderPickupDistrict) {
this.orderPickupDistrict = orderPickupDistrict == null ? null : orderPickupDistrict.trim();
}
/**
* 发货地区县
* @return the value of goods_order.order_pickup_address
* @mbg.generated
*/
public String getOrderPickupAddress() {
return orderPickupAddress;
}
/**
* 发货地区县
* @param orderPickupAddress the value for goods_order.order_pickup_address
* @mbg.generated
*/
public void setOrderPickupAddress(String orderPickupAddress) {
this.orderPickupAddress = orderPickupAddress == null ? null : orderPickupAddress.trim();
}
/**
* 收货地省份
* @return the value of goods_order.order_receive_province
* @mbg.generated
*/
public String getOrderReceiveProvince() {
return orderReceiveProvince;
}
/**
* 收货地省份
* @param orderReceiveProvince the value for goods_order.order_receive_province
* @mbg.generated
*/
public void setOrderReceiveProvince(String orderReceiveProvince) {
this.orderReceiveProvince = orderReceiveProvince == null ? null : orderReceiveProvince.trim();
}
/**
* 收货地城市
* @return the value of goods_order.order_receive_city
* @mbg.generated
*/
public String getOrderReceiveCity() {
return orderReceiveCity;
}
/**
* 收货地城市
* @param orderReceiveCity the value for goods_order.order_receive_city
* @mbg.generated
*/
public void setOrderReceiveCity(String orderReceiveCity) {
this.orderReceiveCity = orderReceiveCity == null ? null : orderReceiveCity.trim();
}
/**
* 收货地区县
* @return the value of goods_order.order_receive_district
* @mbg.generated
*/
public String getOrderReceiveDistrict() {
return orderReceiveDistrict;
}
/**
* 收货地区县
* @param orderReceiveDistrict the value for goods_order.order_receive_district
* @mbg.generated
*/
public void setOrderReceiveDistrict(String orderReceiveDistrict) {
this.orderReceiveDistrict = orderReceiveDistrict == null ? null : orderReceiveDistrict.trim();
}
/**
* 收货地区县
* @return the value of goods_order.order_receive_address
* @mbg.generated
*/
public String getOrderReceiveAddress() {
return orderReceiveAddress;
}
/**
* 收货地区县
* @param orderReceiveAddress the value for goods_order.order_receive_address
* @mbg.generated
*/
public void setOrderReceiveAddress(String orderReceiveAddress) {
this.orderReceiveAddress = orderReceiveAddress == null ? null : orderReceiveAddress.trim();
}
/**
* 备注
* @return the value of goods_order.order_remark
* @mbg.generated
*/
public String getOrderRemark() {
return orderRemark;
}
/**
* 备注
* @param orderRemark the value for goods_order.order_remark
* @mbg.generated
*/
public void setOrderRemark(String orderRemark) {
this.orderRemark = orderRemark == null ? null : orderRemark.trim();
}
/**
* 下单人id
* @return the value of goods_order.order_create_user_id
* @mbg.generated
*/
public String getOrderCreateUserId() {
return orderCreateUserId;
}
/**
* 下单人id
* @param orderCreateUserId the value for goods_order.order_create_user_id
* @mbg.generated
*/
public void setOrderCreateUserId(String orderCreateUserId) {
this.orderCreateUserId = orderCreateUserId == null ? null : orderCreateUserId.trim();
}
/**
* 接单人Id
* @return the value of goods_order.order_receive_user_id
* @mbg.generated
*/
public String getOrderReceiveUserId() {
return orderReceiveUserId;
}
/**
* 接单人Id
* @param orderReceiveUserId the value for goods_order.order_receive_user_id
* @mbg.generated
*/
public void setOrderReceiveUserId(String orderReceiveUserId) {
this.orderReceiveUserId = orderReceiveUserId == null ? null : orderReceiveUserId.trim();
}
/**
* 是否删除 0-否,1-是
* @return the value of goods_order.order_is_delete
* @mbg.generated
*/
public Boolean getOrderIsDelete() {
return orderIsDelete;
}
/**
* 是否删除 0-否,1-是
* @param orderIsDelete the value for goods_order.order_is_delete
* @mbg.generated
*/
public void setOrderIsDelete(Boolean orderIsDelete) {
this.orderIsDelete = orderIsDelete;
}
/**
* 订单创建时间
* @return the value of goods_order.order_create_time
* @mbg.generated
*/
public Date getOrderCreateTime() {
return orderCreateTime;
}
/**
* 订单创建时间
* @param orderCreateTime the value for goods_order.order_create_time
* @mbg.generated
*/
public void setOrderCreateTime(Date orderCreateTime) {
this.orderCreateTime = orderCreateTime;
}
}<file_sep>/dlebvue/src/main.js
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import axios from './api/fetch'
import VueAxios from 'vue-axios'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css';
// import '@/assets/scss/element-variables.scss'
import '@/assets/css/app.css'
// import '@/assets/css/front-loyout.css'
import '@/assets/css/front-loyout-new.css'
import '@/assets/css/admin.css'
import App from './App.vue'
import router, {getLoginPath} from './router'
import _ from 'lodash'
import ElTreeGrid from 'element-tree-grid'
// import common from '@/common/common'
// mock.bootstrap()
// Vue.use(common);
Vue.config.productionTip = false
Vue.use(ElementUI)
Vue.use(VueAxios, axios)
Vue.component(ElTreeGrid.name, ElTreeGrid);
Vue.prototype._btn = function (value) {
if (this.$root.$data.user.userType !== 1){
const button = JSON.parse(localStorage.getItem('buttonRight'));
for (let currentValue of button) {
if (currentValue === value) {
return true;
}
}
return false;
} else {
return true;
}
// return true;
};
let paths = ['/login', '/404', '/Register', '/AdminLogin', '/PostTest', '/ServiceAgreement', '/Payment', '/orderPay']
/* eslint-disable no-new */
const vue = new Vue({
router,
render: h => h(App),
data() {
return {
defaultActive: '',
user: {},
documentClientHeight: document.documentElement.clientHeight
};
},
methods: {
judgeLogin() {
let token = sessionStorage.getItem('dleb_token')
if (!token) {
let pathname = location.pathname
if (_.indexOf(paths, pathname) === -1) {
location.href = getLoginPath(pathname)
}
}
}
},
created() {
this.judgeLogin();
let user = JSON.parse(sessionStorage.getItem('dleb_user'))
this.user = user
window.onresize = _.debounce(() => {
this.documentClientHeight = document.documentElement.clientHeight
}, 100)
}
}).$mount('#app')
router.beforeEach((to, from, next) => {
if (_.indexOf(paths, to.path) === -1) {
vue.judgeLogin();
}
next()
})
<file_sep>/src/main/java/com/test/manage/model/form/Params.java
package com.test.manage.model.form;
public class Params {
private String newPayPassword;
private String oldPayPassword;
private String userMobile;
private String userId;
private String checkNum;
public String getUserMobile() {
return userMobile;
}
public void setUserMobile(String userMobile) {
this.userMobile = userMobile;
}
public String getCheckNum() {
return checkNum;
}
public void setCheckNum(String checkNum) {
this.checkNum = checkNum;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getNewPayPassword() {
return newPayPassword;
}
public void setNewPayPassword(String newPayPassword) {
this.newPayPassword = <PASSWORD>;
}
public String getOldPayPassword() {
return oldPayPassword;
}
public void setOldPayPassword(String oldPayPassword) {
this.oldPayPassword = oldPayPassword;
}
}
<file_sep>/src/main/java/com/test/manage/model/request/UserRequest.java
package com.test.manage.model.request;
import org.hibernate.validator.constraints.NotBlank;
import java.util.List;
public class UserRequest {
@NotBlank(message = "用户名不能为空")
private String userName;
private String userPassword;
@NotBlank(message = "新密码不能为空")
private String newPassword;
@NotBlank(message = "手机号不能为空")
private String mobile;
@NotBlank(message = "验证码不能为空")
private String verification;
// 顶象验证码
private String token;
private String newMobile;
private String newVerification;
private String userCnName;
// 关联角色id
private List<String> roleIds;
// 关联角色id
private List<String> teamIds;
// 用户id
private String userId;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserPassword() {
return userPassword;
}
public void setUserPassword(String userPassword) {
this.userPassword = <PASSWORD>Password;
}
public String getNewPassword() {
return newPassword;
}
public void setNewPassword(String newPassword) {
this.newPassword = newPassword;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getVerification() {
return verification;
}
public void setVerification(String verification) {
this.verification = verification;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public String getNewMobile() {
return newMobile;
}
public void setNewMobile(String newMobile) {
this.newMobile = newMobile;
}
public String getNewVerification() {
return newVerification;
}
public void setNewVerification(String newVerification) {
this.newVerification = newVerification;
}
public List<String> getRoleIds() {
return roleIds;
}
public void setRoleIds(List<String> roleIds) {
this.roleIds = roleIds;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public List<String> getTeamIds() {
return teamIds;
}
public void setTeamIds(List<String> teamIds) {
this.teamIds = teamIds;
}
public String getUserCnName() {
return userCnName;
}
public void setUserCnName(String userCnName) {
this.userCnName = userCnName;
}
}
<file_sep>/src/main/java/com/test/manage/model/form/UserForm.java
package com.test.manage.model.form;
import com.test.manage.model.generator.User;
import com.test.framework.model.BaseForm;
import java.util.Date;
public class UserForm extends BaseForm {
User user;
String Verification;
private String userId;
private String userCompanyId;
private Integer userType;
private Date startTime;
private Date endTime;
private String keyword;
private String status; //状态
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public String getVerification() {
return Verification;
}
public void setVerification(String verification) {
Verification = verification;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUserCompanyId() {
return userCompanyId;
}
public void setUserCompanyId(String userCompanyId) {
this.userCompanyId = userCompanyId;
}
public Integer getUserType() {
return userType;
}
public void setUserType(Integer userType) {
this.userType = userType;
}
public Date getStartTime() {
return startTime;
}
public void setStartTime(Date startTime) {
this.startTime = startTime;
}
public Date getEndTime() {
return endTime;
}
public void setEndTime(Date endTime) {
this.endTime = endTime;
}
@Override
public String getKeyword() {
return keyword;
}
@Override
public void setKeyword(String keyword) {
this.keyword = keyword;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
<file_sep>/src/main/java/com/test/framework/utils/JsonUtils.java
package com.test.framework.utils;
import java.io.IOException;
import java.text.ParseException;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonParser.Feature;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
public class JsonUtils {
private static final Logger logger = LogManager.getLogger();
public static ObjectMapper getObjectMapper(){
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(Feature.ALLOW_COMMENTS, true);
objectMapper.configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
objectMapper.configure(Feature.ALLOW_SINGLE_QUOTES, true);
objectMapper.configure(Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
objectMapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
objectMapper.registerModule(new DateSimpleModule());
return objectMapper;
}
private JsonUtils() {
}
/**
* 将json string反序列化成对象
*
* @param json
* @param valueType
* @return
*/
public static <T> T readValue(String json, Class<T> valueType) {
try {
return getObjectMapper().readValue(json, valueType);
} catch (IOException e) {
logger.error(e);
e.printStackTrace();
}
return null;
}
/**
* 将json array反序列化为对象
*
* @param json
* @param jsonTypeReference
* @return
*/
@SuppressWarnings("unchecked")
public static <T> T readValue(String json, TypeReference<T> typeReference) {
try {
return (T) getObjectMapper().readValue(json, typeReference);
} catch (IOException e) {
logger.error(e);
e.printStackTrace();
}
return null;
}
/**
* serialize any Java value as a String
*/
public static String toJSONString(Object object) {
try {
return getObjectMapper().writeValueAsString(object);
} catch (JsonProcessingException e) {
logger.error(e);
e.printStackTrace();
}
return null;
}
}
class DateSimpleModule extends SimpleModule {
protected static final Logger logger = LogManager.getLogger(DateSimpleModule.class);
private static final long serialVersionUID = -3695931415463414812L;
public DateSimpleModule() {
this.addDeserializer(Date.class, new DateJsonDeserializer());
}
}
class DateJsonDeserializer extends JsonDeserializer<Date> {
private final Set<String> patterns;
public DateJsonDeserializer() {
patterns = new HashSet<>();
patterns.add("yyyy-MM-dd EEE aa hh:mm:ss");
patterns.add("yyyy-MM-dd EEE HH:mm:ss");
patterns.add("yyyy-MM-dd HH:mm:ss");
patterns.add("yyyy-MM-dd HH:mm");
patterns.add("yyyy-MM-dd");
patterns.add("yyyy/MM/dd EEE aa hh:mm:ss");//2016/12/14 星期三 下午 3:52:49
patterns.add("yyyy/MM/dd EEE HH:mm:ss");
patterns.add("yyyy/MM/dd HH:mm:ss");
patterns.add("yyyy/MM/dd HH:mm");
patterns.add("yyyy/MM/dd");
}
@Override
public Date deserialize(JsonParser jsonparser, DeserializationContext deserializationcontext)
throws IOException, JsonProcessingException {
try {
String date = jsonparser.getText();
return DateUtils.parseDate(date, patterns.toArray(new String[] {}));
} catch (ParseException e) {
DateSimpleModule.logger.error(e);
return new Date();
}
}
}
<file_sep>/dlebvue/src/common/mixin.js
// 默认每页条数
const pageSize = 10
const pageSizeK = 10
export const pageMixin = {
data() {
return {
tableMaxHeight: '',
pageSettings: {
total: 0,
pageNum: 1,
pageSize: pageSize,
pageSizes: [10, 20, 50, 100],
layout: 'total, sizes, prev, pager, next, jumper'
},
pageSettingsK: {
totalK: 0,
pageNumK: 1,
pageSizeK: pageSize,
pageSizesK: [10, 20, 50, 100],
layoutK: 'total, sizes, prev, pager, next, jumper'
},
searchForm: {
pageNum: 1,
pageSize: pageSize,
startTime: '',
endTime: ''
},
searchFormK: {
pageNumK: 1,
pageSizeK: pageSizeK,
startTimeK: '',
endTimeK: ''
},
qs: require('qs'),
isShowLoadingIcon: false
}
},
methods: {
// 设置列表时间查询条件默认为最近15天
setDate() {
const start = new Date();
const end = new Date();
start.setTime(start.getTime() - 3600 * 1000 * 24 * 15);
start.setHours(0);
start.setMinutes(0);
start.setSeconds(0);
start.setMilliseconds(0);
end.setHours(0);
end.setMinutes(0);
end.setSeconds(0);
end.setMilliseconds(0);
this.searchForm.startTime = start
this.searchForm.endTime = end
this.searchFormK.startTimeK = start
this.searchFormK.endTimeK = end
},
sizeChange(val) {
this.pageChange(null, val)
},
currentChange(val) {
this.pageChange(val, null)
},
pageChange(pageNum, pageSize) {
if (pageNum) {
this.searchForm.pageNum = pageNum
}
if (pageSize) {
this.searchForm.pageSize = pageSize
}
this.getData()
},
updateTableData(result) {
this.tableList = result.list
this.pageSettings.total = result.total
},
sizeChangeK(valK) {
this.pageChangeK(null, valK)
},
currentChangeK(valK) {
this.pageChangeK(valK, null)
},
pageChangeK(pageNumK, pageSizeK) {
if (pageNumK) {
this.searchFormK.pageNum = pageNumK
}
if (pageSizeK) {
this.searchFormK.pageSize = pageSizeK
}
this.getDataK()
},
updateTableDataK(resultK) {
this.tableListK = resultK.list
this.pageSettingsK.totalK = resultK.total
},
changeTableMaxHeight() {
if (this.$refs.myTable) {
let tmp = 400
let temp = this.$root.$data.documentClientHeight - this.$refs.myTable.$el.offsetTop - 36 - 45 - 8
tmp = temp > tmp ? temp : tmp
this.tableMaxHeight = tmp
}
}
},
watch: {
'$root.$data.documentClientHeight'() {
this.changeTableMaxHeight()
}
},
mounted() {
setTimeout(() => {
this.changeTableMaxHeight()
}, 0)
}
}
<file_sep>/src/main/java/com/test/framework/configurer/JacksonConfigurer.java
package com.test.framework.configurer;
import com.fasterxml.jackson.databind.Module;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class JacksonConfigurer {
@Bean
public Module customModule() {
SimpleModule simpleModule = new SimpleModule();
simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
return simpleModule;
}
}
<file_sep>/src/main/java/com/test/manage/model/generator/OrderTrace.java
package com.test.manage.model.generator;
import java.util.Date;
/**
* 订单跟踪
* order_trace
* @mbg.generated do_not_delete_during_merge
*/
public class OrderTrace {
/**
* ID
* order_trace.order_trace_id
* @mbg.generated
*/
private String orderTraceId;
/**
* 跟踪信息
* order_trace.order_trace_content
* @mbg.generated
*/
private String orderTraceContent;
/**
* 追踪详情
* order_trace.order_trace_detail
* @mbg.generated
*/
private String orderTraceDetail;
/**
* 订单ID
* order_trace.order_trace_order_id
* @mbg.generated
*/
private String orderTraceOrderId;
/**
* 操作人ID
* order_trace.order_trace_create_user_id
* @mbg.generated
*/
private String orderTraceCreateUserId;
/**
* 创建时间
* order_trace.create_time
* @mbg.generated
*/
private Date createTime;
/**
* ID
* @return the value of order_trace.order_trace_id
* @mbg.generated
*/
public String getOrderTraceId() {
return orderTraceId;
}
/**
* ID
* @param orderTraceId the value for order_trace.order_trace_id
* @mbg.generated
*/
public void setOrderTraceId(String orderTraceId) {
this.orderTraceId = orderTraceId == null ? null : orderTraceId.trim();
}
/**
* 跟踪信息
* @return the value of order_trace.order_trace_content
* @mbg.generated
*/
public String getOrderTraceContent() {
return orderTraceContent;
}
/**
* 跟踪信息
* @param orderTraceContent the value for order_trace.order_trace_content
* @mbg.generated
*/
public void setOrderTraceContent(String orderTraceContent) {
this.orderTraceContent = orderTraceContent == null ? null : orderTraceContent.trim();
}
/**
* 追踪详情
* @return the value of order_trace.order_trace_detail
* @mbg.generated
*/
public String getOrderTraceDetail() {
return orderTraceDetail;
}
/**
* 追踪详情
* @param orderTraceDetail the value for order_trace.order_trace_detail
* @mbg.generated
*/
public void setOrderTraceDetail(String orderTraceDetail) {
this.orderTraceDetail = orderTraceDetail == null ? null : orderTraceDetail.trim();
}
/**
* 订单ID
* @return the value of order_trace.order_trace_order_id
* @mbg.generated
*/
public String getOrderTraceOrderId() {
return orderTraceOrderId;
}
/**
* 订单ID
* @param orderTraceOrderId the value for order_trace.order_trace_order_id
* @mbg.generated
*/
public void setOrderTraceOrderId(String orderTraceOrderId) {
this.orderTraceOrderId = orderTraceOrderId == null ? null : orderTraceOrderId.trim();
}
/**
* 操作人ID
* @return the value of order_trace.order_trace_create_user_id
* @mbg.generated
*/
public String getOrderTraceCreateUserId() {
return orderTraceCreateUserId;
}
/**
* 操作人ID
* @param orderTraceCreateUserId the value for order_trace.order_trace_create_user_id
* @mbg.generated
*/
public void setOrderTraceCreateUserId(String orderTraceCreateUserId) {
this.orderTraceCreateUserId = orderTraceCreateUserId == null ? null : orderTraceCreateUserId.trim();
}
/**
* 创建时间
* @return the value of order_trace.create_time
* @mbg.generated
*/
public Date getCreateTime() {
return createTime;
}
/**
* 创建时间
* @param createTime the value for order_trace.create_time
* @mbg.generated
*/
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
}<file_sep>/src/test/java/com/Test.java
package com;
import com.test.Application;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
/**
* @Description:
* @Author:hudi
* @Date: Created in 11:17 2019/3/8
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class Test {
}
<file_sep>/src/main/java/com/test/manage/web/UserController.java
package com.test.manage.web;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.google.j2objc.annotations.AutoreleasePool;
import com.test.manage.model.generator.Company;
import com.test.manage.model.generator.Resource;
import com.test.manage.model.generator.User;
import com.test.manage.model.request.LoginRequest;
import com.test.manage.model.request.UserRequest;
import com.test.manage.service.notice.NoticeService;
import com.test.manage.service.user.UserService;
import com.test.framework.model.ApiResult;
import com.test.framework.model.AuthUser;
import com.test.framework.security.Auth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static com.test.framework.utils.ApiResultUtil.error;
import static com.test.framework.utils.ApiResultUtil.success;
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@Autowired
private NoticeService noticeService;
@Autowired
private Auth auth;
/**
* 用户登录
*
* @param loginRequest
* @return
*/
@PostMapping("/login")
public ApiResult login(@RequestBody @Validated LoginRequest loginRequest) {
return userService.login(loginRequest);
}
@GetMapping("/loginOut")
public ApiResult loginOut(String token) {
userService.loginOut(token);
return success("登出成功");
}
@GetMapping("/getResource")
public ApiResult getResource() {
try {
AuthUser authUser = auth.getCurrentUser();
List<Resource> list = userService.getResource(authUser.getUserId());
return success(list);
} catch (Exception e) {
return error("获取资源失败" + e);
}
}
/**
* 获取企业信息
*
* @param user
* @return
*/
@PostMapping("/getCompanyInformation")
public ApiResult getCompanyInformation(@RequestBody User user) {
Company company = userService.getCompanyInformation(user.getUserCompanyId());
return success(company);
}
/**
* 获取个人用户信息
*
* @param user
* @return
*/
@PostMapping("/getPersonalInformation")
public ApiResult getPersonalInformation(@RequestBody User user) {
User us = userService.getPersonalInformation(user.getUserId());
return success(us);
}
/**
* 判断用户名是否已注册
*
* @param user
* @return
*/
@PostMapping("/register/checkUserName")
public ApiResult checkUserName(@RequestBody User user) {
Boolean b = userService.checkUserName(user);
if (b) {
return success("");
} else {
return error("该用户名已注册过");
}
}
/**
* 重置登录密码
*
* @param userRequest
* @return
*/
@PostMapping("/login/resetPassword")
public ApiResult resetPassword(@RequestBody @Validated UserRequest userRequest) {
if (userService.checkMobile(userRequest)) {
return userService.resetPassword(userRequest);
} else {
return error("预留手机号错误");
}
}
/**
* 更换联系人
*
* @param userRequest
* @return
*/
@PostMapping("/changeMobile")
public ApiResult changeMobile(@RequestBody UserRequest userRequest) {
Integer i = userService.changeMobile(userRequest);
if (i == 2) {
return success("联系人修改成功");
}
return error("联系人修改失败");
}
/**
* 修改登录密码
*
* @param userRequest
* @return
*/
@PostMapping("/changePassword")
public ApiResult changePassword(@RequestBody UserRequest userRequest) {
return userService.changePassword(userRequest);
}
/**
* 用户注册
*
* @return
*/
@RequestMapping("/register")
@Transactional
public ApiResult register(MultipartFile font, MultipartFile back, MultipartFile companyOrganizationCodeImg, MultipartFile companyLicenseNoImg, MultipartFile companyTaxNoImg, String userStr, String userVerificationCode) throws Exception {
User user = JSONObject.parseObject(userStr, new TypeReference<User>() {
});
Company company = JSONObject.parseObject(userStr, new TypeReference<Company>() {
});
Integer userType = user.getUserType();
String mobile = null;
// 0-后台用户,1-个人,2-企业
if (userType == 1) {
mobile = user.getUserMobile();
} else if (userType == 2 || userType == 3) {
mobile = company.getCompanyContactTel();
}
return userService.save(user, company, mobile);
}
/**
* 修改企业信息
*/
@RequestMapping("/changeCompanyInformation")
@Transactional
public void changeCompanyInformation(String userStr) throws Exception {
Company company = JSONObject.parseObject(userStr, new TypeReference<Company>() {
});
userService.changeCompanyInformation(company);
}
/**
* 修改个人用户信息
*/
@RequestMapping("/changePersonalInformation")
@Transactional
public void changePersonalInformation(String userStr) throws Exception {
User user = JSONObject.parseObject(userStr, new TypeReference<User>() {
});
userService.changePersonalInformation(user);
}
@GetMapping("/getUserInfo")
public ApiResult getUserInfo(){
Map<String ,Object> map = new HashMap<>();
map.put("personal",userService.getPersonalInformation(auth.getCurrentUser().getUserId()));
map.put("company",userService.getCompanyInformation(auth.getCurrentUser().getUserCompanyId()));
map.put("notices",noticeService.getNoticeList());
return success(map);
}
}
<file_sep>/src/main/java/com/test/manage/dao/generator/ResourceMapper.java
package com.test.manage.dao.generator;
import com.test.manage.model.generator.Resource;
import com.test.manage.model.generator.ResourceExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface ResourceMapper {
/**
* This method was generated by MyBatis Generator, do not modify.
* @mbg.generated
*/
long countByExample(ResourceExample example);
/**
* This method was generated by MyBatis Generator, do not modify.
* @mbg.generated
*/
int deleteByExample(ResourceExample example);
/**
* This method was generated by MyBatis Generator, do not modify.
* @mbg.generated
*/
int deleteByPrimaryKey(String resourceId);
/**
* This method was generated by MyBatis Generator, do not modify.
* @mbg.generated
*/
int insert(Resource record);
/**
* This method was generated by MyBatis Generator, do not modify.
* @mbg.generated
*/
int insertSelective(Resource record);
/**
* This method was generated by MyBatis Generator, do not modify.
* @mbg.generated
*/
List<Resource> selectByExample(ResourceExample example);
/**
* This method was generated by MyBatis Generator, do not modify.
* @mbg.generated
*/
Resource selectByPrimaryKey(String resourceId);
/**
* This method was generated by MyBatis Generator, do not modify.
* @mbg.generated
*/
int updateByExampleSelective(@Param("record") Resource record, @Param("example") ResourceExample example);
/**
* This method was generated by MyBatis Generator, do not modify.
* @mbg.generated
*/
int updateByExample(@Param("record") Resource record, @Param("example") ResourceExample example);
/**
* This method was generated by MyBatis Generator, do not modify.
* @mbg.generated
*/
int updateByPrimaryKeySelective(Resource record);
/**
* This method was generated by MyBatis Generator, do not modify.
* @mbg.generated
*/
int updateByPrimaryKey(Resource record);
}<file_sep>/src/main/java/com/test/manage/service/role/impl/RoleServiceImpl.java
package com.test.manage.service.role.impl;
import com.test.common.CommonUtil;
import com.test.manage.dao.custom.RoleCuMapper;
import com.test.manage.dao.generator.*;
import com.test.manage.model.generator.*;
import com.test.manage.model.request.RolePageParams;
import com.test.manage.model.request.RoleParams;
import com.test.manage.service.role.RoleService;
import com.test.framework.model.ApiResult;
import com.test.framework.model.AuthUser;
import com.test.framework.security.Auth;
import com.test.framework.utils.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
import java.util.List;
import java.util.Map;
import static com.test.framework.utils.ApiResultUtil.error;
import static com.test.framework.utils.ApiResultUtil.success;
@Service
@Transactional
public class RoleServiceImpl implements RoleService {
@Autowired
private RoleCuMapper roleCuMapper;
@Autowired
private RoleMapper roleMapper;
@Autowired
private Auth auth;
@Autowired
private RoleResourceMapper roleResourceMapper;
@Autowired
private UserMapper userMapper;
@Autowired
private ResourceMapper resourceMapper;
@Autowired
private userRoleMapper userRoleMapper;
private String passwordReg = "^(?=[^A-Z\\u4e00-\\u9fa5]*[0-9])(?=[^A-Z\\u4e00-\\u9fa5]*[a-z])[^A-Z\\u4e00-\\u9fa5]{8,50}$";
@Override
public List<Role> getAllRole() {
RoleExample roleExample = new RoleExample();
roleExample.setOrderByClause("role_index");
RoleExample.Criteria criteria = roleExample.createCriteria();
AuthUser authUser = auth.getCurrentUser();
Integer userType = authUser.getUserType();
// 角色类型 1、前台 2、后台
if (userType == 0) {
criteria.andRoleTypeEqualTo(2).andRoleIsDeleteEqualTo(false);
} else {
criteria.andRoleTypeEqualTo(1).andRoleCompanyIdEqualTo(authUser.getUserCompanyId()).andRoleIsDeleteEqualTo(false);
}
return roleMapper.selectByExample(roleExample);
}
@Override
public ApiResult checkMobile(RoleParams roleParams) {
User user = userMapper.selectByPrimaryKey(roleParams.getUserId());
if (!roleParams.getMobile().equals(user.getUserMobile())) {
return error("预留手机错误");
} else {
return success("");
}
}
@Override
public List<Map<String, Object>> manageList(RolePageParams rolePageParams) {
return roleCuMapper.manageList(rolePageParams);
}
@Override
public List<Map<String, Object>> manageListFront(RolePageParams rolePageParams) {
rolePageParams.setRoleCompanyId(auth.getCurrentUser().getUserCompanyId());
return roleCuMapper.manageListFront(rolePageParams);
}
@Override
public void deleteRole(String roleId) {
AuthUser authUser = auth.getCurrentUser();
Role role = new Role();
role.setRoleId(roleId);
role.setRoleIsDelete(true);
role.setRoleUpdateTime(new Date());
role.setRoleUpdateUserId(authUser.getUserId());
roleMapper.updateByPrimaryKeySelective(role);
}
@Override
public List<Resource> allRoleResources() {
return roleCuMapper.allRoleResources();
}
@Override
public List<Resource> frontRoleResources() {
return roleCuMapper.frontRoleResources();
}
@Override
public void addRole(RoleParams roleParams) {
AuthUser authUser = auth.getCurrentUser();
Role role = new Role();
RoleResource roleResource = new RoleResource();
role.setRoleId(CommonUtil.uuid());
role.setRoleName(roleParams.getRoleName());
role.setRoleEnName(roleParams.getRoleEnName());
role.setRoleIndex(roleParams.getRoleIndex());
role.setRoleCreateUserId(authUser.getUserId());
role.setRoleCreateTime(new Date());
role.setRoleType(2);
roleMapper.insertSelective(role);
roleParams.setRoleId(role.getRoleId());
updateRoleResource(roleParams);
}
@Override
public void addRoleFront(RoleParams roleParams) {
AuthUser authUser = auth.getCurrentUser();
Role role = new Role();
RoleResource roleResource = new RoleResource();
role.setRoleId(CommonUtil.uuid());
role.setRoleName(roleParams.getRoleName());
role.setRoleEnName(roleParams.getRoleEnName());
role.setRoleIndex(roleParams.getRoleIndex());
role.setRoleCreateUserId(authUser.getUserId());
role.setRoleCreateTime(new Date());
role.setRoleCompanyId(authUser.getUserCompanyId());
role.setRoleType(1);
roleMapper.insertSelective(role);
roleParams.setRoleId(role.getRoleId());
updateRoleResource(roleParams);
}
@Override
public void updateRole(RoleParams roleParams) {
AuthUser authUser = auth.getCurrentUser();
Role role = new Role();
BeanUtils.copyProperties(roleParams, role);
role.setRoleUpdateUserId(authUser.getUserId());
role.setRoleUpdateTime(new Date());
roleMapper.updateByPrimaryKeySelective(role);
roleParams.setRoleId(role.getRoleId());
updateRoleResource(roleParams);
}
public void updateRoleResource(RoleParams roleParams) {
AuthUser authUser = auth.getCurrentUser();
//先删除
RoleResourceExample example = new RoleResourceExample();
example.createCriteria()
.andRoleResourceRoleIdEqualTo(roleParams.getRoleId());
roleResourceMapper.deleteByExample(example);
//再增加
if (roleParams.getResourceIds() != null) {
roleParams.getResourceIds().forEach(item -> {
RoleResource roleResource = new RoleResource();
roleResource.setRoleResourceRoleId(roleParams.getRoleId());
roleResource.setRoleResourceResourceId(item);
roleResource.setRoleResourceCreateUserId(authUser.getUserId());
roleResource.setRoleResourceCreateTime(new Date());
roleResourceMapper.insertSelective(roleResource);
});
}
}
public void addFrontUserRole(User user){
Role role = new Role();
role.setRoleId(CommonUtil.uuid());
role.setRoleCompanyId(user.getUserCompanyId());
role.setRoleName("管理员");
role.setRoleEnName("admin");
role.setRoleType(1);
roleMapper.insertSelective(role);
userRole userRole = new userRole();
userRole.setUserRoleRoleId(role.getRoleId());
userRole.setUserRoleUserId(user.getUserId());
userRoleMapper.insertSelective(userRole);
ResourceExample resourceExample = new ResourceExample();
resourceExample.createCriteria().andResourceTypeEqualTo(1).andResourceIsDeleteEqualTo(false);
List<Resource> resources = resourceMapper.selectByExample(resourceExample);
if(resources != null && resources.size() > 0){
for(Resource resource : resources){
RoleResource roleResource = new RoleResource();
roleResource.setRoleResourceResourceId(resource.getResourceId());
roleResource.setRoleResourceRoleId(role.getRoleId());
roleResourceMapper.insertSelective(roleResource);
}
}
}
}
<file_sep>/src/main/java/com/test/manage/model/generator/OrderTraceExample.java
package com.test.manage.model.generator;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class OrderTraceExample {
/**
* This field was generated by MyBatis Generator, do not modify.
* This field corresponds to the database table order_trace
* @mbg.generated
*/
protected String orderByClause;
/**
* This field was generated by MyBatis Generator, do not modify.
* This field corresponds to the database table order_trace
* @mbg.generated
*/
protected boolean distinct;
/**
* This field was generated by MyBatis Generator, do not modify.
* This field corresponds to the database table order_trace
* @mbg.generated
*/
protected List<Criteria> oredCriteria;
/**
* This method was generated by MyBatis Generator, do not modify.
* @mbg.generated
*/
public OrderTraceExample() {
oredCriteria = new ArrayList<Criteria>();
}
/**
* This method was generated by MyBatis Generator, do not modify.
* @mbg.generated
*/
public void setOrderByClause(String orderByClause) {
this.orderByClause = orderByClause;
}
/**
* This method was generated by MyBatis Generator, do not modify.
* @mbg.generated
*/
public String getOrderByClause() {
return orderByClause;
}
/**
* This method was generated by MyBatis Generator, do not modify.
* @mbg.generated
*/
public void setDistinct(boolean distinct) {
this.distinct = distinct;
}
/**
* This method was generated by MyBatis Generator, do not modify.
* @mbg.generated
*/
public boolean isDistinct() {
return distinct;
}
/**
* This method was generated by MyBatis Generator, do not modify.
* @mbg.generated
*/
public List<Criteria> getOredCriteria() {
return oredCriteria;
}
/**
* This method was generated by MyBatis Generator, do not modify.
* @mbg.generated
*/
public void or(Criteria criteria) {
oredCriteria.add(criteria);
}
/**
* This method was generated by MyBatis Generator, do not modify.
* @mbg.generated
*/
public Criteria or() {
Criteria criteria = createCriteriaInternal();
oredCriteria.add(criteria);
return criteria;
}
/**
* This method was generated by MyBatis Generator, do not modify.
* @mbg.generated
*/
public Criteria createCriteria() {
Criteria criteria = createCriteriaInternal();
if (oredCriteria.size() == 0) {
oredCriteria.add(criteria);
}
return criteria;
}
/**
* This method was generated by MyBatis Generator, do not modify.
* @mbg.generated
*/
protected Criteria createCriteriaInternal() {
Criteria criteria = new Criteria();
return criteria;
}
/**
* This method was generated by MyBatis Generator, do not modify.
* @mbg.generated
*/
public void clear() {
oredCriteria.clear();
orderByClause = null;
distinct = false;
}
/**
* order_trace
* @mbg.generated
*/
protected abstract static class GeneratedCriteria {
protected List<Criterion> criteria;
protected GeneratedCriteria() {
super();
criteria = new ArrayList<Criterion>();
}
public boolean isValid() {
return criteria.size() > 0;
}
public List<Criterion> getAllCriteria() {
return criteria;
}
public List<Criterion> getCriteria() {
return criteria;
}
protected void addCriterion(String condition) {
if (condition == null) {
throw new RuntimeException("Value for condition cannot be null");
}
criteria.add(new Criterion(condition));
}
protected void addCriterion(String condition, Object value, String property) {
if (value == null) {
throw new RuntimeException("Value for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value));
}
protected void addCriterion(String condition, Object value1, Object value2, String property) {
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value1, value2));
}
public Criteria andOrderTraceIdIsNull() {
addCriterion("order_trace_id is null");
return (Criteria) this;
}
public Criteria andOrderTraceIdIsNotNull() {
addCriterion("order_trace_id is not null");
return (Criteria) this;
}
public Criteria andOrderTraceIdEqualTo(String value) {
addCriterion("order_trace_id =", value, "orderTraceId");
return (Criteria) this;
}
public Criteria andOrderTraceIdNotEqualTo(String value) {
addCriterion("order_trace_id <>", value, "orderTraceId");
return (Criteria) this;
}
public Criteria andOrderTraceIdGreaterThan(String value) {
addCriterion("order_trace_id >", value, "orderTraceId");
return (Criteria) this;
}
public Criteria andOrderTraceIdGreaterThanOrEqualTo(String value) {
addCriterion("order_trace_id >=", value, "orderTraceId");
return (Criteria) this;
}
public Criteria andOrderTraceIdLessThan(String value) {
addCriterion("order_trace_id <", value, "orderTraceId");
return (Criteria) this;
}
public Criteria andOrderTraceIdLessThanOrEqualTo(String value) {
addCriterion("order_trace_id <=", value, "orderTraceId");
return (Criteria) this;
}
public Criteria andOrderTraceIdLike(String value) {
addCriterion("order_trace_id like", value, "orderTraceId");
return (Criteria) this;
}
public Criteria andOrderTraceIdNotLike(String value) {
addCriterion("order_trace_id not like", value, "orderTraceId");
return (Criteria) this;
}
public Criteria andOrderTraceIdIn(List<String> values) {
addCriterion("order_trace_id in", values, "orderTraceId");
return (Criteria) this;
}
public Criteria andOrderTraceIdNotIn(List<String> values) {
addCriterion("order_trace_id not in", values, "orderTraceId");
return (Criteria) this;
}
public Criteria andOrderTraceIdBetween(String value1, String value2) {
addCriterion("order_trace_id between", value1, value2, "orderTraceId");
return (Criteria) this;
}
public Criteria andOrderTraceIdNotBetween(String value1, String value2) {
addCriterion("order_trace_id not between", value1, value2, "orderTraceId");
return (Criteria) this;
}
public Criteria andOrderTraceContentIsNull() {
addCriterion("order_trace_content is null");
return (Criteria) this;
}
public Criteria andOrderTraceContentIsNotNull() {
addCriterion("order_trace_content is not null");
return (Criteria) this;
}
public Criteria andOrderTraceContentEqualTo(String value) {
addCriterion("order_trace_content =", value, "orderTraceContent");
return (Criteria) this;
}
public Criteria andOrderTraceContentNotEqualTo(String value) {
addCriterion("order_trace_content <>", value, "orderTraceContent");
return (Criteria) this;
}
public Criteria andOrderTraceContentGreaterThan(String value) {
addCriterion("order_trace_content >", value, "orderTraceContent");
return (Criteria) this;
}
public Criteria andOrderTraceContentGreaterThanOrEqualTo(String value) {
addCriterion("order_trace_content >=", value, "orderTraceContent");
return (Criteria) this;
}
public Criteria andOrderTraceContentLessThan(String value) {
addCriterion("order_trace_content <", value, "orderTraceContent");
return (Criteria) this;
}
public Criteria andOrderTraceContentLessThanOrEqualTo(String value) {
addCriterion("order_trace_content <=", value, "orderTraceContent");
return (Criteria) this;
}
public Criteria andOrderTraceContentLike(String value) {
addCriterion("order_trace_content like", value, "orderTraceContent");
return (Criteria) this;
}
public Criteria andOrderTraceContentNotLike(String value) {
addCriterion("order_trace_content not like", value, "orderTraceContent");
return (Criteria) this;
}
public Criteria andOrderTraceContentIn(List<String> values) {
addCriterion("order_trace_content in", values, "orderTraceContent");
return (Criteria) this;
}
public Criteria andOrderTraceContentNotIn(List<String> values) {
addCriterion("order_trace_content not in", values, "orderTraceContent");
return (Criteria) this;
}
public Criteria andOrderTraceContentBetween(String value1, String value2) {
addCriterion("order_trace_content between", value1, value2, "orderTraceContent");
return (Criteria) this;
}
public Criteria andOrderTraceContentNotBetween(String value1, String value2) {
addCriterion("order_trace_content not between", value1, value2, "orderTraceContent");
return (Criteria) this;
}
public Criteria andOrderTraceDetailIsNull() {
addCriterion("order_trace_detail is null");
return (Criteria) this;
}
public Criteria andOrderTraceDetailIsNotNull() {
addCriterion("order_trace_detail is not null");
return (Criteria) this;
}
public Criteria andOrderTraceDetailEqualTo(String value) {
addCriterion("order_trace_detail =", value, "orderTraceDetail");
return (Criteria) this;
}
public Criteria andOrderTraceDetailNotEqualTo(String value) {
addCriterion("order_trace_detail <>", value, "orderTraceDetail");
return (Criteria) this;
}
public Criteria andOrderTraceDetailGreaterThan(String value) {
addCriterion("order_trace_detail >", value, "orderTraceDetail");
return (Criteria) this;
}
public Criteria andOrderTraceDetailGreaterThanOrEqualTo(String value) {
addCriterion("order_trace_detail >=", value, "orderTraceDetail");
return (Criteria) this;
}
public Criteria andOrderTraceDetailLessThan(String value) {
addCriterion("order_trace_detail <", value, "orderTraceDetail");
return (Criteria) this;
}
public Criteria andOrderTraceDetailLessThanOrEqualTo(String value) {
addCriterion("order_trace_detail <=", value, "orderTraceDetail");
return (Criteria) this;
}
public Criteria andOrderTraceDetailLike(String value) {
addCriterion("order_trace_detail like", value, "orderTraceDetail");
return (Criteria) this;
}
public Criteria andOrderTraceDetailNotLike(String value) {
addCriterion("order_trace_detail not like", value, "orderTraceDetail");
return (Criteria) this;
}
public Criteria andOrderTraceDetailIn(List<String> values) {
addCriterion("order_trace_detail in", values, "orderTraceDetail");
return (Criteria) this;
}
public Criteria andOrderTraceDetailNotIn(List<String> values) {
addCriterion("order_trace_detail not in", values, "orderTraceDetail");
return (Criteria) this;
}
public Criteria andOrderTraceDetailBetween(String value1, String value2) {
addCriterion("order_trace_detail between", value1, value2, "orderTraceDetail");
return (Criteria) this;
}
public Criteria andOrderTraceDetailNotBetween(String value1, String value2) {
addCriterion("order_trace_detail not between", value1, value2, "orderTraceDetail");
return (Criteria) this;
}
public Criteria andOrderTraceOrderIdIsNull() {
addCriterion("order_trace_order_id is null");
return (Criteria) this;
}
public Criteria andOrderTraceOrderIdIsNotNull() {
addCriterion("order_trace_order_id is not null");
return (Criteria) this;
}
public Criteria andOrderTraceOrderIdEqualTo(String value) {
addCriterion("order_trace_order_id =", value, "orderTraceOrderId");
return (Criteria) this;
}
public Criteria andOrderTraceOrderIdNotEqualTo(String value) {
addCriterion("order_trace_order_id <>", value, "orderTraceOrderId");
return (Criteria) this;
}
public Criteria andOrderTraceOrderIdGreaterThan(String value) {
addCriterion("order_trace_order_id >", value, "orderTraceOrderId");
return (Criteria) this;
}
public Criteria andOrderTraceOrderIdGreaterThanOrEqualTo(String value) {
addCriterion("order_trace_order_id >=", value, "orderTraceOrderId");
return (Criteria) this;
}
public Criteria andOrderTraceOrderIdLessThan(String value) {
addCriterion("order_trace_order_id <", value, "orderTraceOrderId");
return (Criteria) this;
}
public Criteria andOrderTraceOrderIdLessThanOrEqualTo(String value) {
addCriterion("order_trace_order_id <=", value, "orderTraceOrderId");
return (Criteria) this;
}
public Criteria andOrderTraceOrderIdLike(String value) {
addCriterion("order_trace_order_id like", value, "orderTraceOrderId");
return (Criteria) this;
}
public Criteria andOrderTraceOrderIdNotLike(String value) {
addCriterion("order_trace_order_id not like", value, "orderTraceOrderId");
return (Criteria) this;
}
public Criteria andOrderTraceOrderIdIn(List<String> values) {
addCriterion("order_trace_order_id in", values, "orderTraceOrderId");
return (Criteria) this;
}
public Criteria andOrderTraceOrderIdNotIn(List<String> values) {
addCriterion("order_trace_order_id not in", values, "orderTraceOrderId");
return (Criteria) this;
}
public Criteria andOrderTraceOrderIdBetween(String value1, String value2) {
addCriterion("order_trace_order_id between", value1, value2, "orderTraceOrderId");
return (Criteria) this;
}
public Criteria andOrderTraceOrderIdNotBetween(String value1, String value2) {
addCriterion("order_trace_order_id not between", value1, value2, "orderTraceOrderId");
return (Criteria) this;
}
public Criteria andOrderTraceCreateUserIdIsNull() {
addCriterion("order_trace_create_user_id is null");
return (Criteria) this;
}
public Criteria andOrderTraceCreateUserIdIsNotNull() {
addCriterion("order_trace_create_user_id is not null");
return (Criteria) this;
}
public Criteria andOrderTraceCreateUserIdEqualTo(String value) {
addCriterion("order_trace_create_user_id =", value, "orderTraceCreateUserId");
return (Criteria) this;
}
public Criteria andOrderTraceCreateUserIdNotEqualTo(String value) {
addCriterion("order_trace_create_user_id <>", value, "orderTraceCreateUserId");
return (Criteria) this;
}
public Criteria andOrderTraceCreateUserIdGreaterThan(String value) {
addCriterion("order_trace_create_user_id >", value, "orderTraceCreateUserId");
return (Criteria) this;
}
public Criteria andOrderTraceCreateUserIdGreaterThanOrEqualTo(String value) {
addCriterion("order_trace_create_user_id >=", value, "orderTraceCreateUserId");
return (Criteria) this;
}
public Criteria andOrderTraceCreateUserIdLessThan(String value) {
addCriterion("order_trace_create_user_id <", value, "orderTraceCreateUserId");
return (Criteria) this;
}
public Criteria andOrderTraceCreateUserIdLessThanOrEqualTo(String value) {
addCriterion("order_trace_create_user_id <=", value, "orderTraceCreateUserId");
return (Criteria) this;
}
public Criteria andOrderTraceCreateUserIdLike(String value) {
addCriterion("order_trace_create_user_id like", value, "orderTraceCreateUserId");
return (Criteria) this;
}
public Criteria andOrderTraceCreateUserIdNotLike(String value) {
addCriterion("order_trace_create_user_id not like", value, "orderTraceCreateUserId");
return (Criteria) this;
}
public Criteria andOrderTraceCreateUserIdIn(List<String> values) {
addCriterion("order_trace_create_user_id in", values, "orderTraceCreateUserId");
return (Criteria) this;
}
public Criteria andOrderTraceCreateUserIdNotIn(List<String> values) {
addCriterion("order_trace_create_user_id not in", values, "orderTraceCreateUserId");
return (Criteria) this;
}
public Criteria andOrderTraceCreateUserIdBetween(String value1, String value2) {
addCriterion("order_trace_create_user_id between", value1, value2, "orderTraceCreateUserId");
return (Criteria) this;
}
public Criteria andOrderTraceCreateUserIdNotBetween(String value1, String value2) {
addCriterion("order_trace_create_user_id not between", value1, value2, "orderTraceCreateUserId");
return (Criteria) this;
}
public Criteria andCreateTimeIsNull() {
addCriterion("create_time is null");
return (Criteria) this;
}
public Criteria andCreateTimeIsNotNull() {
addCriterion("create_time is not null");
return (Criteria) this;
}
public Criteria andCreateTimeEqualTo(Date value) {
addCriterion("create_time =", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeNotEqualTo(Date value) {
addCriterion("create_time <>", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeGreaterThan(Date value) {
addCriterion("create_time >", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeGreaterThanOrEqualTo(Date value) {
addCriterion("create_time >=", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeLessThan(Date value) {
addCriterion("create_time <", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeLessThanOrEqualTo(Date value) {
addCriterion("create_time <=", value, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeIn(List<Date> values) {
addCriterion("create_time in", values, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeNotIn(List<Date> values) {
addCriterion("create_time not in", values, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeBetween(Date value1, Date value2) {
addCriterion("create_time between", value1, value2, "createTime");
return (Criteria) this;
}
public Criteria andCreateTimeNotBetween(Date value1, Date value2) {
addCriterion("create_time not between", value1, value2, "createTime");
return (Criteria) this;
}
}
/**
* This class was generated by MyBatis Generator, do not modify.
* order_trace
* @mbg.generated do_not_delete_during_merge
*/
public static class Criteria extends GeneratedCriteria {
protected Criteria() {
super();
}
}
/**
* order_trace
* @mbg.generated
*/
public static class Criterion {
private String condition;
private Object value;
private Object secondValue;
private boolean noValue;
private boolean singleValue;
private boolean betweenValue;
private boolean listValue;
private String typeHandler;
public String getCondition() {
return condition;
}
public Object getValue() {
return value;
}
public Object getSecondValue() {
return secondValue;
}
public boolean isNoValue() {
return noValue;
}
public boolean isSingleValue() {
return singleValue;
}
public boolean isBetweenValue() {
return betweenValue;
}
public boolean isListValue() {
return listValue;
}
public String getTypeHandler() {
return typeHandler;
}
protected Criterion(String condition) {
super();
this.condition = condition;
this.typeHandler = null;
this.noValue = true;
}
protected Criterion(String condition, Object value, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.typeHandler = typeHandler;
if (value instanceof List<?>) {
this.listValue = true;
} else {
this.singleValue = true;
}
}
protected Criterion(String condition, Object value) {
this(condition, value, null);
}
protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.secondValue = secondValue;
this.typeHandler = typeHandler;
this.betweenValue = true;
}
protected Criterion(String condition, Object value, Object secondValue) {
this(condition, value, secondValue, null);
}
}
}<file_sep>/src/main/java/com/test/manage/model/generator/OrderExample.java
package com.test.manage.model.generator;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class OrderExample {
/**
* This field was generated by MyBatis Generator, do not modify.
* This field corresponds to the database table goods_order
* @mbg.generated
*/
protected String orderByClause;
/**
* This field was generated by MyBatis Generator, do not modify.
* This field corresponds to the database table goods_order
* @mbg.generated
*/
protected boolean distinct;
/**
* This field was generated by MyBatis Generator, do not modify.
* This field corresponds to the database table goods_order
* @mbg.generated
*/
protected List<Criteria> oredCriteria;
/**
* This method was generated by MyBatis Generator, do not modify.
* @mbg.generated
*/
public OrderExample() {
oredCriteria = new ArrayList<Criteria>();
}
/**
* This method was generated by MyBatis Generator, do not modify.
* @mbg.generated
*/
public void setOrderByClause(String orderByClause) {
this.orderByClause = orderByClause;
}
/**
* This method was generated by MyBatis Generator, do not modify.
* @mbg.generated
*/
public String getOrderByClause() {
return orderByClause;
}
/**
* This method was generated by MyBatis Generator, do not modify.
* @mbg.generated
*/
public void setDistinct(boolean distinct) {
this.distinct = distinct;
}
/**
* This method was generated by MyBatis Generator, do not modify.
* @mbg.generated
*/
public boolean isDistinct() {
return distinct;
}
/**
* This method was generated by MyBatis Generator, do not modify.
* @mbg.generated
*/
public List<Criteria> getOredCriteria() {
return oredCriteria;
}
/**
* This method was generated by MyBatis Generator, do not modify.
* @mbg.generated
*/
public void or(Criteria criteria) {
oredCriteria.add(criteria);
}
/**
* This method was generated by MyBatis Generator, do not modify.
* @mbg.generated
*/
public Criteria or() {
Criteria criteria = createCriteriaInternal();
oredCriteria.add(criteria);
return criteria;
}
/**
* This method was generated by MyBatis Generator, do not modify.
* @mbg.generated
*/
public Criteria createCriteria() {
Criteria criteria = createCriteriaInternal();
if (oredCriteria.size() == 0) {
oredCriteria.add(criteria);
}
return criteria;
}
/**
* This method was generated by MyBatis Generator, do not modify.
* @mbg.generated
*/
protected Criteria createCriteriaInternal() {
Criteria criteria = new Criteria();
return criteria;
}
/**
* This method was generated by MyBatis Generator, do not modify.
* @mbg.generated
*/
public void clear() {
oredCriteria.clear();
orderByClause = null;
distinct = false;
}
/**
* goods_order
* @mbg.generated
*/
protected abstract static class GeneratedCriteria {
protected List<Criterion> criteria;
protected GeneratedCriteria() {
super();
criteria = new ArrayList<Criterion>();
}
public boolean isValid() {
return criteria.size() > 0;
}
public List<Criterion> getAllCriteria() {
return criteria;
}
public List<Criterion> getCriteria() {
return criteria;
}
protected void addCriterion(String condition) {
if (condition == null) {
throw new RuntimeException("Value for condition cannot be null");
}
criteria.add(new Criterion(condition));
}
protected void addCriterion(String condition, Object value, String property) {
if (value == null) {
throw new RuntimeException("Value for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value));
}
protected void addCriterion(String condition, Object value1, Object value2, String property) {
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value1, value2));
}
public Criteria andOrderIdIsNull() {
addCriterion("order_id is null");
return (Criteria) this;
}
public Criteria andOrderIdIsNotNull() {
addCriterion("order_id is not null");
return (Criteria) this;
}
public Criteria andOrderIdEqualTo(String value) {
addCriterion("order_id =", value, "orderId");
return (Criteria) this;
}
public Criteria andOrderIdNotEqualTo(String value) {
addCriterion("order_id <>", value, "orderId");
return (Criteria) this;
}
public Criteria andOrderIdGreaterThan(String value) {
addCriterion("order_id >", value, "orderId");
return (Criteria) this;
}
public Criteria andOrderIdGreaterThanOrEqualTo(String value) {
addCriterion("order_id >=", value, "orderId");
return (Criteria) this;
}
public Criteria andOrderIdLessThan(String value) {
addCriterion("order_id <", value, "orderId");
return (Criteria) this;
}
public Criteria andOrderIdLessThanOrEqualTo(String value) {
addCriterion("order_id <=", value, "orderId");
return (Criteria) this;
}
public Criteria andOrderIdLike(String value) {
addCriterion("order_id like", value, "orderId");
return (Criteria) this;
}
public Criteria andOrderIdNotLike(String value) {
addCriterion("order_id not like", value, "orderId");
return (Criteria) this;
}
public Criteria andOrderIdIn(List<String> values) {
addCriterion("order_id in", values, "orderId");
return (Criteria) this;
}
public Criteria andOrderIdNotIn(List<String> values) {
addCriterion("order_id not in", values, "orderId");
return (Criteria) this;
}
public Criteria andOrderIdBetween(String value1, String value2) {
addCriterion("order_id between", value1, value2, "orderId");
return (Criteria) this;
}
public Criteria andOrderIdNotBetween(String value1, String value2) {
addCriterion("order_id not between", value1, value2, "orderId");
return (Criteria) this;
}
public Criteria andOrderNoIsNull() {
addCriterion("order_no is null");
return (Criteria) this;
}
public Criteria andOrderNoIsNotNull() {
addCriterion("order_no is not null");
return (Criteria) this;
}
public Criteria andOrderNoEqualTo(String value) {
addCriterion("order_no =", value, "orderNo");
return (Criteria) this;
}
public Criteria andOrderNoNotEqualTo(String value) {
addCriterion("order_no <>", value, "orderNo");
return (Criteria) this;
}
public Criteria andOrderNoGreaterThan(String value) {
addCriterion("order_no >", value, "orderNo");
return (Criteria) this;
}
public Criteria andOrderNoGreaterThanOrEqualTo(String value) {
addCriterion("order_no >=", value, "orderNo");
return (Criteria) this;
}
public Criteria andOrderNoLessThan(String value) {
addCriterion("order_no <", value, "orderNo");
return (Criteria) this;
}
public Criteria andOrderNoLessThanOrEqualTo(String value) {
addCriterion("order_no <=", value, "orderNo");
return (Criteria) this;
}
public Criteria andOrderNoLike(String value) {
addCriterion("order_no like", value, "orderNo");
return (Criteria) this;
}
public Criteria andOrderNoNotLike(String value) {
addCriterion("order_no not like", value, "orderNo");
return (Criteria) this;
}
public Criteria andOrderNoIn(List<String> values) {
addCriterion("order_no in", values, "orderNo");
return (Criteria) this;
}
public Criteria andOrderNoNotIn(List<String> values) {
addCriterion("order_no not in", values, "orderNo");
return (Criteria) this;
}
public Criteria andOrderNoBetween(String value1, String value2) {
addCriterion("order_no between", value1, value2, "orderNo");
return (Criteria) this;
}
public Criteria andOrderNoNotBetween(String value1, String value2) {
addCriterion("order_no not between", value1, value2, "orderNo");
return (Criteria) this;
}
public Criteria andOrderCompanyIdIsNull() {
addCriterion("order_company_id is null");
return (Criteria) this;
}
public Criteria andOrderCompanyIdIsNotNull() {
addCriterion("order_company_id is not null");
return (Criteria) this;
}
public Criteria andOrderCompanyIdEqualTo(String value) {
addCriterion("order_company_id =", value, "orderCompanyId");
return (Criteria) this;
}
public Criteria andOrderCompanyIdNotEqualTo(String value) {
addCriterion("order_company_id <>", value, "orderCompanyId");
return (Criteria) this;
}
public Criteria andOrderCompanyIdGreaterThan(String value) {
addCriterion("order_company_id >", value, "orderCompanyId");
return (Criteria) this;
}
public Criteria andOrderCompanyIdGreaterThanOrEqualTo(String value) {
addCriterion("order_company_id >=", value, "orderCompanyId");
return (Criteria) this;
}
public Criteria andOrderCompanyIdLessThan(String value) {
addCriterion("order_company_id <", value, "orderCompanyId");
return (Criteria) this;
}
public Criteria andOrderCompanyIdLessThanOrEqualTo(String value) {
addCriterion("order_company_id <=", value, "orderCompanyId");
return (Criteria) this;
}
public Criteria andOrderCompanyIdLike(String value) {
addCriterion("order_company_id like", value, "orderCompanyId");
return (Criteria) this;
}
public Criteria andOrderCompanyIdNotLike(String value) {
addCriterion("order_company_id not like", value, "orderCompanyId");
return (Criteria) this;
}
public Criteria andOrderCompanyIdIn(List<String> values) {
addCriterion("order_company_id in", values, "orderCompanyId");
return (Criteria) this;
}
public Criteria andOrderCompanyIdNotIn(List<String> values) {
addCriterion("order_company_id not in", values, "orderCompanyId");
return (Criteria) this;
}
public Criteria andOrderCompanyIdBetween(String value1, String value2) {
addCriterion("order_company_id between", value1, value2, "orderCompanyId");
return (Criteria) this;
}
public Criteria andOrderCompanyIdNotBetween(String value1, String value2) {
addCriterion("order_company_id not between", value1, value2, "orderCompanyId");
return (Criteria) this;
}
public Criteria andOrderReceiveCompanyIdIsNull() {
addCriterion("order_receive_company_id is null");
return (Criteria) this;
}
public Criteria andOrderReceiveCompanyIdIsNotNull() {
addCriterion("order_receive_company_id is not null");
return (Criteria) this;
}
public Criteria andOrderReceiveCompanyIdEqualTo(String value) {
addCriterion("order_receive_company_id =", value, "orderReceiveCompanyId");
return (Criteria) this;
}
public Criteria andOrderReceiveCompanyIdNotEqualTo(String value) {
addCriterion("order_receive_company_id <>", value, "orderReceiveCompanyId");
return (Criteria) this;
}
public Criteria andOrderReceiveCompanyIdGreaterThan(String value) {
addCriterion("order_receive_company_id >", value, "orderReceiveCompanyId");
return (Criteria) this;
}
public Criteria andOrderReceiveCompanyIdGreaterThanOrEqualTo(String value) {
addCriterion("order_receive_company_id >=", value, "orderReceiveCompanyId");
return (Criteria) this;
}
public Criteria andOrderReceiveCompanyIdLessThan(String value) {
addCriterion("order_receive_company_id <", value, "orderReceiveCompanyId");
return (Criteria) this;
}
public Criteria andOrderReceiveCompanyIdLessThanOrEqualTo(String value) {
addCriterion("order_receive_company_id <=", value, "orderReceiveCompanyId");
return (Criteria) this;
}
public Criteria andOrderReceiveCompanyIdLike(String value) {
addCriterion("order_receive_company_id like", value, "orderReceiveCompanyId");
return (Criteria) this;
}
public Criteria andOrderReceiveCompanyIdNotLike(String value) {
addCriterion("order_receive_company_id not like", value, "orderReceiveCompanyId");
return (Criteria) this;
}
public Criteria andOrderReceiveCompanyIdIn(List<String> values) {
addCriterion("order_receive_company_id in", values, "orderReceiveCompanyId");
return (Criteria) this;
}
public Criteria andOrderReceiveCompanyIdNotIn(List<String> values) {
addCriterion("order_receive_company_id not in", values, "orderReceiveCompanyId");
return (Criteria) this;
}
public Criteria andOrderReceiveCompanyIdBetween(String value1, String value2) {
addCriterion("order_receive_company_id between", value1, value2, "orderReceiveCompanyId");
return (Criteria) this;
}
public Criteria andOrderReceiveCompanyIdNotBetween(String value1, String value2) {
addCriterion("order_receive_company_id not between", value1, value2, "orderReceiveCompanyId");
return (Criteria) this;
}
public Criteria andOrderAssignIsNull() {
addCriterion("order_assign is null");
return (Criteria) this;
}
public Criteria andOrderAssignIsNotNull() {
addCriterion("order_assign is not null");
return (Criteria) this;
}
public Criteria andOrderAssignEqualTo(Boolean value) {
addCriterion("order_assign =", value, "orderAssign");
return (Criteria) this;
}
public Criteria andOrderAssignNotEqualTo(Boolean value) {
addCriterion("order_assign <>", value, "orderAssign");
return (Criteria) this;
}
public Criteria andOrderAssignGreaterThan(Boolean value) {
addCriterion("order_assign >", value, "orderAssign");
return (Criteria) this;
}
public Criteria andOrderAssignGreaterThanOrEqualTo(Boolean value) {
addCriterion("order_assign >=", value, "orderAssign");
return (Criteria) this;
}
public Criteria andOrderAssignLessThan(Boolean value) {
addCriterion("order_assign <", value, "orderAssign");
return (Criteria) this;
}
public Criteria andOrderAssignLessThanOrEqualTo(Boolean value) {
addCriterion("order_assign <=", value, "orderAssign");
return (Criteria) this;
}
public Criteria andOrderAssignIn(List<Boolean> values) {
addCriterion("order_assign in", values, "orderAssign");
return (Criteria) this;
}
public Criteria andOrderAssignNotIn(List<Boolean> values) {
addCriterion("order_assign not in", values, "orderAssign");
return (Criteria) this;
}
public Criteria andOrderAssignBetween(Boolean value1, Boolean value2) {
addCriterion("order_assign between", value1, value2, "orderAssign");
return (Criteria) this;
}
public Criteria andOrderAssignNotBetween(Boolean value1, Boolean value2) {
addCriterion("order_assign not between", value1, value2, "orderAssign");
return (Criteria) this;
}
public Criteria andOrderStatusIsNull() {
addCriterion("order_status is null");
return (Criteria) this;
}
public Criteria andOrderStatusIsNotNull() {
addCriterion("order_status is not null");
return (Criteria) this;
}
public Criteria andOrderStatusEqualTo(Integer value) {
addCriterion("order_status =", value, "orderStatus");
return (Criteria) this;
}
public Criteria andOrderStatusNotEqualTo(Integer value) {
addCriterion("order_status <>", value, "orderStatus");
return (Criteria) this;
}
public Criteria andOrderStatusGreaterThan(Integer value) {
addCriterion("order_status >", value, "orderStatus");
return (Criteria) this;
}
public Criteria andOrderStatusGreaterThanOrEqualTo(Integer value) {
addCriterion("order_status >=", value, "orderStatus");
return (Criteria) this;
}
public Criteria andOrderStatusLessThan(Integer value) {
addCriterion("order_status <", value, "orderStatus");
return (Criteria) this;
}
public Criteria andOrderStatusLessThanOrEqualTo(Integer value) {
addCriterion("order_status <=", value, "orderStatus");
return (Criteria) this;
}
public Criteria andOrderStatusIn(List<Integer> values) {
addCriterion("order_status in", values, "orderStatus");
return (Criteria) this;
}
public Criteria andOrderStatusNotIn(List<Integer> values) {
addCriterion("order_status not in", values, "orderStatus");
return (Criteria) this;
}
public Criteria andOrderStatusBetween(Integer value1, Integer value2) {
addCriterion("order_status between", value1, value2, "orderStatus");
return (Criteria) this;
}
public Criteria andOrderStatusNotBetween(Integer value1, Integer value2) {
addCriterion("order_status not between", value1, value2, "orderStatus");
return (Criteria) this;
}
public Criteria andOrderLogisticsNoIsNull() {
addCriterion("order_logistics_no is null");
return (Criteria) this;
}
public Criteria andOrderLogisticsNoIsNotNull() {
addCriterion("order_logistics_no is not null");
return (Criteria) this;
}
public Criteria andOrderLogisticsNoEqualTo(String value) {
addCriterion("order_logistics_no =", value, "orderLogisticsNo");
return (Criteria) this;
}
public Criteria andOrderLogisticsNoNotEqualTo(String value) {
addCriterion("order_logistics_no <>", value, "orderLogisticsNo");
return (Criteria) this;
}
public Criteria andOrderLogisticsNoGreaterThan(String value) {
addCriterion("order_logistics_no >", value, "orderLogisticsNo");
return (Criteria) this;
}
public Criteria andOrderLogisticsNoGreaterThanOrEqualTo(String value) {
addCriterion("order_logistics_no >=", value, "orderLogisticsNo");
return (Criteria) this;
}
public Criteria andOrderLogisticsNoLessThan(String value) {
addCriterion("order_logistics_no <", value, "orderLogisticsNo");
return (Criteria) this;
}
public Criteria andOrderLogisticsNoLessThanOrEqualTo(String value) {
addCriterion("order_logistics_no <=", value, "orderLogisticsNo");
return (Criteria) this;
}
public Criteria andOrderLogisticsNoLike(String value) {
addCriterion("order_logistics_no like", value, "orderLogisticsNo");
return (Criteria) this;
}
public Criteria andOrderLogisticsNoNotLike(String value) {
addCriterion("order_logistics_no not like", value, "orderLogisticsNo");
return (Criteria) this;
}
public Criteria andOrderLogisticsNoIn(List<String> values) {
addCriterion("order_logistics_no in", values, "orderLogisticsNo");
return (Criteria) this;
}
public Criteria andOrderLogisticsNoNotIn(List<String> values) {
addCriterion("order_logistics_no not in", values, "orderLogisticsNo");
return (Criteria) this;
}
public Criteria andOrderLogisticsNoBetween(String value1, String value2) {
addCriterion("order_logistics_no between", value1, value2, "orderLogisticsNo");
return (Criteria) this;
}
public Criteria andOrderLogisticsNoNotBetween(String value1, String value2) {
addCriterion("order_logistics_no not between", value1, value2, "orderLogisticsNo");
return (Criteria) this;
}
public Criteria andOrderGoodsNameIsNull() {
addCriterion("order_goods_name is null");
return (Criteria) this;
}
public Criteria andOrderGoodsNameIsNotNull() {
addCriterion("order_goods_name is not null");
return (Criteria) this;
}
public Criteria andOrderGoodsNameEqualTo(String value) {
addCriterion("order_goods_name =", value, "orderGoodsName");
return (Criteria) this;
}
public Criteria andOrderGoodsNameNotEqualTo(String value) {
addCriterion("order_goods_name <>", value, "orderGoodsName");
return (Criteria) this;
}
public Criteria andOrderGoodsNameGreaterThan(String value) {
addCriterion("order_goods_name >", value, "orderGoodsName");
return (Criteria) this;
}
public Criteria andOrderGoodsNameGreaterThanOrEqualTo(String value) {
addCriterion("order_goods_name >=", value, "orderGoodsName");
return (Criteria) this;
}
public Criteria andOrderGoodsNameLessThan(String value) {
addCriterion("order_goods_name <", value, "orderGoodsName");
return (Criteria) this;
}
public Criteria andOrderGoodsNameLessThanOrEqualTo(String value) {
addCriterion("order_goods_name <=", value, "orderGoodsName");
return (Criteria) this;
}
public Criteria andOrderGoodsNameLike(String value) {
addCriterion("order_goods_name like", value, "orderGoodsName");
return (Criteria) this;
}
public Criteria andOrderGoodsNameNotLike(String value) {
addCriterion("order_goods_name not like", value, "orderGoodsName");
return (Criteria) this;
}
public Criteria andOrderGoodsNameIn(List<String> values) {
addCriterion("order_goods_name in", values, "orderGoodsName");
return (Criteria) this;
}
public Criteria andOrderGoodsNameNotIn(List<String> values) {
addCriterion("order_goods_name not in", values, "orderGoodsName");
return (Criteria) this;
}
public Criteria andOrderGoodsNameBetween(String value1, String value2) {
addCriterion("order_goods_name between", value1, value2, "orderGoodsName");
return (Criteria) this;
}
public Criteria andOrderGoodsNameNotBetween(String value1, String value2) {
addCriterion("order_goods_name not between", value1, value2, "orderGoodsName");
return (Criteria) this;
}
public Criteria andOrderGoodsWeightIsNull() {
addCriterion("order_goods_weight is null");
return (Criteria) this;
}
public Criteria andOrderGoodsWeightIsNotNull() {
addCriterion("order_goods_weight is not null");
return (Criteria) this;
}
public Criteria andOrderGoodsWeightEqualTo(BigDecimal value) {
addCriterion("order_goods_weight =", value, "orderGoodsWeight");
return (Criteria) this;
}
public Criteria andOrderGoodsWeightNotEqualTo(BigDecimal value) {
addCriterion("order_goods_weight <>", value, "orderGoodsWeight");
return (Criteria) this;
}
public Criteria andOrderGoodsWeightGreaterThan(BigDecimal value) {
addCriterion("order_goods_weight >", value, "orderGoodsWeight");
return (Criteria) this;
}
public Criteria andOrderGoodsWeightGreaterThanOrEqualTo(BigDecimal value) {
addCriterion("order_goods_weight >=", value, "orderGoodsWeight");
return (Criteria) this;
}
public Criteria andOrderGoodsWeightLessThan(BigDecimal value) {
addCriterion("order_goods_weight <", value, "orderGoodsWeight");
return (Criteria) this;
}
public Criteria andOrderGoodsWeightLessThanOrEqualTo(BigDecimal value) {
addCriterion("order_goods_weight <=", value, "orderGoodsWeight");
return (Criteria) this;
}
public Criteria andOrderGoodsWeightIn(List<BigDecimal> values) {
addCriterion("order_goods_weight in", values, "orderGoodsWeight");
return (Criteria) this;
}
public Criteria andOrderGoodsWeightNotIn(List<BigDecimal> values) {
addCriterion("order_goods_weight not in", values, "orderGoodsWeight");
return (Criteria) this;
}
public Criteria andOrderGoodsWeightBetween(BigDecimal value1, BigDecimal value2) {
addCriterion("order_goods_weight between", value1, value2, "orderGoodsWeight");
return (Criteria) this;
}
public Criteria andOrderGoodsWeightNotBetween(BigDecimal value1, BigDecimal value2) {
addCriterion("order_goods_weight not between", value1, value2, "orderGoodsWeight");
return (Criteria) this;
}
public Criteria andOrderGoodsCubeIsNull() {
addCriterion("order_goods_cube is null");
return (Criteria) this;
}
public Criteria andOrderGoodsCubeIsNotNull() {
addCriterion("order_goods_cube is not null");
return (Criteria) this;
}
public Criteria andOrderGoodsCubeEqualTo(BigDecimal value) {
addCriterion("order_goods_cube =", value, "orderGoodsCube");
return (Criteria) this;
}
public Criteria andOrderGoodsCubeNotEqualTo(BigDecimal value) {
addCriterion("order_goods_cube <>", value, "orderGoodsCube");
return (Criteria) this;
}
public Criteria andOrderGoodsCubeGreaterThan(BigDecimal value) {
addCriterion("order_goods_cube >", value, "orderGoodsCube");
return (Criteria) this;
}
public Criteria andOrderGoodsCubeGreaterThanOrEqualTo(BigDecimal value) {
addCriterion("order_goods_cube >=", value, "orderGoodsCube");
return (Criteria) this;
}
public Criteria andOrderGoodsCubeLessThan(BigDecimal value) {
addCriterion("order_goods_cube <", value, "orderGoodsCube");
return (Criteria) this;
}
public Criteria andOrderGoodsCubeLessThanOrEqualTo(BigDecimal value) {
addCriterion("order_goods_cube <=", value, "orderGoodsCube");
return (Criteria) this;
}
public Criteria andOrderGoodsCubeIn(List<BigDecimal> values) {
addCriterion("order_goods_cube in", values, "orderGoodsCube");
return (Criteria) this;
}
public Criteria andOrderGoodsCubeNotIn(List<BigDecimal> values) {
addCriterion("order_goods_cube not in", values, "orderGoodsCube");
return (Criteria) this;
}
public Criteria andOrderGoodsCubeBetween(BigDecimal value1, BigDecimal value2) {
addCriterion("order_goods_cube between", value1, value2, "orderGoodsCube");
return (Criteria) this;
}
public Criteria andOrderGoodsCubeNotBetween(BigDecimal value1, BigDecimal value2) {
addCriterion("order_goods_cube not between", value1, value2, "orderGoodsCube");
return (Criteria) this;
}
public Criteria andOrderMoneyIsNull() {
addCriterion("order_money is null");
return (Criteria) this;
}
public Criteria andOrderMoneyIsNotNull() {
addCriterion("order_money is not null");
return (Criteria) this;
}
public Criteria andOrderMoneyEqualTo(BigDecimal value) {
addCriterion("order_money =", value, "orderMoney");
return (Criteria) this;
}
public Criteria andOrderMoneyNotEqualTo(BigDecimal value) {
addCriterion("order_money <>", value, "orderMoney");
return (Criteria) this;
}
public Criteria andOrderMoneyGreaterThan(BigDecimal value) {
addCriterion("order_money >", value, "orderMoney");
return (Criteria) this;
}
public Criteria andOrderMoneyGreaterThanOrEqualTo(BigDecimal value) {
addCriterion("order_money >=", value, "orderMoney");
return (Criteria) this;
}
public Criteria andOrderMoneyLessThan(BigDecimal value) {
addCriterion("order_money <", value, "orderMoney");
return (Criteria) this;
}
public Criteria andOrderMoneyLessThanOrEqualTo(BigDecimal value) {
addCriterion("order_money <=", value, "orderMoney");
return (Criteria) this;
}
public Criteria andOrderMoneyIn(List<BigDecimal> values) {
addCriterion("order_money in", values, "orderMoney");
return (Criteria) this;
}
public Criteria andOrderMoneyNotIn(List<BigDecimal> values) {
addCriterion("order_money not in", values, "orderMoney");
return (Criteria) this;
}
public Criteria andOrderMoneyBetween(BigDecimal value1, BigDecimal value2) {
addCriterion("order_money between", value1, value2, "orderMoney");
return (Criteria) this;
}
public Criteria andOrderMoneyNotBetween(BigDecimal value1, BigDecimal value2) {
addCriterion("order_money not between", value1, value2, "orderMoney");
return (Criteria) this;
}
public Criteria andOrderIssueTimeIsNull() {
addCriterion("order_issue_time is null");
return (Criteria) this;
}
public Criteria andOrderIssueTimeIsNotNull() {
addCriterion("order_issue_time is not null");
return (Criteria) this;
}
public Criteria andOrderIssueTimeEqualTo(Date value) {
addCriterion("order_issue_time =", value, "orderIssueTime");
return (Criteria) this;
}
public Criteria andOrderIssueTimeNotEqualTo(Date value) {
addCriterion("order_issue_time <>", value, "orderIssueTime");
return (Criteria) this;
}
public Criteria andOrderIssueTimeGreaterThan(Date value) {
addCriterion("order_issue_time >", value, "orderIssueTime");
return (Criteria) this;
}
public Criteria andOrderIssueTimeGreaterThanOrEqualTo(Date value) {
addCriterion("order_issue_time >=", value, "orderIssueTime");
return (Criteria) this;
}
public Criteria andOrderIssueTimeLessThan(Date value) {
addCriterion("order_issue_time <", value, "orderIssueTime");
return (Criteria) this;
}
public Criteria andOrderIssueTimeLessThanOrEqualTo(Date value) {
addCriterion("order_issue_time <=", value, "orderIssueTime");
return (Criteria) this;
}
public Criteria andOrderIssueTimeIn(List<Date> values) {
addCriterion("order_issue_time in", values, "orderIssueTime");
return (Criteria) this;
}
public Criteria andOrderIssueTimeNotIn(List<Date> values) {
addCriterion("order_issue_time not in", values, "orderIssueTime");
return (Criteria) this;
}
public Criteria andOrderIssueTimeBetween(Date value1, Date value2) {
addCriterion("order_issue_time between", value1, value2, "orderIssueTime");
return (Criteria) this;
}
public Criteria andOrderIssueTimeNotBetween(Date value1, Date value2) {
addCriterion("order_issue_time not between", value1, value2, "orderIssueTime");
return (Criteria) this;
}
public Criteria andOrderPickupTimeIsNull() {
addCriterion("order_pickup_time is null");
return (Criteria) this;
}
public Criteria andOrderPickupTimeIsNotNull() {
addCriterion("order_pickup_time is not null");
return (Criteria) this;
}
public Criteria andOrderPickupTimeEqualTo(Date value) {
addCriterion("order_pickup_time =", value, "orderPickupTime");
return (Criteria) this;
}
public Criteria andOrderPickupTimeNotEqualTo(Date value) {
addCriterion("order_pickup_time <>", value, "orderPickupTime");
return (Criteria) this;
}
public Criteria andOrderPickupTimeGreaterThan(Date value) {
addCriterion("order_pickup_time >", value, "orderPickupTime");
return (Criteria) this;
}
public Criteria andOrderPickupTimeGreaterThanOrEqualTo(Date value) {
addCriterion("order_pickup_time >=", value, "orderPickupTime");
return (Criteria) this;
}
public Criteria andOrderPickupTimeLessThan(Date value) {
addCriterion("order_pickup_time <", value, "orderPickupTime");
return (Criteria) this;
}
public Criteria andOrderPickupTimeLessThanOrEqualTo(Date value) {
addCriterion("order_pickup_time <=", value, "orderPickupTime");
return (Criteria) this;
}
public Criteria andOrderPickupTimeIn(List<Date> values) {
addCriterion("order_pickup_time in", values, "orderPickupTime");
return (Criteria) this;
}
public Criteria andOrderPickupTimeNotIn(List<Date> values) {
addCriterion("order_pickup_time not in", values, "orderPickupTime");
return (Criteria) this;
}
public Criteria andOrderPickupTimeBetween(Date value1, Date value2) {
addCriterion("order_pickup_time between", value1, value2, "orderPickupTime");
return (Criteria) this;
}
public Criteria andOrderPickupTimeNotBetween(Date value1, Date value2) {
addCriterion("order_pickup_time not between", value1, value2, "orderPickupTime");
return (Criteria) this;
}
public Criteria andOrderFinalPickupTimeIsNull() {
addCriterion("order_final_pickup_time is null");
return (Criteria) this;
}
public Criteria andOrderFinalPickupTimeIsNotNull() {
addCriterion("order_final_pickup_time is not null");
return (Criteria) this;
}
public Criteria andOrderFinalPickupTimeEqualTo(Date value) {
addCriterion("order_final_pickup_time =", value, "orderFinalPickupTime");
return (Criteria) this;
}
public Criteria andOrderFinalPickupTimeNotEqualTo(Date value) {
addCriterion("order_final_pickup_time <>", value, "orderFinalPickupTime");
return (Criteria) this;
}
public Criteria andOrderFinalPickupTimeGreaterThan(Date value) {
addCriterion("order_final_pickup_time >", value, "orderFinalPickupTime");
return (Criteria) this;
}
public Criteria andOrderFinalPickupTimeGreaterThanOrEqualTo(Date value) {
addCriterion("order_final_pickup_time >=", value, "orderFinalPickupTime");
return (Criteria) this;
}
public Criteria andOrderFinalPickupTimeLessThan(Date value) {
addCriterion("order_final_pickup_time <", value, "orderFinalPickupTime");
return (Criteria) this;
}
public Criteria andOrderFinalPickupTimeLessThanOrEqualTo(Date value) {
addCriterion("order_final_pickup_time <=", value, "orderFinalPickupTime");
return (Criteria) this;
}
public Criteria andOrderFinalPickupTimeIn(List<Date> values) {
addCriterion("order_final_pickup_time in", values, "orderFinalPickupTime");
return (Criteria) this;
}
public Criteria andOrderFinalPickupTimeNotIn(List<Date> values) {
addCriterion("order_final_pickup_time not in", values, "orderFinalPickupTime");
return (Criteria) this;
}
public Criteria andOrderFinalPickupTimeBetween(Date value1, Date value2) {
addCriterion("order_final_pickup_time between", value1, value2, "orderFinalPickupTime");
return (Criteria) this;
}
public Criteria andOrderFinalPickupTimeNotBetween(Date value1, Date value2) {
addCriterion("order_final_pickup_time not between", value1, value2, "orderFinalPickupTime");
return (Criteria) this;
}
public Criteria andOrderReceiveTimeIsNull() {
addCriterion("order_receive_time is null");
return (Criteria) this;
}
public Criteria andOrderReceiveTimeIsNotNull() {
addCriterion("order_receive_time is not null");
return (Criteria) this;
}
public Criteria andOrderReceiveTimeEqualTo(Date value) {
addCriterion("order_receive_time =", value, "orderReceiveTime");
return (Criteria) this;
}
public Criteria andOrderReceiveTimeNotEqualTo(Date value) {
addCriterion("order_receive_time <>", value, "orderReceiveTime");
return (Criteria) this;
}
public Criteria andOrderReceiveTimeGreaterThan(Date value) {
addCriterion("order_receive_time >", value, "orderReceiveTime");
return (Criteria) this;
}
public Criteria andOrderReceiveTimeGreaterThanOrEqualTo(Date value) {
addCriterion("order_receive_time >=", value, "orderReceiveTime");
return (Criteria) this;
}
public Criteria andOrderReceiveTimeLessThan(Date value) {
addCriterion("order_receive_time <", value, "orderReceiveTime");
return (Criteria) this;
}
public Criteria andOrderReceiveTimeLessThanOrEqualTo(Date value) {
addCriterion("order_receive_time <=", value, "orderReceiveTime");
return (Criteria) this;
}
public Criteria andOrderReceiveTimeIn(List<Date> values) {
addCriterion("order_receive_time in", values, "orderReceiveTime");
return (Criteria) this;
}
public Criteria andOrderReceiveTimeNotIn(List<Date> values) {
addCriterion("order_receive_time not in", values, "orderReceiveTime");
return (Criteria) this;
}
public Criteria andOrderReceiveTimeBetween(Date value1, Date value2) {
addCriterion("order_receive_time between", value1, value2, "orderReceiveTime");
return (Criteria) this;
}
public Criteria andOrderReceiveTimeNotBetween(Date value1, Date value2) {
addCriterion("order_receive_time not between", value1, value2, "orderReceiveTime");
return (Criteria) this;
}
public Criteria andOrderPickupProvinceIsNull() {
addCriterion("order_pickup_province is null");
return (Criteria) this;
}
public Criteria andOrderPickupProvinceIsNotNull() {
addCriterion("order_pickup_province is not null");
return (Criteria) this;
}
public Criteria andOrderPickupProvinceEqualTo(String value) {
addCriterion("order_pickup_province =", value, "orderPickupProvince");
return (Criteria) this;
}
public Criteria andOrderPickupProvinceNotEqualTo(String value) {
addCriterion("order_pickup_province <>", value, "orderPickupProvince");
return (Criteria) this;
}
public Criteria andOrderPickupProvinceGreaterThan(String value) {
addCriterion("order_pickup_province >", value, "orderPickupProvince");
return (Criteria) this;
}
public Criteria andOrderPickupProvinceGreaterThanOrEqualTo(String value) {
addCriterion("order_pickup_province >=", value, "orderPickupProvince");
return (Criteria) this;
}
public Criteria andOrderPickupProvinceLessThan(String value) {
addCriterion("order_pickup_province <", value, "orderPickupProvince");
return (Criteria) this;
}
public Criteria andOrderPickupProvinceLessThanOrEqualTo(String value) {
addCriterion("order_pickup_province <=", value, "orderPickupProvince");
return (Criteria) this;
}
public Criteria andOrderPickupProvinceLike(String value) {
addCriterion("order_pickup_province like", value, "orderPickupProvince");
return (Criteria) this;
}
public Criteria andOrderPickupProvinceNotLike(String value) {
addCriterion("order_pickup_province not like", value, "orderPickupProvince");
return (Criteria) this;
}
public Criteria andOrderPickupProvinceIn(List<String> values) {
addCriterion("order_pickup_province in", values, "orderPickupProvince");
return (Criteria) this;
}
public Criteria andOrderPickupProvinceNotIn(List<String> values) {
addCriterion("order_pickup_province not in", values, "orderPickupProvince");
return (Criteria) this;
}
public Criteria andOrderPickupProvinceBetween(String value1, String value2) {
addCriterion("order_pickup_province between", value1, value2, "orderPickupProvince");
return (Criteria) this;
}
public Criteria andOrderPickupProvinceNotBetween(String value1, String value2) {
addCriterion("order_pickup_province not between", value1, value2, "orderPickupProvince");
return (Criteria) this;
}
public Criteria andOrderPickupCityIsNull() {
addCriterion("order_pickup_city is null");
return (Criteria) this;
}
public Criteria andOrderPickupCityIsNotNull() {
addCriterion("order_pickup_city is not null");
return (Criteria) this;
}
public Criteria andOrderPickupCityEqualTo(String value) {
addCriterion("order_pickup_city =", value, "orderPickupCity");
return (Criteria) this;
}
public Criteria andOrderPickupCityNotEqualTo(String value) {
addCriterion("order_pickup_city <>", value, "orderPickupCity");
return (Criteria) this;
}
public Criteria andOrderPickupCityGreaterThan(String value) {
addCriterion("order_pickup_city >", value, "orderPickupCity");
return (Criteria) this;
}
public Criteria andOrderPickupCityGreaterThanOrEqualTo(String value) {
addCriterion("order_pickup_city >=", value, "orderPickupCity");
return (Criteria) this;
}
public Criteria andOrderPickupCityLessThan(String value) {
addCriterion("order_pickup_city <", value, "orderPickupCity");
return (Criteria) this;
}
public Criteria andOrderPickupCityLessThanOrEqualTo(String value) {
addCriterion("order_pickup_city <=", value, "orderPickupCity");
return (Criteria) this;
}
public Criteria andOrderPickupCityLike(String value) {
addCriterion("order_pickup_city like", value, "orderPickupCity");
return (Criteria) this;
}
public Criteria andOrderPickupCityNotLike(String value) {
addCriterion("order_pickup_city not like", value, "orderPickupCity");
return (Criteria) this;
}
public Criteria andOrderPickupCityIn(List<String> values) {
addCriterion("order_pickup_city in", values, "orderPickupCity");
return (Criteria) this;
}
public Criteria andOrderPickupCityNotIn(List<String> values) {
addCriterion("order_pickup_city not in", values, "orderPickupCity");
return (Criteria) this;
}
public Criteria andOrderPickupCityBetween(String value1, String value2) {
addCriterion("order_pickup_city between", value1, value2, "orderPickupCity");
return (Criteria) this;
}
public Criteria andOrderPickupCityNotBetween(String value1, String value2) {
addCriterion("order_pickup_city not between", value1, value2, "orderPickupCity");
return (Criteria) this;
}
public Criteria andOrderPickupDistrictIsNull() {
addCriterion("order_pickup_district is null");
return (Criteria) this;
}
public Criteria andOrderPickupDistrictIsNotNull() {
addCriterion("order_pickup_district is not null");
return (Criteria) this;
}
public Criteria andOrderPickupDistrictEqualTo(String value) {
addCriterion("order_pickup_district =", value, "orderPickupDistrict");
return (Criteria) this;
}
public Criteria andOrderPickupDistrictNotEqualTo(String value) {
addCriterion("order_pickup_district <>", value, "orderPickupDistrict");
return (Criteria) this;
}
public Criteria andOrderPickupDistrictGreaterThan(String value) {
addCriterion("order_pickup_district >", value, "orderPickupDistrict");
return (Criteria) this;
}
public Criteria andOrderPickupDistrictGreaterThanOrEqualTo(String value) {
addCriterion("order_pickup_district >=", value, "orderPickupDistrict");
return (Criteria) this;
}
public Criteria andOrderPickupDistrictLessThan(String value) {
addCriterion("order_pickup_district <", value, "orderPickupDistrict");
return (Criteria) this;
}
public Criteria andOrderPickupDistrictLessThanOrEqualTo(String value) {
addCriterion("order_pickup_district <=", value, "orderPickupDistrict");
return (Criteria) this;
}
public Criteria andOrderPickupDistrictLike(String value) {
addCriterion("order_pickup_district like", value, "orderPickupDistrict");
return (Criteria) this;
}
public Criteria andOrderPickupDistrictNotLike(String value) {
addCriterion("order_pickup_district not like", value, "orderPickupDistrict");
return (Criteria) this;
}
public Criteria andOrderPickupDistrictIn(List<String> values) {
addCriterion("order_pickup_district in", values, "orderPickupDistrict");
return (Criteria) this;
}
public Criteria andOrderPickupDistrictNotIn(List<String> values) {
addCriterion("order_pickup_district not in", values, "orderPickupDistrict");
return (Criteria) this;
}
public Criteria andOrderPickupDistrictBetween(String value1, String value2) {
addCriterion("order_pickup_district between", value1, value2, "orderPickupDistrict");
return (Criteria) this;
}
public Criteria andOrderPickupDistrictNotBetween(String value1, String value2) {
addCriterion("order_pickup_district not between", value1, value2, "orderPickupDistrict");
return (Criteria) this;
}
public Criteria andOrderPickupAddressIsNull() {
addCriterion("order_pickup_address is null");
return (Criteria) this;
}
public Criteria andOrderPickupAddressIsNotNull() {
addCriterion("order_pickup_address is not null");
return (Criteria) this;
}
public Criteria andOrderPickupAddressEqualTo(String value) {
addCriterion("order_pickup_address =", value, "orderPickupAddress");
return (Criteria) this;
}
public Criteria andOrderPickupAddressNotEqualTo(String value) {
addCriterion("order_pickup_address <>", value, "orderPickupAddress");
return (Criteria) this;
}
public Criteria andOrderPickupAddressGreaterThan(String value) {
addCriterion("order_pickup_address >", value, "orderPickupAddress");
return (Criteria) this;
}
public Criteria andOrderPickupAddressGreaterThanOrEqualTo(String value) {
addCriterion("order_pickup_address >=", value, "orderPickupAddress");
return (Criteria) this;
}
public Criteria andOrderPickupAddressLessThan(String value) {
addCriterion("order_pickup_address <", value, "orderPickupAddress");
return (Criteria) this;
}
public Criteria andOrderPickupAddressLessThanOrEqualTo(String value) {
addCriterion("order_pickup_address <=", value, "orderPickupAddress");
return (Criteria) this;
}
public Criteria andOrderPickupAddressLike(String value) {
addCriterion("order_pickup_address like", value, "orderPickupAddress");
return (Criteria) this;
}
public Criteria andOrderPickupAddressNotLike(String value) {
addCriterion("order_pickup_address not like", value, "orderPickupAddress");
return (Criteria) this;
}
public Criteria andOrderPickupAddressIn(List<String> values) {
addCriterion("order_pickup_address in", values, "orderPickupAddress");
return (Criteria) this;
}
public Criteria andOrderPickupAddressNotIn(List<String> values) {
addCriterion("order_pickup_address not in", values, "orderPickupAddress");
return (Criteria) this;
}
public Criteria andOrderPickupAddressBetween(String value1, String value2) {
addCriterion("order_pickup_address between", value1, value2, "orderPickupAddress");
return (Criteria) this;
}
public Criteria andOrderPickupAddressNotBetween(String value1, String value2) {
addCriterion("order_pickup_address not between", value1, value2, "orderPickupAddress");
return (Criteria) this;
}
public Criteria andOrderReceiveProvinceIsNull() {
addCriterion("order_receive_province is null");
return (Criteria) this;
}
public Criteria andOrderReceiveProvinceIsNotNull() {
addCriterion("order_receive_province is not null");
return (Criteria) this;
}
public Criteria andOrderReceiveProvinceEqualTo(String value) {
addCriterion("order_receive_province =", value, "orderReceiveProvince");
return (Criteria) this;
}
public Criteria andOrderReceiveProvinceNotEqualTo(String value) {
addCriterion("order_receive_province <>", value, "orderReceiveProvince");
return (Criteria) this;
}
public Criteria andOrderReceiveProvinceGreaterThan(String value) {
addCriterion("order_receive_province >", value, "orderReceiveProvince");
return (Criteria) this;
}
public Criteria andOrderReceiveProvinceGreaterThanOrEqualTo(String value) {
addCriterion("order_receive_province >=", value, "orderReceiveProvince");
return (Criteria) this;
}
public Criteria andOrderReceiveProvinceLessThan(String value) {
addCriterion("order_receive_province <", value, "orderReceiveProvince");
return (Criteria) this;
}
public Criteria andOrderReceiveProvinceLessThanOrEqualTo(String value) {
addCriterion("order_receive_province <=", value, "orderReceiveProvince");
return (Criteria) this;
}
public Criteria andOrderReceiveProvinceLike(String value) {
addCriterion("order_receive_province like", value, "orderReceiveProvince");
return (Criteria) this;
}
public Criteria andOrderReceiveProvinceNotLike(String value) {
addCriterion("order_receive_province not like", value, "orderReceiveProvince");
return (Criteria) this;
}
public Criteria andOrderReceiveProvinceIn(List<String> values) {
addCriterion("order_receive_province in", values, "orderReceiveProvince");
return (Criteria) this;
}
public Criteria andOrderReceiveProvinceNotIn(List<String> values) {
addCriterion("order_receive_province not in", values, "orderReceiveProvince");
return (Criteria) this;
}
public Criteria andOrderReceiveProvinceBetween(String value1, String value2) {
addCriterion("order_receive_province between", value1, value2, "orderReceiveProvince");
return (Criteria) this;
}
public Criteria andOrderReceiveProvinceNotBetween(String value1, String value2) {
addCriterion("order_receive_province not between", value1, value2, "orderReceiveProvince");
return (Criteria) this;
}
public Criteria andOrderReceiveCityIsNull() {
addCriterion("order_receive_city is null");
return (Criteria) this;
}
public Criteria andOrderReceiveCityIsNotNull() {
addCriterion("order_receive_city is not null");
return (Criteria) this;
}
public Criteria andOrderReceiveCityEqualTo(String value) {
addCriterion("order_receive_city =", value, "orderReceiveCity");
return (Criteria) this;
}
public Criteria andOrderReceiveCityNotEqualTo(String value) {
addCriterion("order_receive_city <>", value, "orderReceiveCity");
return (Criteria) this;
}
public Criteria andOrderReceiveCityGreaterThan(String value) {
addCriterion("order_receive_city >", value, "orderReceiveCity");
return (Criteria) this;
}
public Criteria andOrderReceiveCityGreaterThanOrEqualTo(String value) {
addCriterion("order_receive_city >=", value, "orderReceiveCity");
return (Criteria) this;
}
public Criteria andOrderReceiveCityLessThan(String value) {
addCriterion("order_receive_city <", value, "orderReceiveCity");
return (Criteria) this;
}
public Criteria andOrderReceiveCityLessThanOrEqualTo(String value) {
addCriterion("order_receive_city <=", value, "orderReceiveCity");
return (Criteria) this;
}
public Criteria andOrderReceiveCityLike(String value) {
addCriterion("order_receive_city like", value, "orderReceiveCity");
return (Criteria) this;
}
public Criteria andOrderReceiveCityNotLike(String value) {
addCriterion("order_receive_city not like", value, "orderReceiveCity");
return (Criteria) this;
}
public Criteria andOrderReceiveCityIn(List<String> values) {
addCriterion("order_receive_city in", values, "orderReceiveCity");
return (Criteria) this;
}
public Criteria andOrderReceiveCityNotIn(List<String> values) {
addCriterion("order_receive_city not in", values, "orderReceiveCity");
return (Criteria) this;
}
public Criteria andOrderReceiveCityBetween(String value1, String value2) {
addCriterion("order_receive_city between", value1, value2, "orderReceiveCity");
return (Criteria) this;
}
public Criteria andOrderReceiveCityNotBetween(String value1, String value2) {
addCriterion("order_receive_city not between", value1, value2, "orderReceiveCity");
return (Criteria) this;
}
public Criteria andOrderReceiveDistrictIsNull() {
addCriterion("order_receive_district is null");
return (Criteria) this;
}
public Criteria andOrderReceiveDistrictIsNotNull() {
addCriterion("order_receive_district is not null");
return (Criteria) this;
}
public Criteria andOrderReceiveDistrictEqualTo(String value) {
addCriterion("order_receive_district =", value, "orderReceiveDistrict");
return (Criteria) this;
}
public Criteria andOrderReceiveDistrictNotEqualTo(String value) {
addCriterion("order_receive_district <>", value, "orderReceiveDistrict");
return (Criteria) this;
}
public Criteria andOrderReceiveDistrictGreaterThan(String value) {
addCriterion("order_receive_district >", value, "orderReceiveDistrict");
return (Criteria) this;
}
public Criteria andOrderReceiveDistrictGreaterThanOrEqualTo(String value) {
addCriterion("order_receive_district >=", value, "orderReceiveDistrict");
return (Criteria) this;
}
public Criteria andOrderReceiveDistrictLessThan(String value) {
addCriterion("order_receive_district <", value, "orderReceiveDistrict");
return (Criteria) this;
}
public Criteria andOrderReceiveDistrictLessThanOrEqualTo(String value) {
addCriterion("order_receive_district <=", value, "orderReceiveDistrict");
return (Criteria) this;
}
public Criteria andOrderReceiveDistrictLike(String value) {
addCriterion("order_receive_district like", value, "orderReceiveDistrict");
return (Criteria) this;
}
public Criteria andOrderReceiveDistrictNotLike(String value) {
addCriterion("order_receive_district not like", value, "orderReceiveDistrict");
return (Criteria) this;
}
public Criteria andOrderReceiveDistrictIn(List<String> values) {
addCriterion("order_receive_district in", values, "orderReceiveDistrict");
return (Criteria) this;
}
public Criteria andOrderReceiveDistrictNotIn(List<String> values) {
addCriterion("order_receive_district not in", values, "orderReceiveDistrict");
return (Criteria) this;
}
public Criteria andOrderReceiveDistrictBetween(String value1, String value2) {
addCriterion("order_receive_district between", value1, value2, "orderReceiveDistrict");
return (Criteria) this;
}
public Criteria andOrderReceiveDistrictNotBetween(String value1, String value2) {
addCriterion("order_receive_district not between", value1, value2, "orderReceiveDistrict");
return (Criteria) this;
}
public Criteria andOrderReceiveAddressIsNull() {
addCriterion("order_receive_address is null");
return (Criteria) this;
}
public Criteria andOrderReceiveAddressIsNotNull() {
addCriterion("order_receive_address is not null");
return (Criteria) this;
}
public Criteria andOrderReceiveAddressEqualTo(String value) {
addCriterion("order_receive_address =", value, "orderReceiveAddress");
return (Criteria) this;
}
public Criteria andOrderReceiveAddressNotEqualTo(String value) {
addCriterion("order_receive_address <>", value, "orderReceiveAddress");
return (Criteria) this;
}
public Criteria andOrderReceiveAddressGreaterThan(String value) {
addCriterion("order_receive_address >", value, "orderReceiveAddress");
return (Criteria) this;
}
public Criteria andOrderReceiveAddressGreaterThanOrEqualTo(String value) {
addCriterion("order_receive_address >=", value, "orderReceiveAddress");
return (Criteria) this;
}
public Criteria andOrderReceiveAddressLessThan(String value) {
addCriterion("order_receive_address <", value, "orderReceiveAddress");
return (Criteria) this;
}
public Criteria andOrderReceiveAddressLessThanOrEqualTo(String value) {
addCriterion("order_receive_address <=", value, "orderReceiveAddress");
return (Criteria) this;
}
public Criteria andOrderReceiveAddressLike(String value) {
addCriterion("order_receive_address like", value, "orderReceiveAddress");
return (Criteria) this;
}
public Criteria andOrderReceiveAddressNotLike(String value) {
addCriterion("order_receive_address not like", value, "orderReceiveAddress");
return (Criteria) this;
}
public Criteria andOrderReceiveAddressIn(List<String> values) {
addCriterion("order_receive_address in", values, "orderReceiveAddress");
return (Criteria) this;
}
public Criteria andOrderReceiveAddressNotIn(List<String> values) {
addCriterion("order_receive_address not in", values, "orderReceiveAddress");
return (Criteria) this;
}
public Criteria andOrderReceiveAddressBetween(String value1, String value2) {
addCriterion("order_receive_address between", value1, value2, "orderReceiveAddress");
return (Criteria) this;
}
public Criteria andOrderReceiveAddressNotBetween(String value1, String value2) {
addCriterion("order_receive_address not between", value1, value2, "orderReceiveAddress");
return (Criteria) this;
}
public Criteria andOrderRemarkIsNull() {
addCriterion("order_remark is null");
return (Criteria) this;
}
public Criteria andOrderRemarkIsNotNull() {
addCriterion("order_remark is not null");
return (Criteria) this;
}
public Criteria andOrderRemarkEqualTo(String value) {
addCriterion("order_remark =", value, "orderRemark");
return (Criteria) this;
}
public Criteria andOrderRemarkNotEqualTo(String value) {
addCriterion("order_remark <>", value, "orderRemark");
return (Criteria) this;
}
public Criteria andOrderRemarkGreaterThan(String value) {
addCriterion("order_remark >", value, "orderRemark");
return (Criteria) this;
}
public Criteria andOrderRemarkGreaterThanOrEqualTo(String value) {
addCriterion("order_remark >=", value, "orderRemark");
return (Criteria) this;
}
public Criteria andOrderRemarkLessThan(String value) {
addCriterion("order_remark <", value, "orderRemark");
return (Criteria) this;
}
public Criteria andOrderRemarkLessThanOrEqualTo(String value) {
addCriterion("order_remark <=", value, "orderRemark");
return (Criteria) this;
}
public Criteria andOrderRemarkLike(String value) {
addCriterion("order_remark like", value, "orderRemark");
return (Criteria) this;
}
public Criteria andOrderRemarkNotLike(String value) {
addCriterion("order_remark not like", value, "orderRemark");
return (Criteria) this;
}
public Criteria andOrderRemarkIn(List<String> values) {
addCriterion("order_remark in", values, "orderRemark");
return (Criteria) this;
}
public Criteria andOrderRemarkNotIn(List<String> values) {
addCriterion("order_remark not in", values, "orderRemark");
return (Criteria) this;
}
public Criteria andOrderRemarkBetween(String value1, String value2) {
addCriterion("order_remark between", value1, value2, "orderRemark");
return (Criteria) this;
}
public Criteria andOrderRemarkNotBetween(String value1, String value2) {
addCriterion("order_remark not between", value1, value2, "orderRemark");
return (Criteria) this;
}
public Criteria andOrderCreateUserIdIsNull() {
addCriterion("order_create_user_id is null");
return (Criteria) this;
}
public Criteria andOrderCreateUserIdIsNotNull() {
addCriterion("order_create_user_id is not null");
return (Criteria) this;
}
public Criteria andOrderCreateUserIdEqualTo(String value) {
addCriterion("order_create_user_id =", value, "orderCreateUserId");
return (Criteria) this;
}
public Criteria andOrderCreateUserIdNotEqualTo(String value) {
addCriterion("order_create_user_id <>", value, "orderCreateUserId");
return (Criteria) this;
}
public Criteria andOrderCreateUserIdGreaterThan(String value) {
addCriterion("order_create_user_id >", value, "orderCreateUserId");
return (Criteria) this;
}
public Criteria andOrderCreateUserIdGreaterThanOrEqualTo(String value) {
addCriterion("order_create_user_id >=", value, "orderCreateUserId");
return (Criteria) this;
}
public Criteria andOrderCreateUserIdLessThan(String value) {
addCriterion("order_create_user_id <", value, "orderCreateUserId");
return (Criteria) this;
}
public Criteria andOrderCreateUserIdLessThanOrEqualTo(String value) {
addCriterion("order_create_user_id <=", value, "orderCreateUserId");
return (Criteria) this;
}
public Criteria andOrderCreateUserIdLike(String value) {
addCriterion("order_create_user_id like", value, "orderCreateUserId");
return (Criteria) this;
}
public Criteria andOrderCreateUserIdNotLike(String value) {
addCriterion("order_create_user_id not like", value, "orderCreateUserId");
return (Criteria) this;
}
public Criteria andOrderCreateUserIdIn(List<String> values) {
addCriterion("order_create_user_id in", values, "orderCreateUserId");
return (Criteria) this;
}
public Criteria andOrderCreateUserIdNotIn(List<String> values) {
addCriterion("order_create_user_id not in", values, "orderCreateUserId");
return (Criteria) this;
}
public Criteria andOrderCreateUserIdBetween(String value1, String value2) {
addCriterion("order_create_user_id between", value1, value2, "orderCreateUserId");
return (Criteria) this;
}
public Criteria andOrderCreateUserIdNotBetween(String value1, String value2) {
addCriterion("order_create_user_id not between", value1, value2, "orderCreateUserId");
return (Criteria) this;
}
public Criteria andOrderReceiveUserIdIsNull() {
addCriterion("order_receive_user_id is null");
return (Criteria) this;
}
public Criteria andOrderReceiveUserIdIsNotNull() {
addCriterion("order_receive_user_id is not null");
return (Criteria) this;
}
public Criteria andOrderReceiveUserIdEqualTo(String value) {
addCriterion("order_receive_user_id =", value, "orderReceiveUserId");
return (Criteria) this;
}
public Criteria andOrderReceiveUserIdNotEqualTo(String value) {
addCriterion("order_receive_user_id <>", value, "orderReceiveUserId");
return (Criteria) this;
}
public Criteria andOrderReceiveUserIdGreaterThan(String value) {
addCriterion("order_receive_user_id >", value, "orderReceiveUserId");
return (Criteria) this;
}
public Criteria andOrderReceiveUserIdGreaterThanOrEqualTo(String value) {
addCriterion("order_receive_user_id >=", value, "orderReceiveUserId");
return (Criteria) this;
}
public Criteria andOrderReceiveUserIdLessThan(String value) {
addCriterion("order_receive_user_id <", value, "orderReceiveUserId");
return (Criteria) this;
}
public Criteria andOrderReceiveUserIdLessThanOrEqualTo(String value) {
addCriterion("order_receive_user_id <=", value, "orderReceiveUserId");
return (Criteria) this;
}
public Criteria andOrderReceiveUserIdLike(String value) {
addCriterion("order_receive_user_id like", value, "orderReceiveUserId");
return (Criteria) this;
}
public Criteria andOrderReceiveUserIdNotLike(String value) {
addCriterion("order_receive_user_id not like", value, "orderReceiveUserId");
return (Criteria) this;
}
public Criteria andOrderReceiveUserIdIn(List<String> values) {
addCriterion("order_receive_user_id in", values, "orderReceiveUserId");
return (Criteria) this;
}
public Criteria andOrderReceiveUserIdNotIn(List<String> values) {
addCriterion("order_receive_user_id not in", values, "orderReceiveUserId");
return (Criteria) this;
}
public Criteria andOrderReceiveUserIdBetween(String value1, String value2) {
addCriterion("order_receive_user_id between", value1, value2, "orderReceiveUserId");
return (Criteria) this;
}
public Criteria andOrderReceiveUserIdNotBetween(String value1, String value2) {
addCriterion("order_receive_user_id not between", value1, value2, "orderReceiveUserId");
return (Criteria) this;
}
public Criteria andOrderIsDeleteIsNull() {
addCriterion("order_is_delete is null");
return (Criteria) this;
}
public Criteria andOrderIsDeleteIsNotNull() {
addCriterion("order_is_delete is not null");
return (Criteria) this;
}
public Criteria andOrderIsDeleteEqualTo(Boolean value) {
addCriterion("order_is_delete =", value, "orderIsDelete");
return (Criteria) this;
}
public Criteria andOrderIsDeleteNotEqualTo(Boolean value) {
addCriterion("order_is_delete <>", value, "orderIsDelete");
return (Criteria) this;
}
public Criteria andOrderIsDeleteGreaterThan(Boolean value) {
addCriterion("order_is_delete >", value, "orderIsDelete");
return (Criteria) this;
}
public Criteria andOrderIsDeleteGreaterThanOrEqualTo(Boolean value) {
addCriterion("order_is_delete >=", value, "orderIsDelete");
return (Criteria) this;
}
public Criteria andOrderIsDeleteLessThan(Boolean value) {
addCriterion("order_is_delete <", value, "orderIsDelete");
return (Criteria) this;
}
public Criteria andOrderIsDeleteLessThanOrEqualTo(Boolean value) {
addCriterion("order_is_delete <=", value, "orderIsDelete");
return (Criteria) this;
}
public Criteria andOrderIsDeleteIn(List<Boolean> values) {
addCriterion("order_is_delete in", values, "orderIsDelete");
return (Criteria) this;
}
public Criteria andOrderIsDeleteNotIn(List<Boolean> values) {
addCriterion("order_is_delete not in", values, "orderIsDelete");
return (Criteria) this;
}
public Criteria andOrderIsDeleteBetween(Boolean value1, Boolean value2) {
addCriterion("order_is_delete between", value1, value2, "orderIsDelete");
return (Criteria) this;
}
public Criteria andOrderIsDeleteNotBetween(Boolean value1, Boolean value2) {
addCriterion("order_is_delete not between", value1, value2, "orderIsDelete");
return (Criteria) this;
}
public Criteria andOrderCreateTimeIsNull() {
addCriterion("order_create_time is null");
return (Criteria) this;
}
public Criteria andOrderCreateTimeIsNotNull() {
addCriterion("order_create_time is not null");
return (Criteria) this;
}
public Criteria andOrderCreateTimeEqualTo(Date value) {
addCriterion("order_create_time =", value, "orderCreateTime");
return (Criteria) this;
}
public Criteria andOrderCreateTimeNotEqualTo(Date value) {
addCriterion("order_create_time <>", value, "orderCreateTime");
return (Criteria) this;
}
public Criteria andOrderCreateTimeGreaterThan(Date value) {
addCriterion("order_create_time >", value, "orderCreateTime");
return (Criteria) this;
}
public Criteria andOrderCreateTimeGreaterThanOrEqualTo(Date value) {
addCriterion("order_create_time >=", value, "orderCreateTime");
return (Criteria) this;
}
public Criteria andOrderCreateTimeLessThan(Date value) {
addCriterion("order_create_time <", value, "orderCreateTime");
return (Criteria) this;
}
public Criteria andOrderCreateTimeLessThanOrEqualTo(Date value) {
addCriterion("order_create_time <=", value, "orderCreateTime");
return (Criteria) this;
}
public Criteria andOrderCreateTimeIn(List<Date> values) {
addCriterion("order_create_time in", values, "orderCreateTime");
return (Criteria) this;
}
public Criteria andOrderCreateTimeNotIn(List<Date> values) {
addCriterion("order_create_time not in", values, "orderCreateTime");
return (Criteria) this;
}
public Criteria andOrderCreateTimeBetween(Date value1, Date value2) {
addCriterion("order_create_time between", value1, value2, "orderCreateTime");
return (Criteria) this;
}
public Criteria andOrderCreateTimeNotBetween(Date value1, Date value2) {
addCriterion("order_create_time not between", value1, value2, "orderCreateTime");
return (Criteria) this;
}
}
/**
* This class was generated by MyBatis Generator, do not modify.
* goods_order
* @mbg.generated do_not_delete_during_merge
*/
public static class Criteria extends GeneratedCriteria {
protected Criteria() {
super();
}
}
/**
* goods_order
* @mbg.generated
*/
public static class Criterion {
private String condition;
private Object value;
private Object secondValue;
private boolean noValue;
private boolean singleValue;
private boolean betweenValue;
private boolean listValue;
private String typeHandler;
public String getCondition() {
return condition;
}
public Object getValue() {
return value;
}
public Object getSecondValue() {
return secondValue;
}
public boolean isNoValue() {
return noValue;
}
public boolean isSingleValue() {
return singleValue;
}
public boolean isBetweenValue() {
return betweenValue;
}
public boolean isListValue() {
return listValue;
}
public String getTypeHandler() {
return typeHandler;
}
protected Criterion(String condition) {
super();
this.condition = condition;
this.typeHandler = null;
this.noValue = true;
}
protected Criterion(String condition, Object value, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.typeHandler = typeHandler;
if (value instanceof List<?>) {
this.listValue = true;
} else {
this.singleValue = true;
}
}
protected Criterion(String condition, Object value) {
this(condition, value, null);
}
protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.secondValue = secondValue;
this.typeHandler = typeHandler;
this.betweenValue = true;
}
protected Criterion(String condition, Object value, Object secondValue) {
this(condition, value, secondValue, null);
}
}
}<file_sep>/dlebvue/Dockerfile
FROM nginx:stable-alpine
COPY nginx/nginx.conf /etc/nginx/nginx.conf
COPY nginx/nginx.vh.default.conf /etc/nginx/conf.d/default.conf
ADD dist/ /usr/share/nginx/html/
# 替换aliyun镜像,设置时区
RUN echo "https://mirrors.aliyun.com/alpine/latest-stable/main" > /etc/apk/repositories \
&& echo "https://mirrors.aliyun.com/alpine/latest-stable/community" >> /etc/apk/repositories \
&& apk update \
&& apk add --no-cache tzdata \
&& cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime \
&& echo "Asia/Shanghai" > /etc/timezone \
&& apk del tzdata
<file_sep>/README.md
# 德邻E宝
查看java日志
tail -f /app/config/logs/ebpayrun.log
后端JAVA发布.
生产服务器
172.20.120.36
172.20.120.37
```
jar包目录
/app/config/jars
启动命令
sh /app/config/jars/startup.sh
关闭命令
sh /app/config/jars/shutdown.sh
重启命令
sh /app/config/jars/restart.sh
日志位置
tail -f /app/logs/dleb/app.log -n 99
tail -f /app/logs/dleb/error.log -n 99
conf文件夹-平安银行见证宝配置文件
ebpay.jar-德邻e宝springboot包
```
前端代码发布
```
前台发布代码目录
/app/config/vuestatic
打包命令
npm run build
把生成之后的dist目录中的文件拷贝到/app/config/vuestatic
```
<file_sep>/src/main/java/com/test/manage/model/dto/ResourceDto.java
package com.test.manage.model.dto;
import com.test.manage.model.generator.Resource;
public class ResourceDto extends Resource {
private Integer childNum;
public Integer getChildNum() {
return childNum;
}
public void setChildNum(Integer childNum) {
this.childNum = childNum;
}
}
<file_sep>/src/main/java/com/test/manage/service/notice/NoticeService.java
package com.test.manage.service.notice;
import com.test.manage.model.dto.NoticeDto;
import com.test.manage.model.generator.Notice;
import com.test.manage.model.request.QueryParams;
import java.util.List;
public interface NoticeService {
void insertNotice(Notice notice);
void deleteNotice(String id);
List<NoticeDto> getNoticeListAll(QueryParams queryParams);
List<Notice> getNoticeList();
Notice getNoticeById(String id);
}
<file_sep>/src/main/java/com/test/framework/utils/SecurityUtils.java
package com.test.framework.utils;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class SecurityUtils {
static final String KEY_SHA = "SHA";
/**
* 密码加密 SHA加密嵌套MD5加密
*
* @param password
* @return
*/
public static String encrypt(String password) {
String result = "";
byte[] data = password.getBytes();
try {
// 先SHA加密获取实例
MessageDigest sha = MessageDigest.getInstance(KEY_SHA);
// sha 加密
sha.update(data);
// 获得加密以后的字符串
result = new BigInteger(sha.digest()).toString(32);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return result;
}
/**利用MD5进行加密
* @param str 待加密的字符串
* @return 加密后的字符串
* @throws NoSuchAlgorithmException 没有这种产生消息摘要的算法
* @throws UnsupportedEncodingException
*/
public static String md5Encode(String inStr) {
MessageDigest md5 = null;
try {
md5 = MessageDigest.getInstance("MD5");
} catch (Exception e) {
System.out.println(e.toString());
e.printStackTrace();
return "";
}
byte[] byteArray = null;
try {
byteArray = inStr.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
byte[] md5Bytes = md5.digest(byteArray);
StringBuffer hexValue = new StringBuffer();
for (int i = 0; i < md5Bytes.length; i++) {
int val = ((int) md5Bytes[i]) & 0xff;
if (val < 16) {
hexValue.append("0");
}
hexValue.append(Integer.toHexString(val));
}
return hexValue.toString();
}
public static void main(String[] args) throws NoSuchAlgorithmException {
String or = "123";
String re = encrypt(or);
System.out.println(or);
System.out.println("----SHA加密----");
System.out.println(re.toString());
}
}
<file_sep>/dlebvue/server.js
var express = require('express');
var path = require('path');
var history = require('connect-history-api-fallback');
var serveStatic = require('serve-static');
var bodyParser = require('body-parser');
var proxy = require('http-proxy-middleware');
app = express();
app.use(history());
console.log(__dirname)
app.use(serveStatic(__dirname + "/dist"));
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
app.post('/posttest', function (req, res) {
console.log(req.body);
res.redirect('/dashboard/main');
// res.render(__dirname + "/dist/index");
});
var apipath = "http://dlebapi.qiatuchina.com/";
var apiProxy = proxy('/api', {
pathRewrite: {"^/api": ""},
target: apipath,
logLevel: 'debug',
changeOrigin: true // for vhosted sites
});
app.use(apiProxy);
var port = process.env.PORT || 5000;
app.listen(port);
console.log('server started '+ port);
<file_sep>/dlebvue/src/mock/data/orderList.js
import Mock from 'mockjs'
import mock from '../mock'
const OrderList = []
for (let i = 0; i < 100; i++) {
OrderList.push({
id: Mock.Random.guid(),
orderNo: Mock.Random.natural(),
indeed: Mock.Random.boolean(),
to: Mock.Random.city(),
time: Mock.Random.date(),
consigneeContact: Mock.Random.city(),
consigneeName: Mock.Random.city(),
Mobile: Mock.Random.city(),
isPick: Mock.Random.boolean(),
pickTime: Mock.Random.date(),
pickAdd: Mock.Random.city(),
isDelivery: Mock.Random.boolean(),
deliveryAdd: Mock.Random.city(),
cargoName: Mock.Random.city(),
orderQty: Mock.Random.natural(),
orderDimensions: Mock.Random.natural(),
orderWeight: Mock.Random.natural(),
orderVolume: Mock.Random.natural(),
quote: Mock.Random.city(),
transhipQty: Mock.Random.natural(),
transhipWeight: Mock.Random.natural(),
transhipVolume: Mock.Random.natural(),
transhipPrice: Mock.Random.natural(),
receiptReq: Mock.Random.city()
})
}
export { OrderList }
| 5a62218bccb4114e01e6cffdb66526c75cd231a1 | [
"JavaScript",
"Java",
"Dockerfile",
"Markdown"
] | 51 | Java | huxiaodi/Anything | d0fa76288efa2edc94b1aae80e66dcf4e4863c3a | c1f7d9833e382c621da8ebe2e917b8c2b322c976 |
refs/heads/master | <file_sep>import React, { Component } from 'react';
import PageHeader from '../template/pageHeader'
export default props => (
<div>
<PageHeader name='About' small='Me' />
<center>
<img src="https://s-media-cache-ak0.pinimg.com/originals/19/2c/d9/192cd928c4a604cca04b1913550557dd.jpg" />
</center>
</div>
) | cbcf7861b75d03c33891fde4e101cda972c044fe | [
"JavaScript"
] | 1 | JavaScript | FelipeKS97/todo-app-react | 1ddf305083bd8a9be1bcc8b65b790363f7b0c45f | 59719b2cec8f8f09a1d93945140f641eb9f849bf |
refs/heads/master | <repo_name>dalmaboros/regex-lab-v-000<file_sep>/lib/regex_lab.rb
def starts_with_a_vowel?(word)
return true if word.match(/^[aeiouAEIOU]/)
else return false
end
def words_starting_with_un_and_ending_with_ing(text)
text.scan(/\bun\w*ing\b/)
end
def words_five_letters_long(text)
text.scan(/\b\w{5}\b/)
end
def first_word_capitalized_and_ends_with_punctuation?(text)
return true if text.match(/^[A-Z].*\W$/)
else return false
end
def valid_phone_number?(phone)
return true if phone.match(/\d{3}.*\d{3}.*\d{4}/)
end
| a951ae08206ee46557629d1ec4f4e08ff1730405 | [
"Ruby"
] | 1 | Ruby | dalmaboros/regex-lab-v-000 | 32005f0addb103f8417e889090164d1f9c574396 | aba1324b2182772ea0e7888824e1b9f1da7244f1 |
refs/heads/master | <repo_name>hunterirving/DoubleNaught<file_sep>/build/resources/rocky-app.js
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(1);
/***/ }),
/* 1 */
/***/ (function(module, exports, __webpack_require__) {
var rocky = __webpack_require__(2);
//initialize watchface
var d = new Date();
var timeString = d.toLocaleTimeString()
var hmsArray = timeString.split(":")
var timeInSeconds = (parseInt(hmsArray[0]*3600) + parseInt(hmsArray[1]*60) + parseInt(hmsArray[2]*1))
var currentTimeInCentiDays = parseInt(timeInSeconds / 864)
rocky.requestDraw();
rocky.on('draw', function(event) {
var ctx = event.context;
ctx.clearRect(0, 0, ctx.canvas.clientWidth, ctx.canvas.clientHeight);
var offsetY = (ctx.canvas.clientHeight - ctx.canvas.unobstructedHeight) / 2;
var centerX = ctx.canvas.unobstructedWidth / 2;
ctx.fillStyle = 'white';
ctx.textAlign = 'center';
ctx.font = '26px bold Leco-numbers-am-pm';
ctx.fillText(currentTimeInCentiDays, centerX, (66 - offsetY));
});
rocky.on('secondchange', function(event) {
var d = new Date();
var timeString = d.toLocaleTimeString();
var hmsArray = timeString.split(":");
var timeInSeconds = (parseInt(hmsArray[0]*3600) + parseInt(hmsArray[1]*60) + parseInt(hmsArray[2]));
//console.log("currentTimeInCentiDays: " + currentTimeInCentiDays);
if(timeInSeconds % 864 == 0)
{
currentTimeInCentiDays = timeInSeconds / 864
console.log("one centiDay has elapsed: " + currentTimeInCentiDays)
rocky.requestDraw();
}
});
/***/ }),
/* 2 */
/***/ (function(module, exports) {
module.exports = _rocky;
/***/ })
/******/ ]);<file_sep>/src/rocky/index.js
var rocky = require('rocky');
//initialize watchface
var d = new Date();
var timeString = d.toLocaleTimeString()
var hmsArray = timeString.split(":")
var timeInSeconds = (parseInt(hmsArray[0]*3600) + parseInt(hmsArray[1]*60) + parseInt(hmsArray[2]*1))
var currentTimeInCentiDays = parseInt(timeInSeconds / 864)
rocky.requestDraw();
rocky.on('draw', function(event) {
var ctx = event.context;
ctx.clearRect(0, 0, ctx.canvas.clientWidth, ctx.canvas.clientHeight);
var offsetY = (ctx.canvas.clientHeight - ctx.canvas.unobstructedHeight) / 2;
var centerX = ctx.canvas.unobstructedWidth / 2;
ctx.fillStyle = 'white';
ctx.textAlign = 'center';
ctx.font = '26px bold Leco-numbers-am-pm';
ctx.fillText(currentTimeInCentiDays, centerX, (66 - offsetY));
});
rocky.on('secondchange', function(event) {
var d = new Date();
var timeString = d.toLocaleTimeString();
var hmsArray = timeString.split(":");
var timeInSeconds = (parseInt(hmsArray[0]*3600) + parseInt(hmsArray[1]*60) + parseInt(hmsArray[2]));
//console.log("currentTimeInCentiDays: " + currentTimeInCentiDays);
if(timeInSeconds % 864 == 0)
{
currentTimeInCentiDays = timeInSeconds / 864
console.log("one centiDay has elapsed: " + currentTimeInCentiDays)
rocky.requestDraw();
}
});
<file_sep>/README.md
# Double Naught
<h3> "Pebble is dead... <i>Long live Pebble!" </h3> </i>
With the <a href="https://www.wired.com/2016/12/the-inside-story-behind-pebbles-demise/">Great FitBit Buyout of 2016</a> finally laying Pebble to rest, and most developer resources pointing to <a href="http://developer.pebble.com/tutorials/">dead links</a>, there's simply no worse time to get into Pebble development.
...but let's make something anyway.
<h3>Right Into the Future</h3>
It's easy to let your day slip away from you.
Double Naught aims to remind you of the constant passage of time by breaking your day into one hundred 864 second (14.4 minute)-long chunks, and notifies you with a vibrational pulse to the wrist each time 1% of your day has elapsed.
<img src="64centiday.PNG"></img>
<h3>Time Well Spent..?</h3>
A minute is fleeting.
An hour can really drag on.
But one cD (centi-Day) has a real weight to it without overstaying its welcome.
<img width="40%" src="wear.jpg"></img>
Double Naught doesn't have an "activity monitor" to track whether or not you spent your day "well", but each time your wrist pulses, take a brief moment to reflect on how you spent the previous 1% of your day, and how you plan to spend the next one.
.
.
.
"""How we spend our days is, ultimately, how we spend our lives." - <NAME>" - Light Phone 2 Commercial" - <NAME>
| af7f5db4245a98a690a2b3fe9e85e2176fbb2721 | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | hunterirving/DoubleNaught | fe2dbd06501012e409b66bf3f6ea06c65fba0b11 | b3b11a04e9f255a666a8a5eb0b13afda2befecb7 |
refs/heads/master | <repo_name>pticlavilca/CUnity<file_sep>/Assets/Scripts/CUnity.cs
using UnityEngine;
using System.Collections;
public class CUnity : MonoBehaviour {
private string username="";
private string password="";
void OnGUI(){
username = GUI.TextField (new Rect (0, 0, 200, 35),username );
password = GUI.TextField (new Rect (0, 40, 200, 35),password);
if (GUI.Button (new Rect (0, 80, 100, 35), "send")) {
handlerSend(username,password);
}
}
string url = "http://localhost:8080/CJava/CJava?";
HTTP.Request httpRequest;
void handlerSend (string _username, string _password)
{
httpRequest = new HTTP.Request ("get", url + "username=" + _username + "&password=" + _password);
httpRequest.Send ();
while (!httpRequest.isDone) {
Debug.Log("working ...");
}
string path = httpRequest.response.Text;
string[] user = path.Split(':');
Debug.Log ("username :" + user [0]);
Debug.Log ("password :" + user [1]);
}
}
| 31d29684929f1f78c3ec6fcd41089c1befef9e9d | [
"C#"
] | 1 | C# | pticlavilca/CUnity | d86b1231547ed7231591829715485a2fa118d8ca | f5ba4488aa0fdd21bd1b7f584c47c0c0ba8a7978 |
refs/heads/master | <file_sep>
local function eventHandler(self,event,...)
Minimap:SetBlipTexture("Interface\\AddOns\\TechBlip\\ObjectIcons");
end
local frame=CreateFrame("Frame","techMinimapBlipsFrame");
frame:RegisterEvent("PLAYER_ENTERING_WORLD");
frame:SetScript("OnEvent",eventHandler);
| 42b956f80cbf311d1c5dc8a29abd84bc524ff821 | [
"Lua"
] | 1 | Lua | daftmisc/TechBlip | 3191f05479b8d770a285649d2f5132f074029018 | 8759998bbd2b98e476f0ad1c6ad1b3d7baa0a660 |
refs/heads/master | <repo_name>dimaShin/todo-api<file_sep>/docker-compose.yml
version: '2'
# Start messaging broker
services:
postgres:
image: postgres
container_name: TodoAPI_POSTRGESQL
environment:
- POSTGRES_USER=postgres
- POSTGRES_PASSWORD=<PASSWORD>
- PGDATA=/var/lib/volumes/pgdata
volumes:
- ./volumes:/var/lib/volumes
ports:
- "5433:5432"<file_sep>/config.js
module.exports = (ENV) => {
const configs = {
NIXDEV: {
port: '/home/head/sockets/kandy.sock',
psqlPort: 32782
},
'NIXDEV-DEV': {
port: '/home/head/sockets/kandy-dev.sock',
psqlPort: 32782
},
development: {
port: 3000,
db: {
"username": "postgres",
"password": "<PASSWORD>",
"database": "postgres",
"host": "127.0.0.1",
"port": 5433,
"dialect": "postgres",
"pool": {
"max": 10,
"min": 0,
"idle": 10000
},
}
}
};
return configs[ENV];
};<file_sep>/app.js
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const config = require('./config')(process.env.NODE_ENV);
const Db = require('./db');
const db = new Db(config);
const app = express();
const HARDCODED_TOKEN = '<PASSWORD>';
app.use(cors({allowedHeaders: ['x-token, content-type']}));
app.use(bodyParser.json());
app.post('/login', (req, res) => {
try {
const { login, password } = req.body;
if (login === 'admin' && password === '<PASSWORD>') {
res.send({token: HARDCODED_TOKEN});
} else {
res.status(401).send('Invalid login or password');
}
} catch (err) {
res.status(400).send(err);
}
});
app.use('/api/*', (req, res, next) => {
const token = req.header('x-token');
if (!token || token !== HARDCODED_TOKEN) {
return res.sendStatus(401);
} else {
next();
}
});
app.get('/api/todo', async (req, res) => {
try {
res.send( await db.Todo.findAll({ where: { deleted: false }, order: [ ['done'], ['createdAt', 'DESC'] ]}) );
} catch (err) {
res.status(400).send(err);
}
});
app.get('/api/me', async (req, res) => {
res.send( { loggedIn: true } );
});
app.post('/api/todo', async (req, res) => {
try {
res.send( await db.Todo.create(req.body) )
} catch (err) {
res.status(400).send(err);
}
});
app.patch('/api/todo/:id/toggle', async (req, res) => {
try {
const todo = await db.Todo.findById(req.params.id);
todo.set('done', !todo.get('done'));
res.send( await todo.save() );
} catch (err) {
res.status(400).send(err);
}
});
app.delete('/api/todo/:id', async (req, res) => {
try {
const todo = await db.Todo.findById(req.params.id);
todo.set('deleted', true);
res.send( await todo.save() )
} catch (err) {
res.status(400).send(err);
}
});
module.exports = app;
<file_sep>/db.js
const Sequelize = require('sequelize');
const model = (sequelize, DataTypes) => {
return sequelize.define("Users", {
title: {
type : DataTypes.STRING,
allowNull: false
},
description: {
type : DataTypes.STRING,
allowNull: true
},
done: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false
},
deleted: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false
}
}, {
classMethods: {}
});
};
module.exports = class Db {
constructor(config) {
this.initConnection(config.db)
.then(() => console.log('sequelize sync finished OK'))
.catch(err => console.error(err));
}
async initConnection({database, username, password, port, host, pool}) {
let seq = null;
if (process.env.DATABASE_URL) {
seq = new Sequelize(process.env.DATABASE_URL, { pool , dialect: 'postgres' });
} else {
seq = new Sequelize(database, username, password, {
host,
dialect: 'postgres',
port,
pool
});
}
try {
await seq.authenticate();
console.log('db connection established successfully');
this.Todo = model(seq, Sequelize);
return seq.sync({ force: false });
} catch (err) {
return Promise.reject(err);
}
}
};
| bbd033072ec5d11dd1e3245e0e08bd43f67a44ee | [
"JavaScript",
"YAML"
] | 4 | YAML | dimaShin/todo-api | faec87deb1c4e5bb8e3ebf3c7e03c3d881f0e2f6 | 8315cd43f6caa61ad067ac416225db7504ef4db7 |
refs/heads/master | <file_sep>"""
qSearch
QGIS plugin
<NAME>
<EMAIL>
Feb. 2012
"""
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from qgis.core import *
from types import *
from ui_chooselayer import Ui_chooseLayer
try:
_fromUtf8 = QString.fromUtf8
except AttributeError:
_fromUtf8 = lambda s: s
class chooseLayer(QDialog, Ui_chooseLayer ):
def __init__(self,iface):
self.iface = iface
QDialog.__init__(self)
self.setupUi(self)
self.groups = []
def showEvent(self, e):
self.groupCombo.clear()
self.layerCombo.clear()
if len(self.iface.legendInterface().layers())==0: return
setGroup = 0
setLayer = 0
curLayerId = ""
curLayer = self.iface.mapCanvas().currentLayer()
if type(curLayer) != NoneType: curLayerId = curLayer.id()
self.groups = []
self.groups.append( layerGroup("ungroupped") )
g = 0
self.groupCombo.addItem(_fromUtf8(""))
self.groupCombo.setItemText(g, "ungroupped")
for group in self.iface.legendInterface().groupLayerRelationship():
if group[0] == "":
add2group = 0
else:
g += 1
self.groups.append( layerGroup(group[0]) )
self.groupCombo.addItem(_fromUtf8(""))
self.groupCombo.setItemText(g, self.groups[g].name)
add2group = g
for layerid in group[1]:
layer = self.getLayer(layerid)
if layer is not False and layer.type() == QgsMapLayer.VectorLayer:
l = len(self.groups[g].layers)
self.groups[g].addLayer(layerid)
if layer == curLayerId:
setGroup = g
setLayer = l
self.groupCombo.setCurrentIndex(setGroup)
self.on_groupCombo_currentIndexChanged(setGroup)
self.layerCombo.setCurrentIndex(setLayer)
@pyqtSignature("on_groupCombo_currentIndexChanged(int)")
def on_groupCombo_currentIndexChanged(self,g):
self.layerCombo.clear()
for i,layer in enumerate(self.groups[g].layers):
self.layerCombo.addItem(_fromUtf8(""))
self.layerCombo.setItemText(i, self.getLayer(layer).name())
def getLayer(self,layerid):
for layer in self.iface.legendInterface().layers():
if layer.id() == layerid:
return layer
return False
def selectedLayer(self):
g = self.groupCombo.currentIndex()
l = self.layerCombo.currentIndex()
if g == -1 or l == -1: return False
return self.getLayer(self.groups[g].layers[l])
class layerGroup():
def __init__(self,name):
self.name = name
self.layers = []
def addLayer(self,layerid):
self.layers.append(layerid)
<file_sep># -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'ui_searchitem.ui'
#
# Created: Mon Feb 13 11:57:29 2012
# by: PyQt4 UI code generator 4.8.5
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
_fromUtf8 = lambda s: s
class Ui_searchItem(object):
def setupUi(self, searchItem):
searchItem.setObjectName(_fromUtf8("searchItem"))
searchItem.resize(432, 33)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(searchItem.sizePolicy().hasHeightForWidth())
searchItem.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setPointSize(9)
searchItem.setFont(font)
searchItem.setWindowTitle(QtGui.QApplication.translate("searchItem", "Frame", None, QtGui.QApplication.UnicodeUTF8))
searchItem.setFrameShape(QtGui.QFrame.StyledPanel)
searchItem.setFrameShadow(QtGui.QFrame.Raised)
self.gridLayout = QtGui.QGridLayout(searchItem)
self.gridLayout.setMargin(3)
self.gridLayout.setSpacing(3)
self.gridLayout.setObjectName(_fromUtf8("gridLayout"))
self.operatorCombo = QtGui.QComboBox(searchItem)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.operatorCombo.sizePolicy().hasHeightForWidth())
self.operatorCombo.setSizePolicy(sizePolicy)
self.operatorCombo.setMaximumSize(QtCore.QSize(16777215, 16777215))
self.operatorCombo.setObjectName(_fromUtf8("operatorCombo"))
self.operatorCombo.addItem(_fromUtf8(""))
self.operatorCombo.setItemText(0, QtGui.QApplication.translate("searchItem", "equals", None, QtGui.QApplication.UnicodeUTF8))
self.operatorCombo.addItem(_fromUtf8(""))
self.operatorCombo.setItemText(1, QtGui.QApplication.translate("searchItem", "is not equal to", None, QtGui.QApplication.UnicodeUTF8))
self.operatorCombo.addItem(_fromUtf8(""))
self.operatorCombo.setItemText(2, QtGui.QApplication.translate("searchItem", "is greater than", None, QtGui.QApplication.UnicodeUTF8))
self.operatorCombo.addItem(_fromUtf8(""))
self.operatorCombo.setItemText(3, QtGui.QApplication.translate("searchItem", "is strictly greater than", None, QtGui.QApplication.UnicodeUTF8))
self.operatorCombo.addItem(_fromUtf8(""))
self.operatorCombo.setItemText(4, QtGui.QApplication.translate("searchItem", "is lower than", None, QtGui.QApplication.UnicodeUTF8))
self.operatorCombo.addItem(_fromUtf8(""))
self.operatorCombo.setItemText(5, QtGui.QApplication.translate("searchItem", "is strictly lower than", None, QtGui.QApplication.UnicodeUTF8))
self.operatorCombo.addItem(_fromUtf8(""))
self.operatorCombo.setItemText(6, QtGui.QApplication.translate("searchItem", "contains the text", None, QtGui.QApplication.UnicodeUTF8))
self.operatorCombo.addItem(_fromUtf8(""))
self.operatorCombo.setItemText(7, QtGui.QApplication.translate("searchItem", "does not contain the text", None, QtGui.QApplication.UnicodeUTF8))
self.operatorCombo.addItem(_fromUtf8(""))
self.operatorCombo.setItemText(8, QtGui.QApplication.translate("searchItem", "the text is", None, QtGui.QApplication.UnicodeUTF8))
self.operatorCombo.addItem(_fromUtf8(""))
self.operatorCombo.setItemText(9, QtGui.QApplication.translate("searchItem", "the text is not", None, QtGui.QApplication.UnicodeUTF8))
self.gridLayout.addWidget(self.operatorCombo, 1, 3, 1, 1)
self.valueCombo = QtGui.QComboBox(searchItem)
self.valueCombo.setEditable(True)
self.valueCombo.setObjectName(_fromUtf8("valueCombo"))
self.gridLayout.addWidget(self.valueCombo, 1, 4, 1, 1)
self.fieldCombo = QtGui.QComboBox(searchItem)
self.fieldCombo.setObjectName(_fromUtf8("fieldCombo"))
self.gridLayout.addWidget(self.fieldCombo, 1, 2, 1, 1)
self.deleteButton = QtGui.QToolButton(searchItem)
self.deleteButton.setText(QtGui.QApplication.translate("searchItem", "x", None, QtGui.QApplication.UnicodeUTF8))
self.deleteButton.setObjectName(_fromUtf8("deleteButton"))
self.gridLayout.addWidget(self.deleteButton, 1, 0, 1, 1)
self.andCombo = QtGui.QComboBox(searchItem)
self.andCombo.setEnabled(False)
self.andCombo.setMaximumSize(QtCore.QSize(60, 16777215))
self.andCombo.setObjectName(_fromUtf8("andCombo"))
self.andCombo.addItem(_fromUtf8(""))
self.andCombo.setItemText(0, QtGui.QApplication.translate("searchItem", "and", None, QtGui.QApplication.UnicodeUTF8))
self.andCombo.addItem(_fromUtf8(""))
self.andCombo.setItemText(1, QtGui.QApplication.translate("searchItem", "or", None, QtGui.QApplication.UnicodeUTF8))
self.gridLayout.addWidget(self.andCombo, 1, 1, 1, 1)
self.retranslateUi(searchItem)
QtCore.QMetaObject.connectSlotsByName(searchItem)
def retranslateUi(self, searchItem):
pass
<file_sep># -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'ui_chooselayer.ui'
#
# Created: Wed Feb 8 11:40:47 2012
# by: PyQt4 UI code generator 4.8.5
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
_fromUtf8 = lambda s: s
class Ui_chooseLayer(object):
def setupUi(self, chooseLayer):
chooseLayer.setObjectName(_fromUtf8("chooseLayer"))
chooseLayer.resize(313, 111)
chooseLayer.setWindowTitle(QtGui.QApplication.translate("chooseLayer", "qSearch", None, QtGui.QApplication.UnicodeUTF8))
self.gridLayout = QtGui.QGridLayout(chooseLayer)
self.gridLayout.setObjectName(_fromUtf8("gridLayout"))
self.label = QtGui.QLabel(chooseLayer)
self.label.setMaximumSize(QtCore.QSize(50, 16777215))
self.label.setText(QtGui.QApplication.translate("chooseLayer", "Layer", None, QtGui.QApplication.UnicodeUTF8))
self.label.setObjectName(_fromUtf8("label"))
self.gridLayout.addWidget(self.label, 1, 0, 1, 1)
self.layerCombo = QtGui.QComboBox(chooseLayer)
self.layerCombo.setObjectName(_fromUtf8("layerCombo"))
self.gridLayout.addWidget(self.layerCombo, 1, 1, 1, 1)
self.buttonBox = QtGui.QDialogButtonBox(chooseLayer)
self.buttonBox.setOrientation(QtCore.Qt.Horizontal)
self.buttonBox.setStandardButtons(QtGui.QDialogButtonBox.Cancel|QtGui.QDialogButtonBox.Ok)
self.buttonBox.setObjectName(_fromUtf8("buttonBox"))
self.gridLayout.addWidget(self.buttonBox, 2, 0, 1, 2)
self.label_2 = QtGui.QLabel(chooseLayer)
self.label_2.setText(QtGui.QApplication.translate("chooseLayer", "Group", None, QtGui.QApplication.UnicodeUTF8))
self.label_2.setObjectName(_fromUtf8("label_2"))
self.gridLayout.addWidget(self.label_2, 0, 0, 1, 1)
self.groupCombo = QtGui.QComboBox(chooseLayer)
self.groupCombo.setObjectName(_fromUtf8("groupCombo"))
self.gridLayout.addWidget(self.groupCombo, 0, 1, 1, 1)
self.retranslateUi(chooseLayer)
QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL(_fromUtf8("accepted()")), chooseLayer.accept)
QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL(_fromUtf8("rejected()")), chooseLayer.reject)
QtCore.QMetaObject.connectSlotsByName(chooseLayer)
def retranslateUi(self, chooseLayer):
pass
<file_sep>"""
qSearch
QGIS plugin
<NAME>
<EMAIL>
Feb. 2012
"""
import PyQt4
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from qgis.core import *
from ui_editsearch import Ui_editSearch
from ui_searchitem import Ui_searchItem
try:
_fromUtf8 = QString.fromUtf8
except AttributeError:
_fromUtf8 = lambda s: s
# create the dialog to connect layers
class editSearch(QDialog, Ui_editSearch ):
def __init__(self,iface):
self.iface = iface
QDialog.__init__(self)
self.setupUi(self)
self.layer = []
self.settings = QSettings("qSearch","qSearch")
QObject.connect(self.saveButton , SIGNAL( "clicked()" ) , self.saveSearches)
def initUi(self,layer):
self.selectButton.setEnabled(False)
self.progressBar.setVisible(False)
for i in range(self.itemsLayout.count()): self.itemsLayout.itemAt(i).widget().close()
self.layer = layer
self.layerName.setText(layer.name())
self.selection = []
self.items = []
self.searchIndex = len(self.readSearches())
self.aliasBox.setChecked(self.settings.value("onlyAlias",0).toInt()[0])
self.layerLabel.setText("%u feature(s) currently selected in" % layer.selectedFeatureCount())
def fields(self,aliasMode=-1):
# create list of displayed fields
# aliasMode: -1: auto, 0: all, 1: only alias
if aliasMode == 0: aliasMode = False
elif aliasMode == 1: aliasMode = True
else: aliasMode = self.aliasBox.isChecked()
fields = []
for i in self.layer.dataProvider().fields():
alias = self.layer.attributeAlias(i)
if alias == "":
if aliasMode is True: continue
alias = self.layer.dataProvider().fields().get(i).name()
fields.append({'index':i,'alias':alias})
return fields
@pyqtSignature("on_aliasBox_clicked()")
def on_aliasBox_clicked(self):
# new alias mode
aliasMode = self.aliasBox.isChecked()
# previous alias mode: 0: going from all to only aliases, 1 going from only aliases to all
previousAliasMode = int( not aliasMode )
# Look for no selection combos and remove them
item2delete = []
for itemIndex,item in enumerate(self.items):
if item.fieldCombo.currentIndex() == -1:
item.close()
item2delete.append(itemIndex)
self.deleteItem(item2delete)
# Look for fields with no aliases when going from all to only aliases
if aliasMode is True:
item2remove = []
for itemIndex,item in enumerate(self.items):
currentField = self.fields(previousAliasMode)[item.fieldCombo.currentIndex()].get('index')
ok = False
for i,field in enumerate(self.fields()):
if field.get('index') == currentField:
ok = True
break
if ok is False:
item2remove.append(itemIndex)
if len(item2remove)>0:
reply = QMessageBox.question( self , "qSearch" , "Some of the search fields have no aliases, they will be removed. Are you sure to continue?" , QMessageBox.Yes | QMessageBox.No ,QMessageBox.No )
if reply != QMessageBox.Yes:
self.aliasBox.setChecked(False)
return
# remove items with no corresponding aliases
for itemIndex in item2remove: self.items[itemIndex].close()
self.deleteItem(item2remove)
# Apply change
for itemIndex,item in enumerate(self.items):
currentField = self.fields(previousAliasMode)[item.fieldCombo.currentIndex()].get('index')
item.fieldCombo.clear()
for i,field in enumerate(self.fields()):
item.fieldCombo.addItem(field.get('alias'))
if field.get('index') == currentField:
item.fieldCombo.setCurrentIndex(i)
@pyqtSignature("on_addButton_clicked()")
def on_addButton_clicked(self):
itemIndex = len(self.items)
self.items.append( searchItem(self.layer,self.fields,itemIndex) )
QObject.connect(self.items[itemIndex],SIGNAL("itemDeleted(int)"),self.deleteItem)
self.itemsLayout.addWidget(self.items[itemIndex])
def deleteItem(self,item2remove):
if type(item2remove) == int: item2remove = [item2remove]
for offset,itemIndex in enumerate(item2remove):
self.items.pop(itemIndex-offset)
if len(self.items)>0:
self.items[0].andCombo.setEnabled(False)
for itemIndex,item in enumerate(self.items):
item.itemIndex = itemIndex
def loadSearch(self,i):
self.items = []
searches = self.readSearches()
self.searchIndex = i
search = searches[i]
self.searchName.setText(search.get('name'))
self.aliasBox.setChecked(search.get('alias'))
for itemIndex,item in enumerate(search.get('items')):
idx = -1
for i,field in enumerate(self.fields()):
if field.get('index') == item.get('index'):
idx = i
break
if idx==-1: # i.e. the field apparently does not exist anymore
continue
self.items.append( searchItem(self.layer,self.fields,itemIndex) )
QObject.connect(self.items[itemIndex],SIGNAL("itemDeleted(int)"),self.deleteItem)
self.itemsLayout.addWidget(self.items[itemIndex])
self.items[itemIndex].andCombo.setCurrentIndex(item.get('andor'))
self.items[itemIndex].fieldCombo.setCurrentIndex(i)
self.items[itemIndex].operatorCombo.setCurrentIndex(item.get('operator'))
self.items[itemIndex].valueCombo.setEditText(item.get('value'))
def readSearches(self):
loadSearches = self.layer.customProperty("qSearch").toString()
if loadSearches == '':
currentSearches = []
else:
exec("currentSearches = %s" % loadSearches)
return currentSearches
def saveSearches(self):
saveSearch = []
for item in self.items:
saveSearch.append( {'andor': item.andCombo.currentIndex(),
'index': self.fields()[item.fieldCombo.currentIndex()].get('index') ,
'operator': item.operatorCombo.currentIndex(),
'value': item.valueCombo.currentText() } )
currentSearches = self.readSearches()
if self.searchIndex > len(currentSearches)-1: currentSearches.append([])
currentSearches[self.searchIndex] = {'name': self.searchName.text(), 'alias': int(self.aliasBox.isChecked()) ,'items': saveSearch}
self.layer.setCustomProperty("qSearch",repr(currentSearches))
self.emit(SIGNAL("searchSaved ()"))
#print currentSearches
@pyqtSignature("on_searchButton_clicked()")
def on_searchButton_clicked(self):
# index of fields used for search
fields2select = []
for item in self.items:
fields2select.append( self.fields()[item.fieldCombo.currentIndex()].get('index'))
andor = ['and','or']
operators = ['==','!=','>=','>','<=','<','True','False','==','!=']
# create search test
searchCmd = ""
for i,item in enumerate(self.items):
if i>0: searchCmd += " %s " % andor[item.andCombo.currentIndex()]
iOper = item.operatorCombo.currentIndex()
operator = operators[iOper]
if iOper < 6: # => numeric
searchCmd += " fieldmap[%u].toDouble()[0] %s %s " % ( fields2select[i] , operator , item.valueCombo.currentText().toUtf8() )
elif iOper < 8:
searchCmd += " fieldmap[%u].toString().toUtf8().contains(\"%s\") is %s" % ( fields2select[i] , item.valueCombo.currentText().replace('"', '\\"').toUtf8(), operator )
elif iOper < 10:
searchCmd += " fieldmap[%u].toString().toUtf8() %s \"%s\" " % ( fields2select[i] , operator , item.valueCombo.currentText().replace('"', '\\"').toUtf8() )
print searchCmd
# select fields, init search
provider = self.layer.dataProvider()
provider.select(fields2select)
self.selection = []
f = QgsFeature()
# Init progress bar
self.selectButton.setText("Select")
self.selectButton.setEnabled(False)
self.progressBar.setVisible(True)
self.progressBar.setMinimum(0)
self.progressBar.setMaximum(provider.featureCount())
self.progressBar.setValue(0)
k = 0
# browse features
try:
while (provider.nextFeature(f)):
k+=1
self.progressBar.setValue(k)
fieldmap=f.attributeMap()
if eval(searchCmd):
self.selection.append(f.id())
self.selectButton.setText("Select %u features" % len(self.selection))
if len(self.selection)>0:
self.selectButton.setEnabled(True)
except NameError:
QMessageBox.warning( self.iface.mainWindow() , "qSearch","If you are trying to detect text, you should use text equals." )
except SyntaxError:
QMessageBox.warning( self.iface.mainWindow() , "qSearch","If you are trying to detect text, you should use text equals." )
self.progressBar.setVisible(False)
@pyqtSignature("on_selectButton_clicked()")
def on_selectButton_clicked(self):
selection = []
if self.addCurrentBox.isChecked():
selection = self.layer.selectedFeaturesIds()
selection.extend( self.selection )
self.layer.setSelectedFeatures(selection)
self.layerLabel.setText("%u feature(s) currently selected in" % self.layer.selectedFeatureCount())
class searchItem(QFrame, Ui_searchItem):
def __init__(self,layer,fields,itemIndex):
QFrame.__init__(self)
self.setupUi(self)
self.layer = layer
self.fields = fields
self.itemIndex = itemIndex
self.settings = QSettings("qSearch","qSearch")
if itemIndex > 0: self.andCombo.setEnabled(True)
for f in fields(): self.fieldCombo.addItem(f.get('alias'))
@pyqtSignature("on_fieldCombo_currentIndexChanged(int)")
def on_fieldCombo_currentIndexChanged(self,i):
if i < 0: return
self.valueCombo.clear()
ix = self.fields()[i].get('index')
maxUnique = self.settings.value("maxUnique",30).toInt()[0]
for value in self.layer.dataProvider().uniqueValues(ix,maxUnique):
self.valueCombo.addItem(value.toString())
@pyqtSignature("on_deleteButton_clicked()")
def on_deleteButton_clicked(self):
self.close()
self.emit(SIGNAL("itemDeleted(int)"),self.itemIndex)
<file_sep># -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'ui_editsearch.ui'
#
# Created: Thu Apr 12 09:36:53 2012
# by: PyQt4 UI code generator 4.8.5
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
_fromUtf8 = lambda s: s
class Ui_editSearch(object):
def setupUi(self, editSearch):
editSearch.setObjectName(_fromUtf8("editSearch"))
editSearch.resize(576, 357)
editSearch.setWindowTitle(QtGui.QApplication.translate("editSearch", "qSearch", None, QtGui.QApplication.UnicodeUTF8))
self.gridLayout_2 = QtGui.QGridLayout(editSearch)
self.gridLayout_2.setMargin(6)
self.gridLayout_2.setSpacing(6)
self.gridLayout_2.setObjectName(_fromUtf8("gridLayout_2"))
self.progressBar = QtGui.QProgressBar(editSearch)
self.progressBar.setProperty("value", 0)
self.progressBar.setObjectName(_fromUtf8("progressBar"))
self.gridLayout_2.addWidget(self.progressBar, 5, 0, 1, 6)
self.closeButton = QtGui.QPushButton(editSearch)
self.closeButton.setText(QtGui.QApplication.translate("editSearch", "close", None, QtGui.QApplication.UnicodeUTF8))
self.closeButton.setObjectName(_fromUtf8("closeButton"))
self.gridLayout_2.addWidget(self.closeButton, 6, 5, 1, 1)
self.layerName = QtGui.QLineEdit(editSearch)
self.layerName.setEnabled(False)
self.layerName.setObjectName(_fromUtf8("layerName"))
self.gridLayout_2.addWidget(self.layerName, 0, 3, 1, 3)
self.itemsScroll = QtGui.QScrollArea(editSearch)
self.itemsScroll.setWidgetResizable(True)
self.itemsScroll.setAlignment(QtCore.Qt.AlignHCenter|QtCore.Qt.AlignTop)
self.itemsScroll.setObjectName(_fromUtf8("itemsScroll"))
self.scrollAreaWidgetContents_2 = QtGui.QWidget()
self.scrollAreaWidgetContents_2.setGeometry(QtCore.QRect(0, 0, 562, 147))
self.scrollAreaWidgetContents_2.setObjectName(_fromUtf8("scrollAreaWidgetContents_2"))
self.gridLayout_3 = QtGui.QGridLayout(self.scrollAreaWidgetContents_2)
self.gridLayout_3.setMargin(3)
self.gridLayout_3.setSpacing(3)
self.gridLayout_3.setObjectName(_fromUtf8("gridLayout_3"))
self.itemsLayout = QtGui.QVBoxLayout()
self.itemsLayout.setSpacing(3)
self.itemsLayout.setObjectName(_fromUtf8("itemsLayout"))
self.gridLayout_3.addLayout(self.itemsLayout, 0, 0, 1, 1)
self.itemsScroll.setWidget(self.scrollAreaWidgetContents_2)
self.gridLayout_2.addWidget(self.itemsScroll, 3, 0, 1, 6)
self.layerLabel = QtGui.QLabel(editSearch)
self.layerLabel.setText(QtGui.QApplication.translate("editSearch", "0 feature(s) currently selected in", None, QtGui.QApplication.UnicodeUTF8))
self.layerLabel.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
self.layerLabel.setObjectName(_fromUtf8("layerLabel"))
self.gridLayout_2.addWidget(self.layerLabel, 0, 0, 1, 3)
self.selectButton = QtGui.QPushButton(editSearch)
self.selectButton.setEnabled(False)
self.selectButton.setText(QtGui.QApplication.translate("editSearch", "Select", None, QtGui.QApplication.UnicodeUTF8))
self.selectButton.setObjectName(_fromUtf8("selectButton"))
self.gridLayout_2.addWidget(self.selectButton, 4, 4, 1, 2)
self.addCurrentBox = QtGui.QCheckBox(editSearch)
self.addCurrentBox.setLayoutDirection(QtCore.Qt.LeftToRight)
self.addCurrentBox.setText(QtGui.QApplication.translate("editSearch", "add to current selection", None, QtGui.QApplication.UnicodeUTF8))
self.addCurrentBox.setIconSize(QtCore.QSize(16, 16))
self.addCurrentBox.setObjectName(_fromUtf8("addCurrentBox"))
self.gridLayout_2.addWidget(self.addCurrentBox, 4, 3, 1, 1)
self.saveButton = QtGui.QPushButton(editSearch)
self.saveButton.setText(QtGui.QApplication.translate("editSearch", "save search", None, QtGui.QApplication.UnicodeUTF8))
self.saveButton.setObjectName(_fromUtf8("saveButton"))
self.gridLayout_2.addWidget(self.saveButton, 1, 5, 1, 1)
self.aliasBox = QtGui.QCheckBox(editSearch)
self.aliasBox.setText(QtGui.QApplication.translate("editSearch", "Display only fields with aliases", None, QtGui.QApplication.UnicodeUTF8))
self.aliasBox.setObjectName(_fromUtf8("aliasBox"))
self.gridLayout_2.addWidget(self.aliasBox, 2, 3, 1, 3)
self.addButton = QtGui.QPushButton(editSearch)
self.addButton.setText(QtGui.QApplication.translate("editSearch", "Add item", None, QtGui.QApplication.UnicodeUTF8))
self.addButton.setObjectName(_fromUtf8("addButton"))
self.gridLayout_2.addWidget(self.addButton, 2, 0, 1, 1)
self.searchName = QtGui.QLineEdit(editSearch)
self.searchName.setText(QtGui.QApplication.translate("editSearch", "new search", None, QtGui.QApplication.UnicodeUTF8))
self.searchName.setObjectName(_fromUtf8("searchName"))
self.gridLayout_2.addWidget(self.searchName, 1, 3, 1, 2)
self.label = QtGui.QLabel(editSearch)
self.label.setText(QtGui.QApplication.translate("editSearch", "Search name", None, QtGui.QApplication.UnicodeUTF8))
self.label.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
self.label.setObjectName(_fromUtf8("label"))
self.gridLayout_2.addWidget(self.label, 1, 1, 1, 2)
self.searchButton = QtGui.QPushButton(editSearch)
self.searchButton.setText(QtGui.QApplication.translate("editSearch", "Search", None, QtGui.QApplication.UnicodeUTF8))
self.searchButton.setObjectName(_fromUtf8("searchButton"))
self.gridLayout_2.addWidget(self.searchButton, 4, 0, 1, 1)
self.retranslateUi(editSearch)
QtCore.QObject.connect(self.closeButton, QtCore.SIGNAL(_fromUtf8("clicked()")), editSearch.accept)
QtCore.QMetaObject.connectSlotsByName(editSearch)
editSearch.setTabOrder(self.searchButton, self.layerName)
editSearch.setTabOrder(self.layerName, self.itemsScroll)
editSearch.setTabOrder(self.itemsScroll, self.selectButton)
editSearch.setTabOrder(self.selectButton, self.addCurrentBox)
editSearch.setTabOrder(self.addCurrentBox, self.saveButton)
editSearch.setTabOrder(self.saveButton, self.aliasBox)
editSearch.setTabOrder(self.aliasBox, self.addButton)
editSearch.setTabOrder(self.addButton, self.searchName)
editSearch.setTabOrder(self.searchName, self.closeButton)
def retranslateUi(self, editSearch):
pass
<file_sep># -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'ui_settings.ui'
#
# Created: Mon Feb 13 16:52:51 2012
# by: PyQt4 UI code generator 4.8.5
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
_fromUtf8 = lambda s: s
class Ui_settings(object):
def setupUi(self, settings):
settings.setObjectName(_fromUtf8("settings"))
settings.resize(323, 127)
settings.setWindowTitle(QtGui.QApplication.translate("settings", "qSearch :: settings", None, QtGui.QApplication.UnicodeUTF8))
self.gridLayout = QtGui.QGridLayout(settings)
self.gridLayout.setObjectName(_fromUtf8("gridLayout"))
self.aliasBox = QtGui.QCheckBox(settings)
self.aliasBox.setAcceptDrops(False)
self.aliasBox.setText(QtGui.QApplication.translate("settings", "By default, display only fields with aliases", None, QtGui.QApplication.UnicodeUTF8))
self.aliasBox.setObjectName(_fromUtf8("aliasBox"))
self.gridLayout.addWidget(self.aliasBox, 0, 0, 1, 2)
self.label = QtGui.QLabel(settings)
self.label.setText(QtGui.QApplication.translate("settings", "Maximum unique values population", None, QtGui.QApplication.UnicodeUTF8))
self.label.setWordWrap(True)
self.label.setObjectName(_fromUtf8("label"))
self.gridLayout.addWidget(self.label, 1, 0, 1, 1)
self.buttonBox = QtGui.QDialogButtonBox(settings)
self.buttonBox.setOrientation(QtCore.Qt.Horizontal)
self.buttonBox.setStandardButtons(QtGui.QDialogButtonBox.Cancel|QtGui.QDialogButtonBox.Ok)
self.buttonBox.setObjectName(_fromUtf8("buttonBox"))
self.gridLayout.addWidget(self.buttonBox, 4, 0, 1, 1)
self.maxUnique = QtGui.QLineEdit(settings)
self.maxUnique.setMaximumSize(QtCore.QSize(50, 16777215))
self.maxUnique.setLayoutDirection(QtCore.Qt.LeftToRight)
self.maxUnique.setText(QtGui.QApplication.translate("settings", "100", None, QtGui.QApplication.UnicodeUTF8))
self.maxUnique.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
self.maxUnique.setObjectName(_fromUtf8("maxUnique"))
self.gridLayout.addWidget(self.maxUnique, 1, 1, 1, 1)
self.retranslateUi(settings)
QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL(_fromUtf8("accepted()")), settings.accept)
QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL(_fromUtf8("rejected()")), settings.reject)
QtCore.QMetaObject.connectSlotsByName(settings)
def retranslateUi(self, settings):
pass
<file_sep>"""
qSearch
QGIS plugin
<NAME>
<EMAIL>
Feb. 2012
"""
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from qgis.core import *
from ui_settings import Ui_settings
try:
_fromUtf8 = QString.fromUtf8
except AttributeError:
_fromUtf8 = lambda s: s
# create the dialog to connect layers
class settings(QDialog, Ui_settings ):
def __init__(self,iface):
self.iface = iface
QDialog.__init__(self)
# Set up the user interface from Designer.
self.setupUi(self)
QObject.connect(self , SIGNAL( "accepted()" ) , self.applySettings)
# load settings
self.settings = QSettings("qSearch","qSearch")
self.aliasBox.setChecked( self.settings.value("onlyAlias", 0).toInt()[0] )
self.maxUnique.setText( self.settings.value("maxUnique",100).toString() )
def applySettings(self):
self.settings.setValue( "onlyAlias" , int(self.aliasBox.isChecked()) )
self.settings.setValue( "maxUnique" , self.maxUnique.text() )
<file_sep>"""
qSearch
QGIS plugin
<NAME>
<EMAIL>
Feb. 2012
"""
# Import the PyQt and QGIS libraries
import PyQt4
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from qgis.core import *
from qgis.gui import *
import resources
from chooselayer import chooseLayer
from editsearch import editSearch
from settings import settings
try:
_fromUtf8 = QString.fromUtf8
except AttributeError:
_fromUtf8 = lambda s: s
class qSearch(QObject):
def __init__(self, iface):
QObject.__init__(self)
self.iface = iface
# init dialogs
self.chooseLayerDialog = chooseLayer(self.iface)
self.editSearchDialog = editSearch(self.iface)
# load searches when new layers are loaded or when a search is saved
QObject.connect(self.iface.mapCanvas() , SIGNAL("layersChanged ()") , self.fillMenuEntries )
QObject.connect(self.editSearchDialog , SIGNAL("searchSaved ()") , self.fillMenuEntries )
self.menuEntries = []
def initGui(self):
self.newSearchAction = QAction(QIcon(":/plugins/qsearch/icons/search.png"),"new search", self.iface.mainWindow())
QObject.connect(self.newSearchAction, SIGNAL("triggered()"), self.newSearch)
self.iface.addToolBarIcon(self.newSearchAction)
self.iface.addPluginToMenu("&qSearch", self.newSearchAction)
# settings
self.uisettings = settings(self.iface)
self.uisettingsAction = QAction(QIcon(":/plugins/qsearch/icons/settings.png"), "settings", self.iface.mainWindow())
QObject.connect(self.uisettingsAction, SIGNAL("triggered()"), self.uisettings.exec_)
self.iface.addPluginToMenu("&qSearch", self.uisettingsAction)
# help
self.helpAction = QAction(QIcon(":/plugins/qsearch/icons/help.png"), "Help", self.iface.mainWindow())
QObject.connect(self.helpAction, SIGNAL("triggered()"), lambda: QDesktopServices.openUrl(QUrl("https://github.com/3nids/qsearch/wiki")))
self.iface.addPluginToMenu("&qSearch", self.helpAction)
def unload(self):
# Remove the plugin menu item and icon
self.iface.removePluginMenu("&qSearch",self.newSearchAction)
self.iface.removePluginMenu("&qSearch", self.uisettingsAction)
self.iface.removePluginMenu("&qSearch", self.helpAction)
for menu in self.menuEntries:
self.iface.removePluginMenu("&qSearch", menu)
def newSearch(self):
if self.chooseLayerDialog.exec_():
layer = self.chooseLayerDialog.selectedLayer()
if layer is not False:
self.editSearchDialog.initUi(layer)
self.editSearchDialog.show()
def fillMenuEntries(self):
for menu in self.menuEntries:
self.iface.removePluginMenu("&qSearch", menu)
self.menuEntries = []
for layer in self.iface.legendInterface().layers():
searches = layer.customProperty("qSearch","").toString()
if searches != "":
exec("searches = %s" % searches)
for i,search in enumerate(searches):
action = searchAction("%s :: %s" % (layer.name(),search.get('name')), self.iface.mainWindow() , layer, i)
QObject.connect(action, SIGNAL("triggered()"), self.showSearch)
self.iface.addPluginToMenu("&qSearch",action)
self.menuEntries.append( action )
def showSearch(self):
search = self.sender()
self.editSearchDialog.initUi(search.layer)
self.editSearchDialog.loadSearch(search.isearch)
self.editSearchDialog.show()
class searchAction(QAction):
def __init__(self,str,win,layer,isearch):
QAction.__init__(self,str,win)
self.layer = layer
self.isearch = isearch
<file_sep>"""
Item Browser
QGIS plugin
<NAME>
<EMAIL>
Jan. 2012
"""
def name():
return "qSearch"
def description():
return "This plugin produces a friendly interface to perform and save searches in a layer."
def version():
return "Version 1.3.1"
def icon():
return "icons/qsearch2.png"
def qgisMinimumVersion():
return "1.7"
def classFactory(iface):
from qsearch import qSearch
return qSearch(iface)
| d56b1e42ffac50b2f62b4d5bade41c0e5bd23ac4 | [
"Python"
] | 9 | Python | viktorijasolovjova/qsearch | 342bfee8feab57286e18c1104f4dbd5220bf1daf | 807e8138596285b8709f7aa20a9ddb42519d9146 |
refs/heads/master | <repo_name>WPTechCentre/affiliates<file_sep>/README.md
# affiliates
Modifications to Affiliates plugin for WPTechCentre
<file_sep>/class-affiliates-shortcodes.php
<?php
/**
* class-affiliates-shortcodes.php
*
* Copyright (c) 2010-2012 "kento" <NAME> www.itthinx.com
*
* This code is released under the GNU General Public License.
* See COPYRIGHT.txt and LICENSE.txt.
*
* This code is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* This header and all notices must be kept intact.
*
* @author <NAME>
* @package affiliates
* @since affiliates 1.3.0
*/
if ( !defined( 'ABSPATH' ) ) {
exit;
}
/**
* Shortcode handler.
*/
class Affiliates_Shortcodes {
/**
* Add shortcodes.
*/
public static function init() {
add_shortcode( 'affiliates_id', array( __CLASS__, 'affiliates_id' ) );
add_shortcode( 'referrer_id', array( __CLASS__, 'referrer_id' ) );
add_shortcode( 'referrer_user', array( __CLASS__, 'referrer_user' ) );
add_shortcode( 'affiliates_is_affiliate', array( __CLASS__, 'affiliates_is_affiliate' ) );
add_shortcode( 'affiliates_is_not_affiliate', array( __CLASS__, 'affiliates_is_not_affiliate' ) );
add_shortcode( 'affiliates_hits', array( __CLASS__, 'affiliates_hits' ) );
add_shortcode( 'affiliates_visits', array( __CLASS__, 'affiliates_visits' ) );
add_shortcode( 'affiliates_referrals', array( __CLASS__, 'affiliates_referrals' ) );
add_shortcode( 'affiliates_earnings', array( __CLASS__, 'affiliates_earnings' ) );
add_shortcode( 'affiliates_url', array( __CLASS__, 'affiliates_url' ) );
add_shortcode( 'affiliates_login_redirect', array( __CLASS__, 'affiliates_login_redirect' ) );
add_shortcode( 'affiliates_logout', array( __CLASS__, 'affiliates_logout' ) );
add_shortcode( 'affiliates_fields', array( __CLASS__, 'affiliates_fields' ) );
add_action( 'wp_enqueue_scripts', array( __CLASS__, 'wp_enqueue_scripts' ) );
add_shortcode( 'affiliates_support_plan_sale', array( __CLASS__, 'affiliates_support_plan_sale' ) ); // WPTechCentre
}
/**
* Register styles.
*/
public static function wp_enqueue_scripts() {
wp_register_style( 'affiliates-fields', AFFILIATES_PLUGIN_URL . 'css/affiliates-fields.css', array(), AFFILIATES_CORE_VERSION, 'all' );
}
/**
* Affiliate ID shortcode.
* Renders the affiliate's id.
*
* @param array $atts attributes
* @param string $content not used
*/
public static function affiliates_id( $atts, $content = null ) {
global $wpdb;
$output = "";
$user_id = get_current_user_id();
if ( $user_id && affiliates_user_is_affiliate( $user_id ) ) {
$affiliates_table = _affiliates_get_tablename( 'affiliates' );
$affiliates_users_table = _affiliates_get_tablename( 'affiliates_users' );
if ( $affiliate_id = $wpdb->get_var( $wpdb->prepare(
"SELECT $affiliates_users_table.affiliate_id FROM $affiliates_users_table LEFT JOIN $affiliates_table ON $affiliates_users_table.affiliate_id = $affiliates_table.affiliate_id WHERE $affiliates_users_table.user_id = %d AND $affiliates_table.status = 'active'",
intval( $user_id )
))) {
$output .= affiliates_encode_affiliate_id( $affiliate_id );
}
}
return $output;
}
/**
* Referrer ID shortcode.
* Renders the referring affiliate's id.
*
* @param array $atts attributes
* @param string $content not used
*/
public static function referrer_id( $atts, $content = null ) {
$options = shortcode_atts(
array(
'direct' => false
),
$atts
);
extract( $options );
$output = "";
require_once( 'class-affiliates-service.php' );
$affiliate_id = Affiliates_Service::get_referrer_id();
if ( $affiliate_id ) {
if ( $direct || $affiliate_id !== affiliates_get_direct_id() ) {
$output .= affiliates_encode_affiliate_id( $affiliate_id );
}
}
return $output;
}
/**
* Renders the referrer's username.
* @param array $atts
* @param string $content not used
* @return string
*/
public static function referrer_user( $atts, $content = null ) {
$options = shortcode_atts(
array(
'direct' => false,
'display' => 'user_login'
),
$atts
);
extract( $options );
$output = '';
require_once( 'class-affiliates-service.php' );
$affiliate_id = Affiliates_Service::get_referrer_id();
if ( $affiliate_id ) {
if ( $direct || $affiliate_id !== affiliates_get_direct_id() ) {
if ( $user_id = affiliates_get_affiliate_user( $affiliate_id ) ) {
if ( $user = get_user_by( 'id', $user_id ) ) {
switch( $display ) {
case 'user_login' :
$output .= $user->user_login;
break;
case 'user_nicename' :
$output .= $user->user_nicename;
break;
case 'user_email' :
$output .= $user->user_email;
break;
case 'user_url' :
$output .= $user->user_url;
break;
case 'display_name' :
$output .= $user->display_name;
break;
default :
$output .= $user->user_login;
}
$output = wp_strip_all_tags( $output );
}
}
}
}
return $output;
}
/**
* Affiliate content shortcode.
* Renders the content if the current user is an affiliate.
*
* @param array $atts attributes (none used)
* @param string $content this is rendered for affiliates
*/
public static function affiliates_is_affiliate( $atts, $content = null ) {
remove_shortcode( 'affiliates_is_affiliate' );
$content = do_shortcode( $content );
add_shortcode( 'affiliates_is_affiliate', array( __CLASS__, 'affiliates_is_affiliate' ) );
$output = "";
if ( affiliates_user_is_affiliate( get_current_user_id() ) ) {
$output .= $content;
}
return $output;
}
/**
* Non-Affiliate content shortcode.
*
* @param array $atts attributes
* @param string $content this is rendered for non-affiliates
*/
public static function affiliates_is_not_affiliate( $atts, $content = null ) {
remove_shortcode( 'affiliates_is_not_affiliate' );
$content = do_shortcode( $content );
add_shortcode( 'affiliates_is_not_affiliate', array( __CLASS__, 'affiliates_is_not_affiliate' ) );
$output = "";
if ( !affiliates_user_is_affiliate( get_current_user_id() ) ) {
$output .= $content;
}
return $output;
}
/**
* Adjust from und until dates from UTZ to STZ and take into account the
* for option which will adjust the from date to that of the current
* day, the start of the week or the month, leaving the until date
* set to null.
*
* @param string $for "day", "week" or "month"
* @param string $from date/datetime
* @param string $until date/datetime
*/
private static function for_from_until( $for, &$from, &$until ) {
include_once( AFFILIATES_CORE_LIB . '/class-affiliates-date-helper.php');
if ( $for === null ) {
if ( $from !== null ) {
$from = date( 'Y-m-d H:i:s', strtotime( DateHelper::u2s( $from ) ) );
}
if ( $until !== null ) {
$until = date( 'Y-m-d H:i:s', strtotime( DateHelper::u2s( $until ) ) );
}
} else {
$user_now = strtotime( DateHelper::s2u( date( 'Y-m-d H:i:s', time() ) ) );
$user_now_datetime = date( 'Y-m-d H:i:s', $user_now );
$user_daystart_datetime = date( 'Y-m-d', $user_now ) . ' 00:00:00';
$server_now_datetime = DateHelper::u2s( $user_now_datetime );
$server_user_daystart_datetime = DateHelper::u2s( $user_daystart_datetime );
$until = null;
switch ( strtolower( $for ) ) {
case 'day' :
$from = date( 'Y-m-d H:i:s', strtotime( $server_user_daystart_datetime ) );
break;
case 'week' :
$fdow = intval( get_option( 'start_of_week' ) );
$dow = intval( date( 'w', strtotime( $server_user_daystart_datetime ) ) );
$d = $dow - $fdow;
$from = date( 'Y-m-d H:i:s', mktime( 0, 0, 0, date( 'm', strtotime( $server_user_daystart_datetime ) ) , date( 'd', strtotime( $server_user_daystart_datetime ) )- $d, date( 'Y', strtotime( $server_user_daystart_datetime ) ) ) );
break;
case 'month' :
$from = date( 'Y-m', strtotime( $server_user_daystart_datetime ) ) . '-01 00:00:00';
break;
default :
$from = null;
}
}
}
/**
* Hits shortcode - renders the number of hits.
*
* @param array $atts attributes
* @param string $content not used
*/
public static function affiliates_hits( $atts, $content = null ) {
global $wpdb;
include_once( AFFILIATES_CORE_LIB . '/class-affiliates-date-helper.php');
remove_shortcode( 'affiliates_hits' );
$content = do_shortcode( $content );
add_shortcode( 'affiliates_hits', array( __CLASS__, 'affiliates_hits' ) );
$output = "";
$options = shortcode_atts(
array(
'from' => null,
'until' => null,
'for' => null
),
$atts
);
extract( $options );
self::for_from_until( $for, $from, $until );
$user_id = get_current_user_id();
if ( $user_id && affiliates_user_is_affiliate( $user_id ) ) {
$affiliates_table = _affiliates_get_tablename( 'affiliates' );
$affiliates_users_table = _affiliates_get_tablename( 'affiliates_users' );
if ( $affiliate_id = $wpdb->get_var( $wpdb->prepare(
"SELECT $affiliates_users_table.affiliate_id FROM $affiliates_users_table LEFT JOIN $affiliates_table ON $affiliates_users_table.affiliate_id = $affiliates_table.affiliate_id WHERE $affiliates_users_table.user_id = %d AND $affiliates_table.status = 'active'",
intval( $user_id )
))) {
$output .= affiliates_get_affiliate_hits( $affiliate_id, $from, $until, true );
}
}
return $output;
}
/**
* Visits shortcode - renders the number of visits.
*
* @param array $atts attributes
* @param string $content not used
*/
public static function affiliates_visits( $atts, $content = null ) {
global $wpdb;
remove_shortcode( 'affiliates_visits' );
$content = do_shortcode( $content );
add_shortcode( 'affiliates_visits', array( __CLASS__, 'affiliates_visits' ) );
$output = "";
$options = shortcode_atts(
array(
'from' => null,
'until' => null,
'for' => null
),
$atts
);
extract( $options );
self::for_from_until( $for, $from, $until );
$user_id = get_current_user_id();
if ( $user_id && affiliates_user_is_affiliate( $user_id ) ) {
$affiliates_table = _affiliates_get_tablename( 'affiliates' );
$affiliates_users_table = _affiliates_get_tablename( 'affiliates_users' );
if ( $affiliate_id = $wpdb->get_var( $wpdb->prepare(
"SELECT $affiliates_users_table.affiliate_id FROM $affiliates_users_table LEFT JOIN $affiliates_table ON $affiliates_users_table.affiliate_id = $affiliates_table.affiliate_id WHERE $affiliates_users_table.user_id = %d AND $affiliates_table.status = 'active'",
intval( $user_id )
) ) ) {
$output .= affiliates_get_affiliate_visits( $affiliate_id, $from, $until, true );
}
}
return $output;
}
/**
* Referrals shortcode - renders referral information.
*
* @param array $atts attributes
* @param string $content not used
*/
public static function affiliates_referrals( $atts, $content = null ) {
global $wpdb;
remove_shortcode( 'affiliates_referrals' );
$content = do_shortcode( $content );
add_shortcode( 'affiliates_referrals', array( __CLASS__, 'affiliates_referrals' ) );
$output = "";
$options = shortcode_atts(
array(
'status' => null,
'from' => null,
'until' => null,
'show' => 'count',
'currency' => null,
'for' => null,
'if_empty' => null
),
$atts
);
extract( $options );
self::for_from_until( $for, $from, $until );
$user_id = get_current_user_id();
if ( $user_id && affiliates_user_is_affiliate( $user_id ) ) {
$affiliates_table = _affiliates_get_tablename( 'affiliates' );
$affiliates_users_table = _affiliates_get_tablename( 'affiliates_users' );
if ( $affiliate_id = $wpdb->get_var( $wpdb->prepare(
"SELECT $affiliates_users_table.affiliate_id FROM $affiliates_users_table LEFT JOIN $affiliates_table ON $affiliates_users_table.affiliate_id = $affiliates_table.affiliate_id WHERE $affiliates_users_table.user_id = %d AND $affiliates_table.status = 'active'",
intval( $user_id )
))) {
switch ( $show ) {
case 'count' :
switch ( $status ) {
case null :
case AFFILIATES_REFERRAL_STATUS_ACCEPTED :
case AFFILIATES_REFERRAL_STATUS_CLOSED :
case AFFILIATES_REFERRAL_STATUS_PENDING :
case AFFILIATES_REFERRAL_STATUS_REJECTED :
$referrals = affiliates_get_affiliate_referrals( $affiliate_id, $from, $until, $status );
break;
default :
$referrals = "";
}
$output .= $referrals;
break;
case 'total' :
if ( $totals = self::get_total( $affiliate_id, $from, $until, $status ) ) {
if ( count( $totals ) > 0 ) {
$output .= '<ul>';
foreach ( $totals as $currency_id => $total ) {
$output .= '<li>';
$output .= apply_filters( 'affiliates_referrals_display_currency', $currency_id );
$output .= ' ';
$output .= apply_filters( 'affiliates_referrals_display_total', number_format_i18n( $total, apply_filters( 'affiliates_referrals_decimals', 2 ) ), $total, $currency_id );
$output .= '</li>';
}
$output .= '</ul>';
}
}
if ( !$totals || count( $totals ) === 0 ) {
if ( $if_empty !== null ) {
$output .= '<ul>';
$output .= '<li>';
$output .= apply_filters( 'affiliates_referrals_display_total_none', wp_filter_nohtml_kses( $if_empty ) );
$output .= '</li>';
$output .= '</ul>';
}
}
break;
}
}
}
return $output;
}
/**
* Shows monthly earnings.
*
* Note that we don't do any s2u or u2s date adjustments here.
*
* @param array $atts not used; this shortcode does not accept any arguments
* @param string $content not used
*/
public static function affiliates_earnings( $atts, $content = null ) {
global $wpdb;
$output = '';
$user_id = get_current_user_id();
if ( $user_id && affiliates_user_is_affiliate( $user_id ) ) {
if ( $affiliate_ids = affiliates_get_user_affiliate( $user_id ) ) {
$output .= '<table class="affiliates-earnings">';
$output .= '<thead>';
$output .= '<tr>';
$output .= '<th>';
$output .= __( 'Month', AFFILIATES_PLUGIN_DOMAIN );
$output .= '</th>';
$output .= '<th>';
$output .= __( 'Earnings', AFFILIATES_PLUGIN_DOMAIN );
$output .= '</th>';
$output .= '</tr>';
$output .= '</thead>';
$output .= '<tbody>';
$referrals_table = _affiliates_get_tablename( 'referrals' );
if ( $range = $wpdb->get_row( "SELECT MIN(datetime) from_datetime, MAX(datetime) thru_datetime FROM $referrals_table WHERE affiliate_id IN (" . implode( ',', $affiliate_ids ) . ")") ) {
if ( !empty( $range->from_datetime ) ) { // Covers for NULL when no referrals recorded yet, too.
$t = strtotime( $range->from_datetime );
$eom = strtotime( date( 'Y-m-t 23:59:59', time() ) );
while ( $t < $eom ) {
$from = date( 'Y-m', $t ) . '-01 00:00:00';
$thru = date( 'Y-m-t', strtotime( $from ) );
$sums = array();
foreach( $affiliate_ids as $affiliate_id ) {
if ( $totals = self::get_total( $affiliate_id, $from, $thru ) ) {
if ( count( $totals ) > 0 ) {
foreach ( $totals as $currency_id => $total ) {
$sums[$currency_id] = isset( $sums[$currency_id] ) ? bcadd( $sums[$currency_id], $total, AFFILIATES_REFERRAL_AMOUNT_DECIMALS ) : $total;
}
}
}
}
$output .= '<tr>';
// month & year
$output .= '<td>';
$output .= date_i18n( __( 'F Y', AFFILIATES_PLUGIN_DOMAIN ), strtotime( $from ) ); // translators: date format; month and year for earnings display
$output .= '</td>';
// earnings
$output .= '<td>';
if ( count( $sums ) > 1 ) {
$output .= '<ul>';
foreach ( $sums as $currency_id => $total ) {
$output .= '<li>';
$output .= apply_filters( 'affiliates_earnings_display_currency', $currency_id );
$output .= ' ';
$output .= apply_filters( 'affiliates_earnings_display_total', number_format_i18n( $total, apply_filters( 'affiliates_earnings_decimals', 2 ) ), $total, $currency_id );
$output .= '</li>';
}
$output .= '</ul>';
} else if ( count( $sums ) > 0 ) {
$output .= apply_filters( 'affiliates_earnings_display_currency', $currency_id );
$output .= ' ';
$output .= apply_filters( 'affiliates_earnings_display_total', number_format_i18n( $total, apply_filters( 'affiliates_earnings_decimals', 2 ) ), $total, $currency_id );
} else {
$output .= apply_filters( 'affiliates_earnings_display_total_none', __( 'None', AFFILIATES_PLUGIN_DOMAIN ) );
}
$output .= '</td>';
$output .= '</tr>';
$t = strtotime( '+1 month', $t );
}
} else {
$output .= '<td colspan="2">';
$output .= apply_filters( 'affiliates_earnings_display_total_no_earnings', __( 'There are no earnings yet.', AFFILIATES_PLUGIN_DOMAIN ) );
$output .= '</td>';
}
}
$output .= '</tbody>';
$output .= '</table>';
}
}
return $output;
}
/**
* Retrieve totals for an affiliate.
*
* @param int $affiliate_id
* @param string $from_date
* @param string $thru_date
* @param string $status
* @return array of totals indexed by currency_id or false on error
*/
public static function get_total( $affiliate_id, $from_date = null , $thru_date = null, $status = null ) {
global $wpdb;
$referrals_table = _affiliates_get_tablename( 'referrals' );
$where = " WHERE affiliate_id = %d";
$values = array( $affiliate_id );
if ( $from_date ) {
$from_date = date( 'Y-m-d', strtotime( $from_date ) );
}
if ( $thru_date ) {
$thru_date = date( 'Y-m-d', strtotime( $thru_date ) + 24*3600 );
}
if ( $from_date && $thru_date ) {
$where .= " AND datetime >= %s AND datetime < %s ";
$values[] = $from_date;
$values[] = $thru_date;
} else if ( $from_date ) {
$where .= " AND datetime >= %s ";
$values[] = $from_date;
} else if ( $thru_date ) {
$where .= " AND datetime < %s ";
$values[] = $thru_date;
}
if ( !empty( $status ) ) {
$where .= " AND status = %s ";
$values[] = $status;
} else {
$where .= " AND status IN ( %s, %s ) ";
$values[] = AFFILIATES_REFERRAL_STATUS_ACCEPTED;
$values[] = AFFILIATES_REFERRAL_STATUS_CLOSED;
}
$totals = $wpdb->get_results( $wpdb->prepare(
"SELECT SUM(amount) total, currency_id FROM $referrals_table
$where
GROUP BY currency_id
",
$values
) );
if ( $totals ) {
$result = array();
foreach( $totals as $total ) {
if ( ( $total->currency_id !== null ) && ( $total->total !== null ) ) {
$result[$total->currency_id] = $total->total;
}
}
return $result;
} else {
return false;
}
}
/**
* URL shortcode - renders the affiliate url.
*
* @param array $atts attributes
* @param string $content (is not used)
*/
public static function affiliates_url( $atts, $content = null ) {
global $wpdb;
$pname = get_option( 'aff_pname', AFFILIATES_PNAME );
remove_shortcode( 'affiliates_url' );
$content = do_shortcode( $content );
add_shortcode( 'affiliates_url', array( __CLASS__, 'affiliates_url' ) );
$output = "";
$user_id = get_current_user_id();
if ( $user_id && affiliates_user_is_affiliate( $user_id ) ) {
$affiliates_table = _affiliates_get_tablename( 'affiliates' );
$affiliates_users_table = _affiliates_get_tablename( 'affiliates_users' );
if ( $affiliate_id = $wpdb->get_var( $wpdb->prepare(
"SELECT $affiliates_users_table.affiliate_id FROM $affiliates_users_table LEFT JOIN $affiliates_table ON $affiliates_users_table.affiliate_id = $affiliates_table.affiliate_id WHERE $affiliates_users_table.user_id = %d AND $affiliates_table.status = 'active'",
intval( $user_id )
))) {
$encoded_affiliate_id = affiliates_encode_affiliate_id( $affiliate_id );
if ( strlen( $content ) == 0 ) {
$base_url = get_bloginfo( 'url' );
} else {
$base_url = $content;
}
$separator = '?';
$url_query = parse_url( $base_url, PHP_URL_QUERY );
if ( !empty( $url_query ) ) {
$separator = '&';
}
$output .= $base_url . $separator . $pname . '=' . $encoded_affiliate_id;
}
}
return $output;
}
/**
* Renders a login form that can redirect to a url or the current page.
*
* @param array $atts
* @param string $content
* @return string rendered form
*/
public static function affiliates_login_redirect( $atts, $content = null ) {
extract( shortcode_atts( array( 'redirect_url' => '' ), $atts ) );
$form = '';
if ( !is_user_logged_in() ) {
if ( empty( $redirect_url ) ) {
$redirect_url = get_permalink();
}
$form = wp_login_form( array( 'echo' => false, 'redirect' => $redirect_url ) );
}
return $form;
}
/**
* Renders a link to log out.
*
* @param array $atts
* @param string $content not used
* @return string rendered logout link or empty if not logged in
*/
public static function affiliates_logout( $atts, $content = null ) {
if ( is_user_logged_in() ) {
return '<a href="' . esc_url( wp_logout_url() ) .'">' . __( 'Log out', AFFILIATES_PLUGIN_DOMAIN ) . '</a>';
} else {
return '';
}
}
/**
* Affiliate field info.
*
* user_id - print for ... requires AFFILIATES_ADMIN...
* name - field name or names, empty includes all by default
* edit - yes or no
* load_styles - yes or no
*
* @param array $atts
* @param string $content
* @return string
*/
public static function affiliates_fields( $atts, $content = null ) {
$output = '';
if ( is_user_logged_in() ) {
$atts = shortcode_atts(
array(
'edit' => 'yes',
'load_styles' => 'yes',
'name' => '',
'user_id' => null
),
$atts
);
$atts['load_styles'] = strtolower( trim( $atts['load_styles' ] ) );
if ( $atts['load_styles'] == 'yes' ) {
wp_enqueue_style( 'affiliates-fields' );
}
$atts['edit'] = strtolower( trim( $atts['edit' ] ) );
$fields = null;
if ( !empty( $atts['name'] ) ) {
$fields = array_map( 'strtolower', array_map( 'trim', explode( ',', $atts['name'] ) ) );
}
if ( current_user_can( AFFILIATES_ADMINISTER_AFFILIATES ) && !empty( $atts['user_id'] ) ) {
$user_id = intval( trim( $atts['user_id'] ) );
} else {
$user_id = get_current_user_id();
}
$user = get_user_by( 'id', $user_id );
if ( affiliates_user_is_affiliate( $user_id ) ) {
require_once AFFILIATES_CORE_LIB . '/class-affiliates-settings.php';
require_once AFFILIATES_CORE_LIB . '/class-affiliates-settings-registration.php';
$registration_fields = Affiliates_Settings_Registration::get_fields();
if ( $atts['edit'] != 'yes' ) {
unset( $registration_fields['password'] );
}
if ( !empty( $fields ) ) {
$_registration_fields = array();
foreach( $fields as $name ) {
if ( isset( $registration_fields[$name] ) ) {
$_registration_fields[$name] = $registration_fields[$name];
}
}
$registration_fields = $_registration_fields;
}
// handle form submission
if ( $atts['edit'] === 'yes' ) {
if ( !empty( $_POST['affiliate-nonce'] ) && wp_verify_nonce( $_POST['affiliate-nonce'], 'save' ) ) {
if ( !empty( $registration_fields ) ) {
$error = false;
// gather field values
foreach( $registration_fields as $name => $field ) {
if ( $field['enabled'] ) {
$value = isset( $_POST[$name] ) ? $_POST[$name] : '';
$value = Affiliates_Utility::filter( $value );
if ( $field['required'] && empty( $value ) ) {
$error = true;
$output .= '<div class="error">';
$output .= __( '<strong>ERROR</strong>', AFFILIATES_PLUGIN_DOMAIN );
$output .= ' : ';
$output .= sprintf( __( 'Please fill out the field <em>%s</em>.', AFFILIATES_PLUGIN_DOMAIN ), $field['label'] );
$output .= '</div>';
}
$registration_fields[$name]['value'] = $value;
// password check
$type = isset( $field['type'] ) ? $field['type'] : 'text';
if ( $type == 'password' ) {
if ( !empty( $value ) ) {
$value2 = isset( $_POST[$name . '2'] ) ? $_POST[$name . '2'] : '';
$value2 = Affiliates_Utility::filter( $value2 );
if ( $value !== $value2 ) {
$error = true;
$output .= '<div class="error">';
$output .= __( '<strong>ERROR</strong>', AFFILIATES_PLUGIN_DOMAIN );
$output .= ' : ';
$output .= sprintf( __( 'The passwords for the field <em>%s</em> do not match.', AFFILIATES_PLUGIN_DOMAIN ), $field['label'] );
$output .= '</div>';
}
}
}
}
}
$userdata = array();
foreach( $registration_fields as $name => $field ) {
if ( $registration_fields[$name]['enabled'] ) {
$userdata[$name] = $registration_fields[$name]['value'];
}
}
if ( !$error ) {
$updated_user_id = Affiliates_Registration::update_affiliate_user( $user_id, $userdata );
if ( is_wp_error( $updated_user_id ) ) {
$error_messages = implode( '<br/>', $updated_user_id->get_error_messages() );
if ( !empty( $error_messages ) ) {
$output .= '<div class="error">';
$output .= $error_messages;
$output .= '</div>';
}
} else {
$output .= '<div class="updated">';
$output .= __( 'Saved', AFFILIATES_PLUGIN_DOMAIN );
$output .= '</div>';
}
}
}
}
}
// show form
$n = 0;
if ( !empty( $registration_fields ) ) {
if ( $atts['edit'] === 'yes' ) {
$output .= '<form class="affiliates-fields" method="post">';
$output .= '<div>';
} else {
$output .= '<div class="affiliates-fields">';
$output .= '<div>';
}
foreach( $registration_fields as $name => $field ) {
if ( $field['enabled'] ) {
$n++;
$output .= '<div class="field">';
$output .= '<label>';
$output .= esc_html( stripslashes( $field['label'] ) ); // @todo i18n
$type = isset( $field['type'] ) ? $field['type'] : 'text';
$extra = $atts['edit'] != 'yes' ? ' readonly="readonly" ' : '';
switch( $name ) {
case 'user_login' :
$extra .= ' readonly="readonly" ';
$value = $user->user_login;
break;
case 'user_email' :
$value = $user->user_email;
break;
case 'user_url' :
$value = $user->user_url;
break;
case 'password' :
$value = '';
break;
default :
$value = get_user_meta( $user_id, $name , true );
}
$output .= sprintf(
'<input type="%s" class="%s" name="%s" value="%s" %s %s />',
esc_attr( $type ),
'regular-text ' . esc_attr( $name ) . ( $field['required'] ? ' required ' : '' ),
esc_attr( $name ),
esc_attr( stripslashes( $value ) ),
$field['required'] ? ' required="required" ' : '',
$extra
);
$output .= '</label>';
$output .= '</div>';
if ( $type == 'password' ) {
$output .= '<div class="field">';
$output .= '<label>';
$output .= sprintf( __( 'Repeat %s', AFFILIATES_PLUGIN_DOMAIN ), esc_html( stripslashes( $field['label'] ) ) ); // @todo i18n
$output .= sprintf(
'<input type="%s" class="%s" name="%s" value="%s" %s %s />',
esc_attr( $type ),
'regular-text ' . esc_attr( $name ) . ( $field['required'] ? ' required ' : '' ),
esc_attr( $name . '2' ),
esc_attr( $value ),
$field['required'] ? ' required="required" ' : '',
$extra
);
$output .= '</label>';
$output .= '</div>';
}
}
}
if ( $atts['edit'] === 'yes' ) {
$output .= wp_nonce_field( 'save', 'affiliate-nonce', true, false );
$output .= '<div class="save">';
$output .= sprintf( '<input class="button" type="submit" name="save" value="%s" />', __( 'Save', AFFILIATES_PLUGIN_DOMAIN ) );
$output .= '</div>';
$output .= '</div>';
$output .= '</form>';
} else {
$output .= '</div>';
$output .= '</div>';
}
}
}
}
return $output;
}
/**
* Suggest referral shortcode.
* Stores a referral on reaching payment confirmation page (or wherever shortcode is placed).
*/
public static function affiliates_support_plan_sale() {
if( function_exists( 'affiliates_suggest_referral' ) ) {
if( isset( $_REQUEST[ 'success' ] ) && $_REQUEST[ 'success' ] == 'true' ) { // Stripe payment
$sub = 'Subscription ID: ' . $_REQUEST[ 'subscription' ];
$data['cust_id'] = array(
'title' => 'Customer ID: ',
'domain' => 'domain',
'value' => $_REQUEST[ 'cust_id' ]
);
$amount = $_REQUEST[ 'amount' ];
$currency_id = 'GBP';
$status = $_REQUEST[ 'success' ];
$type = $_REQUEST[ 'type' ];
$reference = 'Customer email: ' . $_REQUEST[ 'email' ];
affiliates_suggest_referral( get_the_ID(), $sub, $data, $amount, $currency_id, $status, $type, $reference );
} elseif( isset( $_REQUEST[ 'st' ] ) && $_REQUEST[ 'st' ] == 'Completed' ) { // PayPal payment
$sub = 'Transaction ID: ' . $_REQUEST[ 'tx' ];
$data['cust_id'] = array(
'title' => 'Customer ID: ',
'domain' => 'domain',
'value' => $_REQUEST[ 'cust_id' ]
);
$amount = $_REQUEST[ 'amt' ];
$currency_id = $_REQUEST[ 'cc' ];
$status = $_REQUEST[ 'st' ];
$type = $_REQUEST[ 'type' ];
$reference = 'Customer email: ' . $_REQUEST[ 'email' ];
affiliates_suggest_referral( get_the_ID(), $sub, $data, $amount, $currency_id, $status, $type, $reference );
}
}
}
}
Affiliates_Shortcodes::init();
| 8687e52e2689f5fdd833446d23906c19946bcb97 | [
"Markdown",
"PHP"
] | 2 | Markdown | WPTechCentre/affiliates | 38b76113d9b94659246f7a118f68b7506440e54d | 18478d4726137948d22d165fd52596fde26aa172 |
refs/heads/main | <file_sep># Backend_Project2_IPC1
Backend de la pagina UMedic del proyeco 2 de IPC1 Universidad San Carlos de Guatemala
<file_sep>class Medicina:
# NUESTRO NUEVO CONSTRUCTO
def __init__(self,nombre,precio,descripcion,cantidad,idMed,compradas):
self.nombre = nombre
self.precio = precio
self.descripcion = descripcion
self.cantidad = cantidad
self.idMed = idMed
self.compradas = compradas
# METODOS GET
def getNombre(self):
return self.nombre
def getPrecio(self):
return self.precio
def getDescripicion(self):
return self.descripcion
def getCantidad(self):
return self.cantidad
def getIdmed(self):
return self.idMed
def getCompradas(self):
return self.compradas
# METODOS SET
def setNombre(self, nombre):
self.nombre = nombre
def setPrecio(self, precio):
self.precio = precio
def setDescripcion(self, descripcion):
self.descripcion = descripcion
def setCantidad(self,cantidad):
self.cantidad = cantidad
def setIdmed(self,idMed):
self.idMed = idMed
def setCompradas(self,compradas):
self.compradas = compradas<file_sep>class Enfermera:
# NUESTRO NUEVO CONSTRUCTO
def __init__(self,nombre,apellido,user,contraseña,fecha,telefono,genero):
self.nombre = nombre
self.apellido = apellido
self.user = user
self.contraseña = contraseña
self.fecha = fecha
self.telefono = telefono
self.genero = genero
# METODOS GET
def getNombre(self):
return self.nombre
def getApellido(self):
return self.apellido
def getUser(self):
return self.user
def getContraseña(self):
return self.contraseña
def getFecha(self):
return self.fecha
def getTelefono(self):
return self.telefono
def getGenero(self):
return self.genero
# METODOS SET
def setNombre(self, nombre):
self.nombre = nombre
def setApellido(self, apellido):
self.apellido = apellido
def setUser(self, user):
self.user = user
def setContraseña(self,contraseña):
self.contraseña = contraseña
def setFecha(self,fecha):
self.fecha = fecha
def setTelefono(self,telefono):
self.telefono = telefono
def setGenero(self,genero):
self.genero = genero <file_sep>astroid==2.5.1
click==7.1.2
colorama==0.4.4
Flask==1.1.2
Flask-Cors==3.0.10
gunicorn==20.1.0
isort==5.7.0
itsdangerous==1.1.0
Jinja2==2.11.3
lazy-object-proxy==1.5.2
MarkupSafe==1.1.1
mccabe==0.6.1
pylint==2.7.2
rope==0.18.0
six==1.15.0
toml==0.10.2
Werkzeug==1.0.1
wrapt==1.12.1
<file_sep>class Doctor:
# NUESTRO NUEVO CONSTRUCTOR
def __init__(self,nombre,apellido,user,contraseña,fecha,telefono,especialidad,genero,atendidas):
self.nombre = nombre
self.apellido = apellido
self.user = user
self.contraseña = contraseña
self.fecha = fecha
self.telefono = telefono
self.especialidad = especialidad
self.genero = genero
self.atendidas = atendidas
# METODOS GET
def getNombre(self):
return self.nombre
def getApellido(self):
return self.apellido
def getUser(self):
return self.user
def getContraseña(self):
return self.contraseña
def getFecha(self):
return self.fecha
def getTelefono(self):
return self.telefono
def getEspecialidad(self):
return self.especialidad
def getGenero(self):
return self.genero
def getAtendidas(self):
return self.atendidas
# METODOS SET
def setNombre(self, nombre):
self.nombre = nombre
def setApellido(self, apellido):
self.apellido = apellido
def setUser(self, user):
self.user = user
def setContraseña(self,contraseña):
self.contraseña = contraseña
def setFecha(self,fecha):
self.fecha = fecha
def setTelefono(self,telefono):
self.telefono = telefono
def setEspecialidad(self,especialidad):
self.especialidad = especialidad
def setGenero(self,genero):
self.genero = genero
def setAtendidas(self,atendidas):
self.atendidas = atendidas<file_sep>class Cita:
# NUESTRO NUEVO CONSTRUCTO
def __init__(self,idPaciente,fecha,hora,motivo,idDoctor,idCita,estado):
self.idPaciente = idPaciente
self.fecha = fecha
self.hora = hora
self.motivo = motivo
self.idDoctor = idDoctor
self.idCita= idCita
self.estado = estado
# METODOS GET
def getIdPaciente(self):
return self.idPaciente
def getFecha(self):
return self.fecha
def getHora(self):
return self.hora
def getMotivo(self):
return self.motivo
def getIdDoctor(self):
return self.idDoctor
def getIdCita(self):
return self.idCita
def getEstado(self):
return self.estado
# METODOS SET
def setIdPaciente(self, idPaciente):
self.idPaciente = idPaciente
def setFecha(self, fecha):
self.fecha = fecha
def setHora (self, hora):
self.hora = hora
def setMotivo(self, motivo):
self.motivo = motivo
def setIdDoctor(self, idDoctor):
self.idDoctor = idDoctor
def setIdCita(self, idCita):
self.idCita = idCita
def setEstado(self, estado):
self.estado = estado<file_sep>class Carrito:
# NUESTRO NUEVO CONSTRUCTO
def __init__(self,idPaciente,medicina,cantidad,precio,subtotal):
self.idPaciente = idPaciente
self.medicina=medicina
self.cantidad=cantidad
self.precio=precio
self.subtotal=subtotal
# METODOS GET
def getIdPaciente(self):
return self.idPaciente
def getMedicina(self):
return self.medicina
def getCantidad(self):
return self.cantidad
def getPrecio(self):
return self.precio
def getSubtotal(self):
return self.subtotal
# METODOS SET
def setIdPaciente(self, idPaciente):
self.idPaciente = idPaciente
def setMedicina(self,medicina):
self.medicina=medicina
def setCantidad(self,cantidad):
self.cantidad=cantidad
def setPrecio(self,precio):
self.precio=precio
def setSubtotal(self,subtotal):
self.subtotal=subtotal<file_sep>from flask import Flask,jsonify,request
from flask_cors import CORS
from datetime import datetime
from admin import Administrador
from doctor import Doctor
from enfermera import Enfermera
from paciente import Paciente
from medicina import Medicina
from citas import Cita
import json
idMed=1
idCitas=1
Doctores=[]
Enfermeras=[]
Pacientes=[]
Medicinas=[]
Citas=[]
carrito=[]
CantInicial = []
Admin=Administrador('Abner','Cardona','admin',1234)
#Citas.append(Cita("henry23","14/05/2021","14:00","<NAME>","xd",1,"Pendiente"))
app = Flask(__name__)
CORS(app)
#METODOS DE PRUEBA
@app.route('/', methods=['GET'])
def rutaInicial():
prueba = {
"Nombre":"Henry",
"Edad":19
}
return(jsonify(prueba))
@app.route('/', methods=['POST'])
def rutaPost():
print("prueba post")
prueba = {"MENSAJE":"Se hizo el post correctamente"}
return(jsonify(prueba))
#METODOS PARA DOCTORES
@app.route('/Doctores', methods=['GET'])
def getDoctores():
global Doctores
Datos = []
for doctor in Doctores:
objeto = {
'Nombre': doctor.getNombre(),
'Apellido': doctor.getApellido(),
'User': doctor.getUser(),
'Contraseña' : doctor.getContraseña(),
'Fecha' : doctor.getFecha(),
'Teléfono' : doctor.getTelefono(),
'Especialidad' : doctor.getEspecialidad(),
'Género' : doctor.getGenero()
}
Datos.append(objeto)
return(jsonify(Datos))
@app.route('/Doctores/<string:nombre>', methods=['GET'])
def ObtenerDoctor(nombre):
global Doctores
for doctor in Doctores:
if doctor.getUser() == nombre:
objeto = {
'Nombre': doctor.getNombre(),
'Apellido': doctor.getApellido(),
'User': doctor.getUser(),
'Contraseña' : doctor.getContraseña(),
'Fecha' : doctor.getFecha(),
'Teléfono' : doctor.getTelefono(),
'Especialidad' : doctor.getEspecialidad(),
'Género' : doctor.getGenero()
}
return(jsonify(objeto))
salida = { "Mensaje": "No existe el usuario con ese nombre"}
return(jsonify(salida))
@app.route('/Doctores', methods=['POST'])
def AgregarDoctor():
global Doctores
nombre = request.json['Nombre']
apellido = request.json['Apellido']
user = request.json['User']
contraseña = request.json['Contraseña']
fecha = request.json['Fecha']
telefono = request.json['Teléfono']
especialidad = request.json['Especialidad']
genero = request.json['Género']
nuevo = Doctor(nombre,apellido,user,contraseña,fecha,telefono,especialidad,genero,0)
Doctores.append(nuevo)
return jsonify({'Mensaje':'Se añadió el usuario'})
@app.route('/Doctores/<string:nombre>', methods=['PUT'])
def ActualizarDoctores(nombre):
global Doctores
for i in range(len(Doctores)):
if nombre == Doctores[i].getUser():
Doctores[i].setNombre(request.json['Nombre'])
Doctores[i].setApellido(request.json['Apellido'])
Doctores[i].setUser(request.json['User'])
Doctores[i].setContraseña(request.json['Contraseña'])
Doctores[i].setFecha(request.json['Fecha'])
Doctores[i].setTelefono(request.json['Teléfono'])
Doctores[i].setEspecialidad(request.json['Especialidad'])
Doctores[i].setGenero(request.json['Género'])
return jsonify({'Mensaje':'Se actualizo el dato exitosamente'})
return jsonify({'Mensaje':'No se encontro el dato para actualizar'})
@app.route('/Doctores/<string:nombre>', methods=['DELETE'])
def EliminarDoctor(nombre):
global Doctores
for i in range(len(Doctores)):
if nombre == Doctores[i].getUser():
del Doctores[i]
return jsonify({'Mensaje':'Se elimino el dato exitosamente'})
return jsonify({'Mensaje':'No se encontro el dato para eliminar'})
#METODOS PARA ENFERMERAS
@app.route('/Enfermeras', methods=['GET'])
def getEnfermera():
global Enfermeras
Datos = []
for enfermera in Enfermeras:
objeto = {
'Nombre':enfermera.getNombre(),
'Apellido': enfermera.getApellido(),
'User': enfermera.getUser(),
'Contraseña' : <PASSWORD>(),
'Fecha' : enfermera.getFecha(),
'Teléfono' : enfermera.getTelefono(),
'Género' : enfermera.getGenero()
}
Datos.append(objeto)
return(jsonify(Datos))
@app.route('/Enfermeras/<string:nombre>', methods=['GET'])
def ObtenerEnfermera(nombre):
global Enfermeras
for enfermera in Enfermeras:
if enfermera.getUser() == nombre:
objeto = {
'Nombre':enfermera.getNombre(),
'Apellido': enfermera.getApellido(),
'User': enfermera.getUser(),
'Contraseña' : <PASSWORD>(),
'Fecha' : enfermera.getFecha(),
'Teléfono' : enfermera.getTelefono(),
'Género' : enfermera.getGenero()
}
return(jsonify(objeto))
salida = { "Mensaje": "No existe el usuario con ese nombre"}
return(jsonify(salida))
@app.route('/Enfermeras', methods=['POST'])
def AgregarEnfermera():
global Enfermeras
nombre = request.json['Nombre']
apellido = request.json['Apellido']
user = request.json['User']
contraseña = request.json['Contraseña']
fecha = request.json['Fecha']
telefono = request.json['Teléfono']
genero = request.json['Género']
nuevo = Enfermera(nombre,apellido,user,contraseña,fecha,telefono,genero)
Enfermeras.append(nuevo)
return jsonify({'Mensaje':'Se añadió el usuario'})
@app.route('/Enfermeras/<string:nombre>', methods=['PUT'])
def ActualizarEnfermera(nombre):
global Enfermeras
for i in range(len(Enfermeras)):
if nombre == Enfermeras[i].getUser():
Enfermeras[i].setNombre(request.json['Nombre'])
Enfermeras[i].setApellido(request.json['Apellido'])
Enfermeras[i].setUser(request.json['User'])
Enfermeras[i].setContraseña(request.json['Contraseña'])
Enfermeras[i].setFecha(request.json['Fecha'])
Enfermeras[i].setTelefono(request.json['Teléfono'])
Enfermeras[i].setGenero(request.json['Género'])
return jsonify({'Mensaje':'Se actualizo el dato exitosamente'})
return jsonify({'Mensaje':'No se encontro el dato para actualizar'})
@app.route('/Enfermeras/<string:nombre>', methods=['DELETE'])
def EliminarEnfermera(nombre):
global Enfermeras
for i in range(len(Enfermeras)):
if nombre == Enfermeras[i].getUser():
del Enfermeras[i]
return jsonify({'Mensaje':'Se elimino el dato exitosamente'})
return jsonify({'Mensaje':'No se encontro el dato para eliminar'})
#METODOS PARA PACIENTES
@app.route('/Pacientes', methods=['GET'])
def getPacientes():
global Pacientes
Datos = []
for paciente in Pacientes:
objeto = {
'Nombre': paciente.getNombre(),
'Apellido': paciente.getApellido(),
'User': paciente.getUser(),
'Contraseña' : <PASSWORD>.getContraseña(),
'Fecha' : paciente.getFecha(),
'Teléfono' : paciente.getTelefono(),
'Género' : paciente.getGenero()
}
Datos.append(objeto)
return(jsonify(Datos))
@app.route('/Pacientes/<string:nombre>', methods=['GET'])
def ObtenerPaciente(nombre):
global Pacientes
for paciente in Pacientes:
if paciente.getUser() == nombre:
objeto = {
'Nombre': paciente.getNombre(),
'Apellido': paciente.getApellido(),
'User': paciente.getUser(),
'Contraseña' : <PASSWORD>(),
'Fecha' : paciente.getFecha(),
'Teléfono' : paciente.getTelefono(),
'Género' : paciente.getGenero()
}
return(jsonify(objeto))
salida = { "Mensaje": "No existe el usuario con ese nombre"}
return(jsonify(salida))
@app.route('/Pacientes', methods=['POST'])
def AgregarPaciente():
global Pacientes
compra=[]
nombre = request.json['Nombre']
apellido = request.json['Apellido']
user = request.json['User']
contraseña = request.json['Contraseña']
fecha = request.json['Fecha']
telefono = request.json['Teléfono']
genero = request.json['Género']
nuevo = Paciente(nombre,apellido,user,contraseña,fecha,telefono,genero,compra)
Pacientes.append(nuevo)
mensaje={'Mensaje':'Se añadió el usuario'}
return jsonify(mensaje)
@app.route('/Pacientes/<string:nombre>', methods=['PUT'])
def ActualizarPaciente(nombre):
global Pacientes
for i in range(len(Pacientes)):
if nombre == Pacientes[i].getUser():
Pacientes[i].setNombre(request.json['Nombre'])
Pacientes[i].setApellido(request.json['Apellido'])
Pacientes[i].setUser(request.json['User'])
Pacientes[i].setContraseña(request.json['Contraseña'])
Pacientes[i].setFecha(request.json['Fecha'])
Pacientes[i].setTelefono(request.json['Teléfono'])
Pacientes[i].setGenero(request.json['Género'])
return jsonify({'Mensaje':'Se actualizo el dato exitosamente'})
return jsonify({'Mensaje':'No se encontro el dato para actualizar'})
@app.route('/Pacientes/<string:nombre>', methods=['DELETE'])
def EliminarPaciente(nombre):
global Pacientes
for i in range(len(Pacientes)):
if nombre == Pacientes[i].getUser():
del Pacientes[i]
return jsonify({'Mensaje':'Se elimino el dato exitosamente'})
return jsonify({'Mensaje':'No se encontro el dato para eliminar'})
#METODOS PARA MEDICINA
@app.route('/Medicinas', methods=['GET'])
def getMedicinas():
global Medicinas
Datos = []
for medicina in Medicinas:
objeto = {
'Nombre': medicina.getNombre(),
'Precio': medicina.getPrecio(),
'Descripción': medicina.getDescripicion(),
'Cantidad' : medicina.getCantidad(),
'Id':medicina.getIdmed()
}
Datos.append(objeto)
return(jsonify(Datos))
@app.route('/Medicinas', methods=['POST'])
def AgregarMedicina():
global CantInicial
global Medicinas
global idMed
nombre = request.json['Nombre']
precio = float(request.json['Precio'])
descripcion = request.json['Descripción']
cantidad = request.json['Cantidad']
nuevo = Medicina(nombre,precio,descripcion,cantidad,idMed,0)
Medicinas.append(nuevo)
CantInicial.append(cantidad)
idMed+=1
return jsonify({'Mensaje':'Se añadió el medicamento'})
@app.route('/Medicinas/<int:nombre>', methods=['GET'])
def ObtenerMedicina(nombre):
global Medicinas
for medicina in Medicinas:
if medicina.getIdmed() == nombre:
objeto = {
'Nombre': medicina.getNombre(),
'Precio': medicina.getPrecio(),
'Descripción': medicina.getDescripicion(),
'Cantidad' : medicina.getCantidad()
}
return(jsonify(objeto))
salida = { "Mensaje": "No existe el usuario con ese nombre"}
return(jsonify(salida))
@app.route('/Medicinas/<int:nombre>', methods=['PUT'])
def ActualizarMedicina(nombre):
global Medicinas
for i in range(len(Medicinas)):
if nombre == Medicinas[i].getIdmed():
Medicinas[i].setNombre(request.json['Nombre'])
Medicinas[i].setPrecio(request.json['Precio'])
Medicinas[i].setDescripcion(request.json['Descripción'])
Medicinas[i].setCantidad(request.json['Cantidad'])
return jsonify({'Mensaje':'Se actualizo el dato exitosamente'})
return jsonify({'Mensaje':'No se encontro el dato para actualizar'})
@app.route('/Medicinas/<int:nombre>', methods=['DELETE'])
def EliminarMedicina(nombre):
global Medicinas
for i in range(len(Medicinas)):
if nombre == Medicinas[i].getIdmed():
del Medicinas[i]
return jsonify({'Mensaje':'Se elimino el dato exitosamente'})
return jsonify({'Mensaje':'No se encontro el dato para eliminar'})
#CITAS
@app.route('/Citas/<string:nombre>', methods=['GET'])
def getCitas(nombre):
global Citas
global idCitas
global Doctores
for cita in Citas:
if cita.getIdPaciente() == nombre and (cita.getEstado()=='Pendiente' or cita.getEstado()=='Aceptada' or cita.getEstado()=='Rechazada'):
auxDoc=cita.getIdDoctor()
for doc in Doctores:
if doc.getUser() == auxDoc:
auxDoc=doc.getNombre()+" "+doc.getApellido()
objeto = {
'Motivo': cita.getMotivo(),
'Fecha': cita.getFecha(),
'Hora': cita.getHora(),
'Doctor':auxDoc,
'Estado' : cita.getEstado(),
'IdCita' : cita.getIdCita()
}
return(jsonify(objeto))
salida = { "Mensaje": "No existe el usuario con ese nombre"}
return(jsonify(salida))
@app.route('/Citas', methods=['POST'])
def asignarCita():
global Citas
global idCitas
global Pacientes
paciente = request.json['Paciente']
fecha = request.json['Fecha']
hora = request.json['Hora']
motivo = request.json['Motivo']
doctor = "Pendiente"
estado = "Pendiente"
for aux in Pacientes:
if aux.getUser== paciente:
paciente=aux.getNombre+" "+aux.getApellido
nuevo = Cita(paciente,fecha,hora,motivo,doctor,idCitas,estado)
Citas.append(nuevo)
idCitas+=1
return jsonify({'Mensaje':'Se registró la cita'})
@app.route('/Citas', methods=['GET'])
def getCitasP():
global Citas
Datos = []
for cita in Citas:
objeto = {
'Paciente': cita.getIdPaciente(),
'Fecha': cita.getFecha(),
'Hora': cita.getHora(),
'Motivo' : cita.getMotivo(),
'Doctor': cita.getIdDoctor(),
'Id' : cita.getIdCita(),
'Estado' : cita.getEstado()
}
Datos.append(objeto)
return(jsonify(Datos))
@app.route('/Cita/<int:idcita>', methods=['PUT'])
def AprobarCita(idcita):
global Citas
for i in range(len(Citas)):
if idcita == Citas[i].getIdCita():
Citas[i].setEstado(request.json['Estado'])
Citas[i].setIdDoctor(request.json['IdDoctor'])
return jsonify({'Mensaje':'Se agendo la cita exitosamente'})
return jsonify({'Mensaje':'No se encontro el dato para actualizar'})
@app.route('/CitasA/<int:idcita>', methods=['PUT'])
def AprobarCitaD(idcita):
global Citas
for i in range(len(Citas)):
if idcita == Citas[i].getIdCita():
Citas[i].setEstado(request.json['Estado'])
doctor = request.json['IdDoctor']
Cita_atendida(doctor)
return jsonify({'Mensaje':'Se agendo la cita exitosamente'})
return jsonify({'Mensaje':'No se encontro el dato para actualizar'})
def Cita_atendida(IdDoctor):
global Doctores
for doctor in Doctores:
if doctor.getUser == IdDoctor:
doctor.setAtendidas(doctor.getAtendidas()+1)
@app.route('/CitasA', methods=['GET'])
def getCitasAprobadas():
global Citas
global idCitas
global Doctores
Datos=[]
for cita in Citas:
print("estoy en el for de citas")
auxDoc=cita.getIdDoctor()
for doc in Doctores:
if doc.getUser() == auxDoc:
auxDoc=doc.getNombre()+" "+doc.getApellido()
objeto = {
'Motivo': cita.getMotivo(),
'Fecha': cita.getFecha(),
'Hora': cita.getHora(),
'Doctor':auxDoc,
'Estado' : cita.getEstado()
}
Datos.append(objeto)
return(jsonify(Datos))
@app.route('/CitasA/<string:nombre>', methods=['GET'])
def getCitasPorDoc(nombre):
global Citas
global idCitas
global Doctores
Datos=[]
for cita in Citas:
if cita.getIdDoctor() == nombre:
objeto = {
'Motivo': cita.getMotivo(),
'Fecha': cita.getFecha(),
'Hora': cita.getHora(),
'Doctor': cita.getIdDoctor(),
'Estado' : cita.getEstado(),
'Id': cita.getIdCita()
}
Datos.append(objeto)
return(jsonify(Datos))
@app.route('/Cita/<int:idcita>', methods=['DELETE'])
def EliminarCita(idcita):
global Citas
for i in range(len(Citas)):
if idcita == Citas[i].getIdCita():
del Citas[i]
return jsonify({'Mensaje':'Se eliminó la cita rechazada'})
return jsonify({'Mensaje':'No se encontro el dato para actualizar'})
#carrito
@app.route('/Carrito/<string:nombre>', methods=['GET'])
def getCompra(nombre):
global Pacientes
for paciente in Pacientes:
if paciente.getUser() == nombre:
carrito = paciente.getCarrito()
obj = {
'Nombre':paciente.getNombre()+" "+paciente.getApellido(),
'Carrito': carrito
}
return(jsonify(obj))
salida = { "Mensaje": "No existe el usuario con ese nombre"}
return(jsonify(salida))
@app.route('/Carrito/<int:ide>', methods=['GET'])
def AgregarAlCarrito(ide):
global Medicinas
for medicina in Medicinas:
if medicina.getIdmed() == ide:
objeto = {
'Nombre': medicina.getNombre(),
'Descripción': medicina.getDescripicion(),
'Precio': medicina.getPrecio(),
'Cantidad' : 1,
'Id': medicina.getIdmed()
}
return(jsonify(objeto))
salida = { "Mensaje": "No existe medicamento"}
return(jsonify(salida))
@app.route('/Carrito/<string:nombre>', methods=['POST'])
def guardarCarrito(nombre):
global Pacientes
for i in range(len(Pacientes)):
if nombre == Pacientes[i].getUser():
Pacientes[i].getCarrito().append(request.json['Carrito'])
print(Pacientes[i].getCarrito())
return jsonify({'Mensaje':'Se actualizo el dato exitosamente'})
return jsonify({'Mensaje':'No se encontro el dato para actualizar'})
@app.route('/Carrito/<int:nombre>', methods=['PUT'])
def ActualizarMedicinaMas(nombre):
global Medicinas
for i in range(len(Medicinas)):
Ncantidad=0
if nombre == Medicinas[i].getIdmed():
cantidad = request.json['Cantidad']
print(1+cantidad)
cant=int(Medicinas[i].getCantidad())
Ncantidad = float(cant+1)
Medicinas[i].setCantidad(Ncantidad)
return jsonify({'Mensaje':'Se actualizo el dato exitosamente'})
return jsonify({'Mensaje':'No se encontro el dato para actualizar'})
@app.route('/Carritos/<int:nombre>', methods=['PUT'])
def ActualizarMedicinaMenos(nombre):
global Medicinas
for i in range(len(Medicinas)):
Ncantidad=0
if nombre == Medicinas[i].getIdmed():
cantidad = request.json['Cantidad']
print(1+cantidad)
cant=int(Medicinas[i].getCantidad())
print(cant)
Ncantidad=float(cant-1)
Medicinas[i].setCantidad(Ncantidad)
return jsonify({'Mensaje':'Se actualizo el dato exitosamente'})
return jsonify({'Mensaje':'No se encontro el dato para actualizar'})
#ADMIN
@app.route('/Admin', methods=['GET'])
def ObtenerAdmin():
global Admin
objeto = {
'Nombre': Admin.getNombre(),
'Apellido': Admin.getApellido(),
'User': Admin.getUser(),
'Contraseña' : Admin.getContraseña()
}
return(jsonify(objeto))
if __name__ == "__main__":
app.run(host="0.0.0.0", port=3000, debug=True)
<file_sep>class Administrador:
# NUESTRO NUEVO CONSTRUCTO
def __init__(self,nombre,apellido,user,contraseña):
self.nombre = nombre
self.apellido = apellido
self.user = user
self.contraseña = contraseña
# METODOS GET
def getNombre(self):
return self.nombre
def getApellido(self):
return self.apellido
def getUser(self):
return self.user
def getContraseña(self):
return self.contraseña
# METODOS SET
def setNombre(self, nombre):
self.nombre = nombre
def setApellido(self, apellido):
self.apellido = apellido
def setUser(self, user):
self.user = user
def setContraseña(self,contraseña):
self.contraseña = contraseña
| 6ae23f7c0d6ff78b1fdd4f652ca66e3cfb9da060 | [
"Markdown",
"Python",
"Text"
] | 9 | Markdown | Henry2311/Backend_Project2_IPC1 | c62aec77c45fea9c9fee5ec5d5e5e395c98bf847 | b92aa4737b885900abbc51c7370ff05f3d4338c4 |
refs/heads/master | <file_sep>var User = require('../models/user');
var config = require('../../config/config');
module.exports = function(app, express, passport){
var api = express.Router();
api.get('/auth/twitter', passport.authenticate('twitter'));
api.get('/auth/twitter/callback',
passport.authenticate('twitter', {
successRedirect: '/home',
failureRedirect: '/login'
}), function(req, res){
console.log(req.user);
}
);
return api;
};<file_sep>var TwitterStrategy = require('passport-twitter').Strategy;
var User = require('../app/models/user');
module.exports = function(passport){
// used to serialize the user for the session
passport.serializeUser(function(user, done) {
done(null, user._id);
});
// used to deserialize the user
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
done(err, user);
});
});
passport.use(new TwitterStrategy({
consumerKey: "cEwhmBYgRsMZIwqETtoAY1XlZ",
consumerSecret: "<KEY>",
callbackURL: "http://127.0.0.1:8080/api/auth/twitter/callback"
},
function(token, tokenSecret, profile, done) {
console.log('helllllllllllllll', profile);
process.nextTick(function() {
User.findOne({"user_id": profile.id}, function(err, user) {
if(err) {
return done(err);
}
if(user){
return done(null, user);
}
else{
var newUser = new User();
newUser.user_id = profile.id;
newUser.username = profile.username;
newUser.display_name = profile.displayName;
newUser.token = token;
newUser.save(function(err){
if(err)
throw err;
return done(null, newUser);
});
}
});
});
}));
} | 47e2441002f5109f8ecf270823f786ac2e87fe71 | [
"JavaScript"
] | 2 | JavaScript | shaktimaan30/tweet | 97fb3af4b0da70db335c9217c1c48976740519ce | 06c3f1fe6bd8684d7b610c35dcf6d08a524dbcb4 |
refs/heads/master | <file_sep><?php
use yii\widgets\LinkPager;
/*
* 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.
*/
?>
<!-- Main Wrapper -->
<div id="main-wrapper">
<div class="wrapper style3">
<div class="inner">
<div class="container">
<div class="row">
<div class="8u 12u(mobile)">
<!-- Article list -->
<section class="box article-list">
<h2 class="icon fa-file-text-o">Статьи (Обычная постраничная навигация)</h2>
<!-- Excerpt -->
<?php foreach ($models as $Item):?>
<article class="box excerpt">
<a href="#" class="image left"><img src="images/pic04.jpg" alt="" /></a>
<div>
<header>
<span class="date"><?php echo $Item->date_create;?></span>
<h3><a href="#"><?php echo $Item->title;?></a></h3>
</header>
<p><?php echo $Item->preview_text;?></p>
</div>
</article>
<?php endforeach;?>
</section>
</div>
<div class="4u 12u(mobile)">
<!-- Spotlight -->
<section class="box spotlight">
<h2 class="icon fa-file-text-o">Spotlight</h2>
<article>
<a href="#" class="image featured"><img src="images/pic07.jpg" alt=""></a>
<header>
<h3><a href="#">Neural Implants</a></h3>
<p>The pros and cons. Mostly cons.</p>
</header>
<p>Phasellus quam turpis, feugiat sit amet ornare in, hendrerit in lectus semper mod
quisturpis nisi consequat ornare in, hendrerit in lectus semper mod quis eget mi quat etiam
lorem. Phasellus quam turpis, feugiat sed et lorem ipsum dolor consequat dolor feugiat sed
et tempus consequat etiam.</p>
<p>Lorem ipsum dolor quam turpis, feugiat sit amet ornare in, hendrerit in lectus semper
mod quisturpis nisi consequat etiam lorem sed amet quam turpis.</p>
<footer>
<a href="#" class="button alt icon fa-file-o">Continue Reading</a>
</footer>
</article>
</section>
</div>
</div>
<?php
echo LinkPager::widget([
'pagination' => $pages,
'nextPageLabel' => 'Туды',
'prevPageLabel' => 'Сюды',
'nextPageCssClass' => 'css-class',
'prevPageCssClass' => 'css-class', // все опции сво-ва класса Class yii\widgets\LinkPager
//'options' => [
//'id' => '1245',
//],
]);
?>
</div>
</div>
</div>
</div>
<file_sep><?php
namespace frontend\models;
use Yii;
/**
* This is the model class for table "articles".
*
* @property integer $id
* @property string $title
* @property string $keywords
* @property string $description
* @property string $preview_text
* @property string $preview_picture
* @property string $detail_text
* @property string $detatil_picture
* @property string $date_create
* @property integer $activate
*/
class Articles extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'articles';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['title', 'keywords', 'description', 'preview_text', 'preview_picture', 'detail_text', 'detatil_picture', 'date_create', 'activate'], 'required'],
[['description', 'preview_text', 'detail_text'], 'string'],
[['date_create'], 'safe'],
[['activate'], 'integer'],
[['title', 'preview_picture', 'detatil_picture'], 'string', 'max' => 155],
[['keywords'], 'string', 'max' => 255],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'title' => 'Title',
'keywords' => 'Keywords',
'description' => 'Description',
'preview_text' => 'Preview Text',
'preview_picture' => 'Preview Picture',
'detail_text' => 'Detail Text',
'detatil_picture' => 'Detatil Picture',
'date_create' => 'Date Create',
'activate' => 'Activate',
];
}
}
<file_sep><?php
namespace frontend\controllers;
use Yii;
use frontend\models\Articles;
use yii\data\Pagination;
use yii\data\SqlDataProvider;
class BlogController extends \yii\web\Controller
{
public function actionIndex()
{
// выполняем запрос
$query = Articles::find()->where(['activate' => 1]);
// делаем копию выборки
$countQuery = clone $query;
// подключаем класс Pagination, выводим по 10 пунктов на страницу
$pages = new Pagination(['totalCount' => $countQuery->count(), 'pageSize' => 1]);
// приводим параметры в ссылке к ЧПУ
$pages->pageSizeParam = false;
$models = $query->offset($pages->offset)
->limit($pages->limit)
->all();
$modelArticles = Articles::find()->all();
return $this->render('index', [
//'modelArticles' => $modelArticles],
'models' => $models,
'pages' => $pages,
]);
}
public function actionAjaxpagination()
{
// подсчитываем общее количество пунктов
$totalCount = Yii::$app->db->createCommand('SELECT COUNT(*) FROM articles Where activate=:status', [':status' => 1])->queryScalar();
// выполняем запрос
$sql = 'SELECT COUNT(*) FROM articles Where activate=:status';
$dataProvider = new SqlDataProvider([
'sql' => $sql,
'params' => [':status' => 1],
'totalCount' => (int)$totalCount,
'pagination' => [
// количество пунктов на странице
'pageSize' => 1,
]
]);
$time = date('H:i:s');
// передача данных в представление
return $this->render('ajaxpagination', ['dataProvider' => $dataProvider,'time' => $time]);
}
public function actionPermanent()
{
$modelArticles = Articles::find()->all();
return $this->render('permanent', ['modelArticles' => $modelArticles]);
}
}
<file_sep><?php
/* @var $this yii\web\View */
$this->title = 'My Yii Application';
?>
<!-- Main Wrapper -->
<div id="main-wrapper">
<div class="wrapper style1">
<div class="inner">
<!-- Feature 1 -->
<section class="container box feature1">
<div class="row">
<div class="12u">
<header class="first major">
<h2>This is an important heading</h2>
<p>And this is where we talk about why we’re <strong>pretty awesome</strong> ...</p>
</header>
</div>
</div>
<div class="row">
<div class="4u 12u(mobile)">
<section>
<a href="#" class="image featured"><img src="images/pic01.jpg" alt="" /></a>
<header class="second icon fa-user">
<h3>Here's a Heading</h3>
<p>And a subtitle</p>
</header>
</section>
</div>
<div class="4u 12u(mobile)">
<section>
<a href="#" class="image featured"><img src="images/pic02.jpg" alt="" /></a>
<header class="second icon fa-cog">
<h3>Also a Heading</h3>
<p>And another subtitle</p>
</header>
</section>
</div>
<div class="4u 12u(mobile)">
<section>
<a href="#" class="image featured"><img src="images/pic03.jpg" alt="" /></a>
<header class="second icon fa-bar-chart-o">
<h3>Another Heading</h3>
<p>And yes, a subtitle</p>
</header>
</section>
</div>
</div>
<div class="row">
<div class="12u">
<p>Phasellus quam turpis, feugiat sit amet ornare in, hendrerit in lectus. Praesent semper
bibendum ipsum, et tristique augue fringilla eu. Vivamus id risus vel dolor auctor euismod
quis eget mi. Etiam eu ante risus. Aliquam erat volutpat. Aliquam luctus mattis lectus sit
amet pulvinar. Nam nec turpis.</p>
</div>
</div>
</section>
</div>
</div>
<div class="wrapper style2">
<div class="inner">
<!-- Feature 2 -->
<section class="container box feature2">
<div class="row">
<div class="6u 12u(mobile)">
<section>
<header class="major">
<h2>And this is a subheading</h2>
<p>It’s important but clearly not *that* important</p>
</header>
<p>Phasellus quam turpis, feugiat sit amet ornare in, hendrerit in lectus.
Praesent semper mod quis eget mi. Etiam eu ante risus. Aliquam erat volutpat.
Aliquam luctus et mattis lectus sit amet pulvinar. Nam turpis nisi
consequat etiam.</p>
<footer>
<a href="#" class="button medium icon fa-arrow-circle-right">Let's do this</a>
</footer>
</section>
</div>
<div class="6u 12u(mobile)">
<section>
<header class="major">
<h2>This is also a subheading</h2>
<p>And is as unimportant as the other one</p>
</header>
<p>Phasellus quam turpis, feugiat sit amet ornare in, hendrerit in lectus.
Praesent semper mod quis eget mi. Etiam eu ante risus. Aliquam erat volutpat.
Aliquam luctus et mattis lectus sit amet pulvinar. Nam turpis nisi
consequat etiam.</p>
<footer>
<a href="#" class="button medium alt icon fa-info-circle">Wait, what?</a>
</footer>
</section>
</div>
</div>
</section>
</div>
</div>
<div class="wrapper style3">
<div class="inner">
<div class="container">
<div class="row">
<div class="8u 12u(mobile)">
<!-- Article list -->
<section class="box article-list">
<h2 class="icon fa-file-text-o">Recent Posts</h2>
<!-- Excerpt -->
<article class="box excerpt">
<a href="#" class="image left"><img src="images/pic04.jpg" alt="" /></a>
<div>
<header>
<span class="date">July 24</span>
<h3><a href="#">Repairing a hyperspace window</a></h3>
</header>
<p>Phasellus quam turpis, feugiat sit amet ornare in, hendrerit in lectus
semper mod quisturpis nisi consequat etiam lorem. Phasellus quam turpis,
feugiat et sit amet ornare in, hendrerit in lectus semper mod quis eget mi dolore.</p>
</div>
</article>
<!-- Excerpt -->
<article class="box excerpt">
<a href="#" class="image left"><img src="images/pic05.jpg" alt="" /></a>
<div>
<header>
<span class="date">July 18</span>
<h3><a href="#">Adventuring with a knee injury</a></h3>
</header>
<p>Phasellus quam turpis, feugiat sit amet ornare in, hendrerit in lectus
semper mod quisturpis nisi consequat etiam lorem. Phasellus quam turpis,
feugiat et sit amet ornare in, hendrerit in lectus semper mod quis eget mi dolore.</p>
</div>
</article>
<!-- Excerpt -->
<article class="box excerpt">
<a href="#" class="image left"><img src="images/pic06.jpg" alt="" /></a>
<div>
<header>
<span class="date">July 14</span>
<h3><a href="#">Preparing for Y2K38</a></h3>
</header>
<p>Phasellus quam turpis, feugiat sit amet ornare in, hendrerit in lectus
semper mod quisturpis nisi consequat etiam lorem. Phasellus quam turpis,
feugiat et sit amet ornare in, hendrerit in lectus semper mod quis eget mi dolore.</p>
</div>
</article>
</section>
</div>
<div class="4u 12u(mobile)">
<!-- Spotlight -->
<section class="box spotlight">
<h2 class="icon fa-file-text-o">Spotlight</h2>
<article>
<a href="#" class="image featured"><img src="images/pic07.jpg" alt=""></a>
<header>
<h3><a href="#">Neural Implants</a></h3>
<p>The pros and cons. Mostly cons.</p>
</header>
<p>Phasellus quam turpis, feugiat sit amet ornare in, hendrerit in lectus semper mod
quisturpis nisi consequat ornare in, hendrerit in lectus semper mod quis eget mi quat etiam
lorem. Phasellus quam turpis, feugiat sed et lorem ipsum dolor consequat dolor feugiat sed
et tempus consequat etiam.</p>
<p>Lorem ipsum dolor quam turpis, feugiat sit amet ornare in, hendrerit in lectus semper
mod quisturpis nisi consequat etiam lorem sed amet quam turpis.</p>
<footer>
<a href="#" class="button alt icon fa-file-o">Continue Reading</a>
</footer>
</article>
</section>
</div>
</div>
</div>
</div>
</div>
</div>
<file_sep><?php
use yii\grid\GridView;
use yii\widgets\Pjax;
use yii\helpers\Html;
/*
* 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.
*/
?>
<!-- Main Wrapper -->
<div id="main-wrapper">
<div class="wrapper style3">
<div class="inner">
<div class="container">
<div class="row">
<div class="8u 12u(mobile)">
<!-- Article list -->
<section class="box article-list">
<h2 class="icon fa-file-text-o">Статьи (Обычная постраничная навигация)</h2>
<!-- Excerpt -->
</section>
</div>
<div class="4u 12u(mobile)">
<!-- Spotlight -->
<section class="box spotlight">
<h2 class="icon fa-file-text-o">Spotlight</h2>
<article>
<a href="#" class="image featured"><img src="images/pic07.jpg" alt=""></a>
<header>
<h3><a href="#">Neural Implants</a></h3>
<p>The pros and cons. Mostly cons.</p>
</header>
<p>Phasellus quam turpis, feugiat sit amet ornare in, hendrerit in lectus semper mod
quisturpis nisi consequat ornare in, hendrerit in lectus semper mod quis eget mi quat etiam
lorem. Phasellus quam turpis, feugiat sed et lorem ipsum dolor consequat dolor feugiat sed
et tempus consequat etiam.</p>
<p>Lorem ipsum dolor quam turpis, feugiat sit amet ornare in, hendrerit in lectus semper
mod quisturpis nisi consequat etiam lorem sed amet quam turpis.</p>
<footer>
<a href="#" class="button alt icon fa-file-o">Continue Reading</a>
</footer>
</article>
</section>
</div>
</div>
<?php// var_dump(Pjax::begin())?>
<?php Pjax::begin(); ?>
<?php echo Html::a("Обновить", ['blog/ajaxpagination'], ['class' => 'btn btn-lg btn-primary']);?>
<h1>Сейчас: <?= $time ?></h1>
<?php Pjax::end(); ?>
</div>
</div>
</div>
</div>
<file_sep><?php
/* @var $this \yii\web\View */
/* @var $content string */
use yii\helpers\Html;
use yii\bootstrap\Nav;
use yii\bootstrap\NavBar;
use yii\widgets\Breadcrumbs;
use yii\widgets\Menu;
use frontend\assets\AppAsset;
use common\widgets\Alert;
AppAsset::register($this);
?>
<?php $this->beginPage() ?>
<!DOCTYPE html>
<html lang="<?= Yii::$app->language ?>">
<head>
<meta charset="<?= Yii::$app->charset ?>">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<?= Html::csrfMetaTags() ?>
<title><?= Html::encode($this->title) ?></title>
<?php $this->head() ?>
</head>
<body>
<?php $this->beginBody() ?>
<div id="page-wrapper">
<!-- Header -->
<div id="header-wrapper">
<div class="container">
<!-- Header -->
<header id="header">
<div class="inner">
<!-- Logo -->
<h1><a href="index.html" id="logo">ZeroFour</a></h1>
<!-- Nav -->
<nav id="nav">
<?php echo Menu::widget([
'items' => [
['label' => 'Home', 'url' => ['site/index']],
// 'Products' menu item will be selected as long as the route is 'product/index'
['label' => 'Blog',
'url' => ['services/index'],
'template' => '<a href="{url}" class="url-class">{label}</a>',
'items' => [
['label' => 'Blog pagination', 'url' => ['blog/index']],
['label' => 'Blog ajaxPagination', 'url' => ['blog/ajaxpagination']],
['label' => 'Blog permanentPagination', 'url' => ['blog/permanent']],
]
],
['label' => 'Blog', 'url' => ['site/blog']],
['label' => 'Schedule', 'url' => ['site/schedule']],
['label' => 'Login', 'url' => ['site/login'], 'visible' => Yii::$app->user->isGuest],
],
'encodeLabels' =>'false',
'activeCssClass'=>'current_page_item',
'firstItemCssClass'=>'fist',
'lastItemCssClass' =>'last',
]); ?>
</nav>
</div>
</header>
<!-- Banner -->
<div id="banner">
<h2><strong>ZeroFour:</strong> A free responsive site template
<br />
built on HTML5 and CSS3 by <a href="http://html5up.net">HTML5 UP</a></h2>
<p>Does this statement make you want to click the big shiny button?</p>
<a href="#" class="button big icon fa-check-circle">Yes it does</a>
</div>
</div>
</div>
<?= Breadcrumbs::widget([
'links' => isset($this->params['breadcrumbs']) ? $this->params['breadcrumbs'] : [],
]) ?>
<?= Alert::widget() ?>
<?= $content ?>
<!-- Footer Wrapper -->
<div id="footer-wrapper">
<footer id="footer" class="container">
<div class="row">
<div class="3u 12u(mobile)">
<!-- Links -->
<section>
<h2>Filler Links</h2>
<ul class="divided">
<li><a href="#">Quam turpis feugiat dolor</a></li>
<li><a href="#">Amet ornare in hendrerit </a></li>
<li><a href="#">Semper mod quisturpis nisi</a></li>
<li><a href="#">Consequat etiam phasellus</a></li>
<li><a href="#">Amet turpis, feugiat et</a></li>
<li><a href="#">Ornare hendrerit lectus</a></li>
<li><a href="#">Semper mod quis et dolore</a></li>
<li><a href="#">Amet ornare in hendrerit</a></li>
<li><a href="#">Consequat lorem phasellus</a></li>
<li><a href="#">Amet turpis, feugiat amet</a></li>
<li><a href="#">Semper mod quisturpis</a></li>
</ul>
</section>
</div>
<div class="3u 12u(mobile)">
<!-- Links -->
<section>
<h2>More Filler</h2>
<ul class="divided">
<li><a href="#">Quam turpis feugiat dolor</a></li>
<li><a href="#">Amet ornare in in lectus</a></li>
<li><a href="#">Semper mod sed tempus nisi</a></li>
<li><a href="#">Consequat etiam phasellus</a></li>
</ul>
</section>
<!-- Links -->
<section>
<h2>Even More Filler</h2>
<ul class="divided">
<li><a href="#">Quam turpis feugiat dolor</a></li>
<li><a href="#">Amet ornare hendrerit lectus</a></li>
<li><a href="#">Semper quisturpis nisi</a></li>
<li><a href="#">Consequat lorem phasellus</a></li>
</ul>
</section>
</div>
<div class="6u 12u(mobile)">
<!-- About -->
<section>
<h2><strong>ZeroFour</strong> by HTML5 UP</h2>
<p>Hi! This is <strong>ZeroFour</strong>, a free, fully responsive HTML5 site
template by <a href="http://twitter.com/ajlkn">AJ</a> for <a href="http://html5up.net/">HTML5 UP</a>.
It's <a href="http://html5up.net/license/">Creative Commons Attribution</a>
licensed so use it for any personal or commercial project (just credit us
for the design!).</p>
<a href="#" class="button alt icon fa-arrow-circle-right">Learn More</a>
</section>
<!-- Contact -->
<section>
<h2>Get in touch</h2>
<div>
<div class="row">
<div class="6u 12u(mobile)">
<dl class="contact">
<dt>Twitter</dt>
<dd><a href="#">@untitled-corp</a></dd>
<dt>Facebook</dt>
<dd><a href="#">facebook.com/untitled</a></dd>
<dt>WWW</dt>
<dd><a href="#">untitled.tld</a></dd>
<dt>Email</dt>
<dd><a href="#"><EMAIL></a></dd>
</dl>
</div>
<div class="6u 12u(mobile)">
<dl class="contact">
<dt>Address</dt>
<dd>
1234 Fictional Rd<br />
Nashville, TN 00000-0000<br />
USA
</dd>
<dt>Phone</dt>
<dd>(000) 000-0000</dd>
</dl>
</div>
</div>
</div>
</section>
</div>
</div>
<div class="row">
<div class="12u">
<div id="copyright">
<ul class="menu">
<li>© Untitled. All rights reserved</li><li>Design: <a href="http://html5up.net">HTML5 UP</a></li>
</ul>
</div>
</div>
</div>
</footer>
</div>
</div>
<!-- Scripts -->
<script src="assets/js/jquery.min.js"></script>
<script src="assets/js/jquery.dropotron.min.js"></script>
<script src="assets/js/skel.min.js"></script>
<script src="assets/js/skel-viewport.min.js"></script>
<script src="assets/js/util.js"></script>
<!--[if lte IE 8]><script src="assets/js/ie/respond.min.js"></script><![endif]-->
<script src="assets/js/main.js"></script>
<?php $this->endBody() ?>
</body>
</html>
<?php $this->endPage() ?> | ffa8449abfd2db87e21a2c8db0b9540a73c6dcac | [
"PHP"
] | 6 | PHP | denis82/advanced | 9de93796a7ffc5c84e623a84d7d90957aa7a28b1 | afb9f34c960071d7833b8d81f8dd6768e684d8cb |
refs/heads/master | <file_sep>'use strict';
const productCart = [
{ productname:'iphone-x',qty:10, price:1000 },
{ productname:'macbook pro',qty:200, price:2000},
{ productname:'iwatch',qty:100, price:550 },
{ productname:'macbook air',qty:100, price:1000},
{ productname:'iphone 8',qty:300, price:700 },
{ productname:'iphone 7',qty:100, price:550 },
{ productname:'ipad Retina',qty:20, price:1000},
{ productname:'ipad', qty:10, price:700 },
{ productname:'Magic Mouse',qty:50, price:300},
{ productname:'Magic Trackpad',qty:75, price:200}
];
function getCostOfProductForQtyGreaterThan(n) {
if (typeof n !== 'number') {
throw new Error(`${getCostOfProductForQtyGreaterThan.name}'s argumnent must be a Number`);
}
return productCart.reduce((res, item) => {
const quantity = item.qty || 0;
const price = item.price || 0;
return quantity > n ? res + price * quantity : res;
}, 0);
}
function getCostOfProduct(productName) {
if (typeof productName !== 'string') {
throw new Error(`${getCostOfProduct.name}'s argumnent must be a String`);
}
return productCart.reduce((res, item) => {
const quantity = item.qty || 0;
const price = item.price || 0;
return productName.toLowerCase() === item.productname.toLowerCase()
? res + price * quantity
: res;
}, 0);
}
module.exports = {
getCostOfProductForQtyGreaterThan,
getCostOfProduct
};
| f2b530ce2b957b6b404f0bd75f71c1a1de423413 | [
"JavaScript"
] | 1 | JavaScript | gonlliuk/cost-of-products | 89c5559889282035e4fa4b8aa14d735b0ac97e3c | 138001467352c1efa0d2bb5b720f8d16443fb3a9 |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MsgKit
{
/// <summary>
/// Set of constants - common property set ids - [MS-OXPROPS] 1.3.2
/// </summary>
public class PropertySets
{
public static Guid PS_PUBLIC_STRINGS => new Guid("00020329-0000-0000-C000-000000000046");
public static Guid PS_INTERNET_HEADERS => new Guid("00020386-0000-0000-C000-000000000046");
public static Guid PSETID_Common => new Guid("00062008-0000-0000-C000-000000000046");
public static Guid PS_MAPI => new Guid("00020328-0000-0000-C000-000000000046");
public static Guid PSETID_Task => new Guid("00062003-0000-0000-C000-000000000046");
public static Guid PSETID_Appointment => new Guid("00062002-0000-0000-C000-000000000046");
public static Guid PSETID_Meeting => new Guid("6ED8DA90-450B-101B-98DA-00AA003F1305");
}
}
<file_sep>//
// Email.cs
//
// Author: <NAME> <<EMAIL>>
//
// Copyright (c) 2015-2018 Magic-Sessions. (www.magic-sessions.com)
//
// 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.
//
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using MsgKit.Enums;
using MsgKit.Helpers;
using MsgKit.Mime.Header;
using OpenMcdf;
using MessageImportance = MsgKit.Enums.MessageImportance;
using MessagePriority = MsgKit.Enums.MessagePriority;
using Stream = System.IO.Stream;
namespace MsgKit
{
/// <summary>
/// A class used to make a new Outlook E-mail MSG file
/// </summary>
/// <remarks>
/// See https://msdn.microsoft.com/en-us/library/office/cc979231.aspx
/// </remarks>
public class Post : Message, IDisposable
{
#region Fields
/// <summary>
/// The <see cref="Regex" /> to find the prefix in a subject
/// </summary>
private static readonly Regex SubjectPrefixRegex = new Regex(@"^(\D{1,3}:\s)(.*)$");
/// <summary>
/// The E-mail <see cref="Attachments" />
/// </summary>
private Attachments _attachments;
/// <summary>
/// The subject of the E-mail
/// </summary>
private string _subject;
#endregion
#region Properties
/// <summary>
/// Returns the sender of the E-mail from the <see cref="Recipients" />
/// </summary>
public Sender Sender { get; }
/// <summary>
/// Contains the e-mail address for the messaging user represented by the <see cref="Sender"/>.
/// </summary>
/// <remarks>
/// These properties are examples of the address properties for the messaging user who is being represented by the
/// <see cref="Receiving" /> user. They must be set by the incoming transport provider, which is also responsible for
/// authorization or verification of the delegate. If no messaging user is being represented, these properties should
/// be set to the e-mail address contained in the PR_RECEIVED_BY_EMAIL_ADDRESS (PidTagReceivedByEmailAddress) property.
/// </remarks>
public Representing Representing { get; }
/// <summary>
/// Sets of Returns the name of the parent folder
/// </summary>
public string PostedTo { get; set; }
/// <summary>
/// Returns or sets the Internet Message Id
/// </summary>
/// <remarks>
/// Corresponds to the message ID field as specified in [RFC2822].<br/><br/>
/// If set then this value will be used, when not set the value will be read from the
/// <see cref="Message.TransportMessageHeaders"/> when this property is set
/// </remarks>
public string InternetMessageId { get; set; }
/// <summary>
/// Returns or set the the value of a Multipurpose Internet Mail Extensions (MIME) message's References header field
/// </summary>
/// <remarks>
/// If set then this value will be used, when not set the value will be read from the
/// <see cref="Message.TransportMessageHeaders"/> when this property is set
/// </remarks>
public string InternetReferences { get; set; }
/// <summary>
/// Returns or sets the original message's PR_INTERNET_MESSAGE_ID (PidTagInternetMessageId) property value
/// </summary>
/// <remarks>
/// If set then this value will be used, when not set the value will be read from the
/// <see cref="Message.TransportMessageHeaders"/> when this property is set
/// </remarks>
public string InReplyToId { get; set; }
/// <summary>
/// Returns <c>true</c> when the message is set as a draft message
/// </summary>
public bool Draft { get; }
/// <summary>
/// Specifies the format for an editor to use to display a message.
/// </summary>
public MessageEditorFormat MessageEditorFormat { get; set; }
#endregion
#region Constructor
/// <summary>
/// Creates this object and sets all the needed properties
/// </summary>
/// <param name="sender">The <see cref="Sender"/> of the E-mail</param>
/// <param name="subject">The subject of the E-mail</param>
/// <param name="draft">Set to <c>true</c> to save the E-mail as a draft message</param>
public Post(Sender sender,
string subject,
bool draft = false)
{
Sender = sender;
Subject = subject;
Importance = MessageImportance.IMPORTANCE_NORMAL;
IconIndex = MessageIconIndex.NewMail;
Draft = draft;
}
#endregion
#region WriteToStorage
/// <summary>
/// Writes all the properties that are part of the <see cref="Email"/> object either as <see cref="CFStorage"/>'s
/// or <see cref="CFStream"/>'s to the <see cref="CompoundFile.RootStorage"/>
/// </summary>
internal new void WriteToStorage()
{
var rootStorage = CompoundFile.RootStorage;
Class = MessageClass.IPM_Post;
base.WriteToStorage();
var attachmentCount = Attachments.Count;
TopLevelProperties.AttachmentCount = attachmentCount;
TopLevelProperties.NextAttachmentId = attachmentCount;
//TopLevelProperties.AddProperty(PropertyTags.PR_ENTRYID, Mapi.GenerateEntryId());
//TopLevelProperties.AddProperty(PropertyTags.PR_INSTANCE_KEY, Mapi.GenerateInstanceKey());
TopLevelProperties.AddProperty(PropertyTags.PR_STORE_SUPPORT_MASK, StoreSupportMaskConst.StoreSupportMask, PropertyFlags.PROPATTR_READABLE);
TopLevelProperties.AddProperty(PropertyTags.PR_STORE_UNICODE_MASK, StoreSupportMaskConst.StoreSupportMask, PropertyFlags.PROPATTR_READABLE);
TopLevelProperties.AddProperty(PropertyTags.PR_ALTERNATE_RECIPIENT_ALLOWED, true, PropertyFlags.PROPATTR_READABLE);
TopLevelProperties.AddProperty(PropertyTags.PR_HASATTACH, attachmentCount > 0);
TopLevelProperties.AddProperty(PropertyTags.PR_PARENT_DISPLAY_W, PostedTo);
if (!string.IsNullOrWhiteSpace(InternetMessageId))
TopLevelProperties.AddOrReplaceProperty(PropertyTags.PR_INTERNET_MESSAGE_ID_W, InternetMessageId);
if (!string.IsNullOrWhiteSpace(InternetReferences))
TopLevelProperties.AddOrReplaceProperty(PropertyTags.PR_INTERNET_REFERENCES_W, InternetReferences);
if (!string.IsNullOrWhiteSpace(InReplyToId))
TopLevelProperties.AddOrReplaceProperty(PropertyTags.PR_IN_REPLY_TO_ID_W, InReplyToId);
var messageFlags = MessageFlags.MSGFLAG_UNMODIFIED;
if (attachmentCount > 0)
messageFlags |= MessageFlags.MSGFLAG_HASATTACH;
TopLevelProperties.AddProperty(PropertyTags.PR_INTERNET_CPID, Encoding.UTF8.CodePage);
if (MessageEditorFormat != MessageEditorFormat.EDITOR_FORMAT_DONTKNOW)
TopLevelProperties.AddProperty(PropertyTags.PR_MSG_EDITOR_FORMAT, MessageEditorFormat);
if (!SentOn.HasValue)
SentOn = DateTime.UtcNow;
TopLevelProperties.AddProperty(PropertyTags.PR_ACCESS, MapiAccess.MAPI_ACCESS_DELETE | MapiAccess.MAPI_ACCESS_MODIFY | MapiAccess.MAPI_ACCESS_READ);
TopLevelProperties.AddProperty(PropertyTags.PR_ACCESS_LEVEL, MapiAccess.MAPI_ACCESS_MODIFY);
TopLevelProperties.AddProperty(PropertyTags.PR_OBJECT_TYPE, MapiObjectType.MAPI_MESSAGE);
// http://www.meridiandiscovery.com/how-to/e-mail-conversation-index-metadata-computer-forensics/
// http://stackoverflow.com/questions/11860540/does-outlook-embed-a-messageid-or-equivalent-in-its-email-elements
//propertiesStream.AddProperty(PropertyTags.PR_CONVERSATION_INDEX, Subject);
// TODO: Change modification time when this message is opened and only modified
TopLevelProperties.AddProperty(PropertyTags.PR_PRIORITY, Priority);
if (Draft)
{
messageFlags |= MessageFlags.MSGFLAG_UNSENT;
}
IconIndex = MessageIconIndex.Post;
TopLevelProperties.AddProperty(PropertyTags.PR_MESSAGE_FLAGS, messageFlags);
Sender?.WriteProperties(TopLevelProperties);
Representing?.WriteProperties(TopLevelProperties);
}
#endregion
#region Save
/// <summary>
/// Saves the message to the given <paramref name="stream" />
/// </summary>
/// <param name="stream"></param>
public new void Save(Stream stream)
{
WriteToStorage();
base.Save(stream);
}
/// <summary>
/// Saves the message to the given <paramref name="fileName" />
/// </summary>
/// <param name="fileName"></param>
public new void Save(string fileName)
{
WriteToStorage();
base.Save(fileName);
}
#endregion
#region Dispose
/// <summary>
/// Disposes all the attachment streams
/// </summary>
public new void Dispose()
{
foreach (var attachment in _attachments)
attachment.Stream.Dispose();
base.Dispose();
}
#endregion
}
}<file_sep>//
// Email.cs
//
// Author: <NAME> <<EMAIL>>
//
// Copyright (c) 2015-2018 Magic-Sessions. (www.magic-sessions.com)
//
// 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.
//
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using MsgKit.Enums;
using MsgKit.Helpers;
using MsgKit.Mime.Header;
using OpenMcdf;
using MessageImportance = MsgKit.Enums.MessageImportance;
using MessagePriority = MsgKit.Enums.MessagePriority;
using Stream = System.IO.Stream;
namespace MsgKit
{
/// <summary>
/// A class used to make a new Outlook E-mail MSG file
/// </summary>
/// <remarks>
/// See https://msdn.microsoft.com/en-us/library/office/cc979231.aspx
/// </remarks>
public class Email : Message, IDisposable
{
#region Fields
/// <summary>
/// The E-mail <see cref="Recipients" />
/// </summary>
private Recipients _recipients;
#endregion
#region Properties
/// <summary>
/// Returns the sender of the E-mail from the <see cref="Recipients" />
/// </summary>
public Sender Sender { get; }
/// <summary>
/// Contains the e-mail address for the messaging user represented by the <see cref="Sender"/>.
/// </summary>
/// <remarks>
/// These properties are examples of the address properties for the messaging user who is being represented by the
/// <see cref="Receiving" /> user. They must be set by the incoming transport provider, which is also responsible for
/// authorization or verification of the delegate. If no messaging user is being represented, these properties should
/// be set to the e-mail address contained in the PR_RECEIVED_BY_EMAIL_ADDRESS (PidTagReceivedByEmailAddress) property.
/// </remarks>
public Representing Representing { get; set; }
/// <summary>
/// Returns the E-mail <see cref="Recipients" />
/// </summary>
public Recipients Recipients
{
get { return _recipients ?? (_recipients = new Recipients()); }
}
/// <summary>
/// Contains the e-mail address for the messaging user who receives the message.
/// </summary>
/// <remarks>
/// These properties are examples of the address properties for the messaging user who receives the message. They must
/// be set by the incoming transport provider.
/// </remarks>
public Receiving Receiving { get; set; }
/// <summary>
/// Contains the e-mail address for the messaging user who is represented by the <see cref="Receiving"/> user.
/// </summary>
/// <remarks>
/// These properties are examples of the address properties for the messaging user who is being represented by the
/// <see cref="Receiving" /> user. They must be set by the incoming transport provider, which is also responsible for
/// authorization or verification of the delegate. If no messaging user is being represented, these properties should
/// be set to the e-mail address contained in the PR_RECEIVED_BY_EMAIL_ADDRESS (PidTagReceivedByEmailAddress) property.
/// </remarks>
public ReceivingRepresenting ReceivingRepresenting { get; set; }
/// <summary>
/// Returns the UTC date and time when the <see cref="Message"/> was received
/// </summary>
/// <remarks>
/// This property has to be set to UTC datetime
/// </remarks>
public DateTime? ReceivedOn { get; set; }
/// <summary>
/// Returns or sets the Internet Message Id
/// </summary>
/// <remarks>
/// Corresponds to the message ID field as specified in [RFC2822].<br/><br/>
/// If set then this value will be used, when not set the value will be read from the
/// <see cref="Message.TransportMessageHeaders"/> when this property is set
/// </remarks>
public string InternetMessageId { get; set; }
/// <summary>
/// Returns or set the the value of a Multipurpose Internet Mail Extensions (MIME) message's References header field
/// </summary>
/// <remarks>
/// If set then this value will be used, when not set the value will be read from the
/// <see cref="Message.TransportMessageHeaders"/> when this property is set
/// </remarks>
public string InternetReferences { get; set; }
/// <summary>
/// Returns or sets the original message's PR_INTERNET_MESSAGE_ID (PidTagInternetMessageId) property value
/// </summary>
/// <remarks>
/// If set then this value will be used, when not set the value will be read from the
/// <see cref="Message.TransportMessageHeaders"/> when this property is set
/// </remarks>
public string InReplyToId { get; set; }
/// <summary>
/// Returns <c>true</c> when the message is set as a draft message
/// </summary>
public bool Draft { get; }
/// <summary>
/// Specifies the format for an editor to use to display a message.
/// </summary>
public MessageEditorFormat MessageEditorFormat { get; set; }
#endregion
#region Constructor
/// <summary>
/// Creates this object and sets all the needed properties
/// </summary>
/// <param name="sender">The <see cref="Sender"/> of the E-mail</param>
/// <param name="subject">The subject of the E-mail</param>
/// <param name="draft">Set to <c>true</c> to save the E-mail as a draft message</param>
public Email(Sender sender,
string subject,
bool draft = false)
{
Sender = sender;
Subject = subject;
IconIndex = MessageIconIndex.NewMail;
Draft = draft;
}
/// <summary>
/// Creates this object and sets all the needed properties
/// </summary>
/// <param name="sender">The <see cref="Sender"/> of the E-mail</param>
/// <param name="representing">The <see cref="MsgKit.Representing"/> sender of the E-mail</param>
/// <param name="subject">The subject of the E-mail</param>
/// <param name="draft">Set to <c>true</c> to save the E-mail as a draft message</param>
public Email(Sender sender,
Representing representing,
string subject,
bool draft = false)
{
Sender = sender;
Representing = representing;
Subject = subject;
IconIndex = MessageIconIndex.NewMail;
Draft = draft;
}
#endregion
#region WriteToStorage
/// <summary>
/// Writes all the properties that are part of the <see cref="Email"/> object either as <see cref="CFStorage"/>'s
/// or <see cref="CFStream"/>'s to the <see cref="CompoundFile.RootStorage"/>
/// </summary>
internal new void WriteToStorage()
{
base.WriteToStorage();
TopLevelProperties.AddProperty(PropertyTags.PR_STORE_SUPPORT_MASK, StoreSupportMaskConst.StoreSupportMask, PropertyFlags.PROPATTR_READABLE);
var rootStorage = CompoundFile.RootStorage;
Class = MessageClass.IPM_Note;
MessageSize += Recipients.WriteToStorage(rootStorage);
var recipientCount = Recipients.Count;
TopLevelProperties.RecipientCount = recipientCount;
TopLevelProperties.NextRecipientId = recipientCount;
//TopLevelProperties.AddProperty(PropertyTags.PR_ENTRYID, Mapi.GenerateEntryId());
//TopLevelProperties.AddProperty(PropertyTags.PR_INSTANCE_KEY, Mapi.GenerateInstanceKey());
TopLevelProperties.AddProperty(PropertyTags.PR_STORE_UNICODE_MASK, StoreSupportMaskConst.StoreSupportMask, PropertyFlags.PROPATTR_READABLE);
TopLevelProperties.AddProperty(PropertyTags.PR_ALTERNATE_RECIPIENT_ALLOWED, true, PropertyFlags.PROPATTR_READABLE);
if (!string.IsNullOrWhiteSpace(InternetMessageId))
TopLevelProperties.AddOrReplaceProperty(PropertyTags.PR_INTERNET_MESSAGE_ID_W, InternetMessageId);
if (!string.IsNullOrWhiteSpace(InternetReferences))
TopLevelProperties.AddOrReplaceProperty(PropertyTags.PR_INTERNET_REFERENCES_W, InternetReferences);
if (!string.IsNullOrWhiteSpace(InReplyToId))
TopLevelProperties.AddOrReplaceProperty(PropertyTags.PR_IN_REPLY_TO_ID_W, InReplyToId);
_messageFlags = MessageFlags.MSGFLAG_UNMODIFIED;
TopLevelProperties.AddProperty(PropertyTags.PR_INTERNET_CPID, Encoding.UTF8.CodePage);
if (MessageEditorFormat != MessageEditorFormat.EDITOR_FORMAT_DONTKNOW)
TopLevelProperties.AddProperty(PropertyTags.PR_MSG_EDITOR_FORMAT, MessageEditorFormat);
if (ReceivedOn.HasValue)
{
TopLevelProperties.AddProperty(PropertyTags.PR_MESSAGE_DELIVERY_TIME, ReceivedOn.Value.ToUniversalTime());
TopLevelProperties.AddProperty(PropertyTags.PR_DELIVER_TIME, ReceivedOn.Value.ToUniversalTime());
TopLevelProperties.AddProperty(PropertyTags.PR_LATEST_DELIVERY_TIME, ReceivedOn.Value.ToUniversalTime());
TopLevelProperties.AddProperty(PropertyTags.PR_RECEIPT_TIME, ReceivedOn.Value.ToUniversalTime());
}
TopLevelProperties.AddProperty(PropertyTags.PR_ACCESS, MapiAccess.MAPI_ACCESS_DELETE | MapiAccess.MAPI_ACCESS_MODIFY | MapiAccess.MAPI_ACCESS_READ);
TopLevelProperties.AddProperty(PropertyTags.PR_ACCESS_LEVEL, MapiAccess.MAPI_ACCESS_MODIFY);
TopLevelProperties.AddProperty(PropertyTags.PR_OBJECT_TYPE, MapiObjectType.MAPI_MESSAGE);
// http://www.meridiandiscovery.com/how-to/e-mail-conversation-index-metadata-computer-forensics/
// http://stackoverflow.com/questions/11860540/does-outlook-embed-a-messageid-or-equivalent-in-its-email-elements
//propertiesStream.AddProperty(PropertyTags.PR_CONVERSATION_INDEX, Subject);
// TODO: Change modification time when this message is opened and only modified
var utcNow = DateTime.UtcNow;
if (Draft)
{
_messageFlags |= MessageFlags.MSGFLAG_UNSENT;
IconIndex = MessageIconIndex.UnsentMail;
}
TopLevelProperties.AddProperty(PropertyTags.PR_MESSAGE_FLAGS, _messageFlags);
Sender?.WriteProperties(TopLevelProperties);
Receiving?.WriteProperties(TopLevelProperties);
Representing?.WriteProperties(TopLevelProperties);
ReceivingRepresenting?.WriteProperties(TopLevelProperties);
if (recipientCount > 0)
{
var displayTo = new List<string>();
var displayCc = new List<string>();
var displayBcc = new List<string>();
foreach (var recipient in Recipients)
{
switch (recipient.RecipientType)
{
case RecipientType.To:
if (!string.IsNullOrWhiteSpace(recipient.DisplayName))
displayTo.Add(recipient.DisplayName);
else if (!string.IsNullOrWhiteSpace(recipient.Email))
displayTo.Add(recipient.Email);
break;
case RecipientType.Cc:
if (!string.IsNullOrWhiteSpace(recipient.DisplayName))
displayCc.Add(recipient.DisplayName);
else if (!string.IsNullOrWhiteSpace(recipient.Email))
displayCc.Add(recipient.Email);
break;
case RecipientType.Bcc:
if (!string.IsNullOrWhiteSpace(recipient.DisplayName))
displayBcc.Add(recipient.DisplayName);
else if (!string.IsNullOrWhiteSpace(recipient.Email))
displayBcc.Add(recipient.Email);
break;
default:
throw new ArgumentOutOfRangeException();
}
}
TopLevelProperties.AddProperty(PropertyTags.PR_DISPLAY_TO_W, string.Join(";", displayTo), PropertyFlags.PROPATTR_READABLE);
TopLevelProperties.AddProperty(PropertyTags.PR_DISPLAY_CC_W, string.Join(";", displayCc), PropertyFlags.PROPATTR_READABLE);
TopLevelProperties.AddProperty(PropertyTags.PR_DISPLAY_BCC_W, string.Join(";", displayBcc), PropertyFlags.PROPATTR_READABLE);
AddExtendedProperties();
}
}
private void SetIcon()
{
}
#endregion
#region Save
/// <summary>
/// Saves the message to the given <paramref name="stream" />
/// </summary>
/// <param name="stream"></param>
public new void Save(Stream stream)
{
WriteToStorage();
base.Save(stream);
}
/// <summary>
/// Saves the message to the given <paramref name="fileName" />
/// </summary>
/// <param name="fileName"></param>
public new void Save(string fileName)
{
WriteToStorage();
base.Save(fileName);
}
#endregion
#region Dispose
/// <summary>
/// Disposes all the attachment streams
/// </summary>
public new void Dispose()
{
base.Dispose();
}
#endregion
}
}<file_sep>//
// Conversion.cs
//
// Author: <NAME> <<EMAIL>>
//
// Copyright (c) 2015-2018 Magic-Sessions. (www.magic-sessions.com)
//
// 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.
//
using Ganss.XSS;
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
namespace MsgKit.Helpers
{
/// <summary>
/// This class contains conversion related helper methods
/// </summary>
internal static class Conversion
{
#region ObjectToByteArray
/// <summary>
/// Converts an object to an byte array
/// </summary>
/// <param name="obj">The object to convert</param>
/// <returns></returns>
public static byte[] ObjectToByteArray(Object obj)
{
if (obj == null)
return null;
var binaryFormatter = new BinaryFormatter();
using (var memoryStream = new MemoryStream())
{
binaryFormatter.Serialize(memoryStream, obj);
return memoryStream.ToArray();
}
}
#endregion
#region ByteArrayToObject
/// <summary>
/// Converts a byte array to an Object
/// </summary>
/// <param name="array">The byte array</param>
/// <returns></returns>
public static Object ByteArrayToObject(byte[] array)
{
using (var memmoryStream = new MemoryStream())
{
var binaryFormatter = new BinaryFormatter();
memmoryStream.Write(array, 0, array.Length);
memmoryStream.Seek(0, SeekOrigin.Begin);
return binaryFormatter.Deserialize(memmoryStream);
}
}
#endregion
internal static string PlainTextToHtml(this string plainText) =>
plainText == null ? null :
$@"<!DOCTYPE HTML PUBLIC "" -//W3C//DTD HTML 3.2//EN"">
<HTML>
<HEAD>
<META HTTP-EQUIV=""Content-Type"" CONTENT=""text/html; charset=us-ascii"">
<META NAME=""Generator"" CONTENT=""MsgKit"">
<TITLE>Plain Text</TITLE>
</HEAD>
<BODY>
<!-- Converted from text/plain format -->
<P><FONT SIZE = 2 >{InnerToHtml(plainText)}<BR>
</FONT>
</P>
</BODY>
</HTML> ";
private static string InnerToHtml(string text)
{
text = text
.Replace("&", " &")
.Replace(" ", " ")
.Replace("<", " <")
.Replace(">", ">")
.Replace("'", "'")
.Replace("\"", """)
.Replace("\r\n", "\r")
.Replace("\n", "\r")
.Replace("\r", "<br>\r\n");
return new HtmlSanitizer().Sanitize(text);
}
}
}
<file_sep>//
// Message.cs
//
// Author: <NAME> <<EMAIL>>
//
// Copyright (c) 2015-2018 Magic-Sessions. (www.magic-sessions.com)
//
// 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.
//
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using MsgKit.Enums;
using MsgKit.Helpers;
using MsgKit.Streams;
using OpenMcdf;
using System.Collections.Generic;
using System.Globalization;
using MsgKit.Mime.Header;
// ReSharper disable InconsistentNaming
namespace MsgKit
{
/// <summary>
/// The base class for all the different types of Outlook MSG files
/// </summary>
public class Message : IDisposable
{
# region Fields
/// <summary>
/// The subject of the E-mail
/// </summary>
private string _subject;
/// <summary>
/// The <see cref="Regex" /> to find the prefix in a subject
/// </summary>
private static readonly Regex SubjectPrefixRegex = new Regex(@"^(\D{1,3}:\s)(.*)$");
/// <summary>
/// The E-mail <see cref="Attachments" />
/// </summary>
private Attachments _attachments;
/// <summary>
/// The <see cref="MessageFlags" />
/// </summary>
protected MessageFlags _messageFlags;
#endregion
#region Properties
/// <summary>
/// The <see cref="CompoundFile" />
/// </summary>
internal CompoundFile CompoundFile { get; }
/// <summary>
/// The <see cref="MessageClass"/>
/// </summary>
internal MessageClass Class;
/// <summary>
/// The E-mail <see cref="Attachments" />
/// </summary>
public Attachments Attachments
{
get { return _attachments ?? (_attachments = new Attachments()); }
}
/// <summary>
/// Returns <see cref="Class"/> as a string that is written into the MSG file
/// </summary>
internal string ClassAsString
{
get
{
switch (Class)
{
case MessageClass.Unknown:
throw new ArgumentException("Class field is not set");
case MessageClass.IPM_Note:
return "IPM.Note";
case MessageClass.IPM_Note_SMIME:
return "IPM.Note.SMIME";
case MessageClass.IPM_Note_SMIME_MultipartSigned:
return "IPM.Note.SMIME.MultipartSigned";
case MessageClass.IPM_Note_Receipt_SMIME:
return "IPM.Note.Receipt.SMIME";
case MessageClass.IPM_Post:
return "IPM.Post";
case MessageClass.IPM_Octel_Voice:
return "IPM.Octel.Voice";
case MessageClass.IPM_Voicenotes:
return "IPM.Voicenotes";
case MessageClass.IPM_Sharing:
return "IPM.Sharing";
case MessageClass.REPORT_IPM_NOTE_NDR:
return "REPORT.IPM.NOTE.NDR";
case MessageClass.REPORT_IPM_NOTE_DR:
return "REPORT.IPM.NOTE.DR";
case MessageClass.REPORT_IPM_NOTE_DELAYED:
return "REPORT.IPM.NOTE.DELAYED";
case MessageClass.REPORT_IPM_NOTE_IPNRN:
return "*REPORT.IPM.NOTE.IPNRN";
case MessageClass.REPORT_IPM_NOTE_IPNNRN:
return "*REPORT.IPM.NOTE.IPNNRN";
case MessageClass.REPORT_IPM_SCHEDULE_MEETING_REQUEST_NDR:
return "REPORT.IPM.SCHEDULE. MEETING.REQUEST.NDR";
case MessageClass.REPORT_IPM_SCHEDULE_MEETING_RESP_POS_NDR:
return "REPORT.IPM.SCHEDULE.MEETING.RESP.POS.NDR";
case MessageClass.REPORT_IPM_SCHEDULE_MEETING_RESP_TENT_NDR:
return "REPORT.IPM.SCHEDULE.MEETING.RESP.TENT.NDR";
case MessageClass.REPORT_IPM_SCHEDULE_MEETING_CANCELED_NDR:
return "REPORT.IPM.SCHEDULE.MEETING.CANCELED.NDR";
case MessageClass.REPORT_IPM_NOTE_SMIME_NDR:
return "REPORT.IPM.NOTE.SMIME.NDR";
case MessageClass.REPORT_IPM_NOTE_SMIME_DR:
return "*REPORT.IPM.NOTE.SMIME.DR";
case MessageClass.REPORT_IPM_NOTE_SMIME_MULTIPARTSIGNED_NDR:
return "*REPORT.IPM.NOTE.SMIME.MULTIPARTSIGNED.NDR";
case MessageClass.REPORT_IPM_NOTE_SMIME_MULTIPARTSIGNED_DR:
return "*REPORT.IPM.NOTE.SMIME.MULTIPARTSIGNED.DR";
case MessageClass.IPM_Appointment:
return "IPM.Appointment";
case MessageClass.IPM_Task:
return "IPM.Task";
default:
throw new ArgumentOutOfRangeException();
}
}
}
/// <summary>
/// Contains a number that indicates which icon to use when you display a group
/// of e-mail objects. Default set to <see cref="MessageIconIndex.NewMail" />
/// </summary>
/// <remarks>
/// This property, if it exists, is a hint to the client. The client may ignore the
/// value of this property.
/// </remarks>
public MessageIconIndex IconIndex { get; set; }
/// <summary>
/// The size of the message
/// </summary>
public long MessageSize { get; internal set; }
/// <summary>
/// The <see cref="TopLevelProperties"/>
/// </summary>
internal TopLevelProperties TopLevelProperties;
/// <summary>
/// The <see cref="NamedProperties"/>
/// </summary>
internal NamedProperties NamedProperties;
/// <summary>
/// Returns or sets the UTC date and time the <see cref="Sender"/> has submitted the
/// <see cref="Message"/>
/// </summary>
/// <remarks>
/// This property has to be set to UTC datetime. When not set then the current date
/// and time is used
/// </remarks>
public DateTime? SentOn { get; set; }
/// <summary>
/// Returns or sets the UTC date and time the <see cref="Sender"/> has created the
/// <see cref="Message"/>
/// </summary>
/// <remarks>
/// This property has to be set to UTC datetime. When not set then the current date
/// and time is used
/// </remarks>
public DateTime? CreatedOn { get; set; }
/// <summary>
/// Returns or sets the UTC date and time, when the message was last modified
/// </summary>
/// <remarks>
/// This property has to be set to UTC datetime. When not set then the current date
/// and time is used
/// </remarks>
public DateTime? LastModifiedOn { get; set; }
/// <summary>
/// Name of the last user to modify the message
/// </summary>
public string LastModifiedBy { get; set; }
/// <summary>
/// Returns or sets the text body of the E-mail
/// </summary>
public string BodyText { get; set; }
/// <summary>
/// Returns or sets the html body of the E-mail
/// </summary>
public string BodyHtml { get; set; }
/// <summary>
/// The compressed RTF body part
/// </summary>
/// <remarks>
/// When not set then the RTF is generated from <see cref="BodyHtml"/> (when this property is set)
/// </remarks>
public string BodyRtf { get; set; }
/// <summary>
/// Returns or set to <c>true</c> when <see cref="BodyRtf"/> is compressed
/// </summary>
public bool BodyRtfCompressed { get; set; }
/// <summary>
/// Returns the subject prefix of the E-mail
/// </summary>
public string SubjectPrefix { get; private set; }
/// <summary>
/// Returns or sets the subject of the E-mail
/// </summary>
public string Subject
{
get { return _subject; }
set
{
_subject = value;
SetSubject();
}
}
/// <summary>
/// Returns the normalized subject of the E-mail
/// </summary>
public string SubjectNormalized { get; private set; }
/// <summary>
/// Returns or sets the the depth of the reply in a hierarchical representation of Post objects in one conversation
/// </summary>
public byte[] ConversationIndex { get; set; }
/// <summary>
/// contains an unchanging copy of the original subject.
/// </summary>
public string ConversationTopic { get; set; }
/// <summary>
/// Contains user-specifiable text to be associated with the flag.
/// </summary>
public string FlagRequest { get; set; }
/// <summary>
/// Gets or sets a valud indicating the message sender's opinion of the sensitivity of a message
/// </summary>
public long Sensitiviy { get; set; }
/// <summary>
/// Returns or sets the <see cref="Enums.MessagePriority"/>
/// </summary>
public MessagePriority Priority { get; set; }
/// <summary>
/// Returns or sets the <see cref="Enums.MessageImportance"/>
/// </summary>
public MessageImportance Importance { get; set; }
/// <summary>
/// Returns or sets keywords or categories for the Message object
/// </summary>
public string[] Keywords { get; set; }
/// <summary>
/// Returns or sets the text labels assigned to this Message object
/// </summary>
public string[] Categories { get; set; }
/// <summary>
/// Culture name, like en-gb
/// </summary>
public string Culture { get; set; }
/// <summary>
/// Other property tags, not included in normal list of properties
/// </summary>
public Dictionary<PropertyTag, object> ExtendedProperties { get; set; } = new Dictionary<PropertyTag, object>();
/// <summary>
/// Other named property tags, not included in normal list of properties
/// </summary>
public Dictionary<NamedPropertyTag, object> ExtendedNamedProperties { get; set; } = new Dictionary<NamedPropertyTag, object>();
/// <summary>
/// Sets or returns the <see cref="TransportMessageHeaders"/> property as a string (text).
/// This property expects the headers as a string
/// </summary>
public string TransportMessageHeadersText
{
set
{
TransportMessageHeaders = HeaderExtractor.GetHeaders(value);
}
get { return TransportMessageHeaders != null ? TransportMessageHeaders.ToString() : string.Empty; }
}
/// <summary>
/// Returns or sets the transport message headers. These are only present when
/// the message has been sent outside an Exchange environment to another mailserver
/// <c>null</c> will be returned when not present
/// </summary>
/// <remarks>
/// Use the <see cref="TransportMessageHeaders"/> property if you want to set
/// the headers directly from a string otherwise see the example code below.
/// </remarks>
/// <example>
/// <code>
/// var email = new Email();
/// email.TransportMessageHeaders = new MessageHeader();
/// // ... do something with it, for example
/// email.TransportMessageHeaders.SetHeaderValue("X-MY-CUSTOM-HEADER", "EXAMPLE VALUE");
/// </code>
/// </example>
public MessageHeader TransportMessageHeaders { get; set; }
#endregion
#region Constructor
/// <summary>
/// Creates this object and sets all it's properties
/// </summary>
internal Message()
{
CompoundFile = new CompoundFile();
// In the preceding figure, the "__nameid_version1.0" named property mapping storage contains the
// three streams used to provide a mapping from property ID to property name
// ("__substg1.0_00020102", "__substg1.0_00030102", and "__substg1.0_00040102") and various other
// streams that provide a mapping from property names to property IDs.
var nameIdStorage = CompoundFile.RootStorage.TryGetStorage(PropertyTags.NameIdStorage) ??
CompoundFile.RootStorage.AddStorage(PropertyTags.NameIdStorage);
var entryStream = nameIdStorage.AddStream(PropertyTags.EntryStream);
entryStream.SetData(new byte[0]);
var stringStream = nameIdStorage.AddStream(PropertyTags.StringStream);
stringStream.SetData(new byte[0]);
var guidStream = nameIdStorage.AddStream(PropertyTags.GuidStream);
guidStream.SetData(new byte[0]);
TopLevelProperties = new TopLevelProperties();
NamedProperties = new NamedProperties(TopLevelProperties);
Importance = MessageImportance.IMPORTANCE_NORMAL;
}
internal void WriteToStorage()
{
var rootStorage = CompoundFile.RootStorage;
MessageSize += Attachments.WriteToStorage(rootStorage);
var attachmentCount = Attachments.Count;
TopLevelProperties.NextAttachmentId = attachmentCount;
TopLevelProperties.AttachmentCount = attachmentCount;
TopLevelProperties.AddProperty(PropertyTags.PR_HASATTACH, attachmentCount > 0);
var messageFlags = MessageFlags.MSGFLAG_UNMODIFIED;
if (attachmentCount > 0)
messageFlags |= MessageFlags.MSGFLAG_HASATTACH;
if (!SentOn.HasValue)
SentOn = DateTime.UtcNow;
if (!CreatedOn.HasValue)
CreatedOn = DateTime.UtcNow;
if (!LastModifiedOn.HasValue)
LastModifiedOn = DateTime.UtcNow;
TopLevelProperties.AddProperty(PropertyTags.PR_CLIENT_SUBMIT_TIME, SentOn.Value.ToUniversalTime());
TopLevelProperties.AddProperty(PropertyTags.PR_ORIGINAL_SUBMIT_TIME, SentOn.Value.ToUniversalTime());
TopLevelProperties.AddProperty(PropertyTags.PR_CREATION_TIME, CreatedOn.Value.ToUniversalTime());
TopLevelProperties.AddProperty(PropertyTags.PR_LAST_MODIFICATION_TIME, LastModifiedOn.Value.ToUniversalTime());
TopLevelProperties.AddProperty(PropertyTags.PR_BODY_W, BodyText);
if(string.IsNullOrEmpty(BodyHtml))
{
BodyHtml = BodyText.PlainTextToHtml();
}
if (!string.IsNullOrEmpty(BodyHtml))
{
TopLevelProperties.AddProperty(PropertyTags.PR_HTML, BodyHtml);
TopLevelProperties.AddProperty(PropertyTags.PR_RTF_IN_SYNC, false);
}
else if (string.IsNullOrWhiteSpace(BodyRtf) && !string.IsNullOrWhiteSpace(BodyHtml))
{
BodyRtf = Strings.GetEscapedRtf(BodyHtml);
BodyRtfCompressed = true;
}
if (!string.IsNullOrWhiteSpace(BodyRtf))
{
TopLevelProperties.AddProperty(PropertyTags.PR_RTF_COMPRESSED, new RtfCompressor().Compress(Encoding.ASCII.GetBytes(BodyRtf)));
TopLevelProperties.AddProperty(PropertyTags.PR_RTF_IN_SYNC, BodyRtfCompressed);
}
SetSubject();
TopLevelProperties.AddProperty(PropertyTags.PR_SUBJECT_W, Subject);
TopLevelProperties.AddProperty(PropertyTags.PR_NORMALIZED_SUBJECT_W, SubjectNormalized);
TopLevelProperties.AddProperty(PropertyTags.PR_SUBJECT_PREFIX_W, SubjectPrefix);
TopLevelProperties.AddProperty(PropertyTags.PR_CONVERSATION_TOPIC_W, ConversationTopic);
TopLevelProperties.AddProperty(PropertyTags.PR_CONVERSATION_INDEX, ConversationIndex);
TopLevelProperties.AddProperty(PropertyTags.PR_LAST_MODIFIER_NAME_W, LastModifiedBy);
TopLevelProperties.AddProperty(PropertyTags.PR_SENSITIVITY, Sensitiviy);
TopLevelProperties.AddProperty(PropertyTags.PR_PRIORITY, Priority);
TopLevelProperties.AddProperty(PropertyTags.PR_IMPORTANCE, Importance);
TopLevelProperties.AddProperty(PropertyTags.PR_ICON_INDEX, IconIndex);
SetCulture();
if (TransportMessageHeaders != null)
{
TopLevelProperties.AddProperty(PropertyTags.PR_TRANSPORT_MESSAGE_HEADERS_W, TransportMessageHeaders.ToString());
if (!string.IsNullOrWhiteSpace(TransportMessageHeaders.MessageId))
TopLevelProperties.AddProperty(PropertyTags.PR_INTERNET_MESSAGE_ID_W, TransportMessageHeaders.MessageId);
if (TransportMessageHeaders.References.Any())
TopLevelProperties.AddProperty(PropertyTags.PR_INTERNET_REFERENCES_W, TransportMessageHeaders.References.Last());
if (TransportMessageHeaders.InReplyTo.Any())
TopLevelProperties.AddProperty(PropertyTags.PR_IN_REPLY_TO_ID_W, TransportMessageHeaders.InReplyTo.Last());
}
if (Categories != null && Categories.Any())
NamedProperties.AddProperty(NamedPropertyTags.PidNameKeywords, Categories);
if(!string.IsNullOrWhiteSpace(FlagRequest))
NamedProperties.AddProperty(NamedPropertyTags.PidLidFlagRequest, FlagRequest);
/*if (Categories != null && Categories.Any())
NamedProperties.AddProperty(NamedPropertyTags.PidLidCategories, Categories);*/
}
/// <summary>
/// Writes extended properties.... should be called after super class write.
/// </summary>
protected void AddExtendedProperties()
{
foreach (var prop in ExtendedProperties)
{
TopLevelProperties.AddProperty(prop.Key, prop.Value);
}
foreach (var prop in ExtendedNamedProperties)
{
NamedProperties.AddProperty(prop.Key, prop.Value);
}
}
#endregion
#region SetSubject
/// <summary>
/// These properties are computed by message store or transport providers from the PR_SUBJECT (PidTagSubject)
/// and PR_SUBJECT_PREFIX (PidTagSubjectPrefix) properties in the following manner. If the PR_SUBJECT_PREFIX
/// is present and is an initial substring of PR_SUBJECT, PR_NORMALIZED_SUBJECT and associated properties are
/// set to the contents of PR_SUBJECT with the prefix removed. If PR_SUBJECT_PREFIX is present, but it is not
/// an initial substring of PR_SUBJECT, PR_SUBJECT_PREFIX is deleted and recalculated from PR_SUBJECT using
/// the following rule: If the string contained in PR_SUBJECT begins with one to three non-numeric characters
/// followed by a colon and a space, then the string together with the colon and the blank becomes the prefix.
/// Numbers, blanks, and punctuation characters are not valid prefix characters. If PR_SUBJECT_PREFIX is not
/// present, it is calculated from PR_SUBJECT using the rule outlined in the previous step.This property then
/// is set to the contents of PR_SUBJECT with the prefix removed.
/// </summary>
/// <remarks>
/// When PR_SUBJECT_PREFIX is an empty string, PR_SUBJECT and PR_NORMALIZED_SUBJECT are the same. Ultimately,
/// this property should be the part of PR_SUBJECT following the prefix. If there is no prefix, this property
/// becomes the same as PR_SUBJECT.
/// </remarks>
protected void SetSubject()
{
if (!string.IsNullOrEmpty(SubjectPrefix) && !string.IsNullOrEmpty(Subject))
{
if (Subject.StartsWith(SubjectPrefix))
{
SubjectNormalized = Subject.Substring(SubjectPrefix.Length);
}
else
{
var matches = SubjectPrefixRegex.Matches(Subject);
if (matches.Count > 0)
{
SubjectPrefix = matches.OfType<Match>().First().Groups[1].Value;
SubjectNormalized = matches.OfType<Match>().First().Groups[2].Value;
}
}
}
else if (!string.IsNullOrEmpty(Subject))
{
var matches = SubjectPrefixRegex.Matches(Subject);
if (matches.Count > 0)
{
SubjectPrefix = matches.OfType<Match>().First().Groups[1].Value;
SubjectNormalized = matches.OfType<Match>().First().Groups[2].Value;
}
else
SubjectNormalized = Subject;
}
else
SubjectNormalized = Subject;
if (SubjectPrefix == null) SubjectPrefix = string.Empty;
}
internal void SetCulture()
{
if (string.IsNullOrWhiteSpace(Culture))
{
return;
}
try
{
var info = CultureInfo.GetCultureInfo(Culture);
TopLevelProperties.AddProperty(PropertyTags.PR_MESSAGE_LOCALE_ID, (uint)info.LCID);
}
catch (System.Exception)
{ }
}
#endregion
#region Save
internal void Save()
{
TopLevelProperties.AddProperty(PropertyTags.PR_MESSAGE_CLASS_W, ClassAsString);
TopLevelProperties.WriteProperties(CompoundFile.RootStorage, MessageSize);
NamedProperties.WriteProperties(CompoundFile.RootStorage);
}
/// <summary>
/// Saves the message to the given <paramref name="fileName" />
/// </summary>
/// <param name="fileName"></param>
internal void Save(string fileName)
{
Save();
CompoundFile.Save(fileName);
}
/// <summary>
/// Saves the message to the given <paramref name="stream" />
/// </summary>
/// <param name="stream"></param>
internal void Save(Stream stream)
{
Save();
CompoundFile.Save(stream);
}
#endregion
#region Dispose
/// <summary>
/// Disposes this object and all its resources
/// </summary>
public void Dispose()
{
foreach (var attachment in Attachments)
attachment.Stream.Dispose();
CompoundFile?.Close();
}
#endregion
}
}<file_sep>using MsgKit.Enums;
using MsgKit.Structures;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MsgKit.Helpers
{
public static class PropertyExtensions
{
/// <summary>
/// Get the PropertyId as reconised by Exchange REST Api
/// </summary>
public static string RestPropertyId(this NamedPropertyTag prop) =>
$"{PropertyIdTypeName(prop.Type)} 0x{Property.GetPropertyId(prop.Id, prop.Type)}";
/// <summary>
/// Get the PropertyId as reconised by Exchange REST Api
/// </summary>
public static string RestPropertyId(this PropertyTag prop) =>
$"{PropertyIdTypeName(prop.Type)} 0x{prop.Id.ToString("X4")}";
private static string PropertyIdTypeName(PropertyType type)
{
switch (type)
{
case PropertyType.PT_UNSPECIFIED:
break;
case PropertyType.PT_NULL:
break;
case PropertyType.PT_SHORT:
return "Integer";
case PropertyType.PT_LONG:
return "Integer";
case PropertyType.PT_FLOAT:
break;
case PropertyType.PT_DOUBLE:
break;
case PropertyType.PT_APPTIME:
break;
case PropertyType.PT_ERROR:
break;
case PropertyType.PT_BOOLEAN:
return "Boolean";
case PropertyType.PT_OBJECT:
break;
case PropertyType.PT_LONGLONG:
break;
case PropertyType.PT_UNICODE:
return "String";
case PropertyType.PT_STRING8:
return "String";
case PropertyType.PT_SYSTIME:
return "SystemTime";
case PropertyType.PT_CLSID:
break;
case PropertyType.PT_SVREID:
break;
case PropertyType.PT_SRESTRICT:
break;
case PropertyType.PT_ACTIONS:
break;
case PropertyType.PT_BINARY:
return "Binary";
case PropertyType.PT_MV_SHORT:
return "IntegerArray";
case PropertyType.PT_MV_LONG:
return "IntegerArray";
case PropertyType.PT_MV_FLOAT:
break;
case PropertyType.PT_MV_DOUBLE:
break;
case PropertyType.PT_MV_CURRENCY:
break;
case PropertyType.PT_MV_APPTIME:
break;
case PropertyType.PT_MV_LONGLONG:
break;
case PropertyType.PT_MV_UNICODE:
break;
case PropertyType.PT_MV_STRING8:
return "StringArray";
case PropertyType.PT_MV_SYSTIME:
break;
case PropertyType.PT_MV_CLSID:
break;
case PropertyType.PT_MV_BINARY:
break;
default:
break;
}
throw new System.Exception($"Do not know property type {type.ToString()}");
}
/// <summary>
/// Converts value to specified property type
/// </summary>
/// <param name="propertyType"></param>
/// <param name="value"></param>
/// <returns></returns>
public static object ParsePropertyType(this string value, PropertyType propertyType)
{
switch (propertyType)
{
case PropertyType.PT_UNSPECIFIED:
throw new NotSupportedException("PT_UNSPECIFIED property type is not supported");
case PropertyType.PT_NULL:
return null;
case PropertyType.PT_SHORT:
return Convert.ToInt16(value);
case PropertyType.PT_LONG:
case PropertyType.PT_ERROR:
return Convert.ToInt32(value);
case PropertyType.PT_FLOAT:
return (float) Convert.ToDecimal(value);
case PropertyType.PT_DOUBLE:
return Convert.ToDouble(value);
case PropertyType.PT_APPTIME:
case PropertyType.PT_SYSTIME:
return Convert.ToDateTime(value);
case PropertyType.PT_BOOLEAN:
return Convert.ToBoolean(value);
case PropertyType.PT_OBJECT:
case PropertyType.PT_UNICODE:
case PropertyType.PT_STRING8:
return value;
case PropertyType.PT_I8:
return Convert.ToInt64(value);
case PropertyType.PT_CLSID:
return new Guid(value);
case PropertyType.PT_SVREID:
throw new NotSupportedException("PT_SVREID property type is not supported");
case PropertyType.PT_SRESTRICT:
throw new NotSupportedException("PT_SRESTRICT property type is not supported");
case PropertyType.PT_ACTIONS:
throw new NotSupportedException("PT_ACTIONS property type is not supported");
case PropertyType.PT_BINARY:
return Convert.FromBase64String(value);
case PropertyType.PT_MV_SHORT:
throw new NotSupportedException("PT_MV_SHORT property type is not supported");
case PropertyType.PT_MV_LONG:
throw new NotSupportedException("PT_MV_LONG property type is not supported");
case PropertyType.PT_MV_FLOAT:
throw new NotSupportedException("PT_MV_FLOAT property type is not supported");
case PropertyType.PT_MV_DOUBLE:
throw new NotSupportedException("PT_MV_DOUBLE property type is not supported");
case PropertyType.PT_MV_CURRENCY:
throw new NotSupportedException("PT_MV_CURRENCY property type is not supported");
case PropertyType.PT_MV_APPTIME:
throw new NotSupportedException("PT_MV_APPTIME property type is not supported");
case PropertyType.PT_MV_LONGLONG:
throw new NotSupportedException("PT_MV_LONGLONG property type is not supported");
case PropertyType.PT_MV_TSTRING:
throw new NotSupportedException("PT_MV_TSTRING property type is not supported");
case PropertyType.PT_MV_STRING8:
throw new NotSupportedException("PT_MV_STRING8 property type is not supported");
case PropertyType.PT_MV_SYSTIME:
throw new NotSupportedException("PT_MV_SYSTIME property type is not supported");
case PropertyType.PT_MV_CLSID:
throw new NotSupportedException("PT_MV_CLSID property type is not supported");
case PropertyType.PT_MV_BINARY:
throw new NotSupportedException("PT_MV_BINARY property type is not supported");
default:
return value;
}
}
}
}
<file_sep>//
// NamedProperties.cs
//
// Author: <NAME> <<EMAIL>> and <NAME>
//
// Copyright (c) 2015-2018 Magic-Sessions. (www.magic-sessions.com)
//
// 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.
//
using System;
using System.Collections.Generic;
using System.Linq;
using MsgKit.Enums;
using MsgKit.Structures;
using OpenMcdf;
using System.Text;
using MsgKit.Helpers;
namespace MsgKit.Streams
{
internal sealed class NamedProperties : List<NamedProperty>
{
#region Fields
/// <summary>
/// <see cref="TopLevelProperties" />
/// </summary>
private readonly TopLevelProperties _topLevelProperties;
/// <summary>
/// The offset index for a <see cref="NamedProperty"/>
/// </summary>
private ushort _namedPropertyIndex;
#endregion
#region Constructor
/// <summary>
/// Creates this object
/// </summary>
/// <param name="topLevelProperties">
/// <see cref="TopLevelProperties" />
/// </param>
public NamedProperties(TopLevelProperties topLevelProperties)
{
_topLevelProperties = topLevelProperties;
}
#endregion
#region AddProperty
/// <summary>
/// Adds a <see cref="NamedPropertyTag" />
/// </summary>
/// <remarks>
/// Only support for properties by ID for now.
/// </remarks>
/// <param name="mapiTag"></param>
/// <param name="obj"></param>
internal void AddProperty(NamedPropertyTag mapiTag, object obj)
{
// Named property field 0000. 0x8000 + property offset
//_topLevelProperties.AddProperty(new PropertyTag((ushort)(0x8000 + _namedPropertyIndex++), mapiTag.Type), obj);
var propertyIndex = (ushort)(0x8000 + this.Count);
var kind = mapiTag.Name.StartsWith("PidName") ? PropertyKind.Name : PropertyKind.Lid;
var namedProperty = new NamedProperty
{
NameIdentifier = kind == PropertyKind.Lid ? mapiTag.Id : propertyIndex,
Guid = mapiTag.Guid,
Kind = kind,
Name = mapiTag.Name.Replace("PidName", "").Replace("PidLid",""),
NameSize = (uint)(kind == PropertyKind.Name ? mapiTag.Name.Length : 0)
};
if(mapiTag.Guid != PropertySets.PS_MAPI
&& mapiTag.Guid != PropertySets.PS_PUBLIC_STRINGS
&& !Guids.Contains(mapiTag.Guid))
{
Guids.Add(mapiTag.Guid);
}
_topLevelProperties.AddProperty(new PropertyTag(propertyIndex, mapiTag.Type), obj);
Add(namedProperty);
}
#endregion
private ushort GetGuidIndex(NamedProperty namedProperty)
{
return (ushort)(namedProperty.Guid == PropertySets.PS_MAPI ? 1
: namedProperty.Guid == PropertySets.PS_PUBLIC_STRINGS ? 2
: (Guids.IndexOf(namedProperty.Guid) + 3));
}
private IList<Guid> Guids = new List<Guid>();
#region WriteProperties
/// <summary>
/// Writes the properties to the <see cref="CFStorage" />
/// </summary>
/// <param name="storage"></param>
/// <param name="messageSize"></param>
/// <remarks>
/// Unfortunately this is going to have to be used after we already written the top level properties.
/// </remarks>
internal void WriteProperties(CFStorage storage, long messageSize = 0)
{
// Grab the nameIdStorage, 3.1 on the SPEC
storage = storage.GetStorage(PropertyTags.NameIdStorage);
var entryStream = new EntryStream(storage);
var stringStream = new StringStream(storage);
var guidStream = new GuidStream(storage);
var nameIdMappingStream = new EntryStream(storage);
ushort propertyIndex = 0;
foreach (var guid in Guids.Where(g => g!= PropertySets.PS_MAPI && g != PropertySets.PS_PUBLIC_STRINGS))
guidStream.Add(guid);
foreach (var namedProperty in this)
{
var guidIndex = GetGuidIndex(namedProperty);
var indexAndKind = new IndexAndKindInformation(propertyIndex, guidIndex, namedProperty.Kind);
if (namedProperty.Kind == PropertyKind.Name)
{
var stringStreamItem = new StringStreamItem(namedProperty.Name);
stringStream.Add(stringStreamItem);
entryStream.Add(new EntryStreamItem(stringStream.GetItemByteOffset(stringStreamItem), indexAndKind));
}
else
{
entryStream.Add(new EntryStreamItem(namedProperty.NameIdentifier, indexAndKind));
}
nameIdMappingStream.Add(new EntryStreamItem(GenerateNameIdentifier(namedProperty), indexAndKind));
nameIdMappingStream.Write(storage, GenerateStreamName(namedProperty));
// Dependign on the property type. This is doing name.
//entryStream.Add(new EntryStreamItem(namedProperty.NameIdentifier, new IndexAndKindInformation(propertyIndex, guidIndex, PropertyKind.Lid))); //+3 as per spec.
//entryStream2.Add(new EntryStreamItem(namedProperty.NameIdentifier, new IndexAndKindInformation(propertyIndex, guidIndex, PropertyKind.Lid)));
// 3.2.2 of the SPEC Needs to be written, because the stream changes as per named object.
nameIdMappingStream.Clear();
propertyIndex++;
}
guidStream.Write(storage);
entryStream.Write(storage);
stringStream.Write(storage);
}
#region GenerateStreamString
/// <summary>
/// Generates the stream id of the named properties
/// </summary>
/// <param name="namedProperty"></param>
/// <returns></returns>
internal string GenerateStreamName(NamedProperty namedProperty)
{
var guidTarget = GetGuidIndex(namedProperty);
var identifier = GenerateNameIdentifier(namedProperty);
switch (namedProperty.Kind)
{
case PropertyKind.Lid:
return "__substg1.0_" +
(((4096 + (identifier ^ (guidTarget << 1)) % 0x1F) << 16) | 0x00000102).ToString("X")
.PadLeft(8, '0');
case PropertyKind.Name:
return "__substg1.0_" +
(((0x1000 + ((identifier ^ (guidTarget << 1 | 1)) % 0x1F)) << 16) | 0x00000102).ToString("X8")
.PadLeft(8, '0');
default:
throw new NotImplementedException();
}
}
internal uint GenerateNameIdentifier(NamedProperty namedProperty)
{
switch (namedProperty.Kind)
{
case PropertyKind.Lid:
return namedProperty.NameIdentifier;
case PropertyKind.Name:
return Crc32Calculator.CalculateCrc32(Encoding.Unicode.GetBytes(namedProperty.Name));
default:
throw new NotImplementedException();
}
}
#endregion
#endregion
}
} | 681a64794456e5ff54512d85c5a6f52ed31a1aad | [
"C#"
] | 7 | C# | Repstor/MsgKit | b1a5453cc9af7682dea6d6ac8e1ef749249f8b43 | d1825b60bee523e71d3cbd5ebfd19ceafba91b1b |
refs/heads/master | <repo_name>hoangminhuet99/laravel_quicktask<file_sep>/resources/lang/vi/message.php
<?php
return [
'employee_manage' => 'Quản lý nhân viên',
'create_employee' => 'Thêm mới nhân viên',
'name' => 'Tên',
'email' => 'Email',
'phone' => 'Số điện thoại',
'city' => 'Thành phố',
'language' => 'Ngôn ngữ',
'add_employee' => 'Thêm nhân viên',
'created' => 'Thêm thành công',
'actions' => 'Hành động',
'vn' => 'Tiếng Việt',
'en' => 'Tiếng Anh',
'edit' => 'Sửa',
'php' => 'PHP',
'ruby' => 'RUBY',
'ios' => 'IOS',
'mobile' => 'MOBILE',
'qa' => 'Q&A',
'delete' => 'Xóa',
'id' => 'STT',
'updated' => 'Sửa thành công!',
'update_employee' => 'Chỉnh sửa nhân viên',
'cancel' => 'Hủy',
'deleted' => 'Xóa thành công',
];
<file_sep>/routes/web.php
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
Route::resource('contacts', 'ContactController');
Route::group(['middleware' => 'locale'], function() {
Route::get('lang/{lang}', 'LangController@changeLang')
->name('lang');
});
<file_sep>/config/constants.php
<?php
return [
'php' => 'PHP',
'ruby' => 'RUBY',
'ios' => 'IOS',
'mobile' => 'MOBILE',
'qa' => 'Q&A',
'paginate' => 10,
];
<file_sep>/resources/lang/en/message.php
<?php
return [
'employee_manage' => 'Employee Manage',
'create_employee' => 'Create Employee',
'name' => 'Name',
'email' => 'Email',
'phone' => 'Phone',
'city' => 'City',
'language' => 'Language',
'add_employee' => 'Add Employee',
'saved' => 'Contact saved!',
'actions' => 'Actions',
'edit' => 'Edit',
'vn' => 'Vietnamese',
'en' => 'English',
'php' => 'PHP',
'ruby' => 'RUBY',
'ios' => 'IOS',
'mobile' => 'MOBILE',
'qa' => 'Q&A',
'delete' => 'Delete',
'id' => 'ID',
'update_employee' => 'Update a employee',
'updated' => 'Employee updated!',
'cancel' => 'Cancel',
'deleted' => 'Employee Deleted!',
];
| 027745d68efb6e4d37a803a4d3fa6314300fd7b8 | [
"PHP"
] | 4 | PHP | hoangminhuet99/laravel_quicktask | 0812766361b388d4cbdf053498e6f8961a03bc6d | 462d465a30e7e851295218d21600c9c47b3a7b11 |
refs/heads/main | <repo_name>jtagt/fishington-io-bot<file_sep>/main.py
import cv2
from PIL import ImageGrab, Image
import numpy as np
from matplotlib import pyplot as plt, animation
import threading
import pydirectinput
import math
import time
bobber_low_h = 0
bobber_high_h = 180
bobber_low_s = 0
bobber_high_s = 9
bobber_low_v = 97
bobber_high_v = 255
red_bar_low_h = 103
red_bar_high_h = 115
red_bar_low_s = 193
red_bar_high_s = 194
red_bar_low_v = 176
red_bar_high_v = 255
green_bar_low_h = 37
green_bar_high_h = 104
green_bar_low_s = 211
green_bar_high_s = 255
green_bar_low_v = 172
green_bar_high_v = 236
close_x = 3233
close_y = 611
close_off_x = 40
close_off_y = 44
close_low_h = 0
close_high_h = 36
close_low_s = 0
close_high_s = 31
close_low_v = 36
close_high_v = 255
caught_x = 3030
caught_y = 405
caught_off_x = 21
caught_off_y = 43
caught_low_h = 80
caught_high_h = 123
caught_low_s = 222
caught_high_s = 255
caught_low_v = 180
caught_high_v = 255
x = 2769
y = 780
off_x = 534
off_y = 35
fishing_x = 2807
fishing_y = 815
shop_x = 3189
shop_y = 312
shop_select_all_x = 2614
shop_select_all_y = 314
shop_sell_x = 3032
shop_sell_y = 827
shop_sell_confirm_x = 3153
shop_sell_confirm_y = 711
off_window_x = 2789
off_window_y = 918
last_merge = np.zeros((off_y, off_x))
bobber_plain = np.zeros((off_y, off_x))
red_bar_plain = np.zeros((off_y, off_x))
green_bar_plain = np.zeros((off_y, off_x))
close_image_plain = np.zeros((close_off_y, close_off_x))
caught_image_plain = np.zeros((caught_off_y, caught_off_x))
max_fish = 12
def grab_image():
image = ImageGrab.grab(bbox=(x, y, x + off_x, y + off_y))
image = np.array(image)
return image
def grab_close_image():
image = ImageGrab.grab(bbox=(close_x, close_y, close_x + close_off_x, close_y + close_off_y))
image = np.array(image)
return image
def grab_catch_image():
image = ImageGrab.grab(bbox=(caught_x, caught_y, caught_x + caught_off_x, caught_y + caught_off_y))
image = np.array(image)
return image
def grab_caught_mark_image(image):
frame_HSV = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
frame_threshold = cv2.inRange(frame_HSV, (caught_low_h, caught_low_s, caught_low_v),
(caught_high_h, caught_high_s, caught_high_v))
return frame_threshold
def grab_x_button_image(image):
frame_HSV = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
frame_threshold = cv2.inRange(frame_HSV, (close_low_h, close_low_s, close_low_v),
(close_high_h, close_high_s, close_high_v))
return frame_threshold
def grab_bobber_image(image):
frame_HSV = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
frame_threshold = cv2.inRange(frame_HSV, (bobber_low_h, bobber_low_s, bobber_low_v),
(bobber_high_h, bobber_high_s, bobber_high_v))
return frame_threshold
def grab_green_bar_image(image):
frame_HSV = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
frame_threshold = cv2.inRange(frame_HSV, (green_bar_low_h, green_bar_low_s, green_bar_low_v),
(green_bar_high_h, green_bar_high_s, green_bar_high_v))
return frame_threshold
def grab_red_bar_image(image):
frame_HSV = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
frame_threshold = cv2.inRange(frame_HSV, (red_bar_low_h, red_bar_low_s, red_bar_low_v),
(red_bar_high_h, red_bar_high_s, red_bar_high_v))
return frame_threshold
def blend_images(bobber_img, green_bar_img, red_bar_img):
first_blend = Image.blend(green_bar_img, red_bar_img, 0.5)
second_blend = Image.blend(first_blend, bobber_img, 0.5)
return second_blend
def calculate_mean_center(image):
return np.mean(np.argwhere(image == 255), axis=0)
def convert_image(image_array):
return Image.fromarray(np.uint8(image_array)).convert('RGBA')
def is_valid(image, count):
if np.sum(image == 255) >= count:
return True
return False
def is_valid_below(image, count):
if np.sum(image == 255) <= count:
return True
return False
def get_positions(bobber_image, green_bar_image, red_bar_image):
bobber_center = calculate_mean_center(bobber_image)
if is_valid(bobber_image, 25) and is_valid(green_bar_image, 100):
green_bar_center = calculate_mean_center(green_bar_plain)
if not np.isnan(green_bar_center[0]) and not np.isnan(green_bar_center[1]) and not np.isnan(
bobber_center[0]) and not np.isnan(bobber_center[1]):
return bobber_center, green_bar_center
return None
if is_valid(bobber_image, 25) and is_valid(red_bar_image, 100):
red_bar_center = calculate_mean_center(red_bar_plain)
if not np.isnan(red_bar_center[0]) and not np.isnan(red_bar_center[1]) and not np.isnan(
bobber_center[0]) and not np.isnan(bobber_center[1]):
return bobber_center, red_bar_center
return None
class GameInterpreter(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.fishCount = 0
def run(self):
while True:
global bobber_plain, green_bar_plain, red_bar_plain, last_merge, close_image_plain, caught_image_plain
caught_image = grab_catch_image()
caught_image_plain = grab_caught_mark_image(caught_image)
if is_valid(caught_image_plain, 100) and is_valid_below(caught_image_plain, 350):
print('Caught fish continuing to the awesome')
pydirectinput.click(x=close_x + math.floor(close_off_x / 2), y=close_y + math.floor(close_off_y / 2))
# use relative
close_image = grab_close_image()
close_image_plain = grab_x_button_image(close_image)
if is_valid(close_image_plain, 25) and is_valid_below(close_image_plain, 500):
print('Caught fish')
self.fishCount += 1
time.sleep(1)
pydirectinput.doubleClick(x=close_x + math.floor(close_off_x / 2),
y=close_y + math.floor(close_off_y / 2))
print(f"Now at {self.fishCount}")
if self.fishCount == max_fish:
print('Reached max fish going to sell')
pydirectinput.keyDown(key='w')
time.sleep(5)
pydirectinput.keyUp(key='w')
# at shop now
pydirectinput.click(x=shop_x, y=shop_y) # click shop
time.sleep(0.25)
pydirectinput.click(x=shop_select_all_x, y=shop_select_all_y) # click select all
time.sleep(0.25)
pydirectinput.click(x=shop_sell_x, y=shop_sell_y) # click shop sell button
time.sleep(0.75)
pydirectinput.click(x=shop_sell_confirm_x, y=shop_sell_confirm_y) # confirm sale
time.sleep(0.25)
pydirectinput.click(x=off_window_x, y=off_window_y) # close shop window
time.sleep(0.75)
pydirectinput.keyDown(key='s')
time.sleep(1.5)
pydirectinput.keyUp(key='s')
self.fishCount = 0
print('Sold all fish now at 0 fish')
pydirectinput.mouseDown(x=fishing_x, y=fishing_y)
time.sleep(1)
pydirectinput.mouseUp()
else:
time.sleep(1)
pydirectinput.mouseDown(x=fishing_x, y=fishing_y)
time.sleep(1)
pydirectinput.mouseUp()
image = grab_image()
bobber_plain = grab_bobber_image(image)
green_bar_plain = grab_green_bar_image(image)
red_bar_plain = grab_red_bar_image(image)
positions = get_positions(bobber_plain, green_bar_plain, red_bar_plain)
if positions:
if positions[0][1] > positions[1][1]:
pydirectinput.mouseUp()
print(f"Releasing distance: {positions[0][1] - positions[1][1]}")
else:
pydirectinput.mouseDown()
print(f"Pressing distance: {positions[1][1] - positions[0][1]}")
bobber_converted = convert_image(bobber_plain)
green_bar_converted = convert_image(green_bar_plain)
red_bar_converted = convert_image(red_bar_plain)
last_merge = np.array(blend_images(bobber_converted, green_bar_converted, red_bar_converted))
if cv2.waitKey(1) & 0xFF == ord('q'):
cv2.destroyAllWindows()
break
class PlotVisual:
def __init__(self):
self.img = plt.imshow(last_merge)
self.ani = animation.FuncAnimation(plt.gcf(), self.run, frames=off_y * off_y,
interval=1)
self.lastBobberDraw = None
self.lastTargetDraw = None
self.lastDifferenceDraw = None
def draw_rois(self):
if self.lastBobberDraw:
self.lastBobberDraw.remove()
self.lastBobberDraw = None
if self.lastTargetDraw:
self.lastTargetDraw.remove()
self.lastTargetDraw = None
if self.lastDifferenceDraw:
self.lastDifferenceDraw.remove()
self.lastDifferenceDraw = None
positions = get_positions(bobber_plain, green_bar_plain, red_bar_plain)
if positions:
bobber = [[positions[0][1], positions[0][0]]]
self.lastBobberDraw = plt.plot(*zip(*bobber), marker='o', color='g', ls='')[0]
target = [[positions[1][1], positions[1][0]]]
self.lastTargetDraw = plt.plot(*zip(*target), marker='|', color='r', ls='')[0]
plot_line = [[positions[1][1], positions[1][0]], [positions[0][1], positions[0][0]]]
self.lastDifferenceDraw = plt.plot(*zip(*plot_line), color='y')[0]
def run(self, i):
self.draw_rois()
xi = i // off_y
yi = i % off_x
last_merge[xi, yi] = 1
self.img.set_data(last_merge)
# start the visual
PlotVisual()
# start the interpreting
interpreter = GameInterpreter()
interpreter.start()
# show the visual
plt.show()
<file_sep>/requirements.txt
numpy~=1.20.2
pillow~=8.2.0
opencv-python~=4.5.1.48
PyDirectInput~=1.0.4
matplotlib~=3.4.1 | 8e7accbbd17123441a924789de8236ea4bf3e132 | [
"Python",
"Text"
] | 2 | Python | jtagt/fishington-io-bot | a8d34a6e54c4130fb2d611947db9af8ffaf369a6 | 842a5e5cc005fbe69fa084f6c35388299f5f7829 |
refs/heads/master | <repo_name>utec-ads-2019-2/babelfish-10282-StephanoWurttele<file_sep>/main.cpp
#include <iostream>
#include <string>
#include <sstream>
#include <map>
using namespace std;
int main(){
map<string,string> diccionario;
string n;
string a;
getline(cin,n);
while(n!=""){
stringstream string(n);
string>>n>>a;
diccionario[a]=n;
getline(cin,n);
}
while(cin>>n){
if(!diccionario[n].empty())
cout<<diccionario[n]<<endl;
else
cout<<"eh"<<endl;
}
return 0;
}
| 1fcf31b0c6f6e8dbc4800a876ce920e1005d789a | [
"C++"
] | 1 | C++ | utec-ads-2019-2/babelfish-10282-StephanoWurttele | 4fc36882e05d29bb059b3c5f062f2b80768d9367 | 9ef2edf5a7a07922545d5b81ff985e9396f44633 |
refs/heads/master | <file_sep>class ConvertController < ApplicationController
protect_from_forgery
def index
@convert_target ||= "{'a' => 1, b: {x: 9, y: 8}}"
end
def convert
@convert_target = params[:convert_target]
converted_hash = eval(@convert_target)
@converted = JSON.pretty_generate(converted_hash)
render "convert/index"
end
end
<file_sep>Rails.application.routes.draw do
scope :ruby_hash_converter do
root to: 'convert#index'
post "", to: "convert#convert"
end
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end
| 2df8be1e89866e24791ac43d3d29a44d2e33bf81 | [
"Ruby"
] | 2 | Ruby | setsumaru1992/ruby_hash_converter | 6ebf715b29756b4f86f14cded80803e60cb9fd07 | 8de8041bcecf470e28fa27afd7628a51ac11a2aa |
refs/heads/master | <repo_name>caliahub/install_python<file_sep>/install_python.sh
#!/usr/bin/bash
#
#源码安装python
yum -y install wget gcc zlib*
python_url=https://www.python.org/ftp/python/3.6.4/Python-3.6.4.tgz
install_dir=/app/install
python=/usr/bin/python
python_dir=/usr/local/python3
mkdir -p $install_dir
cd $install_dir
wget $python_url
tar zxvf Python-3.6.4.tgz
mv Python-3.6.4 $python_dir
cd $python_dir
./configure --prefix=$python_dir
make && make install
if [ -f $python ];then
mv $python $python\.bak
fi
ln -s $python_dir/python $python
rm -rf /app/install
| 62a12192064bd47a0dd3eb3227fd4efa1bd4015c | [
"Shell"
] | 1 | Shell | caliahub/install_python | 6de5ca58f0f09160bf1403f054773c9ef12ba8cf | 79fb6653f3f36ccf3300b8a696580ff537a83580 |
refs/heads/master | <file_sep>use bevy::{
// diagnostic::{FrameTimeDiagnosticsPlugin, PrintDiagnosticsPlugin},
input::mouse::{MouseButtonInput, MouseMotion, MouseWheel},
prelude::*,
window::CursorMoved,
window::WindowId,
winit::WinitWindows,
};
use rand::{rngs::StdRng, Rng, SeedableRng};
struct Camera;
struct Player {
pub yaw: f32,
pub pitch: f32,
pub sensitivity: f32,
}
impl Default for Player {
fn default() -> Self {
Self {
yaw: 90.0,
pitch: 0.0,
sensitivity: 30.0,
}
}
}
struct Options {
pub key_backward: KeyCode,
pub key_forward: KeyCode,
pub key_left: KeyCode,
pub key_right: KeyCode,
pub key_up: KeyCode,
pub key_down: KeyCode,
pub speed: f32,
}
impl Default for Options {
fn default() -> Self {
Self {
key_backward: KeyCode::Down,
key_forward: KeyCode::Up,
key_left: KeyCode::Left,
key_right: KeyCode::Right,
key_up: KeyCode::Space,
key_down: KeyCode::LShift,
speed: 10.0,
}
}
}
fn main() {
App::build()
// resources
.init_resource::<State>()
.init_resource::<Options>()
.add_resource(Msaa { samples: 4 })
// plugins
.add_plugins(DefaultPlugins)
// .add_plugin(FrameTimeDiagnosticsPlugin::default())
// .add_plugin(PrintDiagnosticsPlugin::default())
// setup
.add_startup_system(setup.system())
// loop
.add_system(rotate_player.system())
.add_system(move_player.system())
.add_system(mouse_capture_system.system())
.run();
}
fn setup(
commands: &mut Commands,
// asset_server: Res<AssetServer>,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
) {
commands
// light
.spawn(LightBundle {
transform: Transform::from_translation(Vec3::new(0.0, 5.0, 0.0)),
..Default::default()
})
// camera
.spawn(Camera3dBundle {
transform: Transform::from_translation(Vec3::new(50.0, 0.0, 0.0)),
..Default::default()
})
.with(Camera);
let mut rng = StdRng::from_entropy();
let player_handle = meshes.add(Mesh::from(shape::Cube { size: 1.0 }));
let platform_handle = meshes.add(Mesh::from(shape::Plane { size: 100.0 }));
commands
// player
.spawn(PbrBundle {
mesh: player_handle.clone(),
material: materials.add(StandardMaterial {
albedo: Color::rgb(
rng.gen_range(0.0..1.0),
rng.gen_range(0.0..1.0),
rng.gen_range(0.0..1.0),
),
..Default::default()
}),
transform: Transform::from_translation(Vec3::new(0.0, 100.0, 0.0)),
..Default::default()
})
.with(Player::default())
// platform
.spawn(PbrBundle {
mesh: platform_handle.clone(),
material: materials.add(StandardMaterial {
albedo: Color::rgb(
rng.gen_range(0.0..1.0),
rng.gen_range(0.0..1.0),
rng.gen_range(0.0..1.0),
),
..Default::default()
}),
transform: Transform::from_translation(Vec3::new(-5.0, -5.0, -5.0)),
..Default::default()
});
}
#[derive(Default)]
struct State {
// mouse_button_event_reader: EventReader<MouseButtonInput>,
mouse_motion_event_reader: EventReader<MouseMotion>,
// cursor_moved_event_reader: EventReader<CursorMoved>,
// mouse_wheel_event_reader: EventReader<MouseWheel>,
cursor_hidden: bool,
}
fn rotate_player(
mut state: ResMut<State>,
time: Res<Time>,
mouse_motion_events: Res<Events<MouseMotion>>,
mut player_query: Query<(&mut Player, &mut Transform)>,
mut camera_query: Query<(&Camera, &mut Transform)>,
) {
let mut delta = Vec2::zero();
for event in state.mouse_motion_event_reader.iter(&mouse_motion_events) {
delta += event.delta;
}
let mut yaw_rad = 0.0;
let mut pitch_rad = 0.0;
for (mut player, mut transform) in player_query.iter_mut() {
player.yaw -= delta.x * player.sensitivity * time.delta_seconds();
player.pitch += delta.y * player.sensitivity * time.delta_seconds();
// if player.pitch < -90.0 {
// player.pitch = -90.0;
// } else if player.pitch > 90.0 {
// player.pitch = 90.0
// }
yaw_rad = player.yaw.to_radians();
pitch_rad = player.pitch.to_radians();
transform.rotation = Quat::from_axis_angle(Vec3::unit_y(), yaw_rad);
println!("Player yaw = {}, pitch = {}", player.yaw, player.pitch);
}
for (_, mut transform) in camera_query.iter_mut() {
transform.rotation = Quat::from_axis_angle(Vec3::unit_y(), yaw_rad)
* Quat::from_axis_angle(-Vec3::unit_x(), pitch_rad);
}
}
fn movement_axis(input: &Res<Input<KeyCode>>, plus: KeyCode, minus: KeyCode) -> f32 {
let mut axis = 0.0;
if input.pressed(plus) {
axis += 1.0;
}
if input.pressed(minus) {
axis -= 1.0;
}
axis
}
fn movement_offset(input: &Res<Input<KeyCode>>, options: &Res<Options>) -> (f32, f32, f32) {
(
movement_axis(input, options.key_right, options.key_left),
movement_axis(input, options.key_backward, options.key_forward),
movement_axis(input, options.key_up, options.key_down),
)
}
fn forward_vec(rotation: &Quat) -> Vec3 {
rotation.mul_vec3(Vec3::unit_z()).normalize()
}
fn forward_walk_vec(rotation: &Quat) -> Vec3 {
let f = forward_vec(rotation);
// flatten vector by removing y axis info
Vec3::new(f.x, 0.0, f.z).normalize()
}
fn strafe_vec(rotation: &Quat) -> Vec3 {
Quat::from_rotation_y(90.0f32.to_radians())
.mul_vec3(forward_walk_vec(rotation))
.normalize()
}
fn move_player(
time: Res<Time>,
keyboard_input: Res<Input<KeyCode>>,
options: Res<Options>,
// mut player_query: Query<(&Player, &mut Transform)>,
mut camera_query: Query<(&Camera, &mut Transform)>,
) {
let (axis_h, axis_v, axis_float) = movement_offset(&keyboard_input, &options);
for (_, mut transform) in camera_query.iter_mut() {
let rotation = transform.rotation;
let accel = (strafe_vec(&rotation) * axis_h)
+ (forward_walk_vec(&rotation) * axis_v)
+ (Vec3::unit_y() * axis_float);
let accel = accel * options.speed;
transform.translation += accel * time.delta_seconds();
}
}
fn mouse_capture_system(mut state: ResMut<State>, windows: Res<WinitWindows>) {
if !state.cursor_hidden {
if let Some(window) = windows.get_window(WindowId::primary()) {
if window.set_cursor_grab(true).is_ok() {
println!("Snatching users cursor!");
window.set_cursor_visible(false);
state.cursor_hidden = true;
}
}
}
}
<file_sep>[package]
name = "beep-boop"
version = "0.1.0"
authors = ["<NAME> <<EMAIL>>"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
bevy = "0.4" # make sure this is the latest version
rand = "0.8.0"
[profile.dev]
opt-level = 3
<file_sep># SHELLFLAGS = -I nixpkgs=/home/gnzh/mydev/nixpkgs
default: run-nix
run-nix:
nix-shell $(SHELLFLAGS) shell.nix --run 'make run'
run:
cargo run --features bevy/dynamic
shell:
nix-shell $(SHELLFLAGS) shell.nix
| e68fde604e8d58dd8f84cee31731dc897fa14e75 | [
"TOML",
"Rust",
"Makefile"
] | 3 | Rust | Gonzih/bevy-hello-world | 94a281ef0b7d16615dfb2d0da08c5c548999660c | 5d7c0a712e6a753c6cfd3a34c39547e297b05800 |
refs/heads/master | <repo_name>khurramijazm/Reactjs<file_sep>/thisManager.js
var thisManager = function(){
var _Manager = [];
return{
getThis : function(key){
return _Manager[key];
},
setThis : function(obj){
_Manager[obj.key] = obj.value;
}
}
};
var _thisManager = new thisManager();
// React Component
class Header extends Component{
constructor(){
super();
_thisManager.setThis({ key: "Header", value:this}
}
render(data){
console.log('inside the Header render() function ', data? data : ' no data on first initial render');
return <div />
}
}
// Then from any other component living far somewhere you can pass the data to the render function and it works out of the box.
i.e.
class Footer extends Component{
_click(e){
let Header = _thisManager.getThis('Header');
Header.render(" Wow some new data from footer event ");
}
render(){
return(
<div>
<button onClick={this._click.bind(this)}> send data to header and call its render </button>
</div>
);
}
}
| 87857d242e4b98b75b9a0e1a30789701691c3dac | [
"JavaScript"
] | 1 | JavaScript | khurramijazm/Reactjs | f2ffd8641fc4a407aaa64548120c985c0e007a5c | 806fcb259c02e0dc4a1568a9cd9979b031600d4e |
refs/heads/master | <file_sep>using CSharpLab05;
using System.Windows.Controls;
namespace СSharpLab05
{
/// <summary>
/// Логика взаимодействия для TaskManagerView.xaml
/// </summary>
public partial class TaskManagerView : UserControl, INavigatable
{
public TaskManagerView()
{
InitializeComponent();
DataContext = new TaskManagerViewModel();
}
}
}
<file_sep>using System;
using System.ComponentModel;
using System.Diagnostics;
namespace CSharpLab05
{
public class ProcessClass
{
private PerformanceCounter CounterCpu { get; }
private PerformanceCounter RAMCounter { get; }
private readonly long _total = PerformanceInfo.GetWholeMemory() * 10000;
private readonly int _processorCount = Environment.ProcessorCount;
private Process Process;
public string Name { get; set; }
public int Id { get; set; }
public bool IsActive { get; set; }
public double Cpu { get; set; }
public double RAM { get; set; }
public int ThreadNumber { get; set; }
public string Path { get; set; }
public DateTime Time { get; set; }
internal ProcessClass(Process process)
{
Process = process;
Name = process.ProcessName;
Id = process.Id;
ThreadNumber = process.Threads.Count;
SetPathName(process);
SetProcessTime(process);
CounterCpu = new PerformanceCounter("Process", "% Processor Time", process.ProcessName, true);
IsActive = process.Responding;
RAMCounter = new PerformanceCounter("Process", "Working Set", process.ProcessName, true);
UpdateFields();
}
public void UpdateFields()
{
try
{
Cpu = Math.Round(CounterCpu.NextValue() / _processorCount, 2);
}
catch (InvalidOperationException) { }
try {
RAM = Math.Round(RAMCounter.NextValue() / _total,2);
}
catch (InvalidOperationException) { }
ThreadNumber = Process.Threads.Count;
}
private void SetProcessTime(Process process)
{
try
{
Time = process.StartTime;
}
catch (InvalidOperationException)
{
}
catch (Win32Exception)
{
}
}
private void SetPathName(Process process)
{
try
{
Path = process.MainModule.FileName;
}
catch (InvalidOperationException )
{
}
catch (Win32Exception)
{
Path = "Access is forbidden.";
}
}
public override bool Equals(object obj)
{
return obj is ProcessClass other && Id == other.Id;
}
public override int GetHashCode()
{
return base.GetHashCode();
}
}
}<file_sep>using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Windows;
using System.Windows.Input;
namespace CSharpLab05
{
class TaskManagerViewModel : INotifyPropertyChanged
{
private ICommand _killProcess;
private ICommand _openProcess;
private ObservableCollection<ProcessClass> _allProcesses;
private ProcessClass _selectedProcess;
private Thread _moduleThread;
private Thread _dataThread;
internal TaskManagerViewModel()
{
Processes = new ObservableCollection<ProcessClass>();
var processes = Process.GetProcesses();
for (int i = 0; i < processes.Length; i++) _allProcesses.Add(new ProcessClass(processes[i]));
_moduleThread = new Thread(UpdateModules);
_moduleThread.Start();
_dataThread = new Thread(UpdateTaskManager);
_dataThread.Start();
}
public ICommand KillProcessCommand => _killProcess ??
(_killProcess = new RelayCommand<object>(KillProcess,
CanExecuteCommand));
public ICommand OpenFolderCommand => _openProcess ??
(_openProcess = new RelayCommand<object>(OpenFolder,
CanExecuteCommand));
private void OpenFolder(object obj)
{
if (_selectedProcess.Path != "Access is forbidden.")
{
try
{
Process.Start(Path.GetDirectoryName(_selectedProcess.Path));
}
catch (ArgumentException ex)
{
MessageBox.Show(ex.Message);
}
catch (PathTooLongException ex1)
{
MessageBox.Show(ex1.Message);
}
}
else
MessageBox.Show("Access is forbidden.");
}
private void KillProcess(object obj)
{
Process pr = Process.GetProcessById(_selectedProcess.Id);
try
{
pr.Kill();
}
catch (System.ArgumentException e)
{
MessageBox.Show(e.Message);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
public ObservableCollection<ProcessClass> Processes
{
get => _allProcesses;
set
{
_allProcesses = value;
OnPropertyChanged();
}
}
public ProcessClass SelectedProcess
{
get => _selectedProcess;
set
{
_selectedProcess = value;
OnPropertyChanged();
}
}
private void ShowModulesImplementation(object obj)
{
NavigationManager.Instance.Navigate(ViewType.ShowInfo, SelectedProcess);
}
private void UpdateTaskManager()
{
while (StationManager.Stop)
{
Thread.Sleep(5000);
}
_dataThread.Join(2000);
_dataThread.Abort();
_dataThread = null;
}
private void UpdateModules()
{
while (StationManager.Stop)
{
foreach (ProcessClass pr in Processes)
pr.UpdateFields();
Processes=new ObservableCollection<ProcessClass>(Processes);
Thread.Sleep(2000);
}
_moduleThread.Join(2000);
_moduleThread.Abort();
_moduleThread = null;
}
private bool CanExecuteCommand(object obj)
{
return SelectedProcess != null;
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
<file_sep>namespace CSharpLab05
{
internal enum ViewType
{
TaskManager,
ShowInfo
}
interface INavigationModel
{
void Navigate(ViewType viewType,ProcessClass selectedProcess);
}
}
<file_sep>using System;
namespace CSharpLab05
{
internal static class StationManager
{
public static event Action StopThreads;
public static bool Stop = true;
internal static void CloseApp()
{
Stop = false;
StopThreads?.Invoke();
Environment.Exit(0);
}
}
} | 96e957a0a7c629a187b4711e902c2dd0afd751d1 | [
"C#"
] | 5 | C# | Oleeeg/CSharpLab05 | aa66d2794b269ec983f2765be8256655e95e694e | c0e17f0aab4e29eb0c2247349edebef55f60caa5 |
refs/heads/main | <repo_name>NylRJ/AWS-ECS-e-Fargate<file_sep>/src/main/java/com/myorg/Service01Stack.java
package com.myorg;
import software.amazon.awscdk.core.Construct;
import software.amazon.awscdk.core.RemovalPolicy;
import software.amazon.awscdk.core.Stack;
import software.amazon.awscdk.core.StackProps;
import software.amazon.awscdk.services.ecs.AwsLogDriverProps;
import software.amazon.awscdk.services.ecs.Cluster;
import software.amazon.awscdk.services.ecs.ContainerImage;
import software.amazon.awscdk.services.ecs.LogDriver;
import software.amazon.awscdk.services.ecs.patterns.ApplicationLoadBalancedFargateService;
import software.amazon.awscdk.services.ecs.patterns.ApplicationLoadBalancedTaskImageOptions;
import software.amazon.awscdk.services.elasticloadbalancingv2.HealthCheck;
import software.amazon.awscdk.services.logs.LogGroup;
public class Service01Stack extends Stack {
public Service01Stack(final Construct scope, final String id, Cluster cluster) {
this(scope, id, null, cluster);
}
public Service01Stack(final Construct scope, final String id, final StackProps props, Cluster cluster) {
super(scope, id, props);
ApplicationLoadBalancedFargateService service01 = ApplicationLoadBalancedFargateService.Builder.create(this, "ALB01")
.serviceName("service-01")
.cluster(cluster)
.cpu(512)
.memoryLimitMiB(1024)
.desiredCount(2)
.listenerPort(8083)
.taskImageOptions(
ApplicationLoadBalancedTaskImageOptions.builder()
.containerName("transaction-svc")
.image(ContainerImage.fromRegistry("nylrj/i9development:1.0.0"))
.containerPort(8083)
.logDriver(LogDriver.awsLogs(AwsLogDriverProps.builder()
.logGroup(LogGroup.Builder.create(this, "Service01LogGroup")
.logGroupName("Service01")
.removalPolicy(RemovalPolicy.DESTROY)
.build())
.streamPrefix("Service01")
.build()))
.build())
.publicLoadBalancer(true)
.build();
service01.getTargetGroup().configureHealthCheck(new HealthCheck.Builder()
.path("/actuator/health")
.port("8083")
.healthyHttpCodes("200")
.build());
}
}
| f932fd2a4a591f0683c75bf2c404957e7a047c8d | [
"Java"
] | 1 | Java | NylRJ/AWS-ECS-e-Fargate | 7c357b3077e98cf52a360e27d9495d2e0088e650 | 62f18eca70b6141d16b0ef352643042d16c87469 |
refs/heads/master | <file_sep>package Ex;
public class WordNumber {
public static void main(String[] args) {
long num = 0;
if (args.length > 0) {
char firstLetter = args[0].charAt(0);
char secondLetter = args[0].charAt(1);
switch (firstLetter) {
case 'o':
num = 1L;
break;
case 't':
if (secondLetter == 'w'){
num = 2L;
} else if (secondLetter == 'h') {
num = 3L;
} else {
num = 10L;
}
break;
case 'f':
if (secondLetter == 'o'){
num = 4L;
} else {
num = 5L;
}
break;
case 's':
if (secondLetter == 'i') {
num = 6L;
} else {
num = 7L;
}
break;
case 'e':
num = 8L;
break;
case 'n':
num = 9L;
break;
}
System.out.println(num);
} else {
System.out.println("No arguments provided!!");
}
}
}
<file_sep>package testing;
import javafx.scene.shape.Rectangle;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class Maps {
public static void main(String[] args) {
Map look = new Map() {
@Override
public int size() {
return 0;
}
@Override
public boolean isEmpty() {
return false;
}
@Override
public boolean containsKey(Object key) {
return false;
}
@Override
public boolean containsValue(Object value) {
return false;
}
@Override
public Object get(Object key) {
return null;
}
@Override
public Object put(Object key, Object value) {
return null;
}
@Override
public Object remove(Object key) {
return null;
}
@Override
public void putAll(Map m) {
}
@Override
public void clear() {
}
@Override
public Set keySet() {
return null;
}
@Override
public Collection values() {
return null;
}
@Override
public Set<Entry> entrySet() {
return null;
}
};
Rectangle r1 = new Rectangle(0, 0, 5, 5);
look.put("small", r1);
Rectangle r2 = new Rectangle(0, 0, 15, 15);
look.put("medium", r2);
Rectangle r3 = new Rectangle(0, 0, 25, 25);
look.put("large", r3);
Rectangle rect = (Rectangle) look.get("large");
System.out.println(rect);
//Makes no sense!!!
int size = look.size();
System.out.println(size);
boolean isEmpty = look.isEmpty();
System.out.println(isEmpty);
HashMap hash = new HashMap(20, 0.5F);
Rectangle box = new Rectangle(0, 0, 5, 5);
boolean isThere = hash.containsValue(box);
System.out.println(isThere);
}
}<file_sep>package Exc;
import java.util.StringTokenizer;
public class Ex1 {
public static void main(String[] args) {
StringTokenizer bday = new StringTokenizer("04/29/2013", "/");
while (bday.hasMoreTokens())
System.out.print("\t" + bday.nextToken());
}
}
<file_sep>package ex;
import javax.swing.*;
public class DVD extends JFrame {
JButton[] controls = new JButton[5];
public DVD() {
super("DVD");
setSize(500, 80);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
controls[0] = new JButton("Play");
controls[1] = new JButton("Stop/Eject");
controls[2] = new JButton("Rewind");
controls[3] = new JButton("Fast-Forward");
controls[4] = new JButton("Pause");
JPanel panel = new JPanel();
ButtonGroup group = new ButtonGroup();
for (JButton team : controls) {
group.add(team);
panel.add(team);
}
add(panel);
setVisible(true);
}
private static void setLookAndFeel() {
try {
UIManager.setLookAndFeel(
"com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"
);
} catch (Exception exc) {
System.out.println(exc.getMessage());
}
}
public static void main(String[] arguments) {
DVD.setLookAndFeel();
DVD ff = new DVD();
}
}<file_sep>public class Test {
int test = 10;
void printTest() {
int test = 20;
System.out.println("Test: " + test);
}
public static void main(String[] args) {
Test st = new Test();
st.printTest();
}
}
| 0800d611215de153a2607f4781be002b8c07a34b | [
"Java"
] | 5 | Java | kofnik/Java21 | 532a4a5a5a26942a4e61ffcfc9b8bf597dd8d04d | f91c8688eb3fa537c20fed57a61d95ace0a79c7a |
refs/heads/master | <repo_name>vikoivun/helpt<file_sep>/projects/adapters/base.py
class Adapter(object):
def __init__(self, data_source):
self.data_source = data_source
def sync_tasks(self, workspace):
"""
Read tasks for a given workspace.
"""
raise NotImplementedError()
<file_sep>/users/api.py
from dynamic_rest import serializers, viewsets
from .models import User
all_views = []
def register_view(klass, name=None, base_name=None):
if not name:
name = klass.serializer_class.Meta.name
entry = {'class': klass, 'name': name}
if base_name is not None:
entry['base_name'] = base_name
all_views.append(entry)
return klass
class UserSerializer(serializers.DynamicModelSerializer):
class Meta:
model = User
name = 'user'
plural_name = 'user'
@register_view
class UserViewSet(viewsets.DynamicModelViewSet):
queryset = User.objects.all()
serializer_class = UserSerializer
def get_queryset(self):
queryset = super(UserViewSet, self).get_queryset()
filters = self.request.query_params
if 'current' in filters:
queryset = User.objects.filter(pk=self.request.user.pk)
return queryset
<file_sep>/projects/adapters/github.py
from .base import Adapter
from .sync import ModelSyncher
# To handle import of Workspace, that imports GithubAdapter
from django.apps import apps
# Rest of Webhook handling
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
from django.http import HttpResponse, HttpResponseBadRequest
from django.conf.urls import url
import json
# To call Github API
import requests
import requests_cache
import logging
requests_cache.install_cache('github')
logger = logging.getLogger(__name__)
class GitHubAdapter(Adapter):
API_BASE = 'https://api.github.com/'
def api_get(self, path, **kwargs):
# GitHub does not always require authorization
if self.data_source.token:
headers = {'Authorization': 'token {}'.format(self.data_source.token)}
else:
headers = None
url = self.API_BASE + path
objs = []
while True:
resp = requests.get(url, headers=headers, params=kwargs)
assert resp.status_code == 200
objs += resp.json()
next_link = resp.links.get('next')
if not next_link:
break
url = next_link['url']
return objs
def sync_workspaces(self):
pass
def update_task(self, obj, task, users_by_id):
"""
Update a Task object with data from Github issue
:param obj: Task object that should be updated
:param task: Github issue structure, as used in Github APIs
:param users_by_id: List of local users for task assignment
"""
obj.name = task['title']
for f in ['created_at', 'updated_at', 'closed_at']:
setattr(obj, f, task[f])
obj.set_state(task['state'])
obj.save()
assignees = task['assignees']
new_assignees = set()
for assignee in assignees:
user = users_by_id.get(assignee['id'])
if not user:
continue
new_assignees.add(user)
old_assignees = set([x.user for x in obj.assignments.all()])
for user in new_assignees - old_assignees:
obj.assignments.create(user=user)
remove_assignees = old_assignees - new_assignees
if remove_assignees:
obj.assignments.filter(user__in=remove_assignees).delete()
logger.debug('#{}: [{}] {}'.format(task['number'], task['state'], task['title']))
def _get_users_by_id(self):
data_source_users = self.data_source.data_source_users.all()
return {int(u.origin_id): u.user for u in data_source_users}
def sync_tasks(self, workspace):
"""
Synchronize tasks between given workspace and its GitHub source
:param workspace: Workspace to be synced
"""
def close_task(task):
logger.debug("Marking %s closed" % task)
task.set_state('closed')
data = self.api_get('repos/{}/issues'.format(workspace.origin_id))
users_by_id = self._get_users_by_id()
Task = workspace.tasks.model
syncher = ModelSyncher(workspace.tasks.open(),
lambda task: int(task.origin_id),
delete_func=close_task)
for task in data:
obj = syncher.get(task['number'])
if not obj:
obj = Task(workspace=workspace, origin_id=task['number'])
syncher.mark(obj)
self.update_task(obj, task, users_by_id)
syncher.finish()
@csrf_exempt
@require_POST
def receive_github_hook(request):
# TODO: Verify IP whitelist
# TODO: Verify shared secret
try:
event_type = request.META['HTTP_X_GITHUB_EVENT']
except KeyError:
return HttpResponseBadRequest("GitHub event type missing")
# Respond to GitHub ping event, not really necessary, but cute
if event_type == "ping":
return HttpResponse("pong")
if event_type != "issues":
return HttpResponseBadRequest("Event type is not \"issues\". Bad hook configuration?")
try:
event = json.loads(request.body.decode("utf-8"))
# What's the exception for invalid utf-8?
except json.JSONDecodeError:
return HttpResponseBadRequest("Invalid JSON received")
except UnicodeError:
return HttpResponseBadRequest("Invalid character encoding, expecting UTF-8")
# Task management only cares about GitHub issues
if 'issue' in event:
issue_identifier = event['issue']['number']
else:
return HttpResponseBadRequest("Issue structure missing. Bad hook configuration?")
if 'repository' in event:
event_origin = event['repository']['full_name']
else:
return HttpResponseBadRequest("Repository information missing, should be included with issue")
# Work around circular imports
Workspace = apps.get_model(app_label='projects', model_name='Workspace')
try:
workspace = Workspace.objects.get(origin_id=event_origin)
except Workspace.DoesNotExist:
# TODO: Create missing workspaces
return HttpResponse("processed, no applicable workspaces found")
# Tasks must be fetched through workspaces, as their identifiers
# are only unique within workspace
Task = workspace.tasks.model
try:
task = workspace.tasks.get(origin_id=issue_identifier)
except Task.DoesNotExist:
task = Task(workspace=workspace, origin_id=issue_identifier)
adapter = workspace.data_source.adapter
users_by_id = adapter._get_users_by_id()
adapter.update_task(task, event['issue'], users_by_id)
return HttpResponse("processed, acted on")
urls = [url(r'$^', receive_github_hook)]
<file_sep>/projects/migrations/0002_auto_20161010_1731.py
# -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2016-10-10 14:31
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('projects', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='task',
name='name',
field=models.CharField(max_length=200),
),
]
<file_sep>/projects/adapters/__init__.py
from .github import GitHubAdapter
__all__ = ['GitHubAdapter']
<file_sep>/projects/api.py
from dynamic_rest import serializers, viewsets
from .models import Task, Workspace, Project, DataSource
from users.api import UserSerializer
all_views = []
def register_view(klass, name=None, base_name=None):
if not name:
name = klass.serializer_class.Meta.name
entry = {'class': klass, 'name': name}
if base_name is not None:
entry['base_name'] = base_name
all_views.append(entry)
return klass
class ProjectSerializer(serializers.DynamicModelSerializer):
class Meta:
model = Project
name = 'project'
plural_name = 'project'
@register_view
class ProjectViewSet(viewsets.DynamicModelViewSet):
queryset = Project.objects.all()
serializer_class = ProjectSerializer
class DataSourceSerializer(serializers.DynamicModelSerializer):
class Meta:
model = DataSource
name = 'data_source'
plural_name = 'data_source'
@register_view
class DataSourceViewSet(viewsets.DynamicModelViewSet):
queryset = DataSource.objects.all()
serializer_class = DataSourceSerializer
class WorkspaceSerializer(serializers.DynamicModelSerializer):
data_source = serializers.DynamicRelationField(DataSourceSerializer)
class Meta:
model = Workspace
name = 'workspace'
plural_name = 'workspace'
@register_view
class WorkspaceViewSet(viewsets.DynamicModelViewSet):
queryset = Workspace.objects.all()
serializer_class = WorkspaceSerializer
class TaskSerializer(serializers.DynamicModelSerializer):
workspace = serializers.DynamicRelationField(WorkspaceSerializer)
assigned_users = serializers.DynamicRelationField(UserSerializer, many=True)
class Meta:
model = Task
name = 'task'
plural_name = 'task'
@register_view
class TaskViewSet(viewsets.DynamicModelViewSet):
queryset = Task.objects.all()
serializer_class = TaskSerializer
<file_sep>/hours/models.py
from django.conf import settings
from django.db import models
class Entry(models.Model):
STATES = (
('public', 'public'),
('deleted', 'deleted'),
)
user = models.ForeignKey(settings.AUTH_USER_MODEL, db_index=True,
related_name='entries')
date = models.DateField(db_index=True)
task = models.ForeignKey('projects.Task', db_index=True, related_name='entries')
minutes = models.PositiveIntegerField()
state = models.CharField(max_length=20, choices=STATES, default='public')
def __str__(self):
return "{}: {:2f}h on {} by {}".format(self.date, self.minutes / 60.0,
self.task, self.user)
<file_sep>/projects/admin.py
from django.contrib import admin
from .models import GitHubDataSource, Project, Workspace, Task, ProjectUser, DataSourceUser
@admin.register(GitHubDataSource)
class GitHubDataSourceAdmin(admin.ModelAdmin):
pass
@admin.register(Project)
class ProjectAdmin(admin.ModelAdmin):
pass
@admin.register(Task)
class TaskAdmin(admin.ModelAdmin):
pass
@admin.register(Workspace)
class WorkspaceAdmin(admin.ModelAdmin):
pass
@admin.register(ProjectUser)
class ProjectUserAdmin(admin.ModelAdmin):
pass
@admin.register(DataSourceUser)
class DataSourceUserAdmin(admin.ModelAdmin):
pass
<file_sep>/projects/models.py
from django.conf import settings
from django.db import models
from .adapters import GitHubAdapter
class DataSource(models.Model):
TYPES = (
('github', 'GitHub'),
)
name = models.CharField(max_length=100)
type = models.CharField(max_length=20, choices=TYPES)
users = models.ManyToManyField(settings.AUTH_USER_MODEL, through='DataSourceUser')
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
@property
def adapter(self):
if not hasattr(self, '_adapter'):
if self.type == 'github':
self._adapter = GitHubAdapter(self.githubdatasource)
else:
raise NotImplementedError('Unknown data source type: {}'.format(self.type))
return self._adapter
def __str__(self):
return self.name
class GitHubDataSource(DataSource):
"""
GitHubDataSource is a container for GitHub-specific authentication
information. If that is not needed, it merely indicates that the
Datasource gets its information from GitHub
"""
client_id = models.CharField(max_length=100, blank=True, null=True)
client_secret = models.CharField(max_length=100, blank=True, null=True)
token = models.CharField(max_length=100, blank=True, null=True)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.type = 'github'
class DataSourceUser(models.Model):
data_source = models.ForeignKey(DataSource, db_index=True,
related_name='data_source_users')
user = models.ForeignKey(settings.AUTH_USER_MODEL, db_index=True,
related_name='data_source_users')
username = models.CharField(max_length=100, null=True, blank=True, db_index=True)
origin_id = models.CharField(max_length=100, db_index=True)
class Meta:
unique_together = (
('data_source', 'user'),
('data_source', 'username'),
('data_source', 'origin_id'),
)
def __str__(self):
return "{}: {} as {}".format(self.data_source, self.user, self.origin_id)
class Project(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return self.name
class ProjectUser(models.Model):
project = models.ForeignKey(Project, db_index=True, related_name='users')
user = models.ForeignKey(settings.AUTH_USER_MODEL, db_index=True, related_name='projects')
def __str__(self):
return "{} on {}".format(self.user, self.project)
class Workspace(models.Model):
data_source = models.ForeignKey(DataSource, db_index=True,
related_name='workspaces')
project = models.ForeignKey(Project, db_index=True,
related_name='workspaces')
name = models.CharField(max_length=100)
description = models.TextField(null=True, blank=True)
origin_id = models.CharField(max_length=100, db_index=True)
def __str__(self):
return self.name
def sync_tasks(self):
adapter = self.data_source.adapter
adapter.sync_tasks(self)
class TaskQuerySet(models.QuerySet):
def open(self):
return self.filter(state='open')
def closed(self):
return self.filter(state='closed')
class Task(models.Model):
STATE_OPEN = 'open'
STATE_CLOSED = 'closed'
STATES = (
(STATE_OPEN, 'open'),
(STATE_CLOSED, 'closed')
)
name = models.CharField(max_length=200)
workspace = models.ForeignKey(Workspace, db_index=True, related_name='tasks')
origin_id = models.CharField(max_length=100, db_index=True)
state = models.CharField(max_length=10, choices=STATES, db_index=True)
created_at = models.DateTimeField()
updated_at = models.DateTimeField()
closed_at = models.DateTimeField(null=True, blank=True)
assigned_users = models.ManyToManyField(settings.AUTH_USER_MODEL,
through='TaskAssignment',
blank=True)
objects = TaskQuerySet.as_manager()
def __str__(self):
return "{} ({})".format(self.name, self.workspace)
def set_state(self, new_state):
"""
Set the state of this task, verifying valid values
:param new_state: Requested state for this task
"""
if new_state == self.state:
return
assert new_state in [x[0] for x in self.STATES]
self.state = new_state
# FIXME, inquire why the model is saved here
# (update_fields precludes using this for new models)
# self.save(update_fields=['state'])
class Meta:
ordering = ['workspace', 'origin_id']
unique_together = [('workspace', 'origin_id')]
get_latest_by = 'created_at'
class TaskAssignment(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='task_assignments',
db_index=True)
task = models.ForeignKey(Task, related_name='assignments', db_index=True)
def __str__(self):
return "{} assigned to {}".format(self.task, self.user)
class Meta:
unique_together = [('user', 'task')]
<file_sep>/projects/migrations/0003_auto_20161019_1502.py
# -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2016-10-19 12:02
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('projects', '0002_auto_20161010_1731'),
]
operations = [
migrations.AlterField(
model_name='githubdatasource',
name='client_id',
field=models.CharField(blank=True, max_length=100, null=True),
),
migrations.AlterField(
model_name='githubdatasource',
name='client_secret',
field=models.CharField(blank=True, max_length=100, null=True),
),
migrations.AlterField(
model_name='githubdatasource',
name='token',
field=models.CharField(blank=True, max_length=100, null=True),
),
]
<file_sep>/helpt/urls.py
"""helpt URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url, include
from django.contrib import admin
from rest_framework.routers import DefaultRouter
from projects.adapters.github import urls as github_urls
from projects.views import front_page
from projects.api import all_views as project_views
from users.api import all_views as user_views
from hours.api import all_views as hour_views
router = DefaultRouter()
for view in project_views:
router.register(view['name'], view['class'], base_name=view.get('base_name'))
for view in user_views:
router.register(view['name'], view['class'], base_name=view.get('base_name'))
for view in hour_views:
router.register(view['name'], view['class'], base_name=view.get('base_name'))
urlpatterns = [
url('^', include('django.contrib.auth.urls')),
url(r'^admin/', admin.site.urls),
url(r'^v1/', include(router.urls, namespace='v1')),
url(r'^$', front_page),
url(r'^hooks/github/', include(github_urls)),
]
<file_sep>/hours/api.py
from dynamic_rest import serializers, viewsets
from .models import Entry
from users.api import UserSerializer
all_views = []
def register_view(klass, name=None, base_name=None):
if not name:
name = klass.serializer_class.Meta.name
entry = {'class': klass, 'name': name}
if base_name is not None:
entry['base_name'] = base_name
all_views.append(entry)
return klass
class EntrySerializer(serializers.DynamicModelSerializer):
user = serializers.DynamicRelationField(UserSerializer)
class Meta:
model = Entry
name = 'entry'
plural_name = 'entry'
@register_view
class EntryViewSet(viewsets.DynamicModelViewSet):
queryset = Entry.objects.all()
serializer_class = EntrySerializer
<file_sep>/hours/migrations/0002_entry_state.py
# -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2016-09-08 12:48
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('hours', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='entry',
name='state',
field=models.CharField(choices=[('public', 'public'), ('deleted', 'deleted')], default='public', max_length=20),
),
]
| 120d9b8e05fae5ddd18e6b47d11defe079369d36 | [
"Python"
] | 13 | Python | vikoivun/helpt | c54242516aa5825e71b207d08ac60f9f307466fc | 601b530617f56490266b5911c25d7956e6b63722 |
refs/heads/master | <file_sep>package com.lb.recyclerview_fast_scroller;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import com.google.android.material.tabs.TabLayout;
import com.lb.lollipopcontactsrecyclerviewfastscroller.R;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentStatePagerAdapter;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.RecyclerView.State;
import androidx.viewpager.widget.ViewPager;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//note : part of the design library sample code was taken from : https://github.com/sitepoint-editors/Design-Demo/
DesignDemoPagerAdapter adapter = new DesignDemoPagerAdapter(getSupportFragmentManager(), FragmentStatePagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
ViewPager viewPager = findViewById(R.id.viewpager);
viewPager.setAdapter(adapter);
TabLayout tabLayout = findViewById(R.id.tablayout);
tabLayout.setupWithViewPager(viewPager);
}
@Override
public boolean onCreateOptionsMenu(final Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(final MenuItem item) {
String url = null;
switch (item.getItemId()) {
case R.id.menuItem_all_my_apps:
url = "https://play.google.com/store/apps/developer?id=AndroidDeveloperLB";
break;
case R.id.menuItem_all_my_repositories:
url = "https://github.com/AndroidDeveloperLB";
break;
case R.id.menuItem_current_repository_website:
url = "https://github.com/AndroidDeveloperLB/LollipopContactsRecyclerViewFastScroller";
break;
}
if (url == null)
return true;
final Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
startActivity(intent);
return true;
}
static class DesignDemoPagerAdapter extends FragmentStatePagerAdapter {
public DesignDemoPagerAdapter(@NonNull final FragmentManager fm, final int behavior) {
super(fm, behavior);
}
@NonNull
@Override
public Fragment getItem(int position) {
final RecyclerViewFragment recyclerViewFragment = new RecyclerViewFragment();
Bundle args = new Bundle();
args.putInt(RecyclerViewFragment.ITEMS_COUNT, getFragmentItemsCount(position));
recyclerViewFragment.setArguments(args);
return recyclerViewFragment;
}
private int getFragmentItemsCount(int pos) {
return (int) Math.pow(4, (getCount() - pos));
}
@Override
public int getCount() {
return 5;
}
@Override
public CharSequence getPageTitle(int position) {
return "itemsCount: " + getFragmentItemsCount(position);
}
}
public static class RecyclerViewFragment extends Fragment {
public static final String ITEMS_COUNT = "ITEMS_COUNT";
public int numberOfItems;
@Nullable
@Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {
numberOfItems = getArguments().getInt(ITEMS_COUNT);
View rootView = inflater.inflate(R.layout.fragment_recycler_view, container, false);
RecyclerView recyclerView = rootView.findViewById(R.id.recyclerview);
final LargeAdapter adapter = new LargeAdapter(numberOfItems);
recyclerView.setAdapter(adapter);
final RecyclerViewFastScroller fastScroller = rootView.findViewById(R.id.fastscroller);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false) {
@Override
public void onLayoutCompleted(final State state) {
super.onLayoutCompleted(state);
final int firstVisibleItemPosition = findFirstVisibleItemPosition();
final int lastVisibleItemPosition = findLastVisibleItemPosition();
int itemsShown = lastVisibleItemPosition - firstVisibleItemPosition + 1;
//if all items are shown, hide the fast-scroller
fastScroller.setVisibility(adapter.getItemCount() > itemsShown ? View.VISIBLE : View.GONE);
}
});
fastScroller.setRecyclerView(recyclerView);
fastScroller.setViewsToUse(R.layout.recycler_view_fast_scroller__fast_scroller, R.id.fastscroller_bubble, R.id.fastscroller_handle);
//new Handler().postDelayed(new Runnable() {
// @Override
// public void run() {
// adapter.setItemsCount(new Random().nextInt(20));
// adapter.notifyDataSetChanged();
// }
//}, 2000L);
return rootView;
}
}
}
| 57a983d4e961e663455c419b0ad66aa6a953df16 | [
"Java"
] | 1 | Java | seneargroup/LollipopContactsRecyclerViewFastScroller | 0a1fc9cfcc6a03fea2d354a7193c996b5b65af8b | 8df1e2a4dba7ec3a28a1026830b934f2106e6e38 |
refs/heads/master | <file_sep># Image filtering using Pillow
This is an exercise intended to create a command line tool to apply 1 or more filters to an image.
#### Requirements
python 3.5+
```shell script
pip install numpy==1.17.4
pip install Pillow==6.2.1
```
or
```shell script
pip install -r requirements.txt
```
#### Example of usage
```shell script
(venv) python filter_image.py -i <path_to_input_image> -f gray_scale -o output:PNG
```
#### Available commands and rules
* -i or --input, expects a valid image as input. If this flag is not specified, the script will try the first argument as a possible image path. Example `filter_image.py example.jpg -f rotate:45` will work but `filter_image.py -f gray_scale example.jpg` won't;
* -h or --help, shows the list of available commands;
* -o or --output (optional argument), you can choose the name of the output/resulting image by giving it a path and, optionally, a format which should be either PNG or JPG.
Examples: `filter_image.py input.jpg -o result.png -f rotate:45` or `filter_image.py -f gray_scale -o result:JPG -f overlay:python.png -i input.jpg -f rotate:90`. If this tag is not specified, the resulting image will be saved in results/result_<current_time_stamp>.jpg
* -f or --filter, you can have as many of these tags as you want, knowing that the order in which you write them is the order in which they'll be applied to the original image. Every filter you want/need to apply most be preceded by a `-f` or `--filter` tag.
#### Available filters
Applying the filters, it is important to understand the arguments that are mandatory and the ones that are not. Also, the order of the arguments is strict, otherwise the filter will not recognize the argument and will be skipped in the execution.
* **gray_scale**, converts the input image to gray scale mode, no extra arguments.
```shell script
-f gray_scale
```
* **rotate**, rotates the input image in the given angle. Arguments:
- angle, [number, optional, default=45]: Defines the angle of rotation (in degrees). Examples: 45, 220.25, -30.75
- expand, [string, optional, default=false]: Tells the program if it should resize the image to make sure the rotation is not cropped. If you want this to happen make sure to write either 1, yes or true (case insensitive), else it will be considered false
- center, [string, optional, default=none]: If omitted, the rotation will happen in the center of the picture (normal behaviour). To specify a different center specify a string with two int number separated by a comma, like "100,500"
```shell script
-f rotate # will rotate the default 45 degrees
-f rotate:45 # will rotate 45 degrees because it was specified
-f rotate:45:yes # will rotate 45 degrees and expand the image to avoid cropping
-f rotate:45:1 # will rotate 45 degrees and expand the image to avoid cropping
-f rotate:45:true # will rotate 45 degrees and expand the image to avoid cropping
-f rotate:45:<anything_else> # will rotate 45 degrees and NOT expand the image, resulting in image cropping
-f rotate:45:false:100,450 # will rotate 45 degrees and expand the image to avoid cropping and rotate the image based on the new specified center in the coordinates (100, 450)
```
* **flip**, flips the image in an axis. Arguments:
- direction, [string, optional, default=horizontal]: Defines the axis on which the flip will occur. Values: "horizontal" or "vertical"
```shell script
-f flip # will flip the image from left to right
-f flip:h # will flip the image from left to right
-f flip:horizontal # will flip the image from left to right
-f flip:v # will flip the image from top to bottom (upside down)
-f flip:vertical # will flip the image from top to bottom (upside down)
-f flip:<any other thing> # will fail
```
* **sepia**, applies a sepia filter to the image. Arguments:
- ratio, [number, optional, default=1.0]: Defines the percentage, expressed from 0 to 1, of the strength of the sepia filter to be applied to the image.
```shell script
-f sepia # will apply sepia filter with total strength
-f sepia:0.25 # will apply sepia filter with 25% strength
-f sepia:-1 # will convert ratio to 0
-f sepia:1.2 # will convert ratio to 1
-f sepia:ola # will fail
```
* **black_and_white**, converts the image into a bit map, considering the threshold. Arguments:
- threshold, [number, optional, default=150]: Defines the threshold to decided what is converted to black and what is converted to white. Expecting an int number between 0 and 255
```shell script
-f black_and_white # will create a bit map where the pixels that are above 150 (default value) will be white and the rest will be black
-f black_and_white:200 # will create a bit map where the pixels that are above 200 will be white and the rest will be black
-f black_and_white:-100 # will convert threshold to 0, the whole image will be black
-f black_and_white:300 # will convert threshold to 255, the whole image will be white
-f black_and_white:ola # will fail
-f black_and_white:200.05 # will fail
```
* **resize**, resizes input image with the given dimensions. Arguments:
- new_width, [number]: Int number for the desired new width of the resulting image
- new_height, [number, optional, default=proportion]: Int number for the new height. If this field is omitted, the value for the new height will be a calculated from "new width" to keep the image's proportions
```shell script
-f resize:500 # will resize the image to 500 pixels wide and a proportional height
-f resize:500:300 # will resize the image to 500 pixels wide and 300 pixels high
-f resize:250.95 # will fail
-f resize:100:50.25 # will fail
-f resize:100:gibberish # will fail
-f resize # will fail
```
* **overlay**, applies an image with transparency over the original image. Arguments:
- path_to_overlay_image, [string]: Path to an image that has transparency (example, png or gif). If overlay image does not have transparency it will fail
- coordinates, [string, optional, default=0,0]: The anchor in the original image where the program will place the overlay. Defaults to top left corner in the coordinate (0, 0). To work, this field expects to int numbers separated by a comma, like "100,400". If any of the coordinates exceeds the dimensions of the original image, they are adjusted to the very max limit to fit the image
```shell script
-f overlay:<path_to_overlay_image> # will fail if image does not have transparency, else will apply the overlay with the anchor 0,0 (top left corner of the original)
-f overlay:python.png:100,400
-f overlay:python.png:100,AAA # will fail
-f overlay:python.png:BBB,1000 # will fail
-f overlay:<every thing that is not a valid path to an image> # will fail
-f overlay # will fail
```<file_sep># coding: utf-8
import unittest
from PIL import Image
from filter_image import (ImageWorker, InvalidFlipDirectionError, InvalidOverlayCoordinatesError)
import numpy as np
class ImageFilterTests(unittest.TestCase):
def setUp(self):
self.worker = ImageWorker(operation={
'input': Image.open('input.jpg'),
'output': 'results/result.jpg',
'filters': ['sepia', 'overlay:python.png', 'flip:horizontal']
})
def test_gray_scale(self):
img = self.worker.original_image
result = self.worker.gray_scale(image=img)
self.assertEqual(len(result.split()), 1, "Should only have one channel")
self.assertIsInstance(result, Image.Image, "Should result in PIL Image type")
def test_black_and_white_default_threshold(self):
img = self.worker.original_image
result = self.worker.black_and_white(image=img)
self.assertEqual(result.getextrema(), (0, 255), "Should only have binary values, either 0 or 255")
self.assertEqual(len(result.split()), 1, "Should only have one channel")
self.assertIsInstance(result, Image.Image, "Should result in PIL Image type")
def test_black_and_white_with_valid_threshold(self):
img = self.worker.original_image
result = self.worker.black_and_white(image=img, threshold="200")
self.assertEqual(result.getextrema(), (0, 255), "Should only have binary values, either 0 or 255")
self.assertEqual(len(result.split()), 1, "Should only have one channel")
self.assertIsInstance(result, Image.Image, "Should result in PIL Image type")
def test_black_and_white_with_invalid_threshold(self):
img = self.worker.original_image
threshold = "AAA"
with self.assertRaises(ValueError):
result = self.worker.black_and_white(image=img, threshold=threshold)
def test_flip_without_argument(self):
img = self.worker.original_image
result = self.worker.flip(image=img)
self.assertTrue(np.array_equal(np.array(result), np.flip(np.array(img), 1)))
self.assertIsInstance(result, Image.Image, "Should result in PIL Image type")
def test_flip_vertical(self):
img = self.worker.original_image
result = self.worker.flip(image=img, direction='vertical')
self.assertTrue(np.array_equal(np.array(result), np.flip(np.array(img), 0)))
self.assertIsInstance(result, Image.Image, "Should result in PIL Image type")
def test_flip_invalid_direction(self):
with self.assertRaises(InvalidFlipDirectionError):
self.worker.flip(self.worker.original_image, direction='nowhere')
self.worker.flip(self.worker.original_image, direction=[1, 2, 'a'])
self.worker.flip(self.worker.original_image, direction=-100)
def test_resize(self):
new_width = "200"
img = self.worker.original_image
result = self.worker.resize(image=img, new_width=new_width)
self.assertEqual(result.size, (int(new_width), int(int(new_width) * img.size[1] / img.size[0])))
self.assertIsInstance(result, Image.Image, "Should result in PIL Image type")
def test_resize_with_given_height(self):
new_width = 200
new_height = 300
img = self.worker.original_image
result = self.worker.resize(image=img, new_width=new_width, new_height=new_height)
self.assertEqual(result.size, (200, 300))
self.assertIsInstance(result, Image.Image, "Should result in PIL Image type")
def test_resize_with_invalid_input(self):
img = self.worker.original_image
with self.assertRaises(ValueError):
self.worker.resize(image=img, new_width="ola", new_height=100)
self.worker.resize(image=img, new_width=False, new_height="nothing")
def test_sepia(self):
result = self.worker.sepia(image=self.worker.original_image)
# there is no easy way to test if output is in sepia
self.assertIsInstance(result, Image.Image, "Should result in PIL Image type")
def test_sepia_invalid_ratio(self):
img = self.worker.original_image
with self.assertRaises(ValueError):
self.worker.sepia(image=img, ratio="AAA")
self.worker.sepia(image=img, ratio=['things', 'and', 23, 'situations'])
self.worker.sepia(image=img, ratio={'key': 'value'})
def test_rotate(self):
img = self.worker.original_image
self.assertIsInstance(self.worker.rotate(image=img), Image.Image, "Should result in PIL Image type")
self.assertIsInstance(self.worker.rotate(image=img, expand=True), Image.Image,
"Should result in PIL Image type")
self.assertIsInstance(self.worker.rotate(image=img, expand='true'), Image.Image,
"Should result in PIL Image type")
self.assertIsInstance(self.worker.rotate(image=img, expand='tRuE'), Image.Image,
"Should result in PIL Image type")
self.assertIsInstance(self.worker.rotate(image=img, expand='yEs'), Image.Image,
"Should result in PIL Image type")
self.assertIsInstance(self.worker.rotate(image=img, expand='1'), Image.Image,
"Should result in PIL Image type")
self.assertIsInstance(self.worker.rotate(image=img, expand=1), Image.Image,
"Should result in PIL Image type")
self.assertIsInstance(self.worker.rotate(image=img, center="1,1"), Image.Image,
"Should result in PIL Image type")
self.assertIsInstance(self.worker.rotate(image=img, center=(1, 2)), Image.Image,
"Should result in PIL Image type")
def test_rotate_with_invalid_coordinates(self):
img = self.worker.original_image
with self.assertRaises(ValueError):
self.worker.rotate(image=img, center="1,A")
with self.assertRaises(TypeError):
self.worker.rotate(image=img, center=1)
self.worker.rotate(image=img, center=[1, 2, 4, 5])
self.worker.rotate(image=img, center={'x': 12, 'y': 23})
def test_overlay(self):
img = self.worker.original_image
overlay_path = 'python.png'
self.assertIsInstance(self.worker.overlay(image=img, foreground_path=overlay_path), Image.Image,
"Should result in PIL Image type")
self.assertIsInstance(self.worker.overlay(image=img, foreground_path=overlay_path, coordinates=None),
Image.Image, "Should result in PIL Image type")
self.assertIsInstance(self.worker.overlay(image=img, foreground_path=overlay_path, coordinates="10,200"),
Image.Image, "Should result in PIL Image type")
self.assertIsInstance(self.worker.overlay(image=img, foreground_path=overlay_path, coordinates=[]),
Image.Image, "Should result in PIL Image type")
with self.assertRaises(InvalidOverlayCoordinatesError):
self.worker.overlay(image=img, foreground_path=overlay_path, coordinates=(1, 20))
self.worker.overlay(image=img, foreground_path=overlay_path, coordinates=100)
self.worker.overlay(image=img, foreground_path=overlay_path, coordinates="AAA")
self.worker.overlay(image=img, foreground_path=overlay_path, coordinates=[1, 45])
if __name__ == '__main__':
unittest.main()
<file_sep># coding: utf-8
import sys
from os.path import exists, isfile
from os import mkdir
import collections
from PIL import Image
import time
import numpy as np
def has_transparency(image: Image) -> bool:
return image.mode in ['RGBA', 'LA'] or (image.mode == 'P' and 'transparency' in image.info)
class KeyFlagInvokedMoreThanOnceError(Exception):
"""Raised when input or output flags are invoked more than once"""
pass
class InvalidNumberOfArgumentsError(Exception):
"""Raised when input or output flags are invoked more than once"""
pass
class InvalidFlipDirectionError(Exception):
"""Raised when a wrong value for flip filter is provided"""
pass
class ImageWithoutTransparencyError(Exception):
"""Raised when an overlay image without transparency is provided"""
pass
class InvalidOverlayCoordinatesError(Exception):
"""Raised when invalid coordinates where provided to overlay filter"""
pass
class InvalidPILImageCreatedError(Exception):
"""Raised when the program cannot create a valid PIL Image from user input"""
pass
class InvalidOutputFileExtensionProvidedError(Exception):
"""Raised when the program cannot identify a proper extension for the output file"""
pass
class OutputFlagEvokedWithoutValueError(Exception):
"""Raised when the program finds the output flag but no value to match it"""
pass
class InvalidCommandEvokedError(Exception):
"""Raised when the user calls a command that is not available in the command list"""
pass
class InputParser:
help_message = "-i or --input (required), arguments <path_to_original_image>. Example, -i input.jpg. " \
"If this flag is not specified, first argument will be looked at as a possible path.\n" \
"-f or --filter (optional), arguments <name_of_filter>, additional parameters possible separated " \
"by :, example --filter rotate:30 will rotate the input image 30 degrees\n" \
"-h or --help, will show this message with the available commands\n" \
"-o or --output (optional), arguments <path_to_output_image>, additional parameters possible " \
"separated by ':'. Example, -o ola:PNG will save the result in a PNG file called ola.png." \
" If this flag is omitted result will be saved in result.jpg"
allowed_commands = {
'-h': {'aliases': ['--help']},
'-i': {'aliases': ['--input']},
'-f': {'aliases': ['--filter']},
'-o': {'aliases': ['--output']},
}
accepted_output_formats = ['png', 'jpg', 'jpeg']
arguments = None
def __init__(self, untreated_arguments: list):
self.requested_operation = self.translate(arguments=untreated_arguments)
def get_input_image(self):
if '-i' in self.arguments:
try:
candidate = self.arguments[self.arguments.index('-i') + 1]
except IndexError:
candidate = ""
else:
# if no flag -i is found, the program assumes the first argument should be the image
candidate = self.arguments[0]
if exists(candidate) and isfile(candidate):
try:
return Image.open(candidate)
except OSError:
raise InvalidPILImageCreatedError('No proper input image was given. Run with'
' -h or --help flag for list of available commands.')
else:
return candidate
def get_filters_to_apply(self):
requested_filters = []
for index, arg in enumerate(self.arguments):
if arg == '-f':
try:
value = self.arguments[index + 1]
if value and not value.startswith('-'):
requested_filters.append(value)
except IndexError:
pass
return requested_filters
def get_output_image_name(self):
if '-o' in self.arguments:
try:
name = self.arguments[self.arguments.index('-o') + 1]
if ":" in name:
parts = name.split(':')
name = parts[0]
file_format = parts[1].lower()
if '.' in name:
name_parts = name.split('.')
if name_parts[-1] in self.accepted_output_formats:
name_parts.pop(-1)
output_filename = "_".join([part.strip() for part in name_parts])
else:
output_filename = name
else:
if '.' in name:
name_parts = name.split('.')
file_format = name_parts.pop(-1)
output_filename = "_".join([part.strip() for part in name_parts])
else:
raise InvalidOutputFileExtensionProvidedError('Invalid output file extension error:'
' no extension provided')
if file_format not in self.accepted_output_formats:
raise InvalidOutputFileExtensionProvidedError('Invalid output file extension error: provided '
'extension not acceptable, provide jpg or png')
output_filename += "." + file_format
return output_filename
except IndexError as e:
raise OutputFlagEvokedWithoutValueError(str(e) + '. No output value was given but -o flag was evoked.')
else:
return 'result_' + str(int(time.time())) + '.jpg'
def translate(self, arguments: list):
if not arguments:
raise InvalidNumberOfArgumentsError('Invalid number of arguments.\n' + self.help_message)
for key, values in self.allowed_commands.items():
aliases = values.get('aliases', [])
# for all aliases replace them by their original
for alias in aliases:
while alias in arguments:
arguments[arguments.index(alias)] = key
self.arguments = arguments
# if help is requested, discard all others and present help text
if '-h' in self.arguments:
print(self.help_message)
sys.exit(-1)
counter = collections.Counter(self.arguments)
if counter.get('-i', 0) > 1:
raise KeyFlagInvokedMoreThanOnceError('Input flag evoked more than once. Please check your arguments')
if counter.get('-o', 0) > 1:
raise KeyFlagInvokedMoreThanOnceError('Output flag evoked more than once. Please check your arguments')
# looking for invalid commands
invalid = [arg for arg in self.arguments if arg.startswith('-') and arg not in self.allowed_commands.keys()]
if invalid:
raise InvalidCommandEvokedError('Invalid command ' + invalid[0] + '. Run with -h or --help '
'flag for list of available commands.')
return {
'input': self.get_input_image(),
'filters': self.get_filters_to_apply(),
'output': self.get_output_image_name()
}
class ImageWorker:
def __init__(self, operation: dict):
self.original_image = operation.get('input', None)
self.filters_to_apply = operation.get('filters', [])
self.output = operation.get('output')
@staticmethod
def rotate(image: Image, angle: str = '45', expand: str = "false", center: str = None) -> Image:
try:
angle = float(angle)
except ValueError:
raise ValueError('Invalid angle provided for filter rotate: "' + angle + '"')
expd = True if str(expand).lower() in ['true', '1', 'yes'] else False
if center and ',' in center:
try:
coords = [float(part) for part in center.split(',')][:2]
except ValueError:
raise ValueError('Invalid center coordinate values given for '
'filter rotate: "' + center + '", please provide two numbers.')
else:
coords = None
return image.rotate(angle=angle, expand=expd, center=coords)
@staticmethod
def flip(image: Image, direction: str = "horizontal") -> Image:
if not isinstance(direction, str):
direction = str(direction)
if direction.lower() not in ['vertical', 'v', 'horizontal', 'h']:
raise InvalidFlipDirectionError('Invalid direction provided for flip method: "' + direction + '"')
return image.transpose(
Image.FLIP_TOP_BOTTOM if direction.lower() in ['v', 'vertical'] else Image.FLIP_LEFT_RIGHT)
@staticmethod
def gray_scale(image: Image) -> Image:
return image.convert('L')
@staticmethod
def black_and_white(image: Image, threshold: str = '150') -> Image:
try:
th = int(threshold)
except ValueError:
raise ValueError('Invalid threshold provided for filter '
'black_and_white: "' + threshold + '", please provide an int number')
if th < 0:
th = 0
if th > 255:
th = 255
return image.convert('L').point(lambda x: 255 if x >= th else 0, mode='1')
@staticmethod
def resize(image: Image, new_width: str, new_height: str = None) -> Image:
try:
nw = int(new_width)
except ValueError:
raise ValueError('Invalid new width provided '
'for filter resize: "' + new_width + '", please provide an int number.')
if not new_height:
new_size = (nw, int(nw * image.size[1] / image.size[0]))
else:
try:
nh = int(new_height)
new_size = (nw, nh)
except ValueError:
raise ValueError('Invalid new height provided for filter resize: "'
'' + new_height + '", please provide an int number.')
return image.resize(new_size, Image.LANCZOS)
@staticmethod
def sepia(image: Image, ratio: str = None) -> Image:
# got this one from here https://yabirgb.com/blog/creating-a-sepia-filter-with-python/ and adapted
if not ratio:
ratio = 1.0
try:
r = float(ratio)
except ValueError:
raise ValueError('Invalid ratio provided for filter sepia: "' + ratio + '"')
if r < 0:
r = 0.0
if r > 1:
r = 1.0
np_image = np.array(image)
matrix = [[0.393 + 0.607 * (1 - r), 0.769 - 0.769 * (1 - r), 0.189 - 0.189 * (1 - r)],
[0.349 - 0.349 * (1 - r), 0.686 + 0.314 * (1 - r), 0.168 - 0.168 * (1 - r)],
[0.272 - 0.349 * (1 - r), 0.534 - 0.534 * (1 - r), 0.131 + 0.869 * (1 - r)]]
s_map = np.matrix(matrix)
filtered = np.array([x * s_map.T for x in np_image])
filtered[np.where(filtered > 255)] = 255
return Image.fromarray(filtered.astype('uint8'))
@staticmethod
def overlay(image: Image, foreground_path: str, coordinates: str = None) -> Image:
if exists(foreground_path) and isfile(foreground_path):
try:
foreground = Image.open(foreground_path)
except OSError:
raise Exception('No proper overlay image was given. Make sure you are providing a png '
'image file with transparency.')
if has_transparency(foreground):
fg_image_trans = Image.new('RGBA', image.size)
if not coordinates:
# defaults to top left
coords = [0, 0]
else:
if ',' in coordinates:
try:
coords = [int(part) for part in coordinates.split(',')][:2]
if coords[0] >= image.size[0] - foreground.size[0] * 0.5:
coords[0] = image.size[0] - foreground.size[0]
if coords[1] >= image.size[1] - foreground.size[1] * 0.5:
coords[1] = image.size[1] - foreground.size[1]
except Exception as e:
raise InvalidOverlayCoordinatesError(str(e) + '. Invalid coordinates provided, write 2 '
'numbers separated by comma, like "100,200"')
else:
raise InvalidOverlayCoordinatesError('Invalid coordinates provided, write 2 numbers separated '
'by comma, like "100,200"')
fg_image_trans.paste(foreground, coords, mask=foreground.convert('RGBA'))
return Image.alpha_composite(image.convert('RGBA'), fg_image_trans).convert('RGB')
else:
raise ImageWithoutTransparencyError('The image provided for the overlay does not have transparency. '
'Please use an image with transparency to use this filter.')
else:
raise FileNotFoundError('Provided overlay path does not represent a path for an existing file')
def run(self):
if not self.original_image or isinstance(self.original_image, str):
raise InvalidPILImageCreatedError('The image provided does not exist or is invalid.')
result_image = self.original_image
for fta in self.filters_to_apply:
fields = fta.split(':')
filter_name = fields[0]
parameters = [result_image] + fields[1:]
if hasattr(self, filter_name):
try:
result_image = getattr(self, filter_name)(*parameters)
except TypeError:
print('Invalid number of arguments passed to filter "' + filter_name + '". \
Program will skip applying this filter to the resulting image.')
else:
print(filter_name + ' is not implemented (yet!)')
result_image.show()
if not exists('results'):
mkdir('results')
result_image.save('results/' + self.output)
if __name__ == '__main__':
parser = InputParser(untreated_arguments=sys.argv[1:])
ImageWorker(operation=parser.requested_operation).run()
| 38608fb7c42e1de2a9ae0901f3e98704f84e35c6 | [
"Markdown",
"Python"
] | 3 | Markdown | monthero/image_filter | e14add4d4ae7d234ce6e4370f22a38de5c1afb96 | 105f1605d648777d9a563e7c9462912fa24e324b |
refs/heads/master | <file_sep># IN DEVELOPMENT NOT READY FOR WIDESPREAD USE YET
# MyHero Alexa Service
This is the code and details for an Alexa Skill as part of a basic microservice demo application.
This provides a voice interface for a voting system where users can vote for their favorite movie superhero.
Details on deploying the entire demo to a Mantl cluster can be found at
* MyHero Demo - [hpreston/myhero_demo](https://github.com/hpreston/myhero_demo)
The application was designed to provide a simple demo for Cisco Mantl. It is written as a simple Python Flask application and deployed as a docker container.
Other services are:
* Data - [hpreston/myhero_data](https://github.com/hpreston/myhero_data)
* App - [hpreston/myhero_app](https://github.com/hpreston/myhero_app)
* Web - [hpreston/myhero_web](https://github.com/hpreston/myhero_web)
* Ernst - [hpreston/myhero_ernst](https://github.com/hpreston/myhero_ernst)
* Optional Service used along with an MQTT server when App is in "queue" mode
* Spark Bot - [hpreston/myhero_spark](https://github.com/hpreston/myhero_spark)
* Optional Service that allows voting through IM/Chat with a Cisco Spark Bot
* Tropo App - [hpreston/myhero_tropo](https://github.com/hpreston/myhero_tropo)
* Optional Service that allows voting through TXT/SMS messaging
* Alexa Skill - [hpreston/myhero_alexa](https://github.com/hpreston/myhero_alexa)
* Optional Serice that allows voting through a Amazon Alexa voice interface
The docker containers are available at
* Data - [hpreston/myhero_data](https://hub.docker.com/r/hpreston/myhero_data)
* App - [hpreston/myhero_app](https://hub.docker.com/r/hpreston/myhero_app)
* Web - [hpreston/myhero_web](https://hub.docker.com/r/hpreston/myhero_web)
* Ernst - [hpreston/myhero_ernst](https://hub.docker.com/r/hpreston/myhero_ernst)
* Optional Service used along with an MQTT server when App is in "queue" mode
* Spark Bot - [hpreston/myhero_spark](https://hub.docker.com/r/hpreston/myhero_spark)
* Optional Service that allows voting through IM/Chat with a Cisco Spark Bot
* Tropo App - [hpreston/myhero_tropo](https://hub.docker.com/r/hpreston/myhero_tropo)
* Optional Service that allows voting through TXT/SMS messaging
* Alexa Skill - [hpreston/myhero_alexa](https://hub.docker.com/r/hpreston/myhero_alexa)
* Optional Serice that allows voting through a Amazon Alexa voice interface
## Alexa Skill Details
This repo contains the Python code for an AWS Lambda function that can be linked to an Alexa Skill through Amazon's Developer Site. Also included are files with the utterances and intents source needed to fully install the function.
_You will need to replace the URL for your myhero_app service in the code prior to uploading to AWS Lambda_
## Skill Installation Steps
...
## Using the Skill
...
<file_sep>from __future__ import print_function
from config import app_server, app_headers
import requests
# --------------- Helpers that build all of the responses ----------------------
def build_speechlet_response(title, output, reprompt_text, card_text, should_end_session):
return {
'outputSpeech': {
'type': 'SSML',
'ssml': output
},
'card': {
'type': 'Simple',
'title': title,
'content': card_text
},
'reprompt': {
'outputSpeech': {
'type': 'SSML',
'ssml': reprompt_text
}
},
'shouldEndSession': should_end_session
}
def build_response(session_attributes, speechlet_response):
return {
'version': '1.0',
'sessionAttributes': session_attributes,
'response': speechlet_response
}
# --------------- Handle Incoming Requests -------------------------------------
def lambda_handler(event, context):
""" Route the incoming request based on type (LaunchRequest, IntentRequest,
etc.) The JSON body of the request is provided in the event parameter.
"""
print("Full Incoming Event Details: " + str(event))
print("event.session.application.applicationId=" + event['session']['application']['applicationId'])
"""
Uncomment this if statement and populate with your skill's application ID to
prevent someone else from configuring a skill that sends requests to this
function.
Left commented out for sharing on GitHub, set to actual app id when coping to Lambda
"""
# if (event['session']['application']['applicationId'] !=
# "amzn1.echo-sdk-ams.app.c30c2867-91a5-4cc7-8bd3-5148ff1bd18f"):
# raise ValueError("Invalid Application ID")
# Create two main objects from the 'event'
session = event['session']
request = event['request']
# Get or Setup Session Attributes
# Session Attributes are used to track elements like current question details, last intent/function position, etc
session_attributes = load_session_attributes(session)
session["attributes"] = session_attributes
# Write Session attributes to Lambda log for troubleshooting assistance
print("Session Attributes: " + str(session["attributes"]))
# pprint(session["attributes"])
if session['new']:
on_session_started({'requestId': request['requestId']}, session)
if request['type'] == "LaunchRequest":
return on_launch(request, session)
elif request['type'] == "IntentRequest":
return on_intent(request, session)
elif request['type'] == "SessionEndedRequest":
return on_session_ended(request, session)
def on_session_started(session_started_request, session):
""" Called when the session starts """
print("on_session_started requestId=" + session_started_request['requestId'] + ", sessionId=" + session['sessionId'])
def on_launch(launch_request, session):
""" Called when the user launches the skill without specifying what they
want
"""
print("on_launch requestId=" + launch_request['requestId'] + ", sessionId=" + session['sessionId'])
# Dispatch to your skill's launch
return get_welcome_response(launch_request, session)
def on_intent(intent_request, session):
"""
Called when the user specifies an intent for this skill.
Main logic point to determine what action to take based on users
request.
"""
print("on_intent requestId=" + intent_request['requestId'] +
", sessionId=" + session['sessionId'])
# Get key details from intent_request object to work with easier
intent = intent_request['intent']
intent_name = intent_request['intent']['name']
# Find the Previous Place if stored
# "previous_place" is used to deal with intents and responses that are contextual
try:
previous_place = session["attributes"]["previous_place"]
except:
previous_place = None
# Dispatch to your skill's intent handlers
if intent_name == "AMAZON.HelpIntent":
# User has asked for help, return the help menu
return get_help(intent, session)
elif intent_name == "AMAZON.StopIntent":
# Built-in intent for when user says something like "Stop"
# Standard End Game Message
return no_more(intent, session)
elif intent_name == "AMAZON.CancelIntent":
# Built-in intent for when user says something like "Cancel"
# Standard End Game Message
return no_more(intent, session)
elif intent_name == "StartGame":
return get_welcome_response(intent, session)
elif intent_name == "Options":
return return_options(intent, session)
elif intent_name == "Results":
return return_results(intent, session)
elif intent_name == "Vote":
return return_vote(intent, session)
elif intent_name == "AMAZON.YesIntent":
# For when user provides an answer like "Yes"
# Depending on the previous question asked, differnet actions must be taken
if previous_place in ["welcome", "get help"]:
return return_options(intent, session)
else:
# If the a "Yes" response wouldn't make sense based on previous place, end game
return get_welcome_response(intent, session)
elif intent_name == "AMAZON.NoIntent":
# For when user provides an answer like "No"
# Depending on the previous question asked, differnet actions must be taken
if previous_place in ["welcom"]:
return no_more(intent, session)
else:
# Default action to end game
return no_more(intent, session)
else:
# If an intent doesn't match anythign above, it is unexpected
# and raise error. This is mostly here for development and troubleshooting.
# Should NOT occur during normal use.
return get_welcome_response(intent, session)
# raise ValueError("Invalid intent")
def on_session_ended(session_ended_request, session):
""" Called when the user ends the session.
Is not called when the skill returns should_end_session=true
"""
print("on_session_ended requestId=" + session_ended_request['requestId'] + ", sessionId=" + session['sessionId'])
# add cleanup logic here
# --------------- Functions that control the skill's Intents ------------------
def get_welcome_response(request, session):
"""
Welcome the user to the application and provide instructions to get started.
"""
# Setup the response details
card_title = "Welcome to MyHero."
text = "Welcome to MyHero. Let's figure out the best onscreen superhero. " \
"Would you like to hear the options? "
speech_output = "<speak>" + text + "</speak>"
# If the user either does not reply to the welcome message or says something
# that is not understood, they will be prompted again with this text.
reprompt_text = "<speak>Want to hear the options? </speak>"
should_end_session = False
session["attributes"]["previous_place"] = "welcome"
return build_response(
session["attributes"],
build_speechlet_response(
card_title,
speech_output,
reprompt_text,
text,
should_end_session
)
)
def return_options(intent, session):
# Setup the response details
options = get_options()
card_title = "MyHero Voting Options."
text = "The possible hero's you can vote for are as follows. "
for option in options:
text += "%s, " % (option)
text = text[0:-2] + ". "
text += "Who would you like to vote for? "
speech_output = "<speak>" + text + "</speak>"
# If the user either does not reply to the welcome message or says something
# that is not understood, they will be prompted again with this text.
reprompt_text = "<speak>Who would you like to vote for? </speak>"
should_end_session = False
session["attributes"]["previous_place"] = "return options"
return build_response(
session["attributes"],
build_speechlet_response(
card_title,
speech_output,
reprompt_text,
text,
should_end_session
)
)
def return_results(intent, session):
# Setup the response details
results = get_results()
card_title = "MyHero Current Standing."
text = "The current standings are as follows. "
for result in results:
text += "%s has %s " % (result[0], result[1])
if int(result[1]) > 1:
text += "votes. "
else:
text += "vote. "
text += "Who would you like to vote for? "
speech_output = "<speak>" + text + "</speak>"
# If the user either does not reply to the welcome message or says something
# that is not understood, they will be prompted again with this text.
reprompt_text = "<speak>Who would you like to vote for? </speak>"
should_end_session = False
session["attributes"]["previous_place"] = "return results"
return build_response(
session["attributes"],
build_speechlet_response(
card_title,
speech_output,
reprompt_text,
text,
should_end_session
)
)
def return_vote(intent, session):
# Setup the response details
vote = intent['slots']['superhero']['value']
entry = check_vote(vote)
card_title = "MyHero Vote Submitted."
if entry:
text = "Thank you for your vote for %s. It has been recorded. " % (entry[0])
speech_output = "<speak>" + text + "</speak>"
reprompt_text = ""
# If the user either does not reply to the welcome message or says something
# that is not understood, they will be prompted again with this text.
should_end_session = True
else:
text = "I couldn't understand your vote. Please try again. "
speech_output = "<speak>" + text + "</speak>"
reprompt_text = "Please vote again. "
should_end_session = False
session["attributes"]["previous_place"] = "return vote"
return build_response(
session["attributes"],
build_speechlet_response(
card_title,
speech_output,
reprompt_text,
text,
should_end_session
)
)
def get_help(intent, session):
'''
Help function for the skill.
'''
card_title = "MyHero Help"
text = "Looking for help? MyHero is easy to use. " \
"To find out the possible options, just ask 'What are the options?'" \
"To find out the current standings, just ask 'What are the current standings?" \
"And to place a vote, just say 'I'd like to vote for MyHero', and say your vote instead of 'MyHero'. "
speech_output = "<speak>" \
+ text + \
"<break time=\"500ms\" />" \
"Would you like to hear the options? " \
"</speak>"
# If the user either does not reply to the welcome message or says something
# that is not understood, they will be prompted again with this text.
reprompt_text = "<speak>Well, would you like to hear the options? </speak>"
should_end_session = False
session["attributes"]["previous_place"] = "get help"
return build_response(
session["attributes"],
build_speechlet_response(
card_title,
speech_output,
reprompt_text,
text,
should_end_session
)
)
def no_more(intent, session):
'''
User has indicated they are done. Provide a message closing the game, and end session.
'''
reprompt_text = None
card_title = "Thanks for your Vote!"
text = "Thanks so much for stopping by. It is important we find out who the best hero is. "
speech_output = "<speak>" \
+ text + \
"</speak>"
should_end_session = True
return build_response(
session["attributes"],
build_speechlet_response(
card_title,
speech_output,
reprompt_text,
text,
should_end_session
)
)
# ---------------- Functions to generate needed information --------------------
# Utilities to interact with the MyHero-App Server
def get_results():
u = app_server + "/results"
page = requests.get(u, headers = app_headers)
tally = page.json()
tally = sorted(tally.items(), key = lambda (k,v): v, reverse=True)
return tally
def get_options():
u = app_server + "/options"
page = requests.get(u, headers=app_headers)
options = page.json()["options"]
return options
def place_vote(vote):
u = app_server + "/vote/" + vote
page = requests.post(u, headers=app_headers)
return page.json()
def check_vote(vote):
options = get_options()
lower_options = []
dash_to_space_options = []
dash_remove_options = []
vote_index = False
for option in options:
lower_options.append(option.lower())
dash_to_space_options.append(option.replace("-", " ").lower())
dash_remove_options.append(option.replace("-", "").lower())
try:
vote_index = lower_options.index(vote.lower())
vote_submit = options[vote_index]
except ValueError:
try:
vote_index = dash_to_space_options.index(vote.lower())
vote_submit = options[vote_index]
except ValueError:
try:
vote_index = dash_remove_options.index(vote.lower())
vote_submit = options[vote_index]
except ValueError:
print("Couldn't find option for %s. " % (vote))
return False
print("Placing vote for %s. " % (vote_submit))
return ((vote_submit, place_vote(vote_submit)))
def load_session_attributes(session):
'''
Determine either current, or new session_attributes
'''
try:
# First try to pull from existing session
session_attributes = session["attributes"]
except:
# If fails, this is a new session and create new attributes
session_attributes = setup_session_attributes()
return session_attributes
def setup_session_attributes():
'''
Sets up initial Math Dog Session Attributes if new session.
'''
session_attributes = {}
return session_attributes
<file_sep>app_server = "http://myhero-app"
app_server_key = "APP KEY"
app_headers = {}
app_headers["Content-type"] = "application/json"
app_headers["key"] = app_server_key
| 9160d89dba71403d69df9ec7864344fc28559a52 | [
"Markdown",
"Python"
] | 3 | Markdown | juliogomez/myhero_alexa | df3d36f7d98f442f931c1caa35e20d365a5aa41a | 05b714986396e648df63a59ddf7da4a10631f652 |
refs/heads/master | <repo_name>Oclemy/ASPCoreMenuPages<file_sep>/README.md
# ASPCoreMenuPages
This is our first ASP.NET Core MVC tutorial. We use it alongside MaterializeCSS and show and navigate through material menus.More at http://camposha.info/source/asp-net-core-mvc-s1e1-materializecss-navigate-menus-and-pages/
<file_sep>/src/MenuPages/Controllers/HomeController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace MenuPages.Controllers
{
public class HomeController : Controller
{
/*
* ACTION TO RETURN HOMEPAGE
*/
public IActionResult Index()
{
ViewData["description"] = "Welcome to Camposha.info. Alongside ProgrammingWizards TV we provide easy to understand Programming guides in various languages.";
return View();
}
/*
* ACTION TO RETURN ABOUT US PAGE
*/
public IActionResult About()
{
ViewData["description"] = "Camposha.info is a programming tutorials website.Alongside ProgrammingWizards TV, they provide easy to understand programming guides in different programming languages.";
return View();
}
/*
* ACTION TO RETURN CONTACT US PAGE
*/
public IActionResult Contact()
{
ViewData["descritipm"] = "You can contact camposha.info at our website or via our programmingwizards tv youtube channel.";
return View();
}
public IActionResult Error()
{
return View();
}
}
}
| 2fadf0df659f707d1b5f3eff0dfe08419d8d61c4 | [
"Markdown",
"C#"
] | 2 | Markdown | Oclemy/ASPCoreMenuPages | 9aef9a8b23737927f711410a34b599ba9aabfa5a | c4468c82367187bef6ebcd1f7fed0541bda91a26 |
refs/heads/master | <file_sep>require './setting.rb'
CONVERTS = {
:APIKEY => :api_key,
:APISECRET => :api_secret,
:TOKENKEY => :token_key,
:TOKENSECRET => :token_secret
}
@setting = Setting.new false
def read
puts "Reading old settings..."
IO.readlines(@setting.filename).each do |line|
Setting::REGEXP_SETTING_PAIR.match line.chomp do |md|
old_key = md[:key].to_sym
new_key = CONVERTS[old_key]
value = md[:value]
@setting[new_key] = value if CONVERTS.keys.include? old_key
end
end
end
def check
puts "Settings are converting to new version below:"
puts @setting.to_s
print "Save it [y/N]? "
act = gets.chomp
if act == "y" or act == "Y"
puts "Saving..."
@setting.write!
puts "Saved! You can start ke__ri robot now!"
else
puts "ABORT! If you sure to convert old settings, run again this script and type 'y'."
end
end
read
check
<file_sep># encoding: utf-8
require './kekeri.rb'
instance = KeKeRi.new
# Thread.new {
# while true
# begin
# instance.acceptAllFriends
# sleep 30
# rescue
# sleep 10
# retry
# end
# end
# }
Thread.new {
begin
instance.listenChannel while true
rescue
retry
end
}
# check unreadPlurk once on start
begin
instance.checkUnreadPlurk
rescue
puts %(#{Time.now.to_s} [ERROR] Checking unread plurk has error: #{$!.to_s})
end
while true
case gets.chomp
when "check"
p instance.checkUnreadPlurk
when "get"
p instance.getUnreadPlurk
when "close"
exit
end
end
<file_sep>class Setting < Struct.new(:api_key, :api_secret, :token_key, :token_secret)
VERSION = 1.2
OLD_KEYS = %W(APIKEY APISECRET TOKENKEY TOKENSECRET)
attr_reader :filename
def initialize(autoload = true)
@filename = ENV["SETTING_FILE"] || "setting.db"
return unless autoload
wizard unless File.exists? @filename
self.read
wizard unless self.check?
end
# Modify setting in an intaractive way.
def wizard
puts "Please entry below informations,"
print "API key [#{self.api_key}]: "
value = gets.chomp
self.api_key = value unless value.empty?
print "API sercet key [#{self.api_secret}]: "
value = gets.chomp
self.api_secret = value unless value.empty?
print "Token key [#{self.token_key}]: "
value = gets.chomp
self.token_key = value unless value.empty?
print "Token secret key [#{self.token_secret}]: "
value = gets.chomp
self.token_secret = value unless value.empty?
self.write!
puts self.to_s
end
REGEXP_SETTING_PAIR = /^(?<key>\w+)\s*=\s*(?<bracket>'|")(?<value>[[:word:]]*)\k<bracket>$/
def read
puts "Read setting..."
IO.readlines(@filename).each do |line|
REGEXP_SETTING_PAIR.match line.chomp do |md|
key = md[:key].to_sym
value = md[:value]
self[key] = value if self.members.include? key
puts "WARNING! Found old option: #{md[:key]}. You may run setting_upgrade.rb before starting ke__ri robot." if OLD_KEYS.include? md[:key]
end
end
end
def write!
File.open @filename, "w" do |io|
io.puts %(# Notice! Do NOT add option which is not effective. They will be cleared with next wizard.)
io.puts %(# Generated by v#{VERSION}.)
self.members.each do |key|
io.puts %(#{key} = "#{self[key]}")
end
end
end
def check?
self.members.each do |key|
next unless self[key].nil? or self[key].empty?
puts %(Missing necessary key: #{key})
return false
end
true
end
def to_s
result = "{\n"
self.members.each do |key|
result << %(\t#{key} => #{self[key]}\n)
end
result << "}"
end
end
<file_sep>ke__ri-robot
============
Ke __ Ri Robot. ㄎ__ㄖ機器人。
<file_sep># encoding: utf-8
require './plurk.rb'
require './setting.rb'
require 'time'
require 'net/http'
class KeKeRi
REGEXP_CHANNEL = /^CometChannel\.scriptCallback\((.*)\);/
attr_reader :setting
def initialize
@setting = Setting.new
@plurkApi = Plurk.new(@setting.api_key, @setting.api_secret)
@plurkApi.authorize(@setting.token_key, @setting.token_secret)
puts "Ke Ke Ri Robot loaded."
end
def listenChannel
getChannel while @channelUri.nil?
getChannel if @channelOffset == -3
params = { :channel => @channelName, :offset => @channelOffset }
params = params.map { |k,v| "#{k}=#{v}" }.join('&')
uri = URI.parse(@channelUri + "?" + params)
http = Net::HTTP.new(uri.host, uri.port)
http.read_timeout = 170
retryGetting = 0
begin
res = http.start do |h|
h.get(uri.path+"?"+params)
end
rescue
retryGetting += 1
sleep 3
if retryGetting == 5
getChannel
return false
end
retry
end
res = REGEXP_CHANNEL.match res.body
json = JSON.parse res[1]
readed = []
@channelOffset = json["new_offset"].to_i
return if json["data"].nil?
json["data"].each do |plurk|
case plurk["type"]
when "new_response"
when "new_plurk"
responseNewPlurk plurk
end
end
end
def addPlurk(content, options = {})
options = { qualifier: ':', lang: 'tr_ch' }.merge options
begin
json = @plurkApi.post '/APP/Timeline/plurkAdd', options.merge(content: content)
rescue
str = %(#{Time.now.to_s} [ERROR] Adding plurk has error: #{$!.to_s})
if json
str << "(#{json["error_text"]})" if json.key? "error_text"
end
puts str
sleep 120
retry
end
return json
end
def addPrivatePlurk(content, user_id, options = {})
options = { qualifier: ':', lang: 'tr_ch' }.merge options
begin
json = @plurkApi.post '/APP/Timeline/plurkAdd', options.merge(content: content, limited_to: [[user_id]])
rescue
str = %(#{Time.now.to_s} [ERROR] Adding private plurk has error: #{$!.to_s})
if json
str << "(#{json["error_text"]})" if json.key? "error_text"
end
puts str
sleep 120
retry
end
end
def responsePlurk(plurk_id, content, options = {})
options = { qualifier: ':', lang: 'tr_ch' }.merge options
begin
res = @plurkApi.post '/APP/Responses/responseAdd', options.merge(plurk_id: plurk_id, content: content)
rescue
puts %(#{Time.now.to_s} [ERROR] Responsing plurk has error: #{$!.to_s})
end
end
def checkUnreadPlurk
json = @plurkApi.post '/APP/Timeline/getUnreadPlurks', limit: 20
return if json["plurks"].nil?
json["plurks"].each do |plurk|
responseNewPlurk plurk
end
end
private
def getUnreadPlurk
begin
json = @plurkApi.post '/APP/Timeline/getUnreadPlurks'
rescue
puts %(#{Time.now.to_s} [ERROR] Getting unread plurks has error: #{$!.to_s})
sleep 5
retry
end
return json
end
def responsed?(plurk_id)
begin
json = @plurkApi.post '/APP/Responses/get', plurk_id: plurk_id
rescue
puts %(#{Time.now.to_s} [ERROR] Getting response has error: #{$!.to_s})
sleep 5
retry
end
json["responses"].each do |res|
return false if res["user_id"] == 10428113 #<--- 10428113 robot id
end
true
end
UCCU_KE_EMOS = [
[%(http://emos.plurk.com/c24f5a2d357cf6bed76097cb2917135c_w48_h48.jpeg)] * 10,
[%(http://emos.plurk.com/c75c14b823b317b9485f551dc3be8adc_w48_h48.jpeg)] * 10,
[%(http://emos.plurk.com/e01d1a6e849e6fc957a551fdc8f8d189_w48_h48.png)] * 10,
[%(http://emos.plurk.com/4307884b41c65c081c00d7a707b3457a_w48_h48.png)] * 10,
[%(http://emos.plurk.com/2ab4aa6dfacda9b2443a083915bef84f_w48_h48.jpeg --Double Kill--)] * 1
].flatten
UCCU_EMOS = %W(
//emos.plurk.com/0ff9b6499d9fc067076299e4e84cb9f9_w48_h48.jpeg
//emos.plurk.com/40727c48d696d04cbdc8461205e8d127_w48_h48.jpeg
//emos.plurk.com/0dda843baf91d5fc522416746e470d8a_w43_h48.png
//emos.plurk.com/0159d81c5f0d0eee1679d1546a16d430_w48_h48.jpeg
//emos.plurk.com/d560946c25c7238688f1920de0127d33_w48_h48.jpeg
//emos.plurk.com/54a61a948246082c94245b31fc3eb22f_w48_h48.jpeg
//emos.plurk.com/4732b82e8d81f1a147cf5f32ea8f189e_w48_h48.jpeg
//emos.plurk.com/df73fcc3007ead42cc871049677d5e58_w48_h48.jpeg
//emos.plurk.com/a428060b74d0f7f46d72f50eb3ffe8e9_w48_h48.jpeg
//emos.plurk.com/ce5f816d361977120209f9ecba5b5fc1_w48_h48.jpeg
//emos.plurk.com/94accbcde00b9f8e85721a8df10b2acc_w48_h48.jpeg
//emos.plurk.com/1815edc3b780b32136a10775878121d8_w48_h48.jpeg
//emos.plurk.com/785a8439633d9cc2343bd0b25d4446b7_w48_h48.jpeg
//emos.plurk.com/16b7f9906d55be0fabf3d0bbbd35d86a_w48_h48.jpeg
//emos.plurk.com/7618969bf18f69f64db8e41750159c5a_w48_h48.jpeg
//emos.plurk.com/fb20cd88b72e8af6378228d764b68996_w48_h48.jpeg
//emos.plurk.com/266e229f51fb03183241c458c7ecd859_w48_h48.jpeg
//emos.plurk.com/b3a65f97fb489e4e97c9f613d486bae7_w48_h48.gif
//emos.plurk.com/b6fbf8deeb375f417ecb8e290bfd7ca5_w48_h48.jpeg
//emos.plurk.com/c75c14b823b317b9485f551dc3be8adc_w48_h48.jpeg
//emos.plurk.com/c24f5a2d357cf6bed76097cb2917135c_w48_h48.jpeg
//emos.plurk.com/e01d1a6e849e6fc957a551fdc8f8d189_w48_h48.png
//emos.plurk.com/2ab4aa6dfacda9b2443a083915bef84f_w48_h48.jpeg
//emos.plurk.com/4307884b41c65c081c00d7a707b3457a_w48_h48.png
//emos.plurk.com/2eed93c518b44ed937e1d8d82fe83fd5_w48_h48.jpeg
//emos.plurk.com/738d3c68a21ef02777ea0f964d96e030_w48_h48.jpeg
)
def responseNewPlurk(plurk)
return unless responsed? plurk["plurk_id"]
resp = []
case plurk["owner_id"]
when 10428113 # bot id
case plurk["content"]
when /今日ㄎ_ㄖ指數/
resp << "ㄎ_ㄖ的粉專是「 https://www.facebook.com/IamMasterILoveLoly (無限期支持蘿莉控ㄎ_ㄖ大濕) 」\n" +
"歡迎大家相邀厝邊頭尾、親朋好友及舊雨新知來按讚! " + UCCU_KE_EMOS.sample
end
when 5845208 # andy810625
if plurk["content"].match /無聊/
responsePlurk(plurk["plurk_id"], "無聊嗎? 聽我講個笑話吧~ 有一個人叫ㄎ_ㄖ然後他就被ㄎ_ㄖ了...(lmao)", { qualifier: 'says' })
else
if rand(100) > 12
resp << "ㄎ__ㄖ"
else
resp << "我說我是蘿莉控,當時是為了向這個社會證明雨神的ㄎㄖ是真的。\n" +
"我這樣講,是為了整個ㄎㄖ神社的和諧,可是你今天在講我是蘿莉控的時候,你是在撕裂整個社會,謀的是你個人的政治利益。\n" +
"我看待蘿莉控,跟看待你一樣,你們都是我的獵物。作為ㄎㄖ,你們都是獵物而已。"
end
end
else # others
case plurk["content"]
when /ㄎ[__]*ㄖ/
resp << "ㄎ__ㄖ"
when /UCCU/i, /<a[^>]*href="http:\/\/www.plurk.com\/andy810625"[^>]*>/ # @andy810625
resp << UCCU_KE_EMOS.sample
when *UCCU_EMOS.map { |uccu| /<img[^>]*src="[^"]*#{uccu}"[^>]*>/ }
resp << UCCU_KE_EMOS.sample
when /笑話/, /好笑/, /XD/i, /\/\/s\.plurk\.com\/92b595a573d25dd5e39a57b5d56d4d03\.gif/, /\/\/s\.plurk\.com\/615f18f7ea8abc608c4c20eaa667883b\.gif/, /\/\/s\.plurk\.com\/8600839dc03e6275b53fd03a0eba09cf\.gif/
resp << "有一個人很機車,他就被騎走了,有一隻猴子叫ㄎㄖ,他就被……咦,我還以為我記得這個笑話說。"
end
end
return if resp.empty?
responsePlurk(plurk["plurk_id"], resp * " ")
@plurkApi.post '/APP/Timeline/mutePlurks', ids: [[plurk["plurk_id"]]]
end
def getChannel
begin
resp = @plurkApi.post("/APP/Realtime/getUserChannel")
rescue Timeout::Error
sleep 2 # let it take a rest
retry
end
if resp["comet_server"].nil?
puts 'Failed to get channel.'
return false
end
@channelUri = resp["comet_server"]
@channelName = resp["channel_name"]
@channelOffset = -1
puts 'Get channel uri: ' + @channelUri
puts 'Get channel name: ' + @channelName
return true
end
end
<file_sep># encoding: utf-8
require './kekeri.rb'
instance = KeKeRi.new
puts instance.addPlurk <<-END, qualifier: 'feels'
今日ㄎ_ㄖ指數
運輸工具ㄎ_ㄖ:(bz)
天氣ㄎ_ㄖ:(bz)、運氣ㄎ_ㄖ:(bz)
宅氣ㄎ_ㄖ:(bz)、機械ㄎ_ㄖ:(bz)
地牛ㄎ_ㄖ:(bz)、身材ㄎ_ㄖ:(bz)
--
紅色:極為ㄎ_ㄖ、藍色:還滿ㄎ_ㄖ
綠色:略為ㄎ_ㄖ、黑色:極不ㄎ_ㄖ
END
| d0ccd57ff91054e991584018b2ac81cb7a1a86f4 | [
"Markdown",
"Ruby"
] | 6 | Ruby | david50407/ke__ri-robot | e5c80c7d3d1837d1b568265d6876c9b757463eae | b03dafe1083cfc9a97be4070791242e11e5f92de |
refs/heads/master | <file_sep>//
// MainViewController.swift
// MySocialApp
//
// Created by Hugo on 29/07/17.
// Copyright © 2017 Hugo. All rights reserved.
//
import UIKit
class MainViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
}
| fdf56d1caffd4c02e1ef8e4eb23679d07ac3e8be | [
"Swift"
] | 1 | Swift | HugoVP/MySocialApp | ab966e19184ffbeaaa2d208627040f113d634ff8 | e693ac866d3c1d6c3710253f62d43628e566e6a6 |
refs/heads/master | <file_sep><?php
use PHPUnit\Framework\TestCase;
use App\entities\Apartment\ApartmentFactory;
use App\entities\Apartment\MyApartment;
class ApartmentFactoryTest extends TestCase
{
public function testMyApartmentCreation(): void
{
$myApartment = ApartmentFactory::build('My');
$this->assertInstanceOf(MyApartment::class, $myApartment);
}
}
<file_sep><?php
namespace App\entities\Robot\Interfaces;
use App\entities\Apartment\Interfaces\Apartment;
interface Bot
{
}
<file_sep><?php
namespace App\entities\Apartment;
use App\entities\Floor\Interfaces\Floor;
use App\entities\Apartment\Interfaces\Apartment;
class MyApartment implements Apartment
{
private $floor;
public function setFloor(Floor $floorType): void
{
$this->floor = $floorType;
}
public function getFloor(): Floor
{
return $this->floor;
}
}
<file_sep><?php
namespace App\entities\Battery\Interfaces;
interface Battery
{
public function setBatteryMaxCapacity(int $batteryCapacity): void;
public function getBatteryMaxCapacity(): int;
public function setChargingTime(int $time): void;
public function getChargingTime(): int;
public function setBattery(int $currBatteryLevel): void;
public function getBattery(): int;
public function getTimesCharged(): int;
public function setTimesCharged(int $timesCharged): void;
public function isBatteryEmpty(): bool;
}
<file_sep><?php
namespace App\entities\Robot\Interfaces;
interface RobotCost
{
public function setCleaningCost(int $cost) : void;
public function getCleaningCost(): int;
}
<file_sep><?php
namespace App\entities\Floor\Interfaces;
interface Floor
{
public function setArea(int $area): void;
public function getArea() : int;
}
<file_sep><?php
use PHPUnit\Framework\TestCase;
use App\entities\Charger\FastCharger;
use App\entities\Battery\MiniBattery;
class FastChargerTest extends TestCase
{
private static $fastCharger;
private static $battery;
public static function setUpBeforeClass(): void
{
static::$fastCharger = new FastCharger();
static::$battery = new MiniBattery();
static::$battery->setBatteryMaxCapacity(5);
static::$battery->setChargingTime(5);
static::$battery->setTimesCharged(0);
static::$battery->setBattery(5);
}
public static function tearDownAfterClass(): void
{
static::$fastCharger = null;
static::$battery = null;
}
public function testInstallBattery(): void
{
static::$fastCharger->setBattery(static::$battery);
$this->assertInstanceOf(MiniBattery::class, static::$fastCharger->getBattery());
}
public function testGetBattery(): void
{
$this->assertInstanceOf(MiniBattery::class, static::$fastCharger->getBattery());
}
}
<file_sep><?php
use PHPUnit\Framework\TestCase;
use App\entities\Floor\CarpetFloor;
class CarpetFloorTest extends TestCase
{
private static $carpetFloor;
private static $area;
private static $cleaningCost;
public static function setUpBeforeClass(): void
{
static::$carpetFloor = new CarpetFloor();
static::$area = 60;
static::$cleaningCost = 2;
}
public static function tearDownAfterClass(): void
{
static::$carpetFloor = null;
static::$area = null;
}
public function testSetArea(): void
{
static::$carpetFloor->setArea(static::$area);
$this->assertEquals(static::$carpetFloor->getArea(), static::$area);
}
public function testGetArea(): void
{
$this->assertEquals(static::$carpetFloor->getArea(), static::$area);
}
public function testSetCleaningCost(): void
{
static::$carpetFloor->setCleaningCost(static::$cleaningCost);
$this->assertEquals(static::$carpetFloor->getCleaningCost(), static::$cleaningCost);
}
public function testGetCleaningCost(): void
{
$this->assertEquals(static::$carpetFloor->getCleaningCost(), static::$cleaningCost);
}
}
<file_sep><?php
use PHPUnit\Framework\TestCase;
use App\entities\Apartment\MyApartment;
use App\entities\Floor\CarpetFloor;
use App\entities\Floor\HardFloor;
class MyApartmentTest extends TestCase
{
private $myApartment;
protected function setUp(): void
{
$this->myApartment = new MyApartment();
}
protected function tearDown(): void
{
unset($this->myApartment);
}
public function testCarpetSetArea(): void
{
$floor = new CarpetFloor();
$this->myApartment->setFloor($floor);
$this->assertInstanceOf(CarpetFloor::class, $this->myApartment->getFloor());
}
public function testCarpetGetFloor(): void
{
$floor = new CarpetFloor();
$this->myApartment->setFloor($floor);
$this->assertInstanceOf(CarpetFloor::class, $this->myApartment->getFloor());
}
public function testHardSetArea(): void
{
$floor = new HardFloor();
$this->myApartment->setFloor($floor);
$this->assertInstanceOf(HardFloor::class, $this->myApartment->getFloor());
}
public function testHardGetFloor(): void
{
$floor = new HardFloor();
$this->myApartment->setFloor($floor);
$this->assertInstanceOf(HardFloor::class, $this->myApartment->getFloor());
}
}
<file_sep><?php
namespace App\entities\Floor;
use App\entities\Floor\Interfaces\Floor;
use App\entities\Robot\Interfaces\RobotCost;
class HardFloor implements Floor, RobotCost
{
private $area = 0;
private $cleaningCost = 1;
public function setArea(int $area): void
{
$this->area = $area;
}
public function getArea(): int
{
return $this->area;
}
public function setCleaningCost(int $cost): void
{
$this->cleaningCost = $cost;
}
public function getCleaningCost(): int
{
return $this->cleaningCost;
}
}
<file_sep><?php
namespace App\services;
use App\entities\Charger\Interfaces\Charger;
use App\entities\Battery\Interfaces\Battery;
class RechargeService
{
private $charger;
private $battery;
public function __construct(Charger $charger) {
$this->charger = $charger;
$this->battery = $this->charger->getBattery();
}
public function recharge(): void
{
$this->battery->setTimesCharged($this->battery->getTimesCharged() + 1);
$chargingTime = $this->battery->getChargingTime();
$chargePerUnit = 100 / $chargingTime;
$currBatteryLevel = (int)$this->battery->getBattery();
echo "\nCharging battery \n";
for ($i = $currBatteryLevel; $i <= $chargingTime; $i++) {
echo "Battery Charging : " . (int)$chargePerUnit * $i . "%\r";
sleep(1);
}
$this->battery->setBattery($this->battery->getBatteryMaxCapacity());
echo "Battery Charged : 100%\n";
}
public function chargeBatteryIfEmpty() : void
{
if ($this->battery->isBatteryEmpty()) {
$this->recharge();
}
}
public function useBattery($cost): void
{
while ($cost > 0) {
$this->chargeBatteryIfEmpty();
$this->battery->setBattery($this->battery->getBattery() - 1);
$cost--;
sleep(1);
}
}
}
<file_sep><?php
namespace App\helpers;
class helper
{
public static function initialize(array $argv): array
{
$settings = [];
$options = getopt("", ["floor::", "area::"]);
$settings['clean'] = false;
$settings['area'] = (int)$options['area'];
$settings['floorType'] = $options['floor'];
return $settings;
}
public static function resourceValidityCheck(array $settings): array
{
if ($settings['clean']) {
return [
status => false,
message => "Nothing to clean!",
];
}
if ($settings['area'] <= 0) {
return [
status => false,
message => "Invalid Area of the Floor",
];
}
if ($settings['floorType'] == '') {
return [
status => false,
message => "Invalid Floor type",
];
}
return [
status => true,
message => "Good to Go!"
];
}
}
<file_sep><?php
namespace App\services;
use App\entities\Apartment\Interfaces\Apartment;
use App\entities\Robot\Interfaces\Bot;
use App\services\RechargeService;
class CleanerService
{
private $currAreaCleaned = 0;
private $timeSpentOnCleaning = 0;
private $battery;
private $charger;
private $rechargeService;
public function __construct(Apartment $apartment, Bot $robot, RechargeService $rechargeService) {
$this->apartment = $apartment;
$this->robot = $robot;
$this->battery = $robot->getBattery();
$this->charger = $robot->getCharger();
$this->rechargeService = $rechargeService;
}
public function clean(): int
{
$cleaningCost = $this->apartment->getFloor()->getCleaningCost();
$totalArea = $this->apartment->getFloor()->getArea();
$this->currAreaCleaned = 0;
while ($this->currAreaCleaned < $totalArea) {
$this->rechargeService->useBattery($cleaningCost);
$this->timeSpentOnCleaning += $cleaningCost;
$this->currAreaCleaned++;
echo "Floor Apartment Cleaned : " . $this->currAreaCleaned . " m^2 \r";
}
return $this->timeSpentOnCleaning;
}
}
<file_sep><?php
use PHPUnit\Framework\TestCase;
use App\entities\Floor\FloorFactory;
use App\entities\Floor\CarpetFloor;
use App\entities\Floor\HardFloor;
class FloorFactoryTest extends TestCase
{
public function testCarpetFloorCreation(): void
{
$floor = FloorFactory::build('Carpet');
$this->assertInstanceOf(CarpetFloor::class, $floor);
}
public function testHardFloorCreation(): void
{
$floor = FloorFactory::build('Hard');
$this->assertInstanceOf(HardFloor::class, $floor);
}
}
<file_sep><?php
namespace App\entities\Battery;
use App\entities\Battery\Interfaces\Battery;
class MiniBattery implements Battery
{
private $chargingTime = 30;
private $batteryMaxCapacity = 60;
private $timesCharged = 0;
private $currBatteryLevel = 60;
public function setBatteryMaxCapacity(int $batteryCapacity): void
{
$this->batteryMaxCapacity = $batteryCapacity;
}
public function getBatteryMaxCapacity(): int
{
return $this->batteryMaxCapacity;
}
public function setChargingTime(int $time): void
{
$this->chargingTime = $time;
}
public function getChargingTime(): int
{
return $this->chargingTime;
}
public function setBattery(int $currBatteryLevel): void
{
$this->currBatteryLevel = $currBatteryLevel;
}
public function getBattery(): int
{
return $this->currBatteryLevel;
}
public function getTimesCharged(): int
{
return $this->timesCharged;
}
public function setTimesCharged(int $timesCharged): void
{
$this->timesCharged = $timesCharged;
}
public function isBatteryEmpty(): bool
{
return $this->currBatteryLevel <= 0 ? true : false;
}
}
<file_sep><?php
namespace App\entities\Robot;
use App\entities\Robot\Interfaces\Bot;
class RobotFactory
{
public static function build(String $type=''): Bot
{
if ($type == '') {
throw new Exception('Invalid Robot Type');
} else {
$className = 'App\entities\Robot\\' . ucfirst($type) . 'Robot';
if (class_exists($className)) {
return new $className();
} else {
throw new Exception('Robot type not found.');
}
}
}
}
<file_sep><?php
namespace App\entities\Charger;
use App\entities\Charger\Interfaces\Charger;
use App\entities\Battery\Interfaces\Battery;
class FastCharger implements Charger
{
private $battery;
public function setBattery(Battery $battery): void
{
$this->battery = $battery;
}
public function getBattery(): Battery
{
return $this->battery;
}
}
<file_sep># autonomous-cleaning-robot
Autonomous Cleaning Robot
This robot is designed to clean the apartment's floor automatically, also it charges itself automatically if empty.<file_sep><?php
use PHPUnit\Framework\TestCase;
use App\entities\Battery\MiniBattery;
class MiniBatteryTest extends TestCase
{
private static $battery;
public static function setUpBeforeClass(): void
{
static::$battery = new MiniBattery();
static::$battery->setBatteryMaxCapacity(5);
static::$battery->setChargingTime(5);
static::$battery->setTimesCharged(0);
static::$battery->setBattery(5);
}
public static function tearDownAfterClass(): void
{
static::$battery = null;
}
public function testSetBatteryMaxCapacity(): void
{
static::$battery->setBatteryMaxCapacity(5);
$this->assertEquals(5, static::$battery->getBatteryMaxCapacity());
}
public function testGetBatteryMaxCapacity(): void
{
$this->assertEquals(5, static::$battery->getBatteryMaxCapacity());
}
public function testSetChargingTime(): void
{
static::$battery->setChargingTime(5);
$this->assertEquals(5, static::$battery->getChargingTime());
}
public function testGetChargingTime(): void
{
$this->assertEquals(5, static::$battery->getChargingTime());
}
public function testSetBattery(): void
{
static::$battery->setBattery(5);
$this->assertEquals(5, static::$battery->getBattery());
}
public function testGetBattery(): void
{
$this->assertEquals(5, static::$battery->getBattery());
}
public function testSetTimesCharged(): void
{
static::$battery->setTimesCharged(5);
$this->assertEquals(5, static::$battery->getTimesCharged());
}
public function testGetTimesCharged(): void
{
$this->assertEquals(5, static::$battery->getTimesCharged());
}
public function testIsBatteryEmpty(): void
{
static::$battery->setTimesCharged(5);
$this->assertFalse(static::$battery->isBatteryEmpty());
}
}
<file_sep><?php
use PHPUnit\Framework\TestCase;
use App\entities\Charger\FastCharger;
use App\entities\Battery\MiniBattery;
use App\services\RechargeService;
class RechargeChargerTest extends TestCase
{
public function testRechargeBattery(): void
{
$miniBattery = new MiniBattery();
$miniBattery->setBatteryMaxCapacity(5);
$miniBattery->setChargingTime(5);
$miniBattery->setTimesCharged(0);
$miniBattery->setBattery(5);
$fastCharger = new FastCharger();
$fastCharger->setBattery($miniBattery);
$chargeService = new RechargeService($fastCharger);
$chargeService->recharge();
$this->assertEquals(5, $miniBattery->getBattery());
}
}
<file_sep><?php
namespace App\entities\Robot;
use App\entities\Apartment\Interfaces\Apartment;
use App\entities\Robot\Interfaces\Bot;
use App\entities\Battery\Interfaces\Battery;
use App\entities\Charger\Interfaces\Charger;
class CleanerRobot implements Bot
{
private $battery;
private $charger;
public function setBattery(Battery $battery): void
{
$this->battery = $battery;
}
public function getBattery() : Battery
{
return $this->battery;
}
public function setCharger(Charger $charger): void
{
$this->charger = $charger;
}
public function getCharger() : Charger
{
return $this->charger;
}
}
<file_sep><?php
namespace App\entities\Apartment;
use App\entities\Apartment\Interfaces\Apartment;
class ApartmentFactory
{
public static function build(String $type=''): Apartment
{
if ($type == '') {
throw new Exception('Invalid Apartment Type');
} else {
$className = 'App\entities\Apartment\\' . ucfirst($type) . 'Apartment';
if (class_exists($className)) {
return new $className();
} else {
throw new Exception('Apartment type not found.');
}
}
}
}
<file_sep><?php
namespace App\entities\Apartment\Interfaces;
use App\entities\Floor\Interfaces\Floor;
interface Apartment
{
public function setFloor(Floor $floorType): void;
public function getFloor(): Floor;
}
<file_sep><?php
require __DIR__ . '/vendor/autoload.php';
use App\helpers\helper;
use App\entities\Robot\RobotFactory;
use App\entities\Apartment\ApartmentFactory;
use App\entities\Floor\FloorFactory;
use App\entities\Battery\MiniBattery;
use App\entities\Charger\FastCharger;
use App\services\CleanerService;
use App\services\RechargeService;
$settings = Helper::initialize($argv);
$resourceValidity = Helper::resourceValidityCheck($settings);
if ($resourceValidity['status'] == false) {
echo $resourceValidity["message"] . "\n";
die();
}
$floor = FloorFactory::build($settings['floorType']);
$floor->setArea($settings['area']);
$apartment = ApartmentFactory::build('My');
$apartment->setFloor($floor);
$miniBattery = new MiniBattery();
$miniBattery->setBatteryMaxCapacity(60);
$miniBattery->setChargingTime(30);
$miniBattery->setTimesCharged(0);
$miniBattery->setBattery(60);
$fastCharger = new FastCharger();
$fastCharger->setBattery($miniBattery);
$robot = RobotFactory::build('Cleaner');
$robot->setBattery($miniBattery);
$robot->setCharger($fastCharger);
$rechargeServices = new RechargeService($fastCharger);
$cleaner = new CleanerService($apartment, $robot, $rechargeServices);
$cleaningTime = $cleaner->clean();
$display = [
'cleaningTime' => $cleaningTime,
'chargingTime' => ($miniBattery->getTimesCharged() * $miniBattery->getChargingTime()),
'chargedTimes' => $miniBattery->getTimesCharged(),
'batteryRemaining' => $miniBattery->getBattery(),
];
echo "\n\n";
echo "Time Spent on cleaning : " . $display['cleaningTime'] . " seconds\n";
echo "Time Spent on charging : " . $display['chargingTime'] . " seconds\n";
echo "Total Time : " . ($display['chargingTime'] + $display['cleaningTime']) . " seconds\n";
echo "Time Charged : " . $display['chargedTimes'] . " times\n";
echo "Battery remaining : " . $display['batteryRemaining'] . " seconds\n";
echo "\nEvery Task Compeleted !\n";
echo "\n";
<file_sep><?php
use PHPUnit\Framework\TestCase;
use App\entities\Floor\HardFloor;
class HardFloorTest extends TestCase
{
private static $hardFloor;
private static $area;
private static $cleaningCost;
public static function setUpBeforeClass(): void
{
static::$hardFloor = new HardFloor();
static::$area = 60;
static::$cleaningCost = 2;
}
public static function tearDownAfterClass(): void
{
static::$hardFloor = null;
static::$area = null;
static::$cleaningCost = null;
}
public function testSetArea(): void
{
static::$hardFloor->setArea(static::$area);
$this->assertEquals(static::$hardFloor->getArea(), static::$area);
}
public function testGetArea(): void
{
$this->assertEquals(static::$hardFloor->getArea(), static::$area);
}
public function testSetCleaningCost(): void
{
static::$hardFloor->setCleaningCost(static::$cleaningCost);
$this->assertEquals(static::$hardFloor->getCleaningCost(), static::$cleaningCost);
}
public function testGetCleaningCost(): void
{
$this->assertEquals(static::$hardFloor->getCleaningCost(), static::$cleaningCost);
}
}
<file_sep><?php
namespace App\entities\Floor;
use App\entities\Floor\Interfaces\Floor;
class FloorFactory
{
public static function build(String $type=''): Floor
{
if ($type == '') {
throw new Exception('Invalid Floor Type');
} else {
$className = 'App\entities\Floor\\' . ucfirst($type) . 'Floor';
if (class_exists($className)) {
return new $className();
} else {
throw new InvalidArgument();
}
}
}
}
<file_sep><?php
namespace App\entities\Charger\Interfaces;
use App\entities\Battery\Interfaces\Battery;
interface Charger
{
public function setBattery(Battery $battery): void;
}
<file_sep><?php
use PHPUnit\Framework\TestCase;
use App\entities\Charger\FastCharger;
use App\entities\Floor\CarpetFloor;
use App\entities\Apartment\MyApartment;
use App\entities\Battery\MiniBattery;
use App\entities\Robot\CleanerRobot;
use App\services\CleanerService;
use App\services\RechargeService;
use App\entities\Robot\RobotFactory;
use App\entities\Apartment\ApartmentFactory;
use App\entities\Floor\FloorFactory;
class CleanerServiceTest extends TestCase
{
public function testClean(): void
{
$floor = $this->createMock(CarpetFloor::class);
$floor->method('getArea')
->willReturn(10);
$floor->method('getCleaningCost')
->willReturn(1);
$apartment = $this->createMock(MyApartment::class);
$apartment->expects($this->exactly(2))
->method('getFloor')
->willReturn($floor);
$miniBattery = $this->createMock(MiniBattery::class);
$miniBattery->method('getBatteryMaxCapacity')
->willReturn(60);
$miniBattery->method('setBattery');
$miniBattery->method('isBatteryEmpty')
->willReturn(false);
$miniBattery->method('getChargingTime')
->willReturn(30);
$miniBattery->method('getBattery')
->willReturn(60);
$miniBattery->method('getTimesCharged')
->willReturn(0);
$charger = $this->createMock(FastCharger::class);
$charger->method('getBattery')->willReturn($miniBattery);
$cleanerRobot = new CleanerRobot();
$cleanerRobot->setBattery($miniBattery);
$cleanerRobot->setCharger($charger);
$rechargeService = $this->getMockBuilder(RechargeService::class)
->setConstructorArgs([$charger])
->setMethods(null)
->getMock();
$cleaningService = new CleanerService($apartment, $cleanerRobot, $rechargeService);
$this->assertEquals(10, $cleaningService->clean());
}
}
| 223292016ad725a6f016581dc02802dba80c0677 | [
"Markdown",
"PHP"
] | 28 | PHP | akthecoders/autonomous-cleaning-robot | a57e277903709e2912e607cfd29fde25c72356bb | 2b253be6e347ae54710be1dd4e891dace7bb9f7d |
refs/heads/master | <file_sep>#Fri Dec 14 18:11:24 KST 2018
org.eclipse.core.runtime=2
org.eclipse.platform=4.9.0.v20180906-0745
<file_sep>package day_2;
import java.lang.reflect.Array;
import java.util.Arrays;
/**
*
* 변수 : 데이터를 저장하는 기억공간, 기본형 / 참조형
* 배열 Array : 같은 타입 변수들의 묶음
* @author kosta
*
*/
public class Z08_Array {
public static void main(String[] args) {
int a; //변수의 선언
a = 3; // 변수의 초기화
int b = 3; //변수의 선언과 초기화를 한번에
int[] arr; //배열변수의 선언(참조형 변수)
arr = new int[3]; //배열변수의 객체생성
//new 로 메모리를 생성시 각 타입의 기본갑으로 초기화된다.
//정수형은 0, 실수형은 0.0, 문자형 0, 논리형은 false, 참조형 null
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
System.out.println(arr[0]);
//System.out.println(arr[3]); //ArrayIndexOutOfBoundsException
int[] brr = new int[3]; //배열변수의 선언, 객체생성
brr[0] = 10;
brr[1] = 20;
brr[2] = 30;
int[] crr = new int[] {10, 20, 30, };
int[] drr = {10, 20, 30,}; //배열변수의 선언, 객체생성, 초기화를 한번에, 마지막 값에도 콤마 작성을 권장
for (int j = 0; j < drr.length; j++) {
System.out.println(drr[j]);
}
//배열의 합
int[] x = {3, 4, 5, 6, 7,};
int sum=0;
for (int i = 0; i < x.length; i++) {
sum += x[i];
}
System.out.println("배열변수 x의 합 : " + sum);
//배열내 최대값
int[] y = {4, 7, 1, 2, 9, 8, 5,};
int max=y[0];
for (int j = 0; j < y.length; j++) {
if(max < y[j]) {
max = y[j];
}
}
System.out.println("배열내 최대값 : " + max);
//간단히 출력
int[] z = {7,8,5,3,3,4,5,5,4,};
System.out.println("배열 간단히 출력 : " + Arrays.toString(z)); //배열의 원소를 간단히 출력
//배열의 복사(주소만 복사)
//ㅊ
int[] p = {5,6,7,8};
int[] q;
q = p; //배열의 주소를 복사하기 때문에 원본이 하나임
System.out.println("p 배열 : " + Arrays.toString(p));
System.out.println("q 배열 : " + Arrays.toString(q));
q[3] = 100;
System.out.println("복사 후 p 배열 : " + Arrays.toString(p));
System.out.println("복사 후 q 배열 : " + Arrays.toString(q));
//배열의 복사(데이터를 복사)
int[] p2 = {5,6,7,8};
int[] q2 = new int[p2.length];
for (int i = 0; i < p2.length; i++) {
q2[i] = p2[i];
}
System.out.println("p2 배열 : " + Arrays.toString(p2));
System.out.println("q2 배열 : " + Arrays.toString(q2));
q2[3] = 100;
System.out.println("복사 후 p2 배열 : " + Arrays.toString(p2));
System.out.println("복사 후 q2 배열 : " + Arrays.toString(q2));
//배열의 복사(데이터를 복사)
int[] p3 = {5,6,7,8};
int[] q3 = new int[7];
System.arraycopy(p3, 0, q3, 2, p3.length);
System.out.println("p3 배열 : " + Arrays.toString(p3));
System.out.println("q3 배열 : " + Arrays.toString(q3));
q3[3] = 100;
System.out.println("복사 후 p3 배열 : " + Arrays.toString(p3));
System.out.println("복사 후 q3 배열 : " + Arrays.toString(q3));
//다차원 배열
//변수 : 데이터를 저장하는 기억공간
//1차원배열 : 같은 타입 변수들의 묶음
//2차원배열 : 1차원 배열의 묶음
int[][] aa = new int[3][2];
int[][] bb = { {1,2,}, {3,4,}, {5,6,},};
System.out.println("bb배열의 갯수 " + bb.length);
System.out.println("bb[0]배열의 갯수 " + bb[0].length);
for (int i = 0; i < bb.length; i++) {
System.out.print("bb배열 나열 ");
for (int j = 0; j < bb[i].length; j++) {
System.out.print(bb[i][j] + ", ");
}
System.out.println();
}
System.out.println("bb 배열 : " + Arrays.toString(bb)); //bb는 2차원이고, array.toString은 1차원만 나열
System.out.println("bb 배열 : " + Arrays.toString(bb[0]));
} // end of main
} // end of class
<file_sep>package day_4;
import java.util.Comparator;
import java.util.Iterator;
import java.util.TreeSet;
/**
*
* List : 순서존재, 중복허용
* Set : 손서없이, 중복불가
* 중복체크 방법 : Hash기법 -> HashSet(중복체크가 가장 빠름) O[1]
* : Binary Search Tree -> TreeSet O[log n]
* : Linear search 순차검색(중복체크가 가장 느림) O[n]
* TreeSet
* 원소추가시 중복체크하고,
* 1. hashCode()
* 2. equals()
* 중복된 객체면저장하지 않음, 중복이 안되었을때만 저장
* @author Ryush
*
*/
public class Z18_TreeSet {
public static void main(String[] args) {
TreeSet<String> ts = new TreeSet<String>();
ts.add("호랑이");
ts.add("기린");
ts.add("코끼리");
ts.add("호랑이"); //중복된 것은 저장이 안된다.
ts.add("악어");
ts.add("북금곰");
System.out.println(ts); //hs.toString();
System.out.println(ts.size());
System.out.println(ts.contains("캠핑"));
//순회 방법은 HashSet과 동일
//TreeSet 의 최대 장점은 정렬, 저장된 위치 자체가 정렬 된 것
//정렬, 범위정렬시 TreeSet이 가장 유리하다(가장 빠르다)
for (String s : ts) { // 향상된 for문
System.out.print(s + ", ");
}
System.out.println();
Iterator<String> iter = ts.iterator(); //순회를 하기 위한 단방향 이터레이터 객체를 얻어옴(1회용)
while (iter.hasNext()) {
System.out.print(iter.next() + ", ");
}
System.out.println();
System.out.println(ts.subSet("기린", "악어"));
System.out.println(ts.subSet("기린", true, "악어", true)); //포함여부
TreeSet<Girl> tsGirl = new TreeSet<Girl>(new Comparator<Girl>() {
@Override
public int compare(Girl o1, Girl o2) {
// TODO Auto-generated method stub
//return 0;
return o2.age - o1.age; //내림차순
}
});
Girl g1 = new Girl("곰순이", 22);
Girl g2 = new Girl("곰순이", 22);
Girl g3 = new Girl("하니", 25);
Girl g4 = new Girl("곱창", 21);
Girl g5 = new Girl("매드", 222);
Girl g6 = new Girl("바보", 2442);
tsGirl.add(g1);
tsGirl.add(g2);
tsGirl.add(g3);
tsGirl.add(g4);
tsGirl.add(g5);
tsGirl.add(g6);
System.out.println(tsGirl);
System.out.println(tsGirl.size());
System.out.println(g1.hashCode());
System.out.println(g2.hashCode());
System.out.println(g1.equals(g2));
}
}
class Girl implements Comparable<Girl> { //객체를 비교할수 있도록, 비교 메서드 작성, 내부비교기준
String name = "";
int age;
public Girl() {
// TODO Auto-generated constructor stub
}
public Girl(String name, int age) {
super();
this.name = name;
this.age = age;
}
@Override
public int compareTo(Girl o) { // 0 : 같음, 음수: 큰, 양수 : 작은
// TODO Auto-generated method stub
// return 0;
return this.age - o.age;
}
@Override //jdk 1.5버전에 추가된 어노테이션
public String toString() {
// TODO Auto-generated method stub
return "[" + name + "], [" + age + "]";
}
}
<file_sep>package day_2;
public class Z14_Memory {
public static void main(String[] args) {
Cup c1;
c1 = new Cup();
c1.tt();
} // end of main
} // end of class
/*
* 메모리 설명 : 프로그램이 실행될때마다 생성됨
* call stack : 지역변수, 메서드 호출정보
* heap : 인스턴스 변수, 객체생성
* Method Area(class 변수) : static 변수, 클래스정보로딩
*/
class Cup {
int a;
int a2 = a;
static int size;
static int size2 = size;
int a3 = size;
//static int size3 = a; //변수 선언 안됨 (인스턴스 변수(a)와 static 변수(size3) 생성 타이밍 차이
//size3 이 먼저 생성되지만 이 곳에 넣은 인스턴스 변수(a)가 존재하지 않음)
void i1( ) {}
static void s1() {}
void i2() { //인스턴스 메서드
a++;
size++;
i1();
s1();
}
static void s2() {
// a++;
size++;
// i1();
s1();
}
//static 멤버(변수와 메서드)는 non-static 멤버를 참조 할 수 없다.
void tt(){
int x;
System.out.println("tt Method");
uu();
}
void uu(){
int y;
System.out.println("uu Method");
}
static void ss(){
int s;
System.out.println("ss Method");
}
}
<file_sep>package day_2;
/**
*
* static 변수 : 클래스변수, 공통변수
* static 은 변수와 메서드에만 사용 가능, 클래스에는 적용 못함
* @author ryush
*
*/
public class Z13_StaticVariable {
public static void main(String[] args) {
Card c1 = new Card();
Card c2 = new Card();
c1.kind = "다이아몬드";
c1.number = 1;
c1.w = 10; // 참조변수명으로도 접근은 가능하지만,
c1.h = 20;
c1.printCard();
c2.kind = "하트";
c2.number = 10;
Card.w = 30; //static 벼누는 클래스명으로 접근을 권장
Card.h = 40;
c1.printCard();
c2.printCard();
/*
MyMath.mm = new MyMath();
mm.max(7,3);
*/
// 위에처럼 MyMath 객체를 만들어 사용할 수 도 있지만, static 메서드를 선언하면 바로 사용 가능
MyMath.max(7, 3);
} // end of main
} // end of class
/**
* 카드 1장을 추상화한 클래스
*/
class Card {
String kind = "";
int number;
int color;
static int w;
static int h;
void printCard() { // 인스턴스 메서드
System.out.println("[" + kind + "," + number + "]" + " width : " + w + " height : " + h);
}
static void ss() { //static 메서드
w = 20;
//number = 13; //인스턴스 변수는 사용 못하고, static 변수만 사용 가능하다
}
}
class MyMath {
static int max(int a, int b) {
return a >= b ? a : b;
}
static int sum(int a, int b) {
return a + b;
}
}<file_sep>package day_1;
// 한줄주석 : 실행하지 않는 영역, //~끝
/* 여러줄 주석, 부분주석 */
/** 문서주석 : 여러줄 주석, 부분주석과 사용방법은 동일, 이클립스에서 연동 가능
* 클래스, 메서드, 변수의 선언부 앞에 작성해서 설명하는 주석
* 작성자, 작성일, 작성기능, 사용방법 등
*/
public class Hello { //클래스
public static void main(String[] args) { //메인 메서드
System.out.println("안녕 자바야"); // 화면에 글자 출력하는 메소드
}
}
<file_sep>package day_3;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
/**
* 자동리소스 닫기
*/
public class Z02_ExceptionHandling {
public static void main(String[] args) {
/*
FileInputStream fis = null;
try {
fis = new FileInputStream("fime name"); //get file
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if(fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
*/
// 위 코드 간략화( jdk 7버전에서 추가)
// AutoCloseable 인터페이스를 구현하고 있는 객체만 사용가능
try(FileInputStream fis = new FileInputStream("");
FileInputStream fos = new FileInputStream("")) { // 객체를 복수로 관리 가능
} catch (IOException e){
}
} // end of main
} // end of class
<file_sep>package day_3;
import java.util.Scanner;
/**
*
* Scanner 클래스 활용
* @author Ryush
*
*/
public class Z10_IO {
public static void main(String[] args) {
//Scanner 클래스 : 키보드로부터 사용자 입력을 쉽게 받아오기 위해 많이 활용
Scanner sc = new Scanner(System.in);
// sc.nextLine(); // 엔터입력까지의 한줄을 받아옴, 마지막 엔터는 제거 후 문자열로 리턴
//위에 라인과 조금 다르다.
// sc.next(); // String 을 받아옴, 앞부분의 whileSpace(공백, 탭, 줄바꿈) 는 제거, 뒷부분은 남아 있음
// sc.nextInt(); // String 을 받아옴
// sc.nextDouble(); // String 을 받아옴
// sc.nextBoolean(); //String 을 받아옴
//
System.out.println("나이를 입력하세요");
int age = sc.nextInt();
System.out.println("당신의 나이는 " + age + " 입니다.");
System.out.println("이름을 입력하세요");
String name = sc.next();
System.out.println("당신의 이름은 " + name + " 입니다.");
} // end of main
} // end of class
<file_sep>package day_1;
/**자동완성 단축키(ctrl + spaceBar) 활용으로 코드 작성*/
public class Hello3 {
public static void main(String[] args) {
System.out.println("안녕 자바");
}
}
<file_sep>package day_3;
import java.io.FileReader;
import java.util.Arrays;
/**
*
* 문자기반 입력스트림 Reader
* @author Ryush
*
*/
public class Z08_IO {
public static void main(String[] args) {
String fileUrl ="src\\day_3\\ex_files\\input_test.txt";
try (FileReader fr = new FileReader(fileUrl)) {
//int data = fr.read();
//System.out.println((char)data);
// int data;
// while ((data = fr.read()) != -1) {
// System.out.println((char)data);
// }
char[] data = new char[4];
int num = fr.read(data);
System.out.println(Arrays.toString(data));
String s = new String(data, 0, num);
System.out.println(s);
while(true) {
char[] data2 = new char[4];
int num2 = fr.read(data);
if(num2 == -1) {
break;
}
System.out.println("최종 : " + new String(data2));
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
} // end of main
} // end of class
<file_sep>package day_2;
/**
* 자바의 반복문 : for, while, do~while
* @author ryush
*/
public class Z07_While {
public static void main(String[] args) {
/*
while (조건식) { // boolean 이어야 함.
반복할 실행문; // 반복한 실행문이 1개일 경우는 {}생략가능
}
*/
int num = 3;
while (num < 5) {
System.out.println(num);
num++; //증감식이 없다면 무한 반복
}
//do~while : 조건식이 문자 뒤에 있어 최초 한번은 실행문이 실행된다.
/*
do {
반복할 실행문;
} while (조건식); // 마지막에 ; 을 꼭 붙여야 한다, {} 생략할 수 없다.
// 조건식에서 사용하는 변수는 do~while 내에 변수는 사용하지 못한다.
*/
int x = 3;
do {
System.out.println(x);
x++;
} while (x < 3);
/*
* for : 반복범위 or 횟수를 알고 있을 때
* while : 반복범위 or 횟수를 미리 모르는 경우
* do~while : 최소 1번의 실행을 보장해야 하는 경우
*/
}
}
<file_sep>package day_4;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Random;
import java.util.TreeSet;
/**
*
* 문제를 해결시
* 문제파악
* 1. 자료구조의 선택
* 2. 자료구조에 맞는 알고리즘 선택
* @author Ryush
*
*/
public class Z19_Lotto {
public static void main(String[] args) {
// Lotto 번호 1 ~ 45 중 6개를 무작위 출력
// 자료구조 종류 : 배열, list, set
int sn = 1;
int en = 10;
int selectNum = 6;
Random ran = new Random();
System.out.println("====Array====");
//ran.nextInt(10); // 0 <= int 정수 < 10
int[] arrayNum = new int[selectNum];
for (int i = 0; i < arrayNum.length; i++) {
int r = ran.nextInt(en) + 1;
for (int j = 0; j < arrayNum.length; j++) {
if(arrayNum[j] == r) {
i--;
break;
}
}
arrayNum[i] = r;
}
System.out.println(Arrays.toString(arrayNum));
Arrays.sort(arrayNum);
System.out.println(Arrays.toString(arrayNum));
System.out.println("====list====");
ArrayList<Integer> al = new ArrayList<Integer>();
for (int i = 0; i < selectNum; i++) {
int r = ran.nextInt(en) + 1;
if (!al.contains(r)) {
al.add(r);
}
}
System.out.println(al);
Collections.sort(al);
System.out.println(al);
System.out.println("====Set====");
TreeSet<Integer> ts = new TreeSet<Integer>();
while (ts.size() < selectNum) {
int r = ran.nextInt(en) + 1;
ts.add(r);
}
System.out.println(ts);
}
}
<file_sep>package day_3;
import java.io.FileWriter;
/**
*
* 문자기반 출력스트림 Writer
* @author KOSTA
*
*/
public class Z09_IO {
public static void main(String[] args) {
String fileUrl ="src\\day_3\\ex_files\\output_test_str.txt";
try (FileWriter fw = new FileWriter(fileUrl)) {
String str = "안녕하세요\r\n자바를 잘하고 싶네요";
fw.write(str);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
} // end of main
} // end of class
<file_sep>package day_3;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
/**
*
* Stack : LIFO 구조, 출구, 입구 하나
* Queue : FIFO 구조, 출구, 입구 다르다
* @author Ryush
*
*/
public class Z15_StackQueue {
public static void main(String[] args) {
Stack<String> st = new Stack<String>(); //제너릭스 표현
st.push("사과");
st.push("바나나");
st.push("배");
System.out.println(st);
System.out.println(st.pop()); //LIFO 구조로 인해 마지막에 저장된 값이 나온다.
System.out.println(st.pop());
if (!st.empty()) {
System.out.println(st.pop());
}
System.out.println(st);
//Queue 는 interface 라서 객체를 생성할 수 없다.
LinkedList<String> lt = new LinkedList<String>();
lt.offer("된장국");
lt.offer("청국장");
lt.offer("부대찌개");
System.out.println(lt);
System.out.println(lt.poll()); //FIFO 구조로 먼저 들어간 것이 먼저 나온다.
System.out.println(lt.poll());
if(!lt.isEmpty()) {
System.out.println(lt.poll());
}
System.out.println(lt);
} // end of main
} // end of class<file_sep>package day_2;
/**
*
*
* @author ryush
*
*/
public class Z16_Tv {
public static void main(String[] args) {
Tv t1 = new Tv();
t1.name ="삼성파브";
t1.channel = 11;
Tv t2 = new Tv("LG커브", 7);
//t2.name ="LG커브";
//t2.channel = 7;
} //end of main
} //end of class
//모든 클래스는 반드시 하나 이상의 생성자가 존재해야 한다.
//생성자를 작성하지 않으면, 컴파일러는 기본 생성자를 추가해준다.
//생성자를 작성하면, 더이상 컴파일러는 기본 생성자를 추가해주지 않는다.
//생성자를 작성시, 기본생성자를 추가해주는 것이 필요하다.
class Tv {
String name = "";
int channel;
//생성자 constructor : 클래스명과 동일, 객체생성시마다 한번씩 호출됨.
//생성자는 초기화작업이 목적이다.
//return 이 없다.(그래서 void도 사용하지 않는다)
Tv() { //기본생성자
}
Tv(String name, int channel) {
//name = n;
//channel = c;
//name = name;
//channel = channel;
this.name = name;
this.channel = channel;
}
void printTv() {
System.out.println(name + "," + channel);
}
}<file_sep>package day_4;
/**
*
* 프로세스 : 프로그램이 실행된 것
* 쓰레드 : 프로세스에서 수행하는 작업
* 멀티 쓰레드 : 포로세스에서 여러 작업을 (시분할하여) 병렬적으로 수행하는 작업
* 1. Thread 클래스 상속
* 2. Runnable 인터페이스 구현
* @author Ryush
*
*/
public class Z22_Thread {
public static void main(String[] args) {
MyThread mt = new MyThread(); //쓰레드 객체생성
mt.setPriority(10); //우선순의 높이며
mt.start(); //쓰레드 시작
B b = new B(); //Runnable 구현한 객체를 생성
Thread t = new Thread(b);
t.setPriority(1); //우선순위 낮추기
t.setDaemon(true); //데몬 쓰레드 지정
t.start();
for (int i = 0; i < 1000000; i++) {
System.out.println("--");
}
}
}
class A {
}
class B extends A implements Runnable { //자바는 단일 상속만 허용하므로, 쓰레드를 사용하려면 interface를 구현
@Override
public void run() {
// TODO Auto-generated method stub
for (int i = 0; i < 1000000; i++) {
System.out.println("//////");
}
}
}
class MyThread extends Thread {
@Override
public void run() { //별도의 쓰레드에서 수행하고 싶은 작업 기술
// TODO Auto-generated method stub
//super.run();
for (int i = 0; i < 1000000; i++) {
System.out.println("|");
}
}
}
<file_sep>package day_1;
/**
*
* 변수 Variable : 데이터를 저장하는 기억 공간
* @author ryush
*
*/
public class Z01_Variable {
public static void main(String[] args) {
//변수는 기본형(8가지), 참조형(기본형이 아니면)이 있다.
/*
* 정수형 : byte(1), short(2), [int(4)], long(8)
* 실수형 : float(4), [double(8)]
* 문자형 : char(2)
* 논리형 : boolean(1)
*/
//정수형
int a; //변수 선언
a = 8; //변수의 초기화
int b = 8; //변수와 선언과 초기화(동시에)
byte c = 7;
short d = 9;
int f = 10;
long g = 100L; //리터럴 접미사가 필요 L or l
//실수형
float h = 3.14f; //리터럴 접미사가 필요 F or f
double i = 3.14d; //리터럴 접미사가 필요 D or d or 생략가능
//문자형
char j = 'x'; //반드시 글자 하나를 저장, '' 직은따옴표사용
char k = '\u0054'; //java는 유니코드 사용
//논리형
boolean m = true; //논리형 참 true / 거짓 false
/*식별자(변수)의 명명 규칙
* 1. 예약어를 변수명으로 사용할 수 없다.
* 2. 숫자로 시작할 수 없다.
* 3. 특수문자 _ 언더바, $ 달러 두가지만 된다.
* 4. 대소문자가 구분된다.
* 5. 길이 제한이 없다.
*/
/*권장사항
* 변수명은 첫글자 소문자
* 메서드명은 첫글자 소문자
* 클래스명은 첫글자 대문자
*/
//상수 : 값을 변경할 수 없다. (flnal 접두어)
//상수는 대문자로 한다( _ 언더바 사용)
final float Pi = 3.14f;
int x = 3;
int y = 4;
//x = 100;
System.out.println("x : " + x);
System.out.println("y : " + y);
// swap : 값을 교환
int tempx = x;
x = y;
y = tempx;
System.out.println("swap x : " + x);
System.out.println("swap y : " + y);
//정수표현
int w = 9; //10진수
w = 0b11; // 2진수, 0b or 0B 으로 시작 (0~1 표현)
w = 011; //8진수, 0 으로 시작 (0~7 표현)
w = 0x11; //16진수, 0x or 0X 으로 시작 (0~9, a~f 표현)
//실수표현
double t = 3;
t = 3d;
t = 3.0;
t = 3.;
t = .5; //0 을 생략할수 있다
//문자열표현
String s = "안녕하세요";
//문자열연산
s = "abc" + "xyz"; // 문자열의 덧셈연산
s = "abc" + 8; // 문자열 + 비문자열을 문자열로 덧셈연산
//s = 3 + 7; // 비문자열만 있을 경우 에러 발생
s = 3 + 7 + "abc"; //문자열 이전의 비문자열은 연산처리 됨
s = 3 + 4 + "abc" + 3 + 4; //7abc34
System.out.println(s);
//형변환
int ii =3;
double dd = ii; //(double)ii; 컴파일러가 자동형변환(묵시적) 해준다
dd = 3.14;
//ii = dd; //에러, 데이터의 손실이 발생할 수 있는 경우(double이 int 보다 크기때문에)
ii = (int)dd; // 3 출력, int로 형변환함으로써 .14 삭제
System.out.println(ii);
char cc = 'a';
System.out.println((int)cc); // 문자 a의 유니코드 출력
char cc2 = 98;
System.out.println((char)cc2); // 유니코드 98의 해당하는 문자 출력
} // end of main
} // end of class
<file_sep>package day_2;
/**
*
* 변수 scope : 선언된 위치에 따라, 메모리에 생성위치, 생서이점, 소멸시점
* @author ryush
*
*/
public class Z12_Variable {
public static void main(String[] args) {
Variable v = new Variable();
v.i =3;
System.out.println(v.i);
// System.out.println(v.ppp().l);
} // end of main
} // end of class
class Variable {
//전역변수 : 클래스 안쪽 && 메서드 바같쪽에서 선언
int i; // 인스턴스변수, non-static 변수, fields
//메모리 생성시점 : 인스턴스 생성시
//메모리 생성위치 : Heap 영역
//메모리 소며리점 : 참조변수가 없어지면 사용불가, 가비지컬렉터가 지워준다
//초기값 : 각타입의 초기값으로 초기화 됨
static int ii; // static 변수, 클래스변수, 공통변수
//메모리셍성시점 : 클래스 정보가 로딩될 때
//메모리 생성위치 : class Area (Method Area)
//메모리소명시점 : 프로그램 종료시까지 유지된다, 안없어짐.
void ppp() {
//지역변수 : 메서드 안쪽에서 선언 local variable
//메모리 생성시점 : 선언문 실행시
//메모리 생성위치 : call stack 영역
//메모리 소멸시점 : 선언문이 포함된 블럭이 종료 될 때, 즉시 삭제
//초기값이 안 들어있다.
int l = 0;
System.out.println(l); // 초기화 후에 참조 가능하다
}
}<file_sep>package day_2;
/**
*
* 1세대언어 : 기계어, 2세대언어 : 어셈블리어, 3세대언어 : 절차지향언어/객체지향언어
* 절차지향언어 : C
* 객체지향언어 : C++, Python, java
* : 기존의 절차지향언어에 클래스의 개념을 추가한 언어
* class : 새로운 타입의 정의, 사용자정의 타입
* : 구성요소 - 변수, 메서드
* @author kosta
*
*/
public class Z10_Class {
public static void main(String[] args) {
int a;
a = 3;
int b = 4;
Tank t1; //참조변수의 선언
t1 = new Tank(); // 클래스의 객체생성 (인스턴스화)
Tank t2 = new Tank();
t1.hp = 100; // . 멤버접근연산자
t1.px = 20;
t1.py = 30;
t1.printTank();
t2.hp = 200;
t2.px = 120;
t2.py = 30;
t2.printTank();
} // end of main
} // end of class
//변수명 : 첫글자 소문자
//메서드명 : 첫글자 소문자
//클래스명 : 첫글자 대문자
/*
class 클래스명 {
구성요소 : 변수, 메서드
}
*/
class Tank { // 클래스 정의
/** 체력 */
int hp;
/** 좌표 */
int px;
int py;
/**변수의 내용을 출력하는 메서드 */
void printTank() {
System.out.println("위치 x : " + px + ", y : " + py + ", 체력 : " + hp);
}
}<file_sep>package day_3;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
/**
*
* Input/Output
* 바이트기반 입력스트림 : InputStream
* @author Ryush
*
*/
public class Z05_IO {
public static void main(String[] args) {
// 자동리소스 닫기에서 사용가능한 객체 : AutoCoseable 인터페이스를 구현한 객체만 가능
// try (FileInputStream fis = new FileInputStream("G:\\Works\\Edu\\Study_Java\\workspace\\day_3\\src\\day_3\\ex_files\\input_test.txt");) {
try (FileInputStream fis = new FileInputStream("src\\day_3\\ex_files\\input_test.txt")) {
//파일명 : 절대경로, 상대경로(현재프로젝트 폴더)
// FileInputStream fis = new FileInputStream("G:\\Works\\Edu\\Study_Java\\workspace\\day_3\\src\\day_3\\ex_files\\input_test.txt"); //절대경로
// FileInputStream fis = new FileInputStream("input_test.txt"); //상대경로
// int data = fis.read(); //1byte read
// System.out.println((char)data);
//or
// while (true) {
// int data = fis.read();
// if(data == -1) {
// break;
// }
// System.out.println((char)data);
// }
//or
int data;
while((data = fis.read()) != -1) {
System.out.println((char)data);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} // end of main
} // end of class
<file_sep>package day_4;
import java.util.Scanner;
/**
* 쓰레드 상태 제어
*/
public class Z23_Thread {
public static void main(String[] args) {
MyThrea2 mt = new MyThrea2();
mt.start();
Scanner sc = new Scanner(System.in);
while(true) {
int menu = sc.nextInt();
switch (menu) {
case 1: // 쓰레드 멈추기
mt.stop = true; // mt.stop();
System.out.println("쓰레드 정지, 종료");
System.exit(0); // 프로그램 종료
break;
case 2: // 쓰레드 일시정지
mt.suspend = true; // mt.suspend();
System.out.println("쓰레드 일시정지");
break;
case 3: // 쓰레드 재시작
mt.suspend = false; // mt.resume();
System.out.println("쓰레드 리줌, 재시작");
break;
}
}
} // end of main
} // end of class
class MyThrea2 extends Thread {
boolean stop = false;
boolean suspend = false;
@Override
public void run() {
while(!stop) {
if (!suspend) {
System.out.println("|");
}
}
}
}
<file_sep>package day_1;
/**
* 자바의 흐름제어 : 삼항연산자, if~else, switch~case
* @author ryush
*
*/
public class Z04_Switchcase {
public static void main(String[] args) {
/*
switch (조건값) { //조건값은 int, String문자열 만 사용 가능
case 값1:
조건값과 값1이 같은 경우 실행할 문장
break; // switch 문을 빠져나간다
case 값2:
조건값과 값2이 같은 경우 실행할 문장
break;
default:
break;
} // {} 생략할 수 없다.
*/
int num = 3;
switch (num) {
case 1:
System.out.println("일");
break;
case 2:
System.out.println("이");
break;
case 3:
System.out.println("삼");
break;
default:
System.out.println("해당없음");
break;
}
//영어사전
String word = "책";
switch (word) {// jdk 7 버전 이우에 문자열도 사용할 수 있게 되었음.
case "책":
System.out.println("book");
break;
case "사과":
System.out.println("apple");
break;
case "바나나":
System.out.println("banana");
break;
default:
System.out.println("내 사전에는 그런 말 없다.");
break;
}
//달력
int month = 3;
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
System.out.println(month+"월의 마지막 날짜는 31일 입니다.");
break;
case 4:
case 6:
case 9:
case 11:
System.out.println(month+"월의 마지막 날짜는 30일 입니다.");
break;
case 2:
System.out.println(month+"월의 마지막 날짜는 28일 입니다.");
break;
default:
System.out.println(month+"월의 마지막 날짜는 잘 모르겠습니다.");
break;
}
/*
* 삼항연산자 : 한번만 비교하면 되는 간단한 경우에 주로 사용
* if~else : 그 외 조건들에 사용
* switch : 빠르다, 조건값이 int, string 형만 사용 가능하고, 값이 같은 경우만 사용(범위에 대한 표현이 안됨)
*/
} // end of main
} // end of class
<file_sep>package day_2;
/**
* 자바의 반복문 : for, while, do~while
* @author ryush
*/
public class Z06_For {
public static void main(String[] args) {
//탈출기법 : 보통 조건식과 함께 사용
//break : 가장 가까운 switch문 or 반복문을 하나만 탈출
//continue : 가장 가까운 반복문의 다음차ㅜ로 넘어간다
for (int i = 0; i < 10; i++) {
System.out.println(i);
if(i == 3) {
break;
}
}
//홀수만 출력
for (int i = 10; i < 20; i++) {
if(i % 2 == 0) {
continue;
}
System.out.println(i);
}
System.out.println("------------------");
//라벨 : 분기할 시점을 명시, 반복문 앞에 사용
ex : for (int i = 0; i < 3; i++) {
ex2 : for (int j = 10; j < 14; j++) {
System.out.println(i + "--" + j);
if (i == 0 && j == 12) {
break ex;
}
}
}
//존재유무 : 59~67 중에서 13의 배수
//1. flag 변수 사용 : 성능은 좋지만, 변수를 잘 관리해야 한다.
int temp = 0;
for (int i = 59; i < 67; i++) {
if(i % 13 == 0) {
temp++;
break;
}
}
if(temp > 0) {
System.out.println("59~67 중에 13의 배수는 존재한다");
}else {
System.out.println("59~67 중에 13의 배수는 존재하지 않는다");
}
//2. flag 변수 없이 :
for (int i = 59; i < 67; i++) {
if(i % 17 == 0) {
System.out.println("59~67 중에 17의 배수는 존재한다");
break;
}else if(i == 66) {
System.out.println("59~67 중에 17의 배수는 존재하지 않는다");
}
}
} // end of main
} // end of class
| c8608c0b03876c0b835316236855692761a1b1dd | [
"Java",
"INI"
] | 23 | INI | Ryush87/task_jsp | 79938dd8efc3e819e4145060a81a12017f4d192a | 0eb3e8d901342b735a1b648e75a2be2392c9ad26 |
refs/heads/master | <file_sep>#include <jni.h>
#ifdef __cplusplus
extern "C" {
jstring Java_com_safeliao_jniutil_JNIUtil_stringFromJNI( JNIEnv* env, jobject thiz );
}
#endif
<file_sep>include ':app', ':jniutil'
| fc0e1f33658be1bb360ee42d8983ebbf89416bff | [
"C",
"Gradle"
] | 2 | C | kabobobo/JNIUtilSample | d98977401549bc027d4de69bce41ec16274ac07c | 05efa3c1ae43190d11ad3777ccc7f5ac682ba1a1 |
refs/heads/master | <file_sep><!DOCTYPE HTML>
<!--
Site internet Créé par <NAME>
-->
<?php
include 'assets/include/connectBDD.php';
if(isset($_SESSION['id']))
{
$reqUser = $bdd->prepare("SELECT * FROM membres WHERE memId = ?");
$reqUser->execute(array($_SESSION['id']));
$user = $reqUser->fetch();
if(isset($_POST['newNom']) AND !empty($_POST['newNom']) AND $_POST['newNom'] != $user['memNom'])
{
$newNom = htmlspecialchars($_POST['newNom']);
$updateNom = $bdd->prepare("UPDATE membres SET memNom = ? WHERE memId = ?");
$updateNom->execute(array($newNom, $_SESSION['id']));
// header('Location: profil.php?id=' . $_SESSION['id']);
}
if(isset($_POST['newPrenom']) AND !empty($_POST['newPrenom']) AND $_POST['newPrenom'] != $user['memPrenom'])
{
$newPrenom = htmlspecialchars($_POST['newPrenom']);
$updatePrenom = $bdd->prepare("UPDATE membres SET memPrenom = ? WHERE memId = ?");
$updatePrenom->execute(array($newPrenom, $_SESSION['id']));
// header('Location: profil.php?id=' . $_SESSION['id']);
}
if(isset($_POST['newEmail']) AND !empty($_POST['newEmail']) AND $_POST['newEmail'] != $user['memEmail'])
{
$newEmail = htmlspecialchars($_POST['newEmail']);
$updateEmail = $bdd->prepare("UPDATE membres SET memEmail = ? WHERE memId = ?");
$updateEmail->execute(array($newEmail, $_SESSION['id']));
// header('Location: profil.php?id=' . $_SESSION['id']);
}
if(isset($_POST['newUser']) AND !empty($_POST['newUser']) AND $_POST['newUser'] != $user['memUtilisateur'])
{
$newUser = htmlspecialchars($_POST['newUser']);
$updateUser = $bdd->prepare("UPDATE membres SET memUtilisateur = ? WHERE memId = ?");
$updateUser->execute(array($newUser, $_SESSION['id']));
// header('Location: profil.php?id=' . $_SESSION['id']);
}
if(isset($_POST['newPassword']) AND !empty($_POST['newPassword']) AND $_POST['newPassword'] != $user['memMotDePasse'])
{
$newPassword = htmlspecialchars($_POST['newPassword']);
$updatePassword = $bdd->prepare("UPDATE membres SET memMotDePasse = ? WHERE memId = ?");
$updatePassword->execute(array($newPassword, $_SESSION['id']));
// header('Location: profil.php?id=' . $_SESSION['id']);
}
if(isset($_POST['newPassword']) AND !empty($_POST['newPassword']) AND isset($_POST['newPasswordConfirm']) AND !empty($_POST['newPasswordConfirm']))
{
$password = sha1($_POST['newPassword']);
$passwordConfirm = sha1($_POST['newPasswordConfirm']);
if($password == $passwordConfirm)
{
$updatePassword = $bdd->prepare("UPDATE membres SET memMotDePasse = ? WHERE memId = ?");
$updatePassword->execute(array($password, $_SESSION['id']));
// header('Location: profil.php?id=' . $_SESSION['id']);
}else{
$message = "Vos deux mots de passe ne correspondent pas !";
}
}
?>
<html>
<head>
<title>Edition de Profil</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />
<link rel="icon" href="images/favicon.ico" />
<!-- CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<link rel="stylesheet" href="assets/css/style.css" />
<noscript><link rel="stylesheet" href="assets/css/noscript.css" /></noscript>
<!-- SCRIPT -->
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
</head>
<body class="is-preload" onselectstart="return false" oncontextmenu="return false" ondragstart="return false">
<!-- Wrapper -->
<div id="wrapper">
<!-- Header -->
<header id="header">
<a href="index.php" class="logo"><img width="30px" src="images/logo.png"><strong>AUTHEMAN</strong> <span>Victor</span></a>
<nav>
<a href="#menu">Menu</a>
</nav>
</header>
<!-- Menu -->
<?php include 'assets/include/nav.php'; ?>
<!-- Main -->
<div id="main" class="alt">
<!-- One -->
<section id="one">
<div class="inner">
<header class="major">
<h1>Édition de mon profil</h1>
</header>
<form action="" method="post">
<div class="inscription">
<label for="nom">Nom</label>
<input type="text" name="newNom" required="required" value="<?php echo $user['memNom']; ?>">
<label for="prenom">Prénom</label>
<input type="text" name="newPrenom" required="required" value="<?php echo $user['memPrenom']; ?>">
<label for="email">Email</label>
<input type="email" name="newEmail" required="required" value="<?php echo $user['memEmail']; ?>">
<label for="user">Utilisateur</label>
<input type="text" name="newUser" required="required" value="<?php echo $user['memUtilisateur']; ?>">
<label for="password">Mot de passe</label>
<input type="password" name="newPassword">
<label for="passwordConfirm">Confirmer le Mot de passe</label>
<input type="password" name="newPasswordConfirm"><br>
<ul class="actions">
<li><input type="submit" name="formInscription" value="Mettre à jour" class="primary" /></li>
<li><input type="reset" value="Annuler" /></li>
</ul>
</div>
</form>
</header>
</div>
<?php
if(isset($message))
{
?>
<div class="alertMessage alert alert-warning" role="alert">
<?php echo $message; ?>
</div>
<?php
}
?>
</section>
</div>
<!-- Footer -->
<?php include 'assets/include/footer.html'; ?>
</div>
<!-- Scripts -->
<script src="assets/js/jquery.min.js"></script>
<script src="assets/js/jquery.scrolly.min.js"></script>
<script src="assets/js/jquery.scrollex.min.js"></script>
<script src="assets/js/browser.min.js"></script>
<script src="assets/js/breakpoints.min.js"></script>
<script src="assets/js/util.js"></script>
<script src="assets/js/main.js"></script>
</body>
</html>
<?php
} else {
header('Location: connexion.php?page=profil');
}
?>
<file_sep><!DOCTYPE HTML>
<?php include 'assets/include/connectBDD.php'; ?>
<!--
Site internet Créé par AUTHEMAN Victor
-->
<html>
<head>
<title>Mot de passe oublié</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />
<link rel="icon" href="images/favicon.ico" />
<!-- CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<link rel="stylesheet" href="assets/css/style.css" />
<noscript><link rel="stylesheet" href="assets/css/noscript.css" /></noscript>
<!-- SCRIPT -->
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body class="is-preload" onselectstart="return false" oncontextmenu="return false" ondragstart="return false">
<!-- Wrapper -->
<div id="wrapper">
<!-- Header -->
<!-- Note: The "styleN" class below should match that of the banner element. -->
<header id="header">
<a href="index.php" class="logo"><img width="30px" src="images/logo.png"><strong>AUTHEMAN</strong> <span>Victor</span></a>
<nav>
<a href="#menu">Menu</a>
</nav>
</header>
<!-- Menu -->
<?php include 'assets/assets/include/nav.php'; ?>
<!-- Main -->
<div id="main" class="alt">
<!-- One -->
<section class="container-fluid" id="one">
<div class="inner">
<header class="memento major">
<h1>Mot de passe oublié</h1>
</header>
<?php if(!isset($_GET['user']) OR empty($_GET['user'])){ ?>
<form action="#" method="get">
<div class="inscription">
<?php if(isset($_SESSION['erreurMsg'])){ ?>
<div class="alert alert-warning" role="alert">
<?php echo $_SESSION['erreurMsg']; ?>
</div>
<?php } ?>
<label for="user">Saisir votre nom d'utilisateur :</label>
<input id="user" type="text" name="user"><br>
<input type="submit" name="" value="Suivant">
</div>
</form>
<?php
}
if(isset($_GET['user']) AND !empty($_GET['user']))
{
// On sécurise les valeurs
$user = htmlspecialchars($_GET['user']);
// On vérifi si les valeurs existent dans la base de donnée
$req = $bdd->prepare("SELECT * FROM membres WHERE memUtilisateur = ?");
$req->execute(array($user));
$cur = $req->fetch();
// On récupère l'adresse email
$mail = $cur['memEmail'];
if(isset($mail) AND !empty($mail))
{
unset($_SESSION["erreurMsg"]);
$mailVerif = substr($mail, 0, 4);
$mailDisplay = substr($mail, 4);
?>
<form action="#" method="get">
<div class="inscription">
<?php if(isset($_SESSION['sendMsg'])){ ?>
<div class="alert alert-warning" role="alert">
<?php echo $_SESSION['sendMsg']; ?>
</div>
<?php } ?>
<label for="mail">Saisir les 4 premiers caractères de votre adresse email</label>
<?php echo "....".$mailDisplay; ?>
<input maxlength="4" type="text" name="mail" id="mail"><br>
<input type="submit" value="Envoyer">
</div>
</form>
<?php
if(isset($_GET['mail']) AND !empty($_GET['mail']))
{
// On sécurise les valeurs
$mailSaisie = htmlspecialchars($_GET['mail']);
if($mailSaisie == $mailVerif)
{
$_SESSION['sendMsg'] = "Un mail vous à été envoyé";
include 'assets/assets/include/sendMail.php';
}
}
} else {
$_SESSION['erreurMsg'] = "Le nom d'utilisateur n'existe pas";
header("Location: forgotPassword.php");
}
}
?>
</div>
</section>
</div>
<!-- Scripts -->
<script src="assets/js/jquery.min.js"></script>
<script src="assets/js/jquery.scrolly.min.js"></script>
<script src="assets/js/jquery.scrollex.min.js"></script>
<script src="assets/js/browser.min.js"></script>
<script src="assets/js/breakpoints.min.js"></script>
<script src="assets/js/util.js"></script>
<script src="assets/js/main.js"></script>
</body>
</html>
<?php/*
} else{
header('Location: connexion.php?page=card');
}*/
?>
<file_sep><?php
$header="MIME-Version: 1.0\r\n";
$header.='From: "aut<EMAIL>-v<EMAIL>.fr"<<EMAIL>>'."\n";
$header.='Content-Type:text/html; charset"utf-8"'."\n";
$header.='Content-Transfer-Encoding: 8bit';
$messageMail='
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns:v="urn:schemas-microsoft-com:vml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta charset="utf8">
<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0;">
</head>
<body leftmargin="0" topmargin="0" marginwidth="0" marginheight="0">
<table bgcolor="#242943"width="100%" border="0" cellpadding="0" cellspacing="0">
<tbody>
<tr>
<td bgcolor="#242943">
<div>
<table align="center" width="590" border="0" cellpadding="0" cellspacing="0">
<tbody>
<tr>
<td height="30" style="font-size: 30px; line-height: 30px;"> </td>
</tr>
<tr>
<td align="center" style="text-align:center;">
<a href="http://autheman-victor.fr">
<img src="http://autheman-victor.fr/ancienSite/images/logo.png" width="78" border="0" alt="Logo autheman-victor.fr">
</a>
</td>
</tr>
<tr>
<td height="30" style="font-size: 30px; line-height: 30px;"> </td>
</tr>
<tr>
<td align="center" style="font-family: Helvetica, sans-serif; text-align: center; font-size:32px; color: #FFF; mso-line-height-rule: exactly; line-height: 28px;">
Confirmation de votre compte
</td>
</tr>
<tr>
<td height="30" style="font-size: 30px; line-height: 30px;"> </td>
</tr>
<tr>
<td align="center" style="font-family: Helvetica, sans-serif; text-align: center; font-size:15px; color: #878b99; mso-line-height-rule: exactly; line-height: 26px;">
<a href="https://autheman-victor.fr/updatePassword.php">Changer mon mot de passe</a>
</td>
</tr>
<tr>
<td height="30" style="font-size: 30px; line-height: 30px;"> </td>
</tr>
</tbody>
</table>
</div>
</td>
</tr>
</tbody>
</table>
</body>
</html>
';
mail($mail, "Confirmation de compte", $messageMail, $header);
?>
<file_sep>#include <iostream>
using namespace std;
int main(){
int longueur;
int largeur;
int profondeur1;
int profondeur2;
int resultat;
cout<<"Calcul du volume d'une piscine aux deux extrémités différentes"<<endl;
cout<<"Indiquez la longueur"<<endl;
cin>>longueur;
cout<<"Indiquez la largeur"<<endl;
cin>>largeur;
cout<<"Indiquez la première profondeur"<<endl;
cin>>profondeur1;
cout<<"Indiquez la deuxième profondeur"<<endl;
cin>>profondeur2;
resultat=longueur*largeur*(profondeur1*profondeur2)/2;
cout<<"Le volume de votre piscine est de : "<<resultat<<" m³"<<endl;
return 0;
}
<file_sep>#include <iostream>
using namespace std;
int main(){
float nb1;
float nb2;
float somme;
float moy;
float min;
float max;
cout<<"Indiquez un nombre réel"<<endl;
cin>>nb1;
cout<<"Indiquez un deuxième nombre réel"<<endl;
cin>>nb2;
// Somme
somme=nb1+nb2;
cout<<"La somme est de : "<<somme<<endl;
//Moyenne
moy=(nb1+nb2)/2;
cout<<"La moyenne est de : "<<moy<<endl;
//Minimum
min=nb1<nb2;
max=nb1>nb2;
if (nb1<nb2){
cout<<"Le nombre le plus petit est : "<<nb1<<endl;
cout<<"Le nombre le plus grand est : "<<nb2<<endl;
}
else
{
cout<<"Le nombre le plus petit est : "<<nb2<<endl;
cout<<"Le nombre le plus grand est : "<<nb1<<endl;
}
return 0;
}
<file_sep>#include <iostream>
using namespace std;
int main(){
int nbTenPremsPair = 10;
int nbAfficher = 18;
cout<<"Les dix premier nombre pair"<<endl;
for( int noTenPremsPair = 0; noTenPremsPair<nbTenPremsPair; noTenPremsPair++)
{
cout<<nbAfficher-(noTenPremsPair*2)<<endl;
}
cout<<endl;
return 0;
}
<file_sep>-- Base de données C1_Eleve
-- Creation le 08-10-2018
-- Suppression des tables
DROP TABLE if exists C1_Livre;
-- Création de la table
CREATE TABLE C1_Livre(
livId int primary key,
livTitre varchar(50),
livAuteur varchar(50),
livISBN int,
livGenre varchar(20)
) ENGINE=innodb CHARSET=UTF8;
<file_sep><nav id="menu">
<div class="row">
<style media="screen">
.travelNav div.travelNavTitle{
visibility: hidden;
}
.travelNavTitle{
width: 100%;
height: 100%;
padding-top: 50%;
opacity: 0;
transition: translate(-50%, -50%);
transition:visibility 0.2s linear,opacity 0.2s linear;
background-color: rgba(255, 255, 255, 0.5);
}
.travelNav:hover div.travelNavTitle{
visibility: visible;
opacity: 1;
}
</style>
<a href="travel.php?page=travel" style="padding: 0; position: relative; background-image: url('images/travel.jpg'); background-size: cover; background-position: center center; border: white solid 3px;" class="col travelNav">
<div class="travelNavTitle">
<h2 class="text-dark border border-dark" style="width: 50%; margin-right: auto; margin-left: auto;">TRAVEL</h2>
</div>
</a>
<div class="col mr-4">
<ul class="links">
<li><a href="index.php">Accueil</a></li>
<li><a href="about.php">A Propos</a></li>
<li><a href="portfolio.php">Portfolio</a></li>
<li><a class="scrolly" href="index.php#contact">Contact</a></li>
</ul>
<ul class="actions stacked" style="width: 70%; margin-right: auto; margin-left: auto;">
<li><a href="ressources.php" class="button primary fit">Ressources</a></li>
<?php
if(isset($_SESSION['id']))
{
?>
<li><a href="deconnexion.php" class="button fit">Déconnexion</a></li>
<li><a href="profil.php?id=<?php echo $_SESSION['id'] ?>" class="button fit">Mon Profil</a></li>
<?php
} else{
?>
<li><a href="connexion.php?page=profil" class="button fit">Connexion</a></li>
<?php
}
?>
</ul>
</div>
</div>
</nav>
<file_sep><!DOCTYPE HTML>
<?php
include 'assets/include/connectBDD.php';
?>
<!--
Site internet Créé par AUTHEMAN Victor
-->
<html>
<head>
<title>A Propos</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />
<link rel="icon" href="images/favicon.ico" />
<link rel="stylesheet" href="assets/css/style.css" />
<noscript><link rel="stylesheet" href="assets/css/noscript.css" /></noscript>
</head>
<body class="is-preload" onselectstart="return false" oncontextmenu="return false" ondragstart="return false">
<!-- Wrapper -->
<div id="wrapper">
<!-- Header -->
<header id="header">
<a href="index.php" class="logo"><img width="30px" src="images/logo.png"><strong>AUTHEMAN</strong> <span>Victor</span></a>
<nav>
<a href="#menu">Menu</a>
</nav>
</header>
<!-- Menu -->
<?php include 'assets/include/nav.php'; ?>
<!-- Main -->
<div id="main" class="alt">
<!-- One -->
<section id="one">
<div class="inner">
<header class="major">
<h1>Qui suis-je ?</h1>
</header>
<p>Au commencement Dieu créa le ciel et la terre... Houlà je remonte peut-être un petit peu loin là. Tout d'abord je m'appelle Victor j'ai 18 ans aujourd'hui en 2018, et je suis un passionné des nouvelles technologies, du développement et de la programmation en elle-même.</p>
<p>(4 ans), c'est l'âge auquel j'ai touché mon premier ordinateur.<br>(8 ans), l'âge auquel j'ai acheté mon premier livre de programmation HTML, avant cela j'avais déjà un peu touché à la programmation mais sans plus. Et me voilà aujourd'hui dans un BTS SIO (Système d'information aux organisations). En vérité je ne travaillais pas beaucoup à l'école et c'est seulement en seconde année de BAC PRO SEN (Système électronique et numérique) que j'ai commencé à prendre conscience de l'ampleur de mon avenir dans ce merveilleux domaine qui est l'informatique.</p>
<p>Étant détenteur d'un baccalauréat, je suis motivé à obtenir mon BTS et à continuer vers une licence professionnelle Développeur Web et Web designer.</p>
<a class="button" href="assets/files/cv.pdf">Télécharger mon CV</a>
</div>
</section>
</div>
<!-- Contact -->
<?php include 'assets/include/contact.php'; ?>
<!-- Footer -->
<?php include 'assets/include/footer.html'; ?>
</div>
<!-- Scripts -->
<script src="assets/js/jquery.min.js"></script>
<script src="assets/js/jquery.scrolly.min.js"></script>
<script src="assets/js/jquery.scrollex.min.js"></script>
<script src="assets/js/browser.min.js"></script>
<script src="assets/js/breakpoints.min.js"></script>
<script src="assets/js/util.js"></script>
<script src="assets/js/main.js"></script>
</body>
</html>
<file_sep>#include <iostream>
using namespace std;
int main(){
float longueur;
float largeur;
float resultat;
cout<<"Calculateur de surface"<<endl;
cout<<"Indiquez la longueur"<<endl;
cin>>longueur;
cout<<"Indiquez la largeur"<<endl;
cin>>largeur;
resultat=longueur*largeur;
cout<<"La surface est de : "<<resultat<<" m²"<<endl;
return 0;
}
<file_sep><!DOCTYPE HTML>
<?php
include 'assets/include/connectBDD.php';
//if(isset($_GET['id']) AND $_GET['id'] > 0)
if(isset($_SESSION['id']))
{
?>
<!--
Site internet Créé par AUTHEMAN Victor
-->
<html>
<head>
<title>Envie de partir</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />
<link rel="icon" href="images/favicon.ico" />
<!-- CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.0/css/all.css">
<link rel="stylesheet" href="assets/css/style.css" />
<noscript><link rel="stylesheet" href="assets/css/noscript.css" /></noscript>
<!-- SCRIPT -->
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body class="is-preload" onselectstart="return false" oncontextmenu="return false" ondragstart="return false">
<img src="/images/bubble1.png" style="position: absolute; top:0; left:0; z-index: 1;">
<!-- Wrapper -->
<div id="wrapper">
<!-- Header -->
<!-- Note: The "styleN" class below should match that of the banner element. -->
<header id="header" class="alt style2">
<a href="index.php" class="logo"><img width="30px" src="images/logo.png"><strong>AUTHEMAN</strong> <span>Victor</span></a>
<nav>
<a href="#menu">Menu</a>
</nav>
</header>
<!-- Menu -->
<?php include 'assets/include/nav.php'; ?>
<!-- Banner -->
<!-- Note: The "styleN" class below should match that of the header element. -->
<div class="container-fluid" style="background: url('/images/bubble2.png'); background-position: 1200px ; background-repeat: no-repeat;">
<div class="row">
<div class="col">
<script type="text/javascript">
jQuery(function($){
$(document).ready(function(){
function animateFly(){
$('.fly').animate({top:'320px'},2000);
$('.fly').animate({top:'350px'},2000);
animateFly();
}
animateFly();
});
// SCROLL
$(window).scroll(function() {
posScroll = $(document).scrollTop();
if(posScroll >= 200)
$('.fly').css({width:'200px', transition:'250ms'});
else
$('.fly').css({width:'300px', transition:'250ms'});
});
});
</script>
<img style="z-index: -2; position:absolute; left: 50%; top:300px; transform: translate(-50%, -50%); opacity: 0.8;" width="600px" src="images/earth.png" alt="">
<img class="fly" style="z-index: -1; position:fixed; left: 50%; top:350px; transform: translate(-50%, -50%);" width="300" src="images/fly.png" alt="">
<h1 style="text-align: center; position:relative; top:300px; text-shadow: 2px 2px 15px black; width: 800px; transform: translate(-50%, -50%); left: 50%; font-family: 'lato'; font-size: 82pt;">Envie de partir</h1>
<a class="scrollLink" href="#about"><img src="/images/scrolldown.gif" alt="" width="28" style="position:relative; left: 50%; transform: translate(-75%, -50%); top: 400px;"></a>
</div>
</div>
<div id="about" class="container" style="width: 70%;text-align: center; margin-top: 500px; margin-bottom: 100px; padding: 80px; background-color: rgba(35, 40, 65, 0.8); box-shadow: 0 0 150px #000000a6; z-index:444;">
<h1 style="font-size: 52pt; margin-bottom: 0;">Nos voyages</h1>
<p style="font-size: 19pt;">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>
<div class="wavy" style="background: url('/images/wavy.png'); width: 100%; height: 500px; background-repeat: no-repeat; position:relative; "></div>
<div class="container" id="travelName">
<div class="row" style="margin-top: 300px;">
<div class="col-5">
<div class="bg-circle-travel">
</div>
<h1>Travel Name</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
</div>
</div>
<div class="row">
<div class="col-5">
<div class="bg-circle-travel" style="background-position: right;">
</div>
<h1>Travel Name</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
</div>
</div>
<div class="row">
<div class="col-5">
<div class="bg-circle-travel">
</div>
<h1>Travel Name</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
</div>
</div>
</div>
</div>
<div id="about" class="container" style="padding: 0;width: 70%;text-align: center; margin-top: 100px; margin-bottom: 100px; background-color: rgba(35, 40, 65, 1); box-shadow: 0 0 150px #000000a6; z-index:444; height: 550px;">
<div class="main-page">
<div class="maincontent">
<a class="mainlink btn">test</a>
</div>
</div>
<div class="next-page">
<div class="nextcontent">
<iframe style="display: none;" id="next-page" style="width: 100%;" src="https://www.google.com/maps/d/embed?mid=1BZDj8F0fplD1eAlpLEL_PtNP8bPJgvA-" style="height: 480px !important;" width="100%" height="100px"></iframe>
</div>
</div>
</div>
<div class="container-fluid" style="margin-bottom: 400px; position:relative; background: url('/images/bubble4.png') top right no-repeat;">
<div class="row">
<div class="col">
<img style="z-index: -2; position:absolute; left: 50%; top:300px; transform: translate(-50%, -50%); opacity: 0.8;" width="600px" src="images/earth.png" alt="">
<h1 style="text-align: center; position:relative; top:300px; text-shadow: 2px 2px 15px black; width: 1000px; transform: translate(-50%, -50%); left: 50%; font-family: 'lato'; font-size: 82pt;">Nous soutenir <a href="">ici</a></h1>
</div>
</div>
<img src="/images/bubble5.png" style="position: absolute; top:110%; left:-50px; z-index: 1;">
</div>
<!-- Scripts -->
<script src="assets/js/jquery.min.js"></script>
<script src="assets/js/jquery.scrolly.min.js"></script>
<script src="assets/js/jquery.scrollex.min.js"></script>
<script src="assets/js/browser.min.js"></script>
<script src="assets/js/breakpoints.min.js"></script>
<script src="assets/js/util.js"></script>
<script src="assets/js/main.js"></script>
<script src="assets/js/transition.js"></script>
</body>
</html>
<?php
} else{
header('Location: connexion.php');
}
?>
<file_sep>#include <iostream>
using namespace std;
int main()
{
char rep;
float saisie1;
float saisie2;
float resultat;
do{
//boucle d'affichage du menu de saisie du choix
do{
cout<<"Menu de sélection"<<endl;
cout<<"Addition tapez A"<<endl;
cout<<"Multiplication tapez M"<<endl;
cout<<"Soustraction tapez S"<<endl;
cout<<"Division tapez D"<<endl;
cout<<"Quitter tapez Q"<<endl;
cin>>rep;
}//fin de boucle qd le choix est Bon
//Menu de sélection
while(! (rep=='A' || rep=='a' || rep=='M' || rep=='m' || rep=='S' || rep=='s' || rep=='D' || rep=='d' || rep=='Q' || rep=='q'));
//en fonction du choix réalisation de l'opération correspondante
if(rep=='A' || rep=='a')
{
cout<<"Addition"<<endl;
cout<<"Saisir un premier nombre"<<endl;
cin>>saisie1;
cout<<"Saisir un deuxième nombre"<<endl;
cin>>saisie2;
resultat = saisie1 + saisie2;
cout<<"Le résultat est de : "<<resultat<<endl;
}
else
{
if(rep=='M' || rep=='m'){
cout<<"Multiplication"<<endl;
cout<<"Saisir un premier nombre"<<endl;
cin>>saisie1;
cout<<"Saisir un deuxième nombre"<<endl;
cin>>saisie2;
resultat = saisie1 * saisie2;
cout<<"Le resultat est de : "<<resultat<<endl;
}
else
{
if(rep=='S' || rep=='s')
{
cout<<"Soustraction"<<endl;
cout<<"Saisir un premier nombre"<<endl;
cin>>saisie1;
cout<<"Saisir un premier nombre"<<endl;
cin>>saisie2;
resultat = saisie1 - saisie2;
cout<<"Le resultat est de : "<<resultat<<endl;
}
else
{
if(rep=='D' || rep=='d')
{
cout<<"Division"<<endl;
cout<<"Saisir un premier nombre"<<endl;
cin>>saisie1;
cout<<"Saisir un deuxième nombre"<<endl;
cin>>saisie2;
if(saisie1==0 || saisie2==0){
cout<<"Saisir un nombre différent"<<endl;
}
resultat = saisie1 / saisie2;
cout<<"Le resultat est de : "<<resultat<<endl;
}
else
{
if(rep=='Q' || rep=='q')
{
cout<<"Au revoir"<<endl;
}
else
{
cout<<"saisie incorrecte"<<endl;
}
}
}
}
}
}//fin de la boucle principale
while(! (rep=='Q' || rep=='q'));//sortie qd il a tapé q ou Q
return 0;
}//fin du main
<file_sep>/********************************************************************************
** Form generated from reading UI file 'dialogajoutportfolioitems.ui'
**
** Created by: Qt User Interface Compiler version 5.12.2
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef UI_DIALOGAJOUTPORTFOLIOITEMS_H
#define UI_DIALOGAJOUTPORTFOLIOITEMS_H
#include <QtCore/QVariant>
#include <QtWidgets/QApplication>
#include <QtWidgets/QDialog>
#include <QtWidgets/QHBoxLayout>
#include <QtWidgets/QLabel>
#include <QtWidgets/QLineEdit>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QTextEdit>
#include <QtWidgets/QToolButton>
#include <QtWidgets/QVBoxLayout>
#include <QtWidgets/QWidget>
QT_BEGIN_NAMESPACE
class Ui_DialogAjoutPortfolioItems
{
public:
QPushButton *pushButtonAjout;
QPushButton *pushButton_2;
QWidget *widget;
QVBoxLayout *verticalLayout;
QLabel *labelNom;
QLineEdit *lineEditNom;
QLabel *labelDesc;
QTextEdit *textEditDesc;
QLabel *labelUrlMemento;
QLineEdit *lineEditUrlMemento;
QLabel *labelAncre;
QLineEdit *lineEditAncre;
QHBoxLayout *horizontalLayout;
QLabel *labelImg;
QToolButton *toolButtonSelectImg;
void setupUi(QDialog *DialogAjoutPortfolioItems)
{
if (DialogAjoutPortfolioItems->objectName().isEmpty())
DialogAjoutPortfolioItems->setObjectName(QString::fromUtf8("DialogAjoutPortfolioItems"));
DialogAjoutPortfolioItems->resize(391, 552);
pushButtonAjout = new QPushButton(DialogAjoutPortfolioItems);
pushButtonAjout->setObjectName(QString::fromUtf8("pushButtonAjout"));
pushButtonAjout->setEnabled(true);
pushButtonAjout->setGeometry(QRect(200, 510, 83, 28));
pushButtonAjout->setFlat(false);
pushButton_2 = new QPushButton(DialogAjoutPortfolioItems);
pushButton_2->setObjectName(QString::fromUtf8("pushButton_2"));
pushButton_2->setGeometry(QRect(290, 510, 83, 28));
widget = new QWidget(DialogAjoutPortfolioItems);
widget->setObjectName(QString::fromUtf8("widget"));
widget->setGeometry(QRect(20, 20, 351, 481));
verticalLayout = new QVBoxLayout(widget);
verticalLayout->setObjectName(QString::fromUtf8("verticalLayout"));
verticalLayout->setContentsMargins(0, 0, 0, 0);
labelNom = new QLabel(widget);
labelNom->setObjectName(QString::fromUtf8("labelNom"));
verticalLayout->addWidget(labelNom);
lineEditNom = new QLineEdit(widget);
lineEditNom->setObjectName(QString::fromUtf8("lineEditNom"));
verticalLayout->addWidget(lineEditNom);
labelDesc = new QLabel(widget);
labelDesc->setObjectName(QString::fromUtf8("labelDesc"));
verticalLayout->addWidget(labelDesc);
textEditDesc = new QTextEdit(widget);
textEditDesc->setObjectName(QString::fromUtf8("textEditDesc"));
verticalLayout->addWidget(textEditDesc);
labelUrlMemento = new QLabel(widget);
labelUrlMemento->setObjectName(QString::fromUtf8("labelUrlMemento"));
verticalLayout->addWidget(labelUrlMemento);
lineEditUrlMemento = new QLineEdit(widget);
lineEditUrlMemento->setObjectName(QString::fromUtf8("lineEditUrlMemento"));
verticalLayout->addWidget(lineEditUrlMemento);
labelAncre = new QLabel(widget);
labelAncre->setObjectName(QString::fromUtf8("labelAncre"));
verticalLayout->addWidget(labelAncre);
lineEditAncre = new QLineEdit(widget);
lineEditAncre->setObjectName(QString::fromUtf8("lineEditAncre"));
verticalLayout->addWidget(lineEditAncre);
horizontalLayout = new QHBoxLayout();
horizontalLayout->setObjectName(QString::fromUtf8("horizontalLayout"));
labelImg = new QLabel(widget);
labelImg->setObjectName(QString::fromUtf8("labelImg"));
horizontalLayout->addWidget(labelImg);
toolButtonSelectImg = new QToolButton(widget);
toolButtonSelectImg->setObjectName(QString::fromUtf8("toolButtonSelectImg"));
horizontalLayout->addWidget(toolButtonSelectImg);
verticalLayout->addLayout(horizontalLayout);
retranslateUi(DialogAjoutPortfolioItems);
pushButtonAjout->setDefault(true);
QMetaObject::connectSlotsByName(DialogAjoutPortfolioItems);
} // setupUi
void retranslateUi(QDialog *DialogAjoutPortfolioItems)
{
DialogAjoutPortfolioItems->setWindowTitle(QApplication::translate("DialogAjoutPortfolioItems", "Dialog", nullptr));
pushButtonAjout->setText(QApplication::translate("DialogAjoutPortfolioItems", "Ajouter", nullptr));
pushButton_2->setText(QApplication::translate("DialogAjoutPortfolioItems", "Annuler", nullptr));
labelNom->setText(QApplication::translate("DialogAjoutPortfolioItems", "Nom :", nullptr));
labelDesc->setText(QApplication::translate("DialogAjoutPortfolioItems", "Description :", nullptr));
labelUrlMemento->setText(QApplication::translate("DialogAjoutPortfolioItems", "URL Mememto :", nullptr));
labelAncre->setText(QApplication::translate("DialogAjoutPortfolioItems", "Ancre : ", nullptr));
labelImg->setText(QApplication::translate("DialogAjoutPortfolioItems", "Selectionner une image :", nullptr));
toolButtonSelectImg->setText(QApplication::translate("DialogAjoutPortfolioItems", "...", nullptr));
} // retranslateUi
};
namespace Ui {
class DialogAjoutPortfolioItems: public Ui_DialogAjoutPortfolioItems {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_DIALOGAJOUTPORTFOLIOITEMS_H
<file_sep><!DOCTYPE HTML>
<?php
// On se connecte à la base donnée
include 'assets/include/connectBDD.php';
// On récupère l'identifiant choisi
if(isset($_GET['portId']) AND !empty($_GET['portId']) AND $_GET['portId'] > 0)
{
// On sécurise les données
$portId = htmlspecialchars($_GET['portId']);
$req = $bdd->prepare("SELECT * FROM portfolio WHERE portId = ?");
$req->execute(array($portId));
$cur = $req->fetch();
if($cur['portId'] == $portId)
{
?>
<!--
Site internet Créé par <NAME>
-->
<html>
<head>
<title>Portfolio</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />
<link rel="icon" href="images/favicon.ico" />
<!-- CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<link rel="stylesheet" href="assets/css/style.css" />
<noscript><link rel="stylesheet" href="assets/css/noscript.css" /></noscript>
<!-- SCRIPT -->
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body class="is-preload" onselectstart="return false" oncontextmenu="return false" ondragstart="return false">
<!--<div class="loader">
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(window).load(function () {
$(".loader").fadeOut("1000");
})
</script>
<div class="loader_text">CHARGEMENT</div>
</div>-->
<!-- Wrapper -->
<div id="wrapper">
<!-- Header -->
<!-- Note: The "styleN" class below should match that of the banner element. -->
<header id="header">
<a href="index.php" class="logo"><img width="30px" src="images/logo.png"><strong>AUTHEMAN</strong> <span>Victor</span></a>
<nav>
<a href="#menu">Menu</a>
</nav>
</header>
<!-- Menu -->
<?php include 'assets/include/nav.php'; ?>
<!-- Main -->
<div id="main" class="alt">
<!-- One -->
<?php
if(isset($_SESSION['user']) AND $_SESSION['user'] == "admin")
{
?>
<section class="container-fluid" id="one">
<div class="inner">
<header class="memento major">
<h1>Modification de la section : <?php echo $cur['portNom']; ?></h1>
</header>
<form class="" action="#" method="post">
<input type="text" name="nom" placeholder="Nouveau nom" value="<?php if(isset($cur['portNom'])){echo $cur['portNom'];} ?>">
<textarea type="text" name="description" placeholder="Nouvelle description"><?php if(isset($cur['portDesc'])){echo $cur['portDesc'];} ?></textarea>
<input type="text" name="image" placeholder="Nouvelle image" value="<?php if(isset($cur['portImage'])){echo $cur['portImage'];} ?>">
<input type="url" name="mementoURL" placeholder="Nouveau lien memento" value="<?php if(isset($cur['portMementoURL'])){echo $cur['portMementoURL'];} ?>">
<input type="text" name="ancre" placeholder="Nouvelle Ancre" value="<?php if(isset($cur['portAncre'])){echo $cur['portAncre'];} ?>"><br>
<input type="submit" value="Mettre à jour" class="primary">
<?php
// On verifi si l'utilisateur à bien cliqué sur le bouton
if(isset($_POST['nom']))
{
$nom = htmlspecialchars($_POST['nom']);
$update = $bdd->prepare("UPDATE portfolio SET portNom = ? WHERE portId = ?");
$update->execute(array($nom, $portId));
header("Location: portfolio.php");
}
if(isset($_POST['description']))
{
$description = htmlspecialchars($_POST['description']);
$update = $bdd->prepare("UPDATE portfolio SET portDesc = ? WHERE portId = ?");
$update->execute(array($description, $portId));
header("Location: portfolio.php");
}
if(isset($_POST['image']))
{
$image = htmlspecialchars($_POST['image']);
$update = $bdd->prepare("UPDATE portfolio SET portImage = ? WHERE portId = ?");
$update->execute(array($image, $portId));
header("Location: portfolio.php");
}
if(isset($_POST['mementoURL']))
{
$mementoURL = htmlspecialchars($_POST['mementoURL']);
$update = $bdd->prepare("UPDATE portfolio SET portMementoURL = ? WHERE portId = ?");
$update->execute(array($mementoURL, $portId));
header("Location: portfolio.php");
}
if(isset($_POST['ancre']))
{
$ancre = htmlspecialchars($_POST['ancre']);
$update = $bdd->prepare("UPDATE portfolio SET portAncre = ? WHERE portId = ?");
$update->execute(array($ancre, $portId));
header("Location: portfolio.php");
}
?>
</form>
</div>
</section>
<?php
}
?>
<!-- Contact -->
<?php //include 'assets/include/contact.php'; ?>
<!-- Footer -->
<?php //include 'assets/include/footer.html'; ?>
</div>
<?php
// fermeture du if
} else header("Location: portfolio.php"); //echo "Il n'existe pas de $portId";
} else header("Location: portfolio.php");
?>
<!-- Scripts -->
<script src="assets/js/jquery.min.js"></script>
<script src="assets/js/jquery.scrolly.min.js"></script>
<script src="assets/js/jquery.scrollex.min.js"></script>
<script src="assets/js/browser.min.js"></script>
<script src="assets/js/breakpoints.min.js"></script>
<script src="assets/js/util.js"></script>
<script src="assets/js/main.js"></script>
</body>
</html>
<?php/*
} else{
header('Location: connexion.php?page=portfolio');
}*/
?>
<file_sep><!DOCTYPE HTML>
<?php
include 'assets/include/connectBDD.php';
?>
<!--
Site internet Créé par AUTHEMAN Victor
-->
<html>
<head>
<title>Mon expérience</title>
<meta charset="UTF-8" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />
<link rel="icon" href="images/favicon.ico" />
<link rel="stylesheet" href="assets/css/style.css" />
<noscript><link rel="stylesheet" href="assets/css/noscript.css" /></noscript>
</head>
<body class="is-preload" onselectstart="return false" oncontextmenu="return false" ondragstart="return false">
<!-- Wrapper -->
<div id="wrapper">
<!-- Header -->
<header id="header">
<a href="index.php" class="logo"><img width="30px" src="images/logo.png"><strong>AUTHEMAN</strong> <span>Victor</span></a>
<nav>
<a href="#menu">Menu</a>
</nav>
</header>
<!-- Menu -->
<?php include 'assets/include/nav.php'; ?>
<!-- Main -->
<div id="main" class="alt">
<!-- One -->
<section id="one">
<div class="inner">
<section class="intro">
<div class="container">
<h1>Mon expérience professionnel</h1>
</div>
</section>
<section class="timeline">
<ul>
<?php
$req = $bdd->prepare("SELECT year(expDate), expTitre, expLib FROM experienceItem ORDER BY expDate desc");
$req->execute();
while($cur = $req->fetch())
{
?>
<li>
<div>
<time><?php echo $cur[0]; ?> - <?php echo $cur[1]; ?></time> <?php echo $cur[2]; ?>
</div>
</li>
<?php
}
?>
</ul>
</section>
</div>
</section>
</div>
<!-- Contact -->
<?php include 'assets/include/contact.php'; ?>
<!-- Footer -->
<?php include 'assets/include/footer.html'; ?>
</div>
<!-- Scripts -->
<script src="assets/js/jquery.min.js"></script>
<script src="assets/js/jquery.scrolly.min.js"></script>
<script src="assets/js/jquery.scrollex.min.js"></script>
<script src="assets/js/browser.min.js"></script>
<script src="assets/js/breakpoints.min.js"></script>
<script src="assets/js/util.js"></script>
<script src="assets/js/main.js"></script>
<script src="assets/js/timeline_slider.js" charset="utf-8"></script>
</body>
</html>
<file_sep>#ifndef ADMINISTRATION_H
#define ADMINISTRATION_H
#include <QMainWindow>
namespace Ui {
class Administration;
}
class Administration : public QMainWindow
{
Q_OBJECT
public:
explicit Administration(QWidget *parent = nullptr);
~Administration();
// connexion database
public slots:
void remplirTableWidgetPortfolioItem();
private slots:
void on_toolButtonSelectBdd_clicked();
void remplirTableWidgetRessourcesItem();
void on_pushButtonAjoutPortfolioItem_clicked();
void on_tableWidgetPortfolioItems_cellClicked(int row, int column);
private:
Ui::Administration *ui;
};
#endif // ADMINISTRATION_H
<file_sep>DELETE from C1_Livre;
INSERT INTO C1_Livre (livId, livTitre, livAuteur, livISBN, livGenre) VALUES
('1', 'La bite du moine', 'Pedobear', '78563245', 'Action/Aventure');
<file_sep>/********************************************************************************
** Form generated from reading UI file 'administration.ui'
**
** Created by: Qt User Interface Compiler version 5.12.2
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef UI_ADMINISTRATION_H
#define UI_ADMINISTRATION_H
#include <QtCore/QVariant>
#include <QtWidgets/QApplication>
#include <QtWidgets/QHBoxLayout>
#include <QtWidgets/QHeaderView>
#include <QtWidgets/QLabel>
#include <QtWidgets/QMainWindow>
#include <QtWidgets/QMenuBar>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QTabWidget>
#include <QtWidgets/QTableWidget>
#include <QtWidgets/QToolBar>
#include <QtWidgets/QToolButton>
#include <QtWidgets/QWidget>
QT_BEGIN_NAMESPACE
class Ui_Administration
{
public:
QWidget *centralWidget;
QTabWidget *tabWidget;
QWidget *tabPortfolio;
QTableWidget *tableWidgetPortfolioItems;
QPushButton *pushButtonAjoutPortfolioItem;
QWidget *tabRessources;
QTableWidget *tableWidgetRessourcesItems_2;
QPushButton *pushButtonAjoutRessourcesItem_2;
QWidget *layoutWidget;
QHBoxLayout *horizontalLayout;
QLabel *labelToolButton;
QToolButton *toolButtonSelectBdd;
QLabel *labelBddSelect;
QMenuBar *menuBar;
QToolBar *mainToolBar;
void setupUi(QMainWindow *Administration)
{
if (Administration->objectName().isEmpty())
Administration->setObjectName(QString::fromUtf8("Administration"));
Administration->resize(839, 611);
centralWidget = new QWidget(Administration);
centralWidget->setObjectName(QString::fromUtf8("centralWidget"));
tabWidget = new QTabWidget(centralWidget);
tabWidget->setObjectName(QString::fromUtf8("tabWidget"));
tabWidget->setGeometry(QRect(0, 60, 841, 511));
tabPortfolio = new QWidget();
tabPortfolio->setObjectName(QString::fromUtf8("tabPortfolio"));
tableWidgetPortfolioItems = new QTableWidget(tabPortfolio);
tableWidgetPortfolioItems->setObjectName(QString::fromUtf8("tableWidgetPortfolioItems"));
tableWidgetPortfolioItems->setGeometry(QRect(10, 10, 811, 421));
pushButtonAjoutPortfolioItem = new QPushButton(tabPortfolio);
pushButtonAjoutPortfolioItem->setObjectName(QString::fromUtf8("pushButtonAjoutPortfolioItem"));
pushButtonAjoutPortfolioItem->setGeometry(QRect(10, 440, 83, 28));
tabWidget->addTab(tabPortfolio, QString());
tabRessources = new QWidget();
tabRessources->setObjectName(QString::fromUtf8("tabRessources"));
tableWidgetRessourcesItems_2 = new QTableWidget(tabRessources);
tableWidgetRessourcesItems_2->setObjectName(QString::fromUtf8("tableWidgetRessourcesItems_2"));
tableWidgetRessourcesItems_2->setGeometry(QRect(10, 10, 811, 421));
pushButtonAjoutRessourcesItem_2 = new QPushButton(tabRessources);
pushButtonAjoutRessourcesItem_2->setObjectName(QString::fromUtf8("pushButtonAjoutRessourcesItem_2"));
pushButtonAjoutRessourcesItem_2->setGeometry(QRect(10, 440, 83, 28));
tabWidget->addTab(tabRessources, QString());
layoutWidget = new QWidget(centralWidget);
layoutWidget->setObjectName(QString::fromUtf8("layoutWidget"));
layoutWidget->setGeometry(QRect(10, 20, 441, 29));
horizontalLayout = new QHBoxLayout(layoutWidget);
horizontalLayout->setSpacing(6);
horizontalLayout->setContentsMargins(11, 11, 11, 11);
horizontalLayout->setObjectName(QString::fromUtf8("horizontalLayout"));
horizontalLayout->setContentsMargins(0, 0, 0, 0);
labelToolButton = new QLabel(layoutWidget);
labelToolButton->setObjectName(QString::fromUtf8("labelToolButton"));
horizontalLayout->addWidget(labelToolButton);
toolButtonSelectBdd = new QToolButton(layoutWidget);
toolButtonSelectBdd->setObjectName(QString::fromUtf8("toolButtonSelectBdd"));
horizontalLayout->addWidget(toolButtonSelectBdd);
labelBddSelect = new QLabel(layoutWidget);
labelBddSelect->setObjectName(QString::fromUtf8("labelBddSelect"));
horizontalLayout->addWidget(labelBddSelect);
Administration->setCentralWidget(centralWidget);
menuBar = new QMenuBar(Administration);
menuBar->setObjectName(QString::fromUtf8("menuBar"));
menuBar->setGeometry(QRect(0, 0, 839, 25));
Administration->setMenuBar(menuBar);
mainToolBar = new QToolBar(Administration);
mainToolBar->setObjectName(QString::fromUtf8("mainToolBar"));
Administration->addToolBar(Qt::TopToolBarArea, mainToolBar);
retranslateUi(Administration);
tabWidget->setCurrentIndex(0);
QMetaObject::connectSlotsByName(Administration);
} // setupUi
void retranslateUi(QMainWindow *Administration)
{
Administration->setWindowTitle(QApplication::translate("Administration", "Administration", nullptr));
pushButtonAjoutPortfolioItem->setText(QApplication::translate("Administration", "Ajouter", nullptr));
tabWidget->setTabText(tabWidget->indexOf(tabPortfolio), QApplication::translate("Administration", "Portfolio", nullptr));
pushButtonAjoutRessourcesItem_2->setText(QApplication::translate("Administration", "Ajouter", nullptr));
tabWidget->setTabText(tabWidget->indexOf(tabRessources), QApplication::translate("Administration", "Ressources", nullptr));
labelToolButton->setText(QApplication::translate("Administration", "Selectionnez une base de donn\303\251es :", nullptr));
toolButtonSelectBdd->setText(QApplication::translate("Administration", "...", nullptr));
labelBddSelect->setText(QString());
} // retranslateUi
};
namespace Ui {
class Administration: public Ui_Administration {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_ADMINISTRATION_H
<file_sep>-- Base de donées portfolio crée le 22 septembre 2019
-- Par AUTHEMAN Victor
-- sqlite
-- Suppression des tables existantes
DROP TABLE if exists articles;
DROP TABLE if exists card;
DROP TABLE if exists membres;
DROP TABLE if exists commentaires;
DROP TABLE if exists portfolio;
DROP TABLE if exists projets;
CREATE TABLE articles (
artId INTEGER PRIMARY KEY AUTOINCREMENT,
artTitre varchar(255) NOT NULL,
artContenu mediumtext NOT NULL,
artDate datetime NOT NULL,
artDate_time_edition datetime NOT NULL
);
CREATE TABLE card (
cardId INTEGER PRIMARY KEY AUTOINCREMENT,
cardNom varchar(50) DEFAULT NULL,
cardDesc text,
cardURL text,
portId INTEGER(11) NOT NULL,
foreign key(portId) references portfolio(portId)
);
CREATE TABLE membres (
memId INTEGER PRIMARY KEY AUTOINCREMENT,
memNom varchar(255) NOT NULL,
memPrenom varchar(255) NOT NULL,
memEmail varchar(255) NOT NULL,
memUtilisateur varchar(32) NOT NULL,
memMotDePasse text NOT NULL,
memKey varchar(255) NOT NULL,
memConfirme int(11) NOT NULL
);
CREATE TABLE commentaires (
comId INTEGER PRIMARY KEY AUTOINCREMENT,
comUser varchar(255) NOT NULL,
comTexte varchar(1500) NOT NULL,
comType varchar(255) NOT NULL
);
CREATE TABLE portfolio (
portId INTEGER PRIMARY KEY AUTOINCREMENT,
portNom varchar(50) DEFAULT NULL,
portImage varchar(50) DEFAULT NULL,
portDesc text,
portMementoURL text,
portAncre varchar(20)
);
CREATE TABLE projets (
projetId INTEGER PRIMARY KEY AUTOINCREMENT,
projetNom varchar(50) NOT NULL,
projetDes text NOT NULL,
projetIMG varchar(20) NOT NULL,
projetURL text NOT NULL
);
<file_sep>#include <iostream>
using namespace std;
int main(){
string prenom;
string nom;
cout<<"Quelle es votre nom"<<endl;
getline(cin, nom);
cout<<"Quelle est votre prenom"<<endl;
getline(cin,prenom);
cout<<"Bienvenue"<<prenom <<nom<<" au BTS SIO"<<endl;
return 0;
}
<file_sep><!DOCTYPE HTML>
<?php
include 'assets/include/connectBDD.php';
//if(isset($_GET['id']) AND $_GET['id'] > 0)
if(isset($_SESSION['id']))
{
?>
<!--
Site internet Créé par AUTHEMAN Victor
-->
<html>
<head>
<title>Ressources</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />
<link rel="icon" href="images/favicon.ico" />
<!-- CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.0/css/all.css">
<link rel="stylesheet" href="assets/css/style.css" />
<noscript><link rel="stylesheet" href="assets/css/noscript.css" /></noscript>
<!-- SCRIPT -->
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body class="is-preload" onselectstart="return false" oncontextmenu="return false" ondragstart="return false">
<!-- Wrapper -->
<div id="wrapper">
<!-- Header -->
<!-- Note: The "styleN" class below should match that of the banner element. -->
<header id="header" class="alt style2">
<a href="index.php" class="logo"><img width="30px" src="images/logo.png"><strong>AUTHEMAN</strong> <span>Victor</span></a>
<nav>
<a href="#menu">Menu</a>
</nav>
</header>
<!-- Menu -->
<?php include 'assets/include/nav.php'; ?>
<!-- Banner -->
<!-- Note: The "styleN" class below should match that of the header element. -->
<section id="banner" class="style5">
<div class="inner">
<span class="image">
<img src="images/pic07.jpg" alt="" />
</span>
<header class="major">
<h1>Ressources</h1>
</header>
<div class="content">
<p>Toutes les données du fruit de mon travail durant toutes ces années d'études<br>et continues d'évoluer de plus en plus chaque jour.</p>
</div>
</div>
</section>
<!-- Main -->
<div id="main">
<!-- One -->
<section style="background: #242943;" id="one">
<!-- Message de bienvenu après connexion et redirection -->
<?php
if(isset($_GET['user']))
{
?>
<div class="alert alert-success" role="alert">
Bienvenu <?php echo $_GET['user'];?> !
</div>
<?php
}
?>
<!-- SCRIPT disparition .alert -->
<script type="text/javascript">
$(document).ready(function(){
$(".alert").delay(2000).fadeOut()
});
</script>
<div class="inner">
<header class="major">
<h2>Conditions d'utilisation</h2>
</header>
<p>Toutes mes ressources sont disponibles gratuitement sous modalité d'inscription. Ses ressources ont pour but d'aider la majorité à réaliser des projets que j'ai moi-même mis en place. Mes cours sont disponibles sur mon <a href="portfolio.php">portfolio</a> et les différents fichiers de configuration et de programmation sont réparti sur cette page ici même. Faites en bon usage !</p>
</div>
</section>
<!--Carousel Wrapper-->
<section id="two" class="mt-4">
<div class="inner">
<header class="major">
<h2>Mes Projets</h2>
</header>
<div id="carousel-example-1z" class="carousel slide carousel-fade mb-4" data-ride="carousel">
<!--Indicators-->
<ol class="carousel-indicators">
<li data-target="#carousel-example-1z" data-slide-to="0" class="active"></li>
<li data-target="#carousel-example-1z" data-slide-to="1"></li>
<li data-target="#carousel-example-1z" data-slide-to="2"></li>
</ol>
<!--/.Indicators-->
<!--Slides-->
<div class="carousel-inner" role="listbox">
<!--First slide-->
<div class="carousel-item active">
<img class="d-block w-100" src="https://mdbootstrap.com/img/Photos/Slides/img%20(130).jpg"
alt="First slide">
</div>
<!--/First slide-->
<!--Second slide-->
<div class="carousel-item">
<img class="d-block w-100" src="https://mdbootstrap.com/img/Photos/Slides/img%20(129).jpg"
alt="Second slide">
</div>
<!--/Second slide-->
<!--Third slide-->
<div class="carousel-item">
<img class="d-block w-100" src="https://mdbootstrap.com/img/Photos/Slides/img%20(70).jpg"
alt="Third slide">
</div>
<!--/Third slide-->
</div>
<!--/.Slides-->
<!--Controls-->
<a class="carousel-control-prev" href="#carousel-example-1z" role="button" data-slide="prev">
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="sr-only">Previous</span>
</a>
<a class="carousel-control-next" href="#carousel-example-1z" role="button" data-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
<!--/.Controls-->
</div>
<!-- Card -->
<div class="d-flex flex-lg-row flex-sm-column mb-3 justify-content-between">
<style media="screen">
.flex-lg-row .ressourceCard{
max-width: 400px;
width: auto;
}
.ressourceCard img{
border-radius: 5px;
}
</style>
<div class="ressourceCard">
<img width="100%" src="https://jesuisadmin.fr/content/images/2018/11/D-ployez-vos-machines-virtuelles-KVM-sur-Proxmox-avec-Cloud-Init--1-.png" alt="">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>
</div>
<div class="ressourceCard">
<img width="100%" src="https://jesuisadmin.fr/content/images/2018/11/D-ployez-vos-machines-virtuelles-KVM-sur-Proxmox-avec-Cloud-Init--1-.png" alt="">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>
</div>
</div>
</div>
</section>
<!-- Two -->
<section id="three">
<div class="inner">
<header class="major">
<h1>LINUX</h1>
</header>
<ul>
<li><a href="ressources/linux/sources.list">sources.list</a></li>
</ul>
</div>
</section>
<section id="four">
<div class="inner">
<header class="major">
<h1>C++</h1>
<p>Pour info les fichiers c++ ne sont pas compilés</p>
</header>
<ul>
<li><a href="ressources/c++/bienvenue/bienvenue.cpp">bienvenue.cpp</a></li>
<li><a href="ressources/c++/helloworld/helloworld.cpp">helloWorld.cpp</a></li>
<li><a href="ressources/c++/surface/surface.cpp">surface.cpp</a></li>
<li><a href="ressources/c++/volume/volume.cpp">volume.cpp</a></li>
<li><a href="ressources/c++/menuChoix.cpp">menuChoix.cpp</a></li>
</ul>
<p style="margin:0;">Les Boucles :</p>
<ul>
<li><a href="ressources/c++/lesBoucles/cadreRectangle/cadreRectangle.cpp">cadreRectangle.cpp</a></li>
<li><a href="ressources/c++/lesBoucles/rectangle/rectangle.cpp">rectangle.cpp</a></li>
<li><a href="ressources/c++/lesBoucles/tenPrems/tenPrems.cpp">tenPrems.cpp</a></li>
<li><a href="ressources/c++/lesBoucles/tenPremsPair/tenPremsPair.cpp">tenPremsPair.cpp</a></li>
<li><a href="ressources/c++/lesBoucles/tenPremsPairPGPP/tenPremsPairPGPP.cpp">tenPremsPairPGPP.cpp</a></li>
</ul>
<p style="margin:0;">TD C++</p>
<ul>
<li><a href="ressources/c++/tdc++/deuxReels/deuxReels.cpp">deuxReels.cpp</a></li>
<li><a href="ressources/c++/tdc++/login/login.cpp">login.cpp</a></li>
<li><a href="ressources/c++/tdc++/piscine/piscine.cpp">piscine.cpp</a></li>
<li><a href="ressources/c++/tdc++/piscinePlus/piscinePlus.cpp">piscinePlus.cpp</a></li>
<li><a href="ressources/c++/tdc++/plusPetitNombre/plusPetitNombre.cpp">plusPetitNombre.cpp</a></li>
<li><a href="ressources/c++/tdc++/rectangleCarac/rectangleCarac.cpp">rectangleCarac.cpp</a></li>
<li><a href="ressources/c++/tdc++/triNoms/triNoms.cpp">triNoms.cpp</a></li>
</ul>
</div>
</section>
<section id="five">
<div class="inner">
<header class="major">
<h1>SQL</h1>
</header>
<p>Table C1_Livre</p>
<ul>
<li><a href="ressources/sql/C1_Livre.sql">C1_Livre.sql</a></li>
<li><a href="ressources/sql/C1_Livre_Data.sql">C1_Livre_Data.sql</a></li>
</ul>
</div>
</section>
<section id="six">
<div class="inner">
<header class="major">
<h1>HTML5 / CSS3</h1>
</header>
<p>Site vitrine</p>
<ul>
<li><a href="ressources/html/cvEnLigne.zip">cvEnLigne.zip</a></li>
<li><a href="ressources/html/artisans.zip">artisans.zip</a></li>
<li><a href="ressources/html/boutiqueEnLigne.zip">boutiqueEnLigne.zip</a></li>
</ul>
</div>
</section>
</div>
<!-- Contact -->
<?php include 'assets/include/contact.php'; ?>
<!-- Footer -->
<?php include 'assets/include/footer.html'; ?>
</div>
<!-- Scripts -->
<script src="assets/js/jquery.min.js"></script>
<script src="assets/js/jquery.scrolly.min.js"></script>
<script src="assets/js/jquery.scrollex.min.js"></script>
<script src="assets/js/browser.min.js"></script>
<script src="assets/js/breakpoints.min.js"></script>
<script src="assets/js/util.js"></script>
<script src="assets/js/main.js"></script>
</body>
</html>
<?php
} else{
header('Location: connexion.php?page=ressources');
}
?>
<file_sep><!DOCTYPE HTML>
<?php
// Connexion à la base de donnée
include 'assets/include/connectBDD.php';
if(isset($_GET['id']) AND $_GET['id'] > 0)
{
$getId = intval($_GET['id']);
if($getId == $_SESSION['id'])
{
$reqUser = $bdd->prepare('SELECT * FROM membres WHERE memId = ?');
$reqUser->execute(array($getId));
$userInfo = $reqUser->fetch();
?>
<html>
<head>
<title>Profil</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />
<link rel="icon" href="images/favicon.ico" />
<!-- CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<link rel="stylesheet" href="assets/css/style.css" />
<noscript><link rel="stylesheet" href="assets/css/noscript.css" /></noscript>
<!-- SCRIPT -->
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
</head>
<body class="is-preload" onselectstart="return false" oncontextmenu="return false" ondragstart="return false">
<!-- Wrapper -->
<div id="wrapper">
<!-- Header -->
<header id="header">
<a href="index.php" class="logo"><img width="30px" src="images/logo.png"><strong>AUTHEMAN</strong> <span>Victor</span></a>
<nav>
<a href="#menu">Menu</a>
</nav>
</header>
<!-- Menu -->
<?php include 'assets/include/nav.php'; ?>
<!-- Main -->
<div id="banner2" class="profile container-fluid"></div>
<img id="logo" class="img-responsive center-block" src="images/profile.png" alt="">
<div id="main" class="alt">
<!-- One -->
<section id="one">
<div class="inner">
<header class="major">
<h1><?php echo $userInfo['memNom']." ".$userInfo['memPrenom']; ?></h1>
</header>
<ul>
<li>Nom: <?php echo $userInfo['memNom']; ?></li>
<li>Prenom: <?php echo $userInfo['memPrenom']; ?></li>
<li>Email: <?php echo $userInfo['memEmail']; ?></li>
</ul>
<!-- Les commentaires postés -->
<h4>Vos commentaires postés :</h4>
<?php
$req = $bdd->prepare("SELECT * FROM commentaires WHERE comUser = ?");
$req->execute(array($userInfo['memUtilisateur']));
while($cur = $req->fetch())
{
echo "<p>".$cur['comType']." : ".$cur['comTexte']."</p><hr width='500px'>";
}
?>
<?php
if(isset($_SESSION['id']) AND $userInfo['memId'] == $_SESSION['id'])
{
?>
<ul class="actions">
<li><a class="button" href="editionProfil.php">Éditer mon profil</a><br></li>
<li><a class="button primary" href="deconnexion.php">Se déconnecter</a></li>
</ul>
<?php
}
?>
</div>
<?php
if(isset($message))
{
?>
<div class="alertMessage alert alert-warning" role="alert">
<?php echo $message; ?>
</div>
<?php
}
?>
</section>
</div>
<!-- Footer -->
<?php include 'assets/include/footer.html'; ?>
</div>
<!-- Scripts -->
<script src="assets/js/jquery.min.js"></script>
<script src="assets/js/jquery.scrolly.min.js"></script>
<script src="assets/js/jquery.scrollex.min.js"></script>
<script src="assets/js/browser.min.js"></script>
<script src="assets/js/breakpoints.min.js"></script>
<script src="assets/js/util.js"></script>
<script src="assets/js/main.js"></script>
</body>
</html>
<?php
} else header("Location: profil.php?id=".$_SESSION['id']);
} else header('Location: index.php');
?>
<file_sep><!DOCTYPE HTML>
<!--
Site internet Créé par <NAME>
-->
<?php
include 'assets/include/connectBDD.php';
if(!isset($_SESSION['id']))
{
if(isset($_POST['formConnexion']))
{
$user = htmlspecialchars($_POST['user']);
$password = sha1($_POST['password']);
if(!empty($user) AND !empty($password))
{
$reqUser = $bdd->prepare("SELECT * FROM membres WHERE memUtilisateur = ? AND memMotDePasse = ?");
$reqUser->execute(array($user, $password));
$userExist = $reqUser->rowCount();
if($userExist == 1)
{
$userInfo = $reqUser->fetch();
$_SESSION['id'] = $userInfo['memId'];
$_SESSION['user'] = $userInfo['memUtilisateur'];
$_SESSION['email'] = $userInfo['memEmail'];
$page = $_GET['page'];
if(isset($page) AND !empty($page))
{
if($page != "ressources" AND $page != "portfolio" AND $page != "index" AND $page != "profil")
{
header('Location: profil.php?id=' . $_SESSION['id']);
} else {
header("Location: ".$_GET['page'].".php?id=".$_SESSION['id']);
}
} else {
header("Location: profil.php?id=".$_SESSION['id']);
}
} else {
$message = "Le nom d'utilisateur ou le mot de passe est incorrect !";
}
} else {
$message = "Tous les champs doivent être complétés !";
}
}
?>
<html>
<head>
<title>Connexion</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />
<link rel="icon" href="images/favicon.ico" />
<!-- Font Awesome -->
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.2/css/all.css">
<!-- Bootstrap core CSS -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">
<!-- Material Design Bootstrap -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/mdbootstrap/4.8.10/css/mdb.min.css" rel="stylesheet">
<!-- CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<link rel="stylesheet" href="assets/css/style.css" />
<noscript><link rel="stylesheet" href="assets/css/noscript.css" /></noscript>
<!-- SCRIPT -->
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<script>
$('.toast').toast('show');
</script>
</head>
<body class="is-preload" onselectstart="return false" oncontextmenu="return false" ondragstart="return false">
<!-- Wrapper -->
<div id="wrapper" style="padding-top:0 !important">
<!-- Header -->
<header id="header">
<a href="index.php" class="logo"><img width="30px" src="images/logo.png"><strong>AUTHEMAN</strong> <span>Victor</span></a>
<nav>
<a href="#menu">Menu</a>
</nav>
</header>
<!-- Menu -->
<?php include 'assets/include/nav.php'; ?>
<!-- Main -->
<div id="main" class="alt" style="border: none;">
<div class="container-fluid row" style="height: 100vh; margin-bottom: 0 !important">
<div class="col-5" style="background-color: #15233d;clip-path: polygon(92% 0, 92% 40%, 100% 50%, 92% 60%, 92% 100%, 0 100%, 0 0); box-shadow: 10px, 5px, 5px, black;">
<section class="connexion" style="padding-top: 21%;">
<div class="inner">
<div class="connexion">
<header class="major">
<h2>JE N'AI PAS DE COMPTE</h2>
</header>
<p style="width: 80%;">Pour avoir la possibilité d'acceder à mes projet en ressources vous devez au préalable créer un compte utilisateur.</p>
<button type="button" name="button">Inscription</button>
</div>
</div>
</section>
</div>
<div class="col">
<section class="connexion" style="padding-top: 15%;" id="one">
<div class="inner">
<form action="" method="post">
<div class="connexion">
<header class="major">
<h2>JE ME CONNECTE</h2>
</header>
<label for="user">Utilisateur</label>
<input type="text" name="user" required="required">
<label for="password">Mot de passe</label>
<input type="password" name="password" required="required"><br>
<ul class="actions">
<li><input type="submit" name="formConnexion" value="Connexion" class="primary" /></li>
<li><input type="reset" value="Effacer" /></li>
</ul>
<p>Vous ne possédez pas d'identifiant? Vous pouvez vous inscrire dès à présent en cliquant <a href="inscription.php">ici</a> !</p>
<p>Mot de passe oublié ? cliquez <a href="forgotPassword.php">ici</a></p>
</div>
</form>
</div>
</section>
</div>
</div>
</div>
<?php
if(isset($message))
{
?>
<p style="position: absolute; top: 100px; right: 100px;">
<?php echo $message; ?>
</p>
<?php
//echo '<script>alert("TON TEXTE");</script>';
}
?>
</div>
<!-- Scripts -->
<!-- JQuery -->
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<!-- Bootstrap tooltips -->
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.4/umd/popper.min.js"></script>
<!-- Bootstrap core JavaScript -->
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/js/bootstrap.min.js"></script>
<!-- MDB core JavaScript -->
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mdbootstrap/4.8.10/js/mdb.min.js"></script>
<script src="assets/js/jquery.min.js"></script>
<script src="assets/js/jquery.scrolly.min.js"></script>
<script src="assets/js/jquery.scrollex.min.js"></script>
<script src="assets/js/browser.min.js"></script>
<script src="assets/js/breakpoints.min.js"></script>
<script src="assets/js/util.js"></script>
<script src="assets/js/main.js"></script>
</body>
</html>
<?php
} else header("Location: profil.php?id=".$_SESSION['id']);
?>
<file_sep>-- Créé par <NAME>
-- 09/03/2019
-- mysql
-- Suppression des tables
DROP TABLE if exists portfolio;
DROP TABLE if exists card;
-- Création des tables
CREATE TABLE portfolio(
portId int primary key not null auto_increment,
portNom varchar(50),
portImage varchar(50),
portDesc text,
portMementoURL text,
portAncre varchar(20)
)ENGINE=innodb CHARSET=utf8;
CREATE TABLE card(
cardId int primary key not null auto_increment,
cardNom varchar(50),
cardDesc text,
cardURL text,
portId int not null
)ENGINE=innodb CHARSET=utf8;
-- Ajout de clé étrangères
ALTER TABLE card ADD foreign key (portId) references portfolio(portId);
<file_sep><!DOCTYPE php>
<?php
include 'assets/include/connectBDD.php';
?>
<!--
Site internet Créé par <NAME>
-->
<php>
<html>
</div>
<head>
<title><NAME></title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />
<link rel="icon" href="images/favicon.ico" />
<!-- CSS -->
<link rel="stylesheet" href="assets/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="css/particles.css" />
<link rel="stylesheet" href="assets/css/style.css" />
<!--<noscript><link rel="stylesheet" href="assets/css/noscript.css" /></noscript>-->
<!-- SCRIPT -->
<script src="assets/js/bootstrap.min.js"></script>
<script src="assets/js/jquery-3.3.1.min"></script>
</head>
<body class="is-preload" onselectstart="return false" oncontextmenu="return false" ondragstart="return false">
<!-- Wrapper -->
<div id="wrapper">
<?php
if(isset($_COOKIE['accept_cookie']))
{
$showCookie = false;
} else {
$showCookie = true;
}
if($showCookie) { ?>
<div class="alertCookies" role="alert">
<p>Nous utilisons des cookies pour vous offrir une meilleure expérience de navigation, analyser le trafic du site, personnaliser le contenu et diffuser des publicités ciblées. Si vous continuez à utiliser ce site, vous consentez à notre utilisation des cookies.</p>
<a href="assets\php\accept_cookie.php" class="button cookies">Accepter</a>
</div>
<script>
$(document).ready(function(){
$(".cookies").click(function(){
$(".alertCookies").fadeOut()
});
});
</script>
<?php } ?>
<!-- Header -->
<header id="header" class="alt">
<a href="index.php" class="logo"><img width="30px" src="images/logo.png"><strong>AUTHEMAN</strong> <span>Victor</span></a>
<nav>
<a href="#menu">Menu</a>
</nav>
</header>
<!-- Menu -->
<?php include 'assets/include/nav.php'; ?>
<!-- Banner -->
<section id="banner" class="major">
<!--<audio src="song/startup.mp3" autoplay></audio>-->
<div class="inner" id="home_wave">
<header class="major">
<h1 class="data">Développeur Web, Web Designer</h1>
</header>
<div class="content">
<p>Créateur de site internet responsive avec HTML5,<br />
CSS3, PHP, JavaScipt & Bootstrap</p>
<ul class="actions">
<div class="grid__item theme-2">
<li><a href="#one" class="particles-button button next scrolly">Plus d'info</a></li>
</div>
</ul>
</div>
</div>
</section>
<section class="container-fluid p-0">
<div class="row" style="height: 75vh; margin:0;">
<style media="screen">
#aboutProfile::after{
background-color: white;
}
</style>
<div class="col-lg bg-light" id="aboutProfile" style="background-image: linear-gradient(rgba(0, 0, 0, 0), rgba(0, 0, 0, 0)), url('images/profileAbout.jpg'); background-repeat: no-repeat; background-size: cover; background-position: center center; background-color: #15233d;clip-path: polygon(92% 0, 92% 40%, 100% 50%, 92% 60%, 92% 100%, 0 100%, 0 0); box-shadow: 10px, 5px, 5px, black;">
</div>
<div class="col-lg position-relative">
<div class="inner position-absolute text-center w-100" style="top: 50%; left: 50%; transform: translate(-50%, -50%);">
<header>
<h1 class="display-5"><span class="border border-1 p-4"><NAME></span></h1>
</header>
<h5 style="font-size: 18pt;">Developpeur Web & Web Designer</h5>
<p style="font-size: 15pt;">Etudiant du BTS Dominique Villars, 05000 GAP FRANCE</p>
<div class="icon d-flex flex-row justify-content-center">
<a class="m-2 border-0" href="https://github.com/vautheman"><i class="fab fa-github fa-2x"></i></a>
<a class="m-2 border-0" href="https://www.facebook.com/authemanvicko"><i class="fab fa-facebook fa-2x"></i></a>
<a class="m-2 border-0" href="https://www.linkedin.com/in/victor-autheman-developer"><i class="fab fa-linkedin-in fa-2x"></i></a>
</div>
</div>
</div>
</div>
<div class="p-4 bg-dark" style="height: 100px; background: url('https://backgroundcheckall.com/wp-content/uploads/2017/12/dark-floral-background-9942.jpg');">
</div>
</section>
<!-- Main -->
<div id="main">
<!-- One -->
<section id="one" class="tiles">
<article>
<span class="image">
<img src="images/pic01.jpg" alt="" />
</span>
<header class="major">
<h3><a href="about.php" class="link">A Propos</a></h3>
<p>Qui suis-je !</p>
</header>
</article>
<article>
<span class="image">
<img src="images/pic02.jpg" alt="" />
</span>
<header class="major">
<h3><a href="parcours.php" class="link">Mon Parcours</a></h3>
<p>Comment suis-je arrivé jusqu'ici ?</p>
</header>
</article>
<article>
<span class="image">
<img src="images/pic03.jpg" alt="" />
</span>
<header class="major">
<h3><a href="competences.php" class="link">Mes Compétences</a></h3>
<p>Ce que j'apprends et ce que j'ai appris.</p>
</header>
</article>
<article>
<span class="image">
<img src="images/pic04.jpg" alt="" />
</span>
<header class="major">
<h3><a href="experience.php" class="link">Mon Expérience</a></h3>
<p>Tout ce qu'il faut savoir sur mon expérience professionnel et scolaire.</p>
</header>
</article>
<article>
<span class="image">
<img src="images/pic05.jpg" alt="" />
</span>
<header class="major">
<h3><a href="portfolio.php" class="link">Portfolio</a></h3>
<p>Mes compétences sur "papier" que je tiens à partager.</p>
</header>
</article>
<article>
<span class="image">
<img src="images/pic06.jpg" alt="" />
</span>
<header class="major">
<h3><a href="assets/files/cv.pdf" class="link">Curriculum Vitae</a></h3>
<p>Tout ce que j'ai décris ci-dessus en version pdf.</p>
</header>
</article>
</section>
<!-- Two -->
<section id="two" class="two mb-4">
<div class="inner">
<header class="major">
<h2>Ressources</h2>
</header>
<p>Toutes mes ressources sont disponibles gratuitement sous modalité d'inscription. Ses ressources ont pour but d'aider la majorité à réaliser des projets que j'ai moi-même mis en place. Mes cours sont disponibles sur mon <a href="portfolio.php">portfolio</a> et les différents fichiers de configuration et de programmation sont réparti sur cette page ici même.<br>Faites en bon usage !</p>
<ul class="actions">
<li><a href="ressources.php" class="button next">En savoir Plus</a></li>
</ul>
</div>
</section>
<section id="three" class="three">
<style media="screen">
.carousel-item{
height: 400px;
}
</style>
<!--Carousel Wrapper-->
<div id="carousel-example-2" class="carousel slide carousel-fade" data-ride="carousel">
<!--Indicators-->
<ol class="carousel-indicators">
<li data-target="#carousel-example-2" data-slide-to="0" class="active"></li>
<li data-target="#carousel-example-2" data-slide-to="1"></li>
<li data-target="#carousel-example-2" data-slide-to="2"></li>
</ol>
<!--/.Indicators-->
<!--Slides-->
<div class="carousel-inner" role="listbox">
<div class="carousel-item active">
<div class="view">
<img class="d-block w-100" src="images/slider1.jpg"
alt="First slide">
<div class="mask rgba-black-light"></div>
</div>
<div class="carousel-caption">
<h3 class="h3-responsive">Light mask</h3>
<p>First text</p>
</div>
</div>
<div class="carousel-item">
<!--Mask color-->
<div class="view">
<img class="d-block w-100" src="https://mdbootstrap.com/img/Photos/Slides/img%20(6).jpg"
alt="Second slide">
<div class="mask rgba-black-strong"></div>
</div>
<div class="carousel-caption">
<h3 class="h3-responsive">Strong mask</h3>
<p>Secondary text</p>
</div>
</div>
<div class="carousel-item">
<!--Mask color-->
<div class="view">
<img class="d-block w-100" src="https://mdbootstrap.com/img/Photos/Slides/img%20(9).jpg"
alt="Third slide">
<div class="mask rgba-black-slight"></div>
</div>
<div class="carousel-caption">
<h3 class="h3-responsive">Slight mask</h3>
<p>Third text</p>
</div>
</div>
</div>
<!--/.Slides-->
<!--Controls-->
<a class="carousel-control-prev" href="#carousel-example-2" role="button" data-slide="prev">
<span class="carousel-control-prev-icon" aria-hidden="true"></span>
<span class="sr-only">Previous</span>
</a>
<a class="carousel-control-next" href="#carousel-example-2" role="button" data-slide="next">
<span class="carousel-control-next-icon" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
<!--/.Controls-->
</div>
<!--/.Carousel Wrapper-->
</section>
<section id="four" class="four mb-4" style="background-color: #242943; border-bottom: solid 1px rgba(212, 212, 255, 0.1);">
<div class="inner">
<header class="major">
<h2>Derniers Tutoriel</h2>
</header>
<p>Voici mes derniers tutoriels disponible dans mon portfolio</p>
<div class="row">
<?php
$req = $bdd->prepare("SELECT * FROM card LIMIT 6");
$req->execute();
while($curCard = $req->fetch())
{
?>
<div class="column-4 column-12-medium">
<div class="carte" style="background-color: #15233d;">
<div class="container text-left">
<h4><b><?php echo $curCard['cardNom']; ?></b></h4>
<p><?php echo substr($curCard['cardDesc'], 0, 70).'...'; ?></p>
<?php if(isset($_SESSION['user']) AND $_SESSION['user'] == "admin"){ ?>
<ul class="actions">
<li><a class="button primary" href="cardModif.php?cardId=<?php echo $curCard['cardId']; ?>">Modifier</a></li>
<li><a class="button primary" href="cardSuppr.php?cardId=<?php echo $curCard['cardId']; ?>">Supprimer</a></li>
</ul>
<?php } ?>
<ul class="actions">
<li><a target="_blank" href="<?php echo $curCard['cardURL']; ?>" class="button">Ouvrir</a></li>
</ul>
</div>
</div>
</div>
<?php
}
?>
</div>
<ul class="actions">
<li><a href="portfolio.php" class="button next">En savoir Plus</a></li>
</ul>
</div>
</section>
</div>
<!-- Contact -->
<?php include 'assets/include/contact.php'; ?>
<!-- Footer -->
<?php include 'assets/include/footer.html'; ?>
</div>
<!-- Scripts -->
<script src="https://kit.fontawesome.com/6d49d39f46.js" crossorigin="anonymous"></script>
<script src="assets/js/jquery.min.js"></script>
<script src="assets/js/jquery.scrolly.min.js"></script>
<script src="assets/js/jquery.scrollex.min.js"></script>
<script src="assets/js/browser.min.js"></script>
<script src="assets/js/breakpoints.min.js"></script>
<script src="assets/js/util.js"></script>
<script src="assets/js/main.js"></script>
<script type="text/javascript">
const text = baffle(".data");
text.set({
characters : '▒░▒ █░/░▒ >░█░▓ ▓▓/ ░█▓█> /▒▓░ >░> ░░<> █/█▓',
speed: 120
})
text.start();
text.reveal(2000);
</script>
</body>
</html>
</php>
<file_sep><?php
if(isset($_POST['mailForm']))
{
if(!empty($_POST['nom']) AND !empty($_POST['mail']) AND !empty($_POST['message']))
{
$nom = htmlspecialchars($_POST['nom']);
$mail = htmlspecialchars($_POST['mail']);
$messageMailExpediteur = htmlspecialchars($_POST['message']);
$header="MIME-Version: 1.0\r\n";
$header.='From: "autheman-victor.fr"<<EMAIL>>'."\n";
$header.='Content-Type:text/html; charset"utf-8"'."\n";
$header.='Content-Transfer-Encoding: 8bit';
$messageMail='
<html>
<body>
<div align="center">
<h4>Vous avez reçu un mail à partir de votre site Internet !</h4>
<p>Nom de l\'expéditeur : '.$nom.'<br>
<p>Email de l\'expéditeur :'.$mail.'<br>
<br>
<p>'.$messageMailExpediteur.'</p>
<br>
</div>
</body>
</html>
';
mail("<EMAIL>", "CONTACT - WebSite", $messageMail, $header);
} else {
$erreur = "Tous les champs doivent êtres complétés !";
}
}
if(isset($_GET['mail']))
{
if($_GET['mail'] == 1)
{
}
}
?>
<section id="contact">
<div class="inner">
<section>
<form id="form" method="post" action="#form">
<div class="fields">
<div class="field half">
<label for="nom">Nom</label>
<input type="text" name="nom" id="name" value="<?php if(isset($_POST['nom'])) { echo $_POST['nom']; } ?>" />
</div>
<div class="field half">
<label for="mail">Email</label>
<input type="email" name="mail" id="email" value="<?php if(isset($_POST['mail'])) { echo $_POST['mail']; } ?>" />
</div>
<div class="field">
<label for="message">Message</label>
<textarea name="message" id="message" rows="6"><?php if(isset($_POST['message'])) { echo $_POST['message']; } ?></textarea>
</div>
</div>
<ul class="actions">
<li><input type="submit" name="mailForm" value="Envoyer" class="primary" /></li>
<li><input type="reset" value="Effacer" /></li>
</ul>
</form>
<?php
if(isset($erreur))
{
?>
<div class="alert alert-danger" role="alert">
<strong style="color: #721c24;">Erreur !</strong><?php echo $erreur; ?>
</div>
<?php
}
?>
</section>
<section class="split">
<section>
<div class="contact-method">
<span class="icon alt fa-envelope"></span>
<h3>Email</h3>
<a href="mailto:<EMAIL>"><EMAIL></a>
</div>
</section>
<section>
<div class="contact-method">
<span class="icon alt fa-phone"></span>
<h3>Téléphone</h3>
<span>06 49 25 95 06</span>
</div>
</section>
<section>
<div class="contact-method">
<span class="icon alt fa-home"></span>
<h3>Address</h3>
<span>6 Rue des Remparts<br />
GAP, 05000<br />
FRANCE, Hautes-Alpes</span>
</div>
</section>
</section>
</div>
</section>
<file_sep>#include <iostream>
using namespace std;
int main(){
int longueur;
int largeur;
int profondeur;
int resultat;
cout<<"Calcul du volume d'une piscine"<<endl;
cout<<"Indiquez la longueur"<<endl;
cin>>longueur;
cout<<"Indiquez la largeur"<<endl;
cin>>largeur;
cout<<"Indiquez la profondeur"<<endl;
cin>>profondeur;
resultat=longueur*largeur*profondeur;
cout<<"Le volume de votre piscine est de : "<<resultat<<" m³"<<endl;
return 0;
}
<file_sep>#include <iostream>
using namespace std;
int main(){
string user;
getchar pwd;
cout<<"Authentification requise"<<endl;
// User
cout<<"User :"<<endl;
cin>>user;
//Password
cout<<"password :"<<endl;
cin>>pwd;
if (user=="root" && pwd=="123"){
cout<<"Bonjour admin"<<endl;
}
else
{
cout<<"Erreur d'authentification"<<endl;
}
return 0;
}
<file_sep><!DOCTYPE HTML>
<?php
include 'assets/include/connectBDD.php';
//if(isset($_GET['id']) AND $_GET['id'] > 0)
//if(isset($_SESSION['id']))
//{
?>
<!--
Site internet Créé par <NAME>
-->
<html>
<div class="loader">
<script type="text/javascript" src="assets/js/jquery-latest.js"></script>
<script type="text/javascript">
$(window).load(function() {
$(".loader").fadeOut("1000");
})
</script>
</div>
<head>
<title>Portfolio</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />
<link rel="icon" href="images/favicon.ico" />
<!-- CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<link rel="stylesheet" href="assets/css/style.css" />
<noscript><link rel="stylesheet" href="assets/css/noscript.css" /></noscript>
<!-- SCRIPT -->
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body class="is-preload" onselectstart="return false" oncontextmenu="return false" ondragstart="return false">
<!--<div class="loader">
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(window).load(function () {
$(".loader").fadeOut("1000");
})
</script>
<div class="loader_text">CHARGEMENT</div>
</div>-->
<!-- Wrapper -->
<div id="wrapper">
<!-- Header -->
<!-- Note: The "styleN" class below should match that of the banner element. -->
<header id="header" class="alt style6">
<a href="index.php" class="logo"><img width="30px" src="images/logo.png"><strong>AUTHEMAN</strong> <span>Victor</span></a>
<nav>
<a href="#menu">Menu</a>
</nav>
</header>
<!-- Menu -->
<?php include 'assets/include/nav.php'; ?>
<!-- Banner -->
<!-- Note: The "styleN" class below should match that of the header element. -->
<section id="banner" class="style6 videoBack">
<div class="inner">
<span class="image">
<img src="images/pic07.jpg" alt="" />
</span>
<header class="major">
<h1>Portfolio</h1>
</header>
<div class="content">
<p>Tout ce que j'ai appris et ce que vous pouvez apprendre !</p>
</div>
</div>
</section>
<!-- Main -->
<div id="main">
<!--<section style="position: fixed; display: flex; flex-direction: column; ; z-index: 5; bottom: 0; right:0;" id="menu-secondary">
<?php/*
$req = $bdd->prepare("SELECT * from portfolio");
$req->execute();
// On ouvre la boucle pour l'affichage du menu secondaire
while($cur = $req->fetch())
{
echo "<a class='scrolly icon-anchor' href='#".$cur['portAncre']."'><img src='images/portfolio/icon/".$cur['portImage']."' width='50px' height='50px' alt='' data-position='center center' /></a>";
}*/
?>
</section>-->
<!-- One -->
<section id="one">
<!-- SCRIPT disparition .alert -->
<script type="text/javascript">
$(document).ready(function(){
$(".alert").delay(2000).fadeOut()
});
</script>
<div class="inner">
<header class="major">
<h2>Conditions d'utilisation</h2>
</header>
<p>Je mets mon portfolio à disposition de tous gratuitement sous modalité d'inscription. Celui-ci a pour but d'aider la majorité d'entre vous à réaliser des projets que j'ai moi-même mis en place. Mes cours et différents fichiers de configuration et de programmation en font partie.<br />Faites en bon usage !</p>
</div>
</section>
<section>
<div class="inner">
<header class="major">
<?php if(isset($_GET['search']) AND !empty($_GET['search'])){
$search = htmlspecialchars($_GET['search']);
?>
<h2 style="display: inline-block; ">Résultat pour : <?php echo $search; ?></h2>
<?php } else { ?>
<h2 style="display: inline-block; ">Derniers articles</h2>
<?php } ?>
<form class="" action="" method="get">
<input style="display: inline-block;" type="search" name="search" value="" placeholder="Rechercher ...">
</form>
</header>
<div class="row">
<?php
if(isset($_GET['search']) AND !empty($_GET['search']))
{
// Si une recherche existe alors :
$search = htmlspecialchars($_GET['search']);
$req = $bdd->prepare("SELECT * FROM card WHERE cardNom LIKE ? OR cardContenu LIKE ? OR cardDesc LIKE ? LIMIT 6");
$req->execute(array("%".$search."%", "%".$search."%", "%".$search."%"));
while($curCard = $req->fetch())
{
?>
<div class="column-4 column-12-medium">
<div class="carte" style="background-color: #15233d;">
<div class="container text-left">
<h4><b><?php echo $curCard['cardNom']; ?></b></h4>
<p><?php echo substr($curCard['cardDesc'], 0, 70).'...'; ?></p>
<ul class="actions">
<?php
// Récupèration du nombre de commentaire
$reqCom = $bdd->prepare("SELECT * FROM commentaires WHERE comCard = ?");
$reqCom->execute(array($curCard['cardId']));
$nbCom = 0;
?>
<li><i class="fas fa-comment-alt"></i> <?php while($curCom = $reqCom->fetch()){$nbCom++;} echo $nbCom; ?></li>
<li><i class="fas fa-calendar-alt"></i> <?php $date=date_create($curCard['cardDate']); echo date_format($date, 'd/m/Y'); ?></li>
</ul>
<ul class="actions">
<li><a target="_blank" href="article.php?id=<?php echo $curCard['cardId']; ?>" class="button">Consulter</a></li>
<div>
<li style="display: inline-block;"><a style="border: none !important; bottom:0;" title="Télécharger" target="_blank" href="<?php echo $curCard['cardURL']; ?>"><i class="fas fa-external-link-alt fa-lg"></i></a></li>
<?php if(isset($_SESSION['user']) AND $_SESSION['user'] == "admin"){ ?>
<li style="display: inline-block;"><a style="border: none !important; bottom:0;" href="cardModif.php?cardId=<?php echo $curCard['cardId']; ?>" class="text-warning"><i class="fas fa-edit fa-lg"></i></a></li>
<li style="display: inline-block;"><a style="border: none !important; bottom:0;" href="cardSuppr.php?cardId=<?php echo $curCard['cardId']; ?>" class="text-danger"><i class="fas fa-trash fa-lg"></i></a></li>
<?php } ?>
</div>
</ul>
</div>
</div>
</div>
<?php
}
} else {
// sinon
$req = $bdd->prepare("SELECT * FROM card LIMIT 6");
$req->execute();
while($curCard = $req->fetch())
{
?>
<div class="column-4 column-12-medium">
<div class="carte" style="background-color: #15233d;">
<div class="container text-left">
<h4><b><?php echo $curCard['cardNom']; ?></b></h4>
<p><?php echo substr($curCard['cardDesc'], 0, 70).'...'; ?></p>
<ul class="actions">
<?php
// Récupèration du nombre de commentaire
$reqCom = $bdd->prepare("SELECT * FROM commentaires WHERE comCard = ?");
$reqCom->execute(array($curCard['cardId']));
$nbCom = 0;
?>
<li><i class="fas fa-comment-alt"></i> <?php while($curCom = $reqCom->fetch()){$nbCom++;} echo $nbCom; ?></li>
<li><i class="fas fa-calendar-alt"></i> <?php $date=date_create($curCard['cardDate']); echo date_format($date, 'd/m/Y'); ?></li>
</ul>
<ul class="actions">
<li><a target="_blank" href="article.php?id=<?php echo $curCard['cardId']; ?>" class="button">Consulter</a></li>
<div>
<li style="display: inline-block;"><a style="border: none !important; bottom:0;" title="Télécharger" target="_blank" href="<?php echo $curCard['cardURL']; ?>"><i class="fas fa-external-link-alt fa-lg"></i></a></li>
<?php if(isset($_SESSION['user']) AND $_SESSION['user'] == "admin"){ ?>
<li style="display: inline-block;"><a style="border: none !important; bottom:0;" href="cardModif.php?cardId=<?php echo $curCard['cardId']; ?>" class="text-warning"><i class="fas fa-edit fa-lg"></i></a></li>
<li style="display: inline-block;"><a style="border: none !important; bottom:0;" href="cardSuppr.php?cardId=<?php echo $curCard['cardId']; ?>" class="text-danger"><i class="fas fa-trash fa-lg"></i></a></li>
<?php } ?>
</div>
</ul>
</div>
</div>
</div>
<?php
}
}
?>
</div>
<?php if(!(isset($_GET['search']) AND !empty($_GET['search']))){ ?>
<ul class="pagination">
<li><span class="button small disabled">Prev</span></li>
<li><a href="#" class="page active">1</a></li>
<li><a href="#" class="page">2</a></li>
<li><a href="#" class="page">3</a></li>
<li><span>…</span></li>
<li><a href="#" class="page">8</a></li>
<li><a href="#" class="page">9</a></li>
<li><a href="#" class="page">10</a></li>
<li><a href="#" class="button small">Next</a></li>
</ul>
<?php } ?>
</div>
</section>
<?php
if(isset($_SESSION['user']) AND $_SESSION['user'] == "admin")
{
?>
<section>
<div class="inner">
<header class="major">
<h2>Ajouter une section</h2>
</header>
<form method="post">
<input type="text" required name="nom" placeholder="Nom de la section">
<input type="text" required name="description" placeholder="Description de la section">
<input type="text" required name="image" placeholder="Image de la section">
<input type="url" name="mementoURL" placeholder="URL Du memento">
<input type="text" required name="ancre" placeholder="Ancre de la section"><br>
<input type="submit" value="Publier" class="primary" />
<?php
// On récupère les valeurs
if(isset($_POST['nom']) AND isset($_POST['description']) AND isset($_POST['image']) AND isset($_POST['mementoURL']) AND isset($_POST['ancre']))
{
// On sécurise les valeurs
$nom = htmlspecialchars($_POST['nom']);
$description = htmlspecialchars($_POST['description']);
$image = htmlspecialchars($_POST['image']);
$mementoURL = htmlspecialchars($_POST['mementoURL']);
$ancre = htmlspecialchars($_POST['ancre']);
// On ajoute les valeurs dans la base de donnée
if(!empty($nom) AND !empty($description) AND !empty($image) AND !empty($ancre))
{
$req = $bdd->prepare("INSERT INTO portfolio(portNom, portDesc, portImage, portMementoURL, portAncre) VALUES(?, ?, ?, ?, ?)");
$req->execute(array($nom, $description, $image, $mementoURL, $ancre));
} else $message = "Veuillez remplir le formulaire";
}
?>
</form>
<?php
if(isset($message))
{
?>
<div class="alert alert-warning" role="alert">
<?php echo $message; ?>
</div>
<?php
}
?>
</div>
</section>
<?php
// fin si
}
?>
<!-- Two -->
<section id="two" class="spotlights">
<?php
$req = $bdd->prepare("SELECT * from portfolio");
$req->execute();
// On ouvre la boucle pour l'affichage des sections
while($cur = $req->fetch())
{
?>
<section id="<?php echo $cur['portAncre']; ?>">
<a href="portfolioDisplay.php?portId=<?php echo $cur['portId']; ?>" class="image">
<img src="images/portfolio/icon/<?php echo $cur['portImage']; ?>" alt="" data-position="center center" />
</a>
<div class="content">
<div class="inner">
<header class="major">
<h3><?php echo $cur['portNom']; ?></h3>
</header>
<p><?php echo $cur['portDesc']; ?></p>
<ul class="actions">
<li><a href="portfolioDisplay.php?portId=<?php echo $cur['portId']; ?>" class="button">En savoir plus</a></li>
<?php if(isset($_SESSION['user']) AND $_SESSION['user'] == "admin"){ ?>
<li><a href="portfolioModif.php?portId=<?php echo $cur['portId']; ?>" class="button primary">Modifier</a></li>
<li><a href="portfolioSuppr.php?portId=<?php echo $cur['portId']; ?>" onclick="if (confirm('Voulez-vous vraiment executer')){testerRadio(r1);}" class="button primary">Supprimer</a></li>
<?php } ?>
</ul>
</div>
</div>
</section>
<?php
}
?>
</section>
<!-- Three -->
<section id="four">
<div class="inner">
<header class="major">
<h2>Ressources</h2>
</header>
<p>Toutes mes ressources sont disponible gratuitement sous modalité d'inscription. Ses ressources ont pour but d'aider la majorité à réalisé des projets que j'ai moi même mis en place. Mes cours et différents fichiers de configurations et de programmations y font parti.<br />Faites en bonne usage !</p>
<ul class="actions">
<li><a href="ressources.php" class="button next">En savoir Plus</a></li>
</ul>
</div>
</section>
</div>
<!-- Contact -->
<?php include 'assets/include/contact.php'; ?>
<!-- Footer -->
<?php include 'assets/include/footer.html'; ?>
</div>
<!-- Scripts -->
<script src="assets/js/jquery.min.js"></script>
<script src="assets/js/jquery.scrolly.min.js"></script>
<script src="assets/js/jquery.scrollex.min.js"></script>
<script src="assets/js/browser.min.js"></script>
<script src="assets/js/breakpoints.min.js"></script>
<script src="assets/js/util.js"></script>
<script src="assets/js/main.js"></script>
<script src="https://kit.fontawesome.com/3ba462b0e4.js" crossorigin="anonymous"></script>
</body>
</html>
<?php/*
} else{
header('Location: connexion.php?page=portfolio');
}*/
?>
<file_sep><?php
include 'assets/include/connectBDD.php';
if($bdd)
{
echo "ok";
} else echo "fail";
$req = $bdd->prepare("SELECT * FROM card");
$req->execute();
while($cur = $req->fetch())
{
echo $cur['cardNom'];
}
?>
<file_sep>#include "administration.h"
#include "ui_administration.h"
#include "dialogajoutportfolioitems.h"
#include <QDebug>
#include <QSqlDatabase>
#include <QFileDialog>
#include <QSqlQuery>
Administration::Administration(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::Administration)
{
ui->setupUi(this);
ui->pushButtonAjoutPortfolioItem->setEnabled(false);
}
Administration::~Administration()
{
delete ui;
}
void Administration::on_toolButtonSelectBdd_clicked()
{
QString dbPath = QFileDialog::getOpenFileName(this, "Selectionner votre base de données", ".bdd");
QString dbName = QFileInfo(dbPath).fileName();
ui->labelBddSelect->setText(dbName);
if(!dbPath.isNull())
{
if(!dbPath.isEmpty())
{
//Administration w;
//w.connectDB();
qDebug()<<dbPath;
// Instanciation de la variable db
auto db = QSqlDatabase::addDatabase("QSQLITE");
// Définition des paramètres de connexion à la base de donnée
db.setDatabaseName(dbPath);
if(db.open()) {
qDebug() << "Ok - ouverture de la base de données";
Administration::remplirTableWidgetPortfolioItem();
} else {
qDebug() << "Echec d'ouverture de la base de données";
//qDebug() << dbGestion.lastError();
}
ui->pushButtonAjoutPortfolioItem->setEnabled(true);
}
}
return void();
}
void Administration::remplirTableWidgetPortfolioItem()
{
// On déclare le nombre de colonne du tableau
ui->tableWidgetPortfolioItems->setColumnCount(6);
// On crée un tableau dans lequel on va stocker les noms des colonnes
QStringList tableHeader;
// On stocke le nom des colonnes
tableHeader<<"Nom"<<"Image"<<"Description"<<"URL Memento"<<"Ancre";
// On injecte ce tableau dans notre QTableWidget
ui->tableWidgetPortfolioItems->setHorizontalHeaderLabels(tableHeader);
QSqlQuery requete;
// On effectue une première requete pour récupérer le nombre de ligne
requete.exec("SELECT * FROM portfolio");
// On déclare le nombre de ligne à 0
int rowCountTable = 0;
// On effectue une boucle afin d'additionner le nombre de boucle
while(requete.next())
{
rowCountTable ++;
}
// On effectue une deuxième requete pour récupérer le contenu du portfolio
if(requete.exec("SELECT * FROM portfolio"))
{
// On déclare le nombre de ligne du tableau en fonction du nombre de ligne que renvoi la requete
ui->tableWidgetPortfolioItems->setRowCount(rowCountTable);
// On déclare le nombre de ligne à 0
int rowCount = 0;
// On effectue une boucle qui va remplir les lignes unes à unes
while(requete.next())
{
qDebug()<<requete.value(1).toString();
// On déclare le nom des differentes données que nous renvoi la requete
QString portNom = requete.value(1).toString();
QString portImg = requete.value(2).toString();
QString portDesc = requete.value(3).toString();
QString portUrlMemento = requete.value(4).toString();
QString portAncre = requete.value(5).toString();
// On insere ensuite ces données dans le tableau
//ui->tableWidgetPortfolioItems->setItem(rowCount, 0, new QTableWidgetItem(QString::number(rowCount+1)));
ui->tableWidgetPortfolioItems->setCellWidget(rowCount, 0, new QPushButton);
ui->tableWidgetPortfolioItems->setItem(rowCount, 1, new QTableWidgetItem(portNom));
ui->tableWidgetPortfolioItems->setItem(rowCount, 2, new QTableWidgetItem(portImg));
ui->tableWidgetPortfolioItems->setItem(rowCount, 3, new QTableWidgetItem(portDesc));
ui->tableWidgetPortfolioItems->setItem(rowCount, 4, new QTableWidgetItem(portUrlMemento));
ui->tableWidgetPortfolioItems->setItem(rowCount, 5, new QTableWidgetItem(portAncre));
// On incremente de +1 le nombre de ligne
rowCount ++;
}
}
//ui->tableWidgetPortfolioItems->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
ui->tableWidgetPortfolioItems->resizeColumnsToContents();
ui->tableWidgetPortfolioItems->horizontalHeader()->setStretchLastSection(true);
ui->tableWidgetPortfolioItems->verticalHeader()->setStretchLastSection(true);
}
void Administration::on_pushButtonAjoutPortfolioItem_clicked()
{
DialogAjoutPortfolioItems windowAjoutPortfolioItems(this);
windowAjoutPortfolioItems.exec();
}
void Administration::remplirTableWidgetRessourcesItem()
{
}
void Administration::on_tableWidgetPortfolioItems_cellClicked(int row, int column)
{
}
<file_sep><?php
include 'assets/include/connectBDD.php';
if(isset($_GET['user'], $_GET['key']) AND !empty($_GET['user']) AND !empty($_GET['key']))
{
$user = htmlspecialchars(urldecode($_GET['user']));
$key = htmlspecialchars($_GET['key']);
$reqUser = $bdd->prepare("SELECT * FROM membres WHERE memUtilisateur = ? AND memKey = ?");
$reqUser->execute(array($user, $key));
$userExist = $reqUser->rowCount();
if($userExist == 1)
{
$user = $reqUser->fetch();
if($user['memConfirme'] == 0)
{
$updateUser = $bdd->prepare("UPDATE membres SET memConfirme = 1 WHERE memKey = ?");
$updateUser->execute(array($key));
$message = "Votre compte à bien été confirmé !";
$messageConnexion = 'Vous pouvez vous connecter en cliquant <a href="connexion.php?page=index">ici</a>';
} else {
$message = "Votre compte à déjà été confirmé !";
}
} else {
$message = "L'utilisateur n'existe pas !";
}
} else {
header('Location: inscription.php');
}
?>
<!DOCTYPE HTML>
<!--
Site internet Créé par <NAME>
-->
<html>
<head>
<title>A Propos</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />
<link rel="icon" href="images/favicon.ico" />
<link rel="stylesheet" href="assets/css/style.css" />
<noscript><link rel="stylesheet" href="assets/css/noscript.css" /></noscript>
</head>
<body class="is-preload">
<!-- Wrapper -->
<div id="wrapper">
<!-- Header -->
<header id="header">
<a href="index.php" class="logo"><img width="30px" src="images/logo.png"><strong>AUTHEMAN</strong> <span>Victor</span></a>
<nav>
<a href="#menu">Menu</a>
</nav>
</header>
<!-- Menu -->
<?php include 'assets/include/nav.php'; ?>
<!-- Main -->
<div id="main" class="alt">
<!-- One -->
<section id="one">
<div class="inner">
<header class="major">
<h1>
<?php
if(isset($message)){
echo $message;
}
?>
</h1>
<p>
<?php
if(isset($messageConnexion)){
echo $messageConnexion;
}
?>
</p>
</header>
</div>
</section>
</div>
<!-- Footer -->
<?php include 'assets/include/footer.html'; ?>
</div>
<!-- Scripts -->
<script src="assets/js/jquery.min.js"></script>
<script src="assets/js/jquery.scrolly.min.js"></script>
<script src="assets/js/jquery.scrollex.min.js"></script>
<script src="assets/js/browser.min.js"></script>
<script src="assets/js/breakpoints.min.js"></script>
<script src="assets/js/util.js"></script>
<script src="assets/js/main.js"></script>
</body>
</html>
<file_sep><?php
session_start();
$bdd = new PDO('mysql:host=172.16.17.32; dbname=authe858327', 'authe858327', '3q5krvgsyi');
//$bdd = new PDO('sqlite:assets/include/database_portfolio.bdd');
$bdd->query("SET NAMES UTF8");
?>
<div class="loader">
<script type="text/javascript" src="/assets/js/jquery-latest.js"></script>
<script type="text/javascript">
$(window).load(function() {
$(".loader").fadeOut("1000");
})
</script>
</div>
<file_sep>#include <iostream>
using namespace std;
int main(){
int nbTenPrems;
nbTenPrems = 10;
cout<<"Les dix premier entier"<<endl;
for( int noTenPrems = 0; noTenPrems<nbTenPrems; noTenPrems++)
{
cout<<noTenPrems<<endl;
}
cout<<endl;
return 0;
}
<file_sep><!DOCTYPE HTML>
<?php
// On se connecte à la base donnée
include 'assets/include/connectBDD.php';
// On récupère l'identifiant choisi
if(isset($_GET['id']) AND !empty($_GET['id']))
{
?>
<!--
Site internet Créé par <NAME>
-->
<html>
<head>
<title>Portfolio</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />
<link rel="icon" href="images/favicon.ico" />
<!-- CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<link rel="stylesheet" href="assets/css/style.css" />
<noscript><link rel="stylesheet" href="assets/css/noscript.css" /></noscript>
<!-- SCRIPT -->
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body class="is-preload" onselectstart="return false" oncontextmenu="return false" ondragstart="return false">
<!--<div class="loader">
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(window).load(function () {
$(".loader").fadeOut("1000");
})
</script>
<div class="loader_text">CHARGEMENT</div>
</div>-->
<!-- Wrapper -->
<div id="wrapper">
<!-- Header -->
<!-- Note: The "styleN" class below should match that of the banner element. -->
<header id="header">
<?php include 'assets/include/header.php'; ?>
</header>
<!-- Menu -->
<?php include 'assets/include/nav.php'; ?>
<!-- Main -->
<div id="main" class="alt">
<!-- One -->
<?php
$req = $bdd->prepare("SELECT * FROM card WHERE cardId = ?");
$req->execute(array($_GET['id']));
$cur = $req->fetch();
?>
<style media="screen">
div.article img{
width: 100% !important;
height: auto !important;
}
</style>
<div class="container article" style="margin-top: 50px; margin-bottom: 100px;">
<div class="text-left row justify-content-between">
<div class="col-lg-9 col-sm-12 p-4 mb-4" style="background: #2a2f4a;">
<div class="row m-0 mb-4">
<div class="col float-left p-0">
<?php
$reqPrev = $bdd->prepare("SELECT * FROM card WHERE cardId<? ");
$reqPrev->execute(array($_GET['id']));
$curPrev = $reqPrev->fetch();
if(!empty($curPrev[0]))
{
?>
<a class="float-left border-0" href="article.php?id=<?php echo $curPrev[0]; ?>"><i class="fas fa-arrow-left mr-2"></i> <?php echo $curPrev['cardNom']; ?></a>
<?php } ?>
</div>
<div class="col">
<?php
$reqNext = $bdd->prepare("SELECT * FROM card WHERE cardId>? ");
$reqNext->execute(array($_GET['id']));
$curNext = $reqNext->fetch();
if(!empty($curNext[0]))
{
?>
<a class="float-right border-0" href="article.php?id=<?php echo $curNext[0]; ?>"><?php echo $curNext['cardNom']; ?> <i class="fas fa-arrow-right ml-2"></i></a>
<?php } ?>
</div>
</div>
<div class="inner">
<header class="major inline">
<h1><?php echo $cur['cardNom']; ?></h1>
<a href="#espace-commentaires" class="scrolly">Voir les commentaires</a>
</header>
<div>
<ul class="actions">
<li><a class="button" target="_blank" href="<?php echo $cur['cardURL']; ?>">Télécharger</a></li>
<?php if(isset($_SESSION['id'])){ ?>
<li><a class="button primary" href="cardModif.php?cardId=<?php echo $cur['cardId']; ?>">Modifier</a></li>
<li><a class="button primary" href="cardSuppr.php?cardId=<?php echo $cur['cardId']; ?>">Supprimer</a></li>
<?php } ?>
</ul>
</div>
<?php echo $cur['cardContenu']; ?>
<!-- ESPACE COMMENTAIRE -->
<?php
if(isset($_POST['submitCommentaire']))
{
if(isset($_SESSION['user'], $_POST['commentaire'], $_POST['title']) AND !empty($_SESSION['user']) AND !empty($_POST['commentaire']) AND !empty($_POST['title']))
{
$user = htmlspecialchars($_SESSION['user']);
$commentaire = htmlspecialchars($_POST['commentaire']);
$title = htmlspecialchars($_POST['title']);
$reqUser = $bdd->prepare("SELECT * FROM commentaires WHERE comUser = ? AND comCard = ?");
$reqUser->execute(array($user, $_GET['id']));
$userExist = $reqUser->rowCount();
if($userExist == 5)
{
$c_erreur = "Vous avez atteint votre cota de commentaire !";
} else {
// On récupère la section qu'apartient la card
$reqSection = $bdd->prepare("SELECT portNom FROM portfolio NATURAL JOIN card WHERE cardId = ?");
$reqSection->execute(array($_GET["id"]));
$curSection = $reqSection->fetch();
$date = date('Y-m-d');
$ins = $bdd->prepare('INSERT INTO commentaires (comUser, comTitle, comTexte, comDate, comType, comCard) VALUES (?, ?, ?, ?, ?, ?)');
$ins->execute(array($user, $title, $commentaire, $date, $curSection[0], $_GET['id']));
$c_message = "Votre commentaire a bien été posté !";
}
} else {
$c_erreur = "Tous les champs doivent être complétés";
}
}
$commentaire = $bdd->prepare('SELECT * FROM commentaires WHERE comCard = ? ORDER BY comId desc');
$commentaire->execute(array($_GET['id']));
?>
<header class="major">
<h2 id="espace-commentaires">Espace commentaires</h2>
</header>
<h3>Règlement</h3>
<p>- Écrire dans un français correct - Respecter les autres - Pas de pubs et de spams - 5 Commentaires maximum</p>
<?php
if(isset($_SESSION['user']))
{
?>
<form action="#commentaire" id="commentaire" method="post">
<label for="title">Quel titre</label>
<input type="text" name="title" id="title"><br>
<label for="commentaire">Votre commentaire</label>
<textarea name="commentaire"></textarea><br>
<input type="submit" name="submitCommentaire" value="Poster">
</form>
<?php
}
if(isset($c_message))
{
?>
<div class="alert alert-success" role="alert">
<?php echo $c_message;?>
</div>
<?php
}
if(isset($c_erreur))
{
?>
<div class="alert alert-danger" role="alert">
<?php echo $c_erreur;?>
</div>
<?php
}
?>
<br>
<?php
while($c=$commentaire->fetch())
{
?>
<b><i class="fas fa-user"></i> <?= $c['comUser'] ?></b> -
<?= $c['comTitle'] ?><br>
<?= $c['comTexte'] ?><br>
<?= $c['comDate'] ?><br><hr>
<?php
}
?>
</div>
</div>
<div class="p-2 col col-sm ml-4" style="background: #2a2f4a;">
<div class="tuto">
<h4>Tutoriels récents</h4>
<ul class="alt" style="font-size: 12pt;">
<?php
$reqTuto = $bdd->prepare("SELECT * FROM card ORDER BY cardId desc LIMIT 5");
$reqTuto->execute();
while($curTuto = $reqTuto->fetch())
{
?>
<li><a href="<?php echo $curTuto['cardURL']; ?>"><?php echo $curTuto['cardNom']; ?></a></li>
<?php
}
?>
</div>
<div class="commentaires">
<h4>Commentaires récents</h4>
<ul class="alt" style="font-size: 12pt;">
<?php
$reqCom = $bdd->prepare("SELECT * FROM commentaires ORDER BY comId desc LIMIT 5");
$reqCom->execute();
while($curCom = $reqCom->fetch())
{
?>
<li style="word-wrap: break-word;"><b><?php echo $curCom['comUser'];?> : <?php echo $curCom['comType']; ?><br></b> <?php echo $curCom['comTexte']; ?><br></li>
<?php
}
?>
</ul>
</div>
<div class="connecte">
<h4>Restez connecté</h4>
<ul class="icons">
<li><a href="#" class="icon brands fa-twitter"><span class="label">Twitter</span></a></li>
<li><a href="#" class="icon brands fa-facebook-f"><span class="label">Facebook</span></a></li>
<li><a href="#" class="icon brands fa-instagram"><span class="label">Instagram</span></a></li>
<li><a href="#" class="icon brands fa-github"><span class="label">Github</span></a></li>
<li><a href="#" class="icon brands fa-dribbble"><span class="label">Dribbble</span></a></li>
<li><a href="#" class="icon brands fa-tumblr"><span class="label">Tumblr</span></a></li>
</ul>
</div>
</div>
</div>
</div>
<!-- Contact -->
<?php include 'assets/include/contact.php'; ?>
<!-- Footer -->
<?php include 'assets/include/footer.html'; ?>
</div>
<!-- Scripts -->
<script src="assets/js/jquery.min.js"></script>
<script src="assets/js/jquery.scrolly.min.js"></script>
<script src="assets/js/jquery.scrollex.min.js"></script>
<script src="assets/js/browser.min.js"></script>
<script src="assets/js/breakpoints.min.js"></script>
<script src="assets/js/util.js"></script>
<script src="assets/js/main.js"></script>
<script src="https://kit.fontawesome.com/3ba462b0e4.js" crossorigin="anonymous"></script>
</body>
</html>
<?php
} else{
header('Location: portfolio.php');
}
?>
<file_sep><!DOCTYPE HTML>
<?php
include 'assets/include/connectBDD.php';
?>
<!--
Site internet Créé par AUTHEMAN Victor
-->
<html>
<head>
<title>Mes Compétences</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />
<link rel="icon" href="images/favicon.ico" />
<!-- CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<link rel="stylesheet" href="assets/css/style.css" />
<noscript><link rel="stylesheet" href="assets/css/noscript.css" /></noscript>
<!-- SCRIPT -->
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
</head>
<body class="is-preload" onselectstart="return false" oncontextmenu="return false" ondragstart="return false">
<!-- Wrapper -->
<div id="wrapper">
<!-- Header -->
<header id="header">
<<a href="index.php" class="logo"><img width="30px" src="images/logo.png"><strong>AUTHEMAN</strong> <span>Victor</span></a>
<nav>
<a href="#menu">Menu</a>
</nav>
</header>
<!-- Menu -->
<?php include 'assets/include/nav.php'; ?>
<!-- Main -->
<div id="main" class="alt">
<!-- One -->
<section id="one">
<div class="inner">
<header class="major">
<h1>Mes compétences</h1>
</header>
<div class="row">
<div class="col-6">
<h5 class="progressTitle">Javascript</h5>
<div class="progress">
<div class="progress-bar" role="progressbar" style="width: 20%" aria-valuenow="20" aria-valuemin="0" aria-valuemax="100"></div>
</div>
<h5 class="progressTitle">PHP</h5>
<div class="progress">
<div class="progress-bar bg-success" role="progressbar" style="width: 25%" aria-valuenow="25" aria-valuemin="0" aria-valuemax="100"></div>
</div>
<h5 class="progressTitle">HTML(5)</h5>
<div class="progress">
<div class="progress-bar bg-info" role="progressbar" style="width: 50%" aria-valuenow="50" aria-valuemin="0" aria-valuemax="100"></div>
</div>
<h5 class="progressTitle">CSS(3)</h5>
<div class="progress">
<div class="progress-bar bg-warning" role="progressbar" style="width: 75%" aria-valuenow="75" aria-valuemin="0" aria-valuemax="100"></div>
</div>
<h5 class="progressTitle">Word Press</h5>
<div class="progress">
<div class="progress-bar bg-danger" role="progressbar" style="width: 100%" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100"></div>
</div>
</div>
<div class="col-6">
<h5 class="progressTitle">Dépannage Informatique</h5>
<div class="progress">
<div class="progress-bar" role="progressbar" style="width: 100%" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100"></div>
</div>
<h5 class="progressTitle">Suite Office</h5>
<div class="progress">
<div class="progress-bar bg-success" role="progressbar" style="width: 100%" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100"></div>
</div>
<h5 class="progressTitle">Suite Adobe (Photoshop, Illustrator, Première pro & After Effect)</h5>
<div class="progress">
<div class="progress-bar bg-info" role="progressbar" style="width: 100%" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100"></div>
</div>
<h5 class="progressTitle">Graphiste</h5>
<div class="progress">
<div class="progress-bar bg-warning" role="progressbar" style="width: 100%" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100"></div>
</div>
</div>
</div>
</div>
</section>
</div>
<!-- Contact -->
<?php include 'assets/include/contact.php'; ?>
<!-- Footer -->
<?php include 'assets/include/footer.html'; ?>
</div>
<!-- Scripts -->
<script src="assets/js/jquery.min.js"></script>
<script src="assets/js/jquery.scrolly.min.js"></script>
<script src="assets/js/jquery.scrollex.min.js"></script>
<script src="assets/js/browser.min.js"></script>
<script src="assets/js/breakpoints.min.js"></script>
<script src="assets/js/util.js"></script>
<script src="assets/js/main.js"></script>
</body>
</html>
<file_sep>#include "dialogajoutportfolioitems.h"
#include "ui_dialogajoutportfolioitems.h"
#include "administration.h"
#include <QDebug>
#include <QFileDialog>
#include <QSqlQuery>
#include <QSqlDatabase>
DialogAjoutPortfolioItems::DialogAjoutPortfolioItems(QWidget *parent) :
QDialog(parent),
ui(new Ui::DialogAjoutPortfolioItems)
{
ui->setupUi(this);
}
DialogAjoutPortfolioItems::~DialogAjoutPortfolioItems()
{
delete ui;
}
void DialogAjoutPortfolioItems::on_toolButtonSelectImg_clicked()
{
// On configure le bouton d'importation de l'image
pathImgPortfolioItem = QFileDialog::getOpenFileName(this, "Choisissez l'image du rayon","","*.png *.jpg");
if(!pathImgPortfolioItem.isEmpty())
{
if(!pathImgPortfolioItem.isNull())
{
qDebug()<<pathImgPortfolioItem;
}
}
return void();
}
void DialogAjoutPortfolioItems::on_pushButtonAjout_clicked()
{
// On récupère le contenu des inputs
QString portNom = ui->lineEditNom->text();
qDebug()<<portNom;
QString portDesc = ui->textEditDesc->toPlainText();
qDebug()<<portDesc;
QString portUrlMemento = ui->lineEditUrlMemento->text();
qDebug()<<portUrlMemento;
QString portAncre = ui->lineEditAncre->text();
qDebug()<<portAncre;
// On récupère le nom de l'image dans le chemin
pathImgPortfolioItem = QFileInfo(pathImgPortfolioItem).fileName();
// On défini l'image avev son nom
QString portImg = pathImgPortfolioItem;
qDebug()<<portImg;
// On execute la requete d'implementation dans la base de données
QSqlQuery requete;
if(requete.prepare("INSERT INTO portfolio(portNom, portImage, portDesc, portMementoURL, portAncre) VALUES(:portNom, :portImg, :portDesc, :portMementoUrl, :portAncre);"))
{
requete.bindValue(":portMementoUrl", portUrlMemento);
requete.bindValue(":portAncre", portAncre);
requete.bindValue(":portNom", portNom);
requete.bindValue(":portImg", portImg);
requete.bindValue(":portDesc", portDesc);
requete.exec();
qDebug()<<"requete - ok";
} else qDebug()<<"Erreur de requete";
Administration w;
w.remplirTableWidgetPortfolioItem();
close();
}
<file_sep><!DOCTYPE HTML>
<?php
// On se connecte à la base donnée
include 'assets/include/connectBDD.php';
// On vérifie si la session
if(isset($_SESSION['sendMsg']) AND isset($_GET['id']) AND isset($_GET['mail']) AND !empty($_GET['id']) AND !empty($_GET['mail']))
{
// On sécurise les valeurs
$id = htmlspecialchars($_GET['id']);
$mail = htmlspecialchars($_GET['mail']);
?>
<!--
Site internet Créé par AUTHEMAN Victor
-->
<html>
<head>
<title>Edit : <?php echo $cur['cardNom']; ?></title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />
<link rel="icon" href="images/favicon.ico" />
<!-- CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<link rel="stylesheet" href="assets/css/style.css" />
<noscript><link rel="stylesheet" href="assets/css/noscript.css" /></noscript>
<!-- SCRIPT -->
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body class="is-preload" onselectstart="return false" oncontextmenu="return false" ondragstart="return false">
<!-- Wrapper -->
<div id="wrapper">
<!-- Header -->
<!-- Note: The "styleN" class below should match that of the banner element. -->
<header id="header">
<a href="index.php" class="logo"><img width="30px" src="images/logo.png"><strong>AUTHEMAN</strong> <span>Victor</span></a>
<nav>
<a href="#menu">Menu</a>
</nav>
</header>
<!-- Menu -->
<?php include 'assets/include/nav.php'; ?>
<!-- Main -->
<div id="main" class="alt">
<!-- One -->
<section class="container-fluid" id="one">
<div class="inner">
<header class="memento major">
<h1>Changement Mot de passe</h1>
</header>
<form action="#" method="get">
<input type="<PASSWORD>" name="password" placeholder="<PASSWORD>">
<input type="<PASSWORD>" name="password2" placeholder="Confirmation du mot de passe">
<input type="submit" class="button primary" value="Mettre à jour">
</form>
<?php
if(isset($_GET['password']) AND isset($_GET['password2']) AND !empty($_GET['password']) AND !empty($_GET['password2']))
{
// On sécurise les valeurs
$password = $_GET['password'];
$password2 = $_GET['password2'];
if($password == $password2)
{
$password = <PASSWORD>($password);
$req = $bdd->prepare("UPDATE membres SET memMotDePasse=? WHERE memId = ?");
$req->execute(array($password, $id));
} else echo "Erreur : les deux mot de passe ne correspondent pas !";
}
?>
</div>
</section>
<!-- Scripts -->
<script src="assets/js/jquery.min.js"></script>
<script src="assets/js/jquery.scrolly.min.js"></script>
<script src="assets/js/jquery.scrollex.min.js"></script>
<script src="assets/js/browser.min.js"></script>
<script src="assets/js/breakpoints.min.js"></script>
<script src="assets/js/util.js"></script>
<script src="assets/js/main.js"></script>
</body>
</html>
<?php } ?>
<file_sep><!DOCTYPE HTML>
<?php
include 'assets/include/connectBDD.php';
if(isset($_POST['formInscription']))
{
$nom = htmlspecialchars($_POST['nom']);
$prenom = htmlspecialchars($_POST['prenom']);
$user = htmlspecialchars($_POST['user']);
$email = htmlspecialchars($_POST['email']);
$password = sha1($_POST['password']);
$passwordConfirm = sha1($_POST['passwordConfirm']);
if(!empty($_POST['nom']) AND !empty($_POST['prenom']) AND !empty($_POST['email']) AND !empty($_POST['user']) AND !empty($_POST['password']) AND !empty($_POST['passwordConfirm']))
{
$reqUser = $bdd->prepare("SELECT * FROM membres WHERE memUtilisateur = ?");
$reqUser->execute(array($user));
$userExist = $reqUser->rowCount();
if($userExist == 0)
{
$userlenght = strlen($user);
if($userlenght <= 32)
{
if(filter_var($email, FILTER_VALIDATE_EMAIL))
{
$reqMail = $bdd->prepare("SELECT * FROM membres WHERE memEmail = ?");
$reqMail->execute(array($email));
$mailExist = $reqMail->rowCount();
if($mailExist == 0)
{
if($password == $passwordConfirm)
{
$longueurKey = 15;
$key = "";
for($i=1;$i<$longueurKey;$i++) {
$key .= mt_rand(0,9);
}
$insertMembres = $bdd->prepare("INSERT INTO membres(memNom, memPrenom, memEmail, memUtilisateur, memMotDePasse, memKey) VALUES(?, ?, ?, ?, ?, ?)");
$insertMembres->execute(array($nom, $prenom, $email, $user, $password, $key));
$header="MIME-Version: 1.0\r\n";
$header.='From: "<EMAIL>"<<EMAIL>>'."\n";
$header.='Content-Type:text/html; charset"utf-8"'."\n";
$header.='Content-Transfer-Encoding: 8bit';
$messageMail='
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns:v="urn:schemas-microsoft-com:vml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta charset="utf8">
<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0;">
</head>
<body leftmargin="0" topmargin="0" marginwidth="0" marginheight="0">
<table bgcolor="#242943"width="100%" border="0" cellpadding="0" cellspacing="0">
<tbody>
<tr>
<td bgcolor="#242943">
<div>
<table align="center" width="590" border="0" cellpadding="0" cellspacing="0">
<tbody>
<tr>
<td height="30" style="font-size: 30px; line-height: 30px;"> </td>
</tr>
<tr>
<td align="center" style="text-align:center;">
<a href="http://autheman-victor.fr">
<img src="http://autheman-victor.fr/ancienSite/images/logo.png" width="78" border="0" alt="Logo autheman-victor.fr">
</a>
</td>
</tr>
<tr>
<td height="30" style="font-size: 30px; line-height: 30px;"> </td>
</tr>
<tr>
<td align="center" style="font-family: Helvetica, sans-serif; text-align: center; font-size:32px; color: #FFF; mso-line-height-rule: exactly; line-height: 28px;">
Confirmation de votre compte
</td>
</tr>
<tr>
<td height="30" style="font-size: 30px; line-height: 30px;"> </td>
</tr>
<tr>
<td align="center" style="font-family: Helvetica, sans-serif; text-align: center; font-size:15px; color: #878b99; mso-line-height-rule: exactly; line-height: 26px;">
<a href="https://autheman-victor.fr/confirmation.php?user='.urlencode($user).'&key='.$key.'">Confirmation</a>
</td>
</tr>
<tr>
<td height="30" style="font-size: 30px; line-height: 30px;"> </td>
</tr>
</tbody>
</table>
</div>
</td>
</tr>
</tbody>
</table>
</body>
</html>
';
mail($email, "Confirmation de compte", $messageMail, $header);
$messageValide = "Un mail de confirmation vous à été envoyé !";
} else {
$message = "Vos mot de passe ne correspondent pas !";
}
} else {
$message = "Adresse mail déjà utilisé !";
}
} else {
$message = "Votre addresse email n'est pas valide !";
}
} else {
$message = "Votre nom d'utilisateur ne doit pas dépasser 255 caractères !";
}
} else {
$message = "Le nom d'utilisateur existe déjà !";
}
} else {
$message = "Tous les champs doivent êtres complétés";
}
}
?>
<html>
<head>
<title>Connexion</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />
<link rel="icon" href="images/favicon.ico" />
<!-- CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<link rel="stylesheet" href="assets/css/style.css" />
<noscript><link rel="stylesheet" href="assets/css/noscript.css" /></noscript>
<!-- SCRIPT -->
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
</head>
<body class="is-preload">
<!-- Wrapper -->
<div id="wrapper">
<!-- Header -->
<header id="header">
<a href="index.php" class="logo"><strong>AUTHEMAN</strong> <span>Victor</span></a>
<nav>
<a href="#menu">Menu</a>
</nav>
</header>
<!-- Menu -->
<?php include 'assets/include/nav.php'; ?>
<!-- Main -->
<div id="main" class="alt">
<!-- One -->
<section class="inscription" id="one">
<form action="" method="post">
<div class="inscription">
<label for="nom">Nom</label>
<input type="text" name="nom" required="required" value="<?php if(isset($_POST['nom'])) { echo $_POST['nom']; } ?>">
<label for="prenom">Prénom</label>
<input type="text" name="prenom" required="required" value="<?php if(isset($_POST['prenom'])) { echo $_POST['prenom']; } ?>">
<label for="email">Email</label>
<input type="email" name="email" required="required" value="<?php if(isset($_POST['email'])) { echo $_POST['email']; } ?>">
<label for="user">Utilisateur</label>
<input type="text" name="user" required="required" value="<?php if(isset($_POST['user'])) { echo $_POST['user']; } ?>">
<label for="password">Mot de passe</label>
<input type="password" name="password" required="required">
<label for="passwordConfirm">Confirmer le Mot de passe</label>
<input type="password" name="passwordConfirm" required="required"><br>
<input type="checkbox" name="conditions" id="conditions" required="required" />
<label for="conditions">J'accepte les <a href="mentions-legales/conditions-utilisations.php">conditions d'utilisation</a></label><br>
<ul class="actions">
<li><input type="submit" name="formInscription" value="Inscription" class="primary" /></li>
<li><input type="reset" value="Effacer" /></li>
</ul>
</div>
</form>
<?php
if(isset($message))
{
?>
<div class="alertMessage alert alert-warning" role="alert">
<?php echo $message; ?>
</div>
<?php
}
if(isset($messageValide))
{
?>
<div class="alertMessage alert alert-success" role="alert">
<?php echo $messageValide; ?>
</div>
<?php
}
?>
</section>
</div>
<!-- Footer -->
<?php include 'assets/include/footer.html'; ?>
</div>
<!-- Scripts -->
<script src="assets/js/jquery.min.js"></script>
<script src="assets/js/jquery.scrolly.min.js"></script>
<script src="assets/js/jquery.scrollex.min.js"></script>
<script src="assets/js/browser.min.js"></script>
<script src="assets/js/breakpoints.min.js"></script>
<script src="assets/js/util.js"></script>
<script src="assets/js/main.js"></script>
</body>
</html>
<file_sep><?php
// On se connecte à la base de donnée
include 'assets/include/connectBDD.php';
// On vérifi si l'administrateur est connecté
if(isset($_SESSION['user']) AND $_SESSION['user'] == "admin")
{
// On vérifi si l'identifiant de la section a supprimer existe
if(isset($_GET['portId']) AND !empty($_GET['portId']) AND $_GET['portId'] > 0)
{
// On sécurise les valeurs
$portId = htmlspecialchars($_GET['portId']);
// supprime toutes les cartes
$req = $bdd->prepare("DELETE FROM card WHERE portId = ?");
$req->execute(array($portId));
// On supprime la section de la base de donnée
$req = $bdd->prepare("DELETE FROM portfolio WHERE portId = ?");
$req->execute(array($portId));
header("Location: portfolio.php");
} else header("Location: portfolio.php");
} else header("Location: portfolio.php");
?>
<file_sep><!DOCTYPE HTML>
<?php include 'assets/include/connectBDD.php'; ?>
<!--
Site internet Créé par AUTHEMAN Victor
-->
<html>
<head>
<title>A Propos</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />
<link rel="icon" href="images/favicon.ico" />
<noscript><link rel="stylesheet" href="assets/css/noscript.css" /></noscript>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="assets/css/style.css" />
</head>
<body class="is-preload">
<!-- Wrapper -->
<div id="wrapper">
<!-- Header -->
<header id="header">
<audio src="song/music.mp3" autoplay loop>
</audio>
<a href="index.php" class="logo"><img width="30px" src="images/logo.png"><strong>AUTHEMAN</strong> <span>Victor</span></a>
<nav>
<a href="#menu">Menu</a>
</nav>
</header>
<!-- Menu -->
<?php include 'assets/include/nav.php'; ?>
<!-- Main -->
<div id="main" class="alt">
<!-- One -->
<section id="one">
<div class="inner">
<header class="major">
<div class="alert alert-danger" role="alert">
<h4 class="alert-heading">Erreur 404</h4>
<p style="padding-bottom: 0; margin-bottom: 0;">La page que vous recherchez est incorrect ou n'est pas disponible pour le moment !</p>
<hr>
<p class="mb-0">Réessayez plus tard ou saisissez une adresse valide !</p>
</div>
</header>
</div>
</section>
</div>
<!-- Footer -->
<?php include 'assets/include/footer.html'; ?>
</div>
<!-- Scripts -->
<script src="assets/js/jquery.min.js"></script>
<script src="assets/js/jquery.scrolly.min.js"></script>
<script src="assets/js/jquery.scrollex.min.js"></script>
<script src="assets/js/browser.min.js"></script>
<script src="assets/js/breakpoints.min.js"></script>
<script src="assets/js/util.js"></script>
<script src="assets/js/main.js"></script>
</body>
</html>
<file_sep>#ifndef DIALOGAJOUTPORTFOLIOITEMS_H
#define DIALOGAJOUTPORTFOLIOITEMS_H
#include <QDialog>
namespace Ui {
class DialogAjoutPortfolioItems;
}
class DialogAjoutPortfolioItems : public QDialog
{
Q_OBJECT
public:
explicit DialogAjoutPortfolioItems(QWidget *parent = nullptr);
~DialogAjoutPortfolioItems();
QString pathImgPortfolioItem;
private slots:
void on_toolButtonSelectImg_clicked();
void on_pushButtonAjout_clicked();
private:
Ui::DialogAjoutPortfolioItems *ui;
};
#endif // DIALOGAJOUTPORTFOLIOITEMS_H
<file_sep>#include <iostream>
using namespace std;
int main(){
int largeur = 80;
int longueur = 25;
for(int noLargeur = 0; noLargeur<largeur; noLargeur++)
{
for(int noLongueur = 0; noLargeur<largeur; noLargeur++)
{
}
<file_sep><!DOCTYPE HTML>
<?php
// On se connecte à la base donnée
include 'assets/include/connectBDD.php';
// On récupère l'identifiant choisi
if(isset($_GET['cardId']) AND !empty($_GET['cardId']) AND $_GET['cardId'] > 0)
{
// On sécurise les données
$cardId = htmlspecialchars($_GET['cardId']);
$req = $bdd->prepare("SELECT * FROM card WHERE cardId = ?");
$req->execute(array($cardId));
$cur = $req->fetch();
if($cur['cardId'] == $cardId)
{
?>
<!--
Site internet Créé par <NAME>
-->
<html>
<head>
<title>Edit : <?php echo $cur['cardNom']; ?></title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />
<link rel="icon" href="images/favicon.ico" />
<!-- CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<link rel="stylesheet" href="assets/css/style.css" />
<noscript><link rel="stylesheet" href="assets/css/noscript.css" /></noscript>
<!-- SCRIPT -->
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://cdn.ckeditor.com/4.13.0/standard/ckeditor.js"></script>
</head>
<body class="is-preload" onselectstart="return false" oncontextmenu="return false" ondragstart="return false">
<!--<div class="loader">
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(window).load(function () {
$(".loader").fadeOut("1000");
})
</script>
<div class="loader_text">CHARGEMENT</div>
</div>-->
<!-- Wrapper -->
<div id="wrapper">
<!-- Header -->
<!-- Note: The "styleN" class below should match that of the banner element. -->
<header id="header">
<a href="index.php" class="logo"><img width="30px" src="images/logo.png"><strong>AUTHEMAN</strong> <span>Victor</span></a>
<nav>
<a href="#menu">Menu</a>
</nav>
</header>
<!-- Menu -->
<?php include 'assets/include/nav.php'; ?>
<!-- Main -->
<div id="main" class="alt">
<!-- One -->
<?php
if(isset($_SESSION['user']) AND $_SESSION['user'] == "admin")
{
?>
<section class="container-fluid" id="one">
<div class="inner">
<header class="memento major">
<h1>Edition : <?php echo $cur['cardNom']; ?></h1>
</header>
<form action="#" method="post">
<input type="text" name="nom" placeholder="Titre de la carte" value="<?php if(isset($cur['cardNom'])){echo $cur['cardNom'];} ?>">
<input type="text" name="description" placeholder="Description de la carte" value="<?php if(isset($cur['cardDesc'])){echo $cur['cardDesc'];} ?>">
<input type="url" name="lien" placeholder="Lien de la carte" value="<?php if(isset($cur['cardURL'])){echo $cur['cardURL'];} ?>">
<textarea name="contenu"><?php if(isset($cur['cardContenu'])){echo $cur['cardContenu'];} ?></textarea><br>
<script>
CKEDITOR.replace( 'contenu' );
</script>
<input name="utiliser" type="submit" value="Mettre à jour" class="primary" />
<?php
// On verifi si l'utilisateur à bien cliqué sur le bouton
if(isset($_POST['nom']))
{
$nom = htmlspecialchars($_POST['nom']);
$update = $bdd->prepare("UPDATE card SET cardNom = ? WHERE cardId = ?");
$update->execute(array($nom, $cardId));
}
if(isset($_POST['description']))
{
$description = htmlspecialchars($_POST['description']);
$update = $bdd->prepare("UPDATE card SET cardDesc = ? WHERE cardId = ?");
$update->execute(array($description, $cardId));
}
if(isset($_POST['lien']))
{
$lien = htmlspecialchars($_POST['lien']);
$update = $bdd->prepare("UPDATE card SET cardURL = ? WHERE cardId = ?");
$update->execute(array($lien, $cardId));
}
if(isset($_POST['contenu']))
{
$contenu = $_POST['contenu'];
$update = $bdd->prepare("UPDATE card SET cardContenu = ? WHERE cardId = ?");
$update->execute(array($contenu, $cardId));
}
?>
</form>
</div>
</section>
<?php
}
?>
<!-- Contact -->
<?php //include 'assets/include/contact.php'; ?>
<!-- Footer -->
<?php //include 'assets/include/footer.html'; ?>
</div>
<?php
// fermeture du if
} else header("Location: portfolioDisplay.php?portId=".$cur['portId']); //echo "Il n'existe pas de $cardId";
} else header("Location: portfolioDisplay.php?portId=".$cur['portId']);
?>
<!-- Scripts -->
<script src="assets/js/jquery.min.js"></script>
<script src="assets/js/jquery.scrolly.min.js"></script>
<script src="assets/js/jquery.scrollex.min.js"></script>
<script src="assets/js/browser.min.js"></script>
<script src="assets/js/breakpoints.min.js"></script>
<script src="assets/js/util.js"></script>
<script src="assets/js/main.js"></script>
</body>
</html>
<?php
if(isset($_POST['utiliser']))
{
header("Location: portfolioDisplay.php?portId=".$cur['portId']);
}
?>
<?php/*
} else{
header('Location: connexion.php?page=card');
}*/
?>
<file_sep>
#include <iostream>
using namespace std;
int main(){
string name1;
string name2;
cout<<"Indiquez un nom"<<endl;
getline(cin, name1);
cout<<"Indiquez un deuxième nom"<<endl;
getline(cin, name2);
if (name1 < name2){
cout<<name1<<endl<<name2<<endl;
}
else
{
cout<<name2<<endl<<name1<<endl;
}
return 0;
}
<file_sep>#include <iostream>
using namespace std;
int main(){
int nbTenPremsPair;
nbTenPremsPair = 10;
cout<<"Les dix premier nombre pair"<<endl;
for( int noTenPremsPair = 0; noTenPremsPair<nbTenPremsPair; noTenPremsPair+=2)
{
cout<<noTenPremsPair<<endl;
}
cout<<endl;
return 0;
}
<file_sep><?php
include 'assets/include/connectBDD.php';
$_SESSION = array();
session_destroy();
header('Location: connexion.php?page=profil');
?>
<file_sep><!DOCTYPE HTML>
<?php
// On se connecte à la base donnée
include 'assets/include/connectBDD.php';
// On récupère l'identifiant choisi
if(isset($_GET['portId']) AND !empty($_GET['portId']) AND $_GET['portId'] > 0)
{
// On sécurise les données
$portId = htmlspecialchars($_GET['portId']);
$req = $bdd->prepare("SELECT * FROM portfolio WHERE portId = ?");
$req->execute(array($portId));
$cur = $req->fetch();
if($cur['portId'] == $portId)
{
?>
<!--
Site internet Créé par <NAME>
-->
<html>
<head>
<title>Portfolio</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />
<link rel="icon" href="images/favicon.ico" />
<!-- CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<link rel="stylesheet" href="assets/css/style.css" />
<noscript><link rel="stylesheet" href="assets/css/noscript.css" /></noscript>
<!-- SCRIPT -->
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://cdn.ckeditor.com/4.13.0/standard/ckeditor.js"></script>
</head>
<body class="is-preload" onselectstart="return false" oncontextmenu="return false" ondragstart="return false">
<!--<div class="loader">
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(window).load(function () {
$(".loader").fadeOut("1000");
})
</script>
<div class="loader_text">CHARGEMENT</div>
</div>-->
<!-- Wrapper -->
<div id="wrapper">
<!-- Header -->
<!-- Note: The "styleN" class below should match that of the banner element. -->
<header id="header">
<?php include 'assets/include/header.php'; ?>
</header>
<!-- Menu -->
<?php include 'assets/include/nav.php'; ?>
<!-- Main -->
<div id="main" class="alt">
<!-- One -->
<section class="container-fluid" id="one">
<div class="inner">
<header class="memento major">
<h1><?php echo $cur['portNom']; ?></h1>
<a class="button" href="<?php echo $cur['portMementoURL']; ?>">Memento</a>
</header>
<p class="portDesc"><?php echo $cur['portDesc']; ?></p>
<div class="row">
<?php
$reqCard = $bdd->prepare("SELECT * FROM card WHERE portId = ?");
$reqCard->execute(array($portId));
while($curCard = $reqCard->fetch())
{
?>
<div class="column-4 column-12-medium">
<div class="carte">
<div class="container text-left">
<h4><b><?php echo $curCard['cardNom']; ?></b></h4>
<p><?php echo substr($curCard['cardDesc'], 0, 70).'...'; ?></p>
<ul class="actions">
<?php
// Récupèration du nombre de commentaire
$reqCom = $bdd->prepare("SELECT * FROM commentaires WHERE comCard = ?");
$reqCom->execute(array($curCard['cardId']));
$nbCom = 0;
?>
<li><i class="fas fa-comment-alt"></i> <?php while($curCom = $reqCom->fetch()){$nbCom++;} echo $nbCom; ?></li>
<li><i class="fas fa-calendar-alt"></i> <?php $date=date_create($curCard['cardDate']); echo date_format($date, 'd/m/Y'); ?></li>
</ul>
<ul class="actions">
<li><a target="_blank" href="article.php?id=<?php echo $curCard['cardId']; ?>" class="button">Consulter</a></li>
<div>
<li style="display: inline-block;"><a style="border: none !important; bottom:0;" title="Télécharger" target="_blank" href="<?php echo $curCard['cardURL']; ?>"><i class="fas fa-external-link-alt fa-lg"></i></a></li>
<?php if(isset($_SESSION['user']) AND $_SESSION['user'] == "admin"){ ?>
<li style="display: inline-block;"><a style="border: none !important; bottom:0;" href="cardModif.php?cardId=<?php echo $curCard['cardId']; ?>" class="text-warning"><i class="fas fa-edit fa-lg"></i></a></li>
<li style="display: inline-block;"><a style="border: none !important; bottom:0;" href="cardSuppr.php?cardId=<?php echo $curCard['cardId']; ?>" class="text-danger"><i class="fas fa-trash fa-lg"></i></a></li>
<?php } ?>
</div>
</ul>
</div>
</div>
</div>
<?php } // fin de la boucle ?>
</div>
</div>
</section>
<?php
if(isset($_SESSION['user']) AND $_SESSION['user'] == "admin")
{
?>
<section>
<div class="inner">
<header class="major">
<h2>Ajouter une carte</h2>
</header>
<form action="#" method="post">
<input type="text" required name="titre" placeholder="Titre de la carte">
<input type="text" required name="description" placeholder="Description de la carte">
<input type="url" required name="lien" placeholder="Lien de la carte">
<textarea name="contenu"></textarea><br>
<script>
CKEDITOR.replace( 'contenu' );
</script>
<input type="submit" value="Publier" class="primary" />
<?php
// On vérifi si les valeurs existent
if(isset($_POST['titre']) AND isset($_POST['description']) AND isset($_POST['lien']) AND isset($_POST['contenu']))
{
// On sécurise les valeurs
$titre = htmlspecialchars($_POST['titre']);
$description = htmlspecialchars($_POST['description']);
$lien = htmlspecialchars($_POST['lien']);
$contenu = $_POST['contenu'];
// On vérifi si les variables ne sont pas vides
if(!empty($titre) AND !empty($description) AND !empty($lien) AND !empty($contenu))
{
// On récupère l'id de la section pour la sauvegarder dans une variable
$portId = htmlspecialchars($_GET['portId']);
// On ajoute les valeurs dans la base de donnée
$req = $bdd->prepare("INSERT INTO card(cardNom, cardDesc, cardURL, cardContenu, portId) VALUES(?, ?, ?, ?, ?)");
$req->execute(array($titre, $description, $lien, $contenu, $portId));
header("Location: portfolioDisplay.php?portId=".$portId);
}
}
?>
</form>
</div>
</section>
<?php } ?>
<!-- Contact -->
<?php include 'assets/include/contact.php'; ?>
<!-- Footer -->
<?php include 'assets/include/footer.html'; ?>
</div>
<?php
// fermeture du if
} else header("Location: portfolio.php"); //echo "Il n'existe pas de $portId";
} else header("Location: portfolio.php");
?>
<!-- Scripts -->
<script src="assets/js/jquery.min.js"></script>
<script src="assets/js/jquery.scrolly.min.js"></script>
<script src="assets/js/jquery.scrollex.min.js"></script>
<script src="assets/js/browser.min.js"></script>
<script src="assets/js/breakpoints.min.js"></script>
<script src="assets/js/util.js"></script>
<script src="assets/js/main.js"></script>
<script src="https://kit.fontawesome.com/3ba462b0e4.js" crossorigin="anonymous"></script>
</body>
</html>
<?php/*
} else{
header('Location: connexion.php?page=portfolio');
}*/
?>
| b593708850614cb186f251ebe7733e699db2f35e | [
"SQL",
"C++",
"PHP"
] | 48 | PHP | vautheman/Book-2019 | dfdc00192525d9152203e417f84afb9b208f3a2e | b44ed743d006fe98525ee757a40876d61fddc77b |
refs/heads/master | <repo_name>MAEXOMEN/AEschool<file_sep>/system/elements/user.php
<div id="ae_element_user">
<img id="ae_element_user_image" src="logo.svg"/><div id="ae_element_user_right_column">
<h3 id="ae_element_user_name"><?php echo $user_name; ?></h3>
<h5 id="ae_element_user_subtitle"><?php echo $user_subtitle; ?></h5>
<a class="ae_element_user_button clickable" href="settings"><i class="fa fa-cogs clickable" aria-hidden="true"></i> <?php echo $settings; ?></a>
</div>
<a class="ae_element_user_button clickable" href="out/"><i class="fa fa-power-off clickable" aria-hidden="true"></i> <?php echo $logout; ?></a>
</div>
<file_sep>/content/reader.php
<?php
$t = "aeStudent";
$nav = json_decode(file_get_contents("content/navigation.json"));
$strings = json_decode(file_get_contents("content/language/DE_de.json"));
foreach ($nav->$t as $temp)
{
$use = $temp->name;
if (strpos($temp->name, '@strings-') !== false)
{
$str = preg_replace('/^@strings-/', '', $temp->name);
@$use = $strings->$str;
$temp->name = $use;
}
$html = '<a class="ae_element_sidebar_item clickable" href="'.$temp->link.'"><div class="ae_element_sidebar_item_icon clickable"><i class="'.$temp->icon.' ae_element_sidebar_item_icon_img clickable" aria-hidden="true"></i></div><div class="ae_element_sidebar_item_name clickable">'.$use.'</div></a>';
echo $html;
}
?>
<file_sep>/index.php
<?php
session_start();
$user_name = "<NAME>";
$user_subtitle = "Goethe-Gymnasium";
$site_title = "Dashboard";
$product = "ÆSCHOOL";
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title id="ae_site_title"><?php echo $product . " - " . $site_title;?></title>
<link rel="stylesheet" href="system/design/fonts/font-awesome/css/font-awesome.min.css">
<link rel="stylesheet" href="system/design/site.css" media="screen and (min-width: 5in) and (min-height: 400px)" title="no title" charset="utf-8">
<style media="screen">div#ae_element_header_name_holder_two{margin-left: 100%;}div#ae_element_user{visibility: hidden;}</style>
</head>
<body>
<?php include "system/elements/header.php"; ?>
<?php include "system/elements/sidebar.php"; ?>
<?php include "system/elements/content.php"; ?>
<?php include "system/elements/user.php"; ?>
</body>
</html>
<file_sep>/system/elements/sidebar.php
<nav id="ae_element_sidebar">
<?php include("content/reader.php"); ?>
</nav>
| 99263fa64e8eaa09eb88f2d1c66cd0b95f3444aa | [
"PHP"
] | 4 | PHP | MAEXOMEN/AEschool | 1071949890cc41b6285707fb101b8581514399d6 | ed4e5a04ee29cbb587283b09facc965662f81528 |
refs/heads/master | <file_sep><?php
require('../model/database.php');
if(isset($_POST['message'])){
$message = trim($_POST['message']);
if(!empty($message)){
$addedQuery = $db->prepare("
INSERT INTO todo (message, user, isComplete, submissionDate)
VALUES (:message, :user, 0, NOW())
");
$addedQuery->execute([
'message' => $message,
'user' => $_SESSION['user_id']
]);
}
}
header('Location: /toDoListApp/index.php');
?><file_sep><?php
require_once 'model/database.php';
$itemsQuery = $db->prepare("
SELECT id, message, isComplete
FROM todo
WHERE user = :user
");
$itemsQuery->execute(['user' => $_SESSION['user_id']]);
$items = $itemsQuery->rowCount() ? $itemsQuery : [];
?>
<?php include('view/header.php') ?>
<?php include('model/toDoApp.php') ?>
<?php include('view/footer.php') ?>
<file_sep><!DOCTYPE HTML>
<link rel="stylesheet" href="main.css">
<body>
<div class="list">
<h1 class="header">Optimized To-do List</h1>
<?php if(!empty($items)): ?>
<ul class="items">
<?php foreach($items as $item): ?>
<li>
<span class="item<?php echo $item['isComplete'] ? ' done' : '' ?>"><?php echo $item['message']; ?></span>
<?php if(!$item['isComplete']): ?>
<a href="#" class="done-button">Mark as done</a>
<?php endif; ?>
</li>
<?php endforeach; ?>
</ul>
<?php else: ?>
<p> You haven't added any items yet! </p>
<?php endif; ?>
<form class="item-add" action="view/toDoAdd.php" method="post">
<input type="text" name="message" placeholder="Type a new item here." class="input" autocomplete="off" required>
<input type="submit" value ="Add" class="submit">
</form>
</body>
</html>
| 9986066b3dff00631e7b9de754a3dba87264ba83 | [
"PHP"
] | 3 | PHP | domingle/toDoListApp | 8b4919f74d4f904620f992bcb58dde856fe17c9c | fc8fc93a7da663ff2cd772780d81586a4394fb17 |
refs/heads/master | <repo_name>honeybadger26/katamino_solver<file_sep>/C/solver.c
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/time.h>
#include <unistd.h>
#include "block.h"
#include "puzzle.h"
/*
* stores the placement information for each block
*/
struct PlacementInfo {
int x;
int y;
int permutation;
};
/*
* prints the game board
*/
void print_board(int board[HEIGHT][WIDTH]) {
for (int i=0; i < HEIGHT; i++) {
for (int j=0; j < WIDTH; j++)
printf("%d ", board[i][j]);
printf("\n");
}
printf("\n");
}
/*
* finds if block can be placed at x, y position on board
* if block cannot be placed returns 0
*/
int place_block(int board[HEIGHT][WIDTH], int x, int y, struct Block block) {
int height = block.height;
int width = block.width;
// check if can place block
for (int i=0; i < height; i++) {
for (int j=0; j < width; j++) {
if (x+i >= HEIGHT || y+j >= WIDTH) return 0;
if (board[x+i][y+j] != 0 && block.array[i*width + j] != 0) return 0;
}
}
// place block
for (int i=0; i < height; i++) {
for (int j=0; j < width; j++) {
if (board[x+i][y+j] == 0)
board[x+i][y+j] = block.array[i*width + j];
}
}
return 1;
}
/*
* block = uninitialised block reference
* block_num = an index of a block from BLOCKS that will be used
* to base this newly creted block off of
* permutation_num = the requested permutation. possible values:
* 0-3 = 0, 90, 180, 270 degree rotations
* 4-7 = same rotations as 0-3, but reflected horizontally
*/
void set_permutation(struct Block* block, int block_num, int permutation_num) {
int height;
int width;
// change height and width if rotating 90 or 270 degrees
if (permutation_num % 2 == 0) {
height = BLOCKS[block_num].height;
width = BLOCKS[block_num].width;
} else {
height = BLOCKS[block_num].width;
width = BLOCKS[block_num].height;
}
block->height = height;
block->width = width;
int block_array[height][width];
// rotate block
for (int i=0; i < height; i++) {
for (int j=0; j < width; j++) {
int index;
switch (permutation_num % 4) {
case 0:
index = i*width + j;
break;
case 1:
index = height*(width - j - 1) + i;
break;
case 2:
index = width*(height - i) - j - 1;
break;
case 3:
index = height*(j + 1) - i - 1;
break;
default:
break;
}
block_array[i][j] = BLOCKS[block_num].array[index];
}
}
// reflect if necessary
if (permutation_num >= 4) {
int reflected_block[height][width];
for (int i=0; i < height; i++) {
for (int j=0; j < width; j++)
reflected_block[i][j] = block_array[i][width-j-1];
}
block->array = *reflected_block;
return;
}
block->array = *block_array;
return;
}
int solve() {
// 0 = running, 1 = success, -1 = failed
int status = 0;
// initialise boards
int boards[NUM_BLOCKS][HEIGHT][WIDTH];
memset(boards, 0, sizeof(int) * NUM_BLOCKS * HEIGHT * WIDTH);
// create array of placement info
struct PlacementInfo bl_info[NUM_BLOCKS];
for (int i=0; i < NUM_BLOCKS; i++) {
bl_info[i].x = 0;
bl_info[i].y = 0;
bl_info[i].permutation = -1;
}
int block_num = 0;
while (status == 0) {
// copy previous board
for (int i=0; i < HEIGHT; i++) {
for (int j=0; j < WIDTH; j++) {
if (block_num == 0)
boards[block_num][i][j] = 0;
else
boards[block_num][i][j] = boards[block_num-1][i][j];
}
}
int x = bl_info[block_num].x,
y = bl_info[block_num].y,
permutation = bl_info[block_num].permutation;
// check whether we need to step back to previous block
int go_back = 0;
// go to next permutation
if (++permutation >= 8) {
permutation = 0;
// go to next y value
if (++y >= WIDTH) {
y = 0;
// go to next x value
if (++x >= HEIGHT) {
// cannot place block so step back
bl_info[block_num].x = 0;
bl_info[block_num].y = 0;
bl_info[block_num].permutation = -1;
go_back = 1;
// solution not found
if (--block_num < 0)
status = -1;
}
}
}
if (go_back == 1)
continue;
// save block placement
bl_info[block_num].x = x;
bl_info[block_num].y = y;
bl_info[block_num].permutation = permutation;
struct Block block;
set_permutation(&block, block_num, permutation);
// try to place block
if (place_block(boards[block_num], x, y, block) == 1) {
print_board(boards[block_num]);
// solution found
if (++block_num >= NUM_BLOCKS)
status = 1;
}
}
// solution not found
if (status == -1) printf("no solution found");
return 0;
}
int main() {
struct timeval start, end;
gettimeofday(&start, NULL);
solve();
gettimeofday(&end, NULL);
double time_taken = end.tv_sec + end.tv_usec / 1e6 -
start.tv_sec - start.tv_usec / 1e6;
printf("execution time: %f seconds\n", time_taken);
return 0;
}
<file_sep>/C/block.h
#ifndef BLOCK_H
#define BLOCK_H
// stores info for particular block
struct Block {
int height;
int width;
int *array;
};
#endif
<file_sep>/Python/solver.py
import time
import copy, puzzle
from puzzle import blocks as BLOCKS
from puzzle import HEIGHT
from puzzle import WIDTH
# prints the board
def print_board(board):
for i in range(HEIGHT):
for j in range(WIDTH):
print("%d " % board[i][j], end="")
print("")
print("")
# place the block at the given location
def place_block(board, x, y, block):
# checks whether block can be placed
for i in range(len(block)):
for j in range(len(block[i])):
if x + i >= HEIGHT or y + j >= WIDTH:
return False
if board[x+i][y+j] != 0 and block[i][j] != 0:
return False
# place block
for i in range(len(block)):
for j in range(len(block[i])):
if board[x+i][y+j] == 0:
board[x+i][y+j] = block[i][j]
return True
def set_permutation(block_num, permutation_num):
# returns the different rotations (0, 90, 180, 270) of a given block
new_block = []
# 90 and 270 degrees require change of width and height
if permutation_num % 2 == 0:
height = len(BLOCKS[block_num])
width = len(BLOCKS[block_num][0])
else:
height = len(BLOCKS[block_num][0])
width = len(BLOCKS[block_num])
rotation = permutation_num % 4
# rotate block
for i in range(height):
new_block.append([])
for j in range(width):
if rotation == 0:
new_block[i].append(BLOCKS[block_num][i][j])
elif rotation == 1:
new_block[i].append(BLOCKS[block_num][width-j-1][i])
elif rotation == 2:
new_block[i].append(BLOCKS[block_num][height-i-1][height-j-1])
else:
new_block[i].append(BLOCKS[block_num][j][height-i-1])
# reflect block
if permutation_num >= 4:
reflected_block = []
for i in range(height):
reflected_block.append([])
for j in range(width):
reflected_block[i].append(new_block[i][-j-1])
return reflected_block
return new_block
def solve():
# holds whether running, failed or solved
status = 0
boards = [[[ 0 for _ in range(WIDTH) ]
for __ in range(HEIGHT) ]
for ___ in range(len(BLOCKS)) ]
bl_info = [ dict(x=0, y=0, permutation=0) for _ in range(len(BLOCKS)) ]
block_num = 0
while status == 0:
for i in range(HEIGHT):
for j in range(WIDTH):
if block_num == 0:
boards[block_num][i][j] = 0
else:
boards[block_num][i][j] = boards[block_num-1][i][j]
x = bl_info[block_num]['x']
y = bl_info[block_num]['y']
permutation = bl_info[block_num]['permutation']
go_back = False
permutation += 1
if permutation >= 8:
permutation = 0
y += 1
if y > WIDTH:
y = 0
x += 1
if x > HEIGHT:
bl_info[block_num]['x'] = 0
bl_info[block_num]['y'] = 0
bl_info[block_num]['permutation'] = 0
go_back = True
block_num -= 1
if block_num < 0:
status = -1
if go_back:
continue
bl_info[block_num]['x'] = x
bl_info[block_num]['y'] = y
bl_info[block_num]['permutation'] = permutation
block = set_permutation(block_num, permutation)
if place_block(boards[block_num], x, y, block):
print_board(boards[block_num])
block_num += 1
if block_num >= len(BLOCKS):
status = 1
if status == -1:
print("no solution found")
def main():
start = time.time()
solve()
end = time.time()
print("exection time: %s seconds\n" % (end-start))
if __name__ == "__main__":
# execute only if run as a script
main()
<file_sep>/README.md
# Katamino Solver
Solver scripts for the board game Katamino
## C
```
cd C
gcc -o solver solver.c
./solver
```
## Python
```
cd Python
python solver.py
```
| 4c6c1d2b337160d3ce301c979fa592c8a4a59032 | [
"Markdown",
"C",
"Python"
] | 4 | C | honeybadger26/katamino_solver | 261ea8642be10555faaaffe0ba1f53b33830d302 | 76c3ca03b03d204acacb67a85cc96d6baf5604c8 |
refs/heads/main | <repo_name>yuukwada/kadai_daily_report_system<file_sep>/src/controllers/reports/ReportsFavoriteDestroy.java
package controllers.reports;
import java.io.IOException;
import javax.persistence.EntityManager;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import models.Employee;
import models.Favorite;
import models.Report;
import utils.DBUtil;
/**
* Servlet implementation class ReportsFavoriteDestroy
*/
@WebServlet("/reports/favorite_destroy")
public class ReportsFavoriteDestroy extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public ReportsFavoriteDestroy() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
EntityManager em=DBUtil.createEntityManager();
Employee login_employee = (Employee)request.getSession().getAttribute("login_employee");
Report report=em.find(Report.class,Integer.parseInt(request.getParameter("report_id")));
int favorited_count=(Integer.parseInt(request.getParameter("favorited_count")));
report.setFavorited_count(favorited_count -1);
Integer favorite_id=em.createNamedQuery("getFavoriteId",Integer.class)
.setParameter("report",report)
.setParameter("employee",login_employee)
.getSingleResult();
Favorite f =em.find(Favorite.class,favorite_id);
em.getTransaction().begin();
em.remove(f);
em.getTransaction().commit();
em.close();
response.sendRedirect(request.getContextPath()+"/reports/index");
}
}
<file_sep>/src/models/Favorite.java
package models;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
@Table(name="favorite")
@NamedQueries({
@NamedQuery(
name = "getFavoriteCounts",
query = "SELECT COUNT(f) FROM Favorite AS f WHERE f.employee = :employee"),
@NamedQuery(
name = "getFavoritedReports",
query = "SELECT f.report FROM Favorite AS f WHERE f.employee = :employee"),
@NamedQuery(
name = "getFavoriteEmployees",
query = "SELECT f.employee FROM Favorite AS f WHERE f.report = :report"),
@NamedQuery(
name="getFavoriteId",
query="SELECT f.id FROM Favorite AS f WHERE f.report=:report AND f.employee=:employee"),
@NamedQuery(
name="getFavoriteReportCount",
query="SELECT COUNT(f) FROM Favorite AS f WHERE f.report=:report")
})
@Entity
public class Favorite {
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@ManyToOne
@JoinColumn(name="favorite_Employee")
private Employee employee;
@ManyToOne
@JoinColumn(name="favorite_Report")
private Report report;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Employee getEmployee() {
return employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
public Report getReport() {
return report;
}
public void setReport(Report report) {
this.report = report;
}
}
| 4b64eacf1c6eaa8aa2c65e5ebca3a55fd5f8e798 | [
"Java"
] | 2 | Java | yuukwada/kadai_daily_report_system | 82ea34620c00a19f67d768c8d6a24a03918d064e | e261d7a6c80a369988cca04749685e0c0a531961 |
refs/heads/master | <repo_name>benvolia/unicef-innovation-settlement-monitoring<file_sep>/data/DATASETS.md
# Datasets
- `IOM DTM Mosul Crisis Dataset.xlsx`: *Provides a list of settlements in Iraq. Downloaded in January 2018 from http://iraqdtm.iom.int/. For now, we are only interested in locationType = Formal Camp*
- - `IOM DTM Mosul Crisis Dataset - formal camps with general infrastructure link.xlsx`: *Provides a list of settlements in Iraq filtered to Formal Camps only. Downloaded in January 2018 from http://iraqdtm.iom.int/. We also added links to PDFs of General Infrastructure when available. These PDFs are helpful to match images and camps and understand their structure.*
## Note
When adding a dataset to the repository, please add it in the data folder. In addition, add a bullet in this document, specifying the source and date of download.<file_sep>/data/GoogleSatelliteImageDownloader.py
#!/usr/bin/python
# GoogleSatelliteImageDownloader.py
#
# A script which when given a longitude, latitude and zoom level downloads a
# high resolution google satellite image
import io
import sys, os
from urllib2 import Request, urlopen, URLError
import PIL
from PIL import Image
class GoogleSatelliteImageDownloader:
"""
A class which generates high resolution google maps images given
a longitude, latitude and zoom level.
"""
def __init__(self, lat, lng, zoom=12):
"""
GoogleMapDownloader Constructor
Args:
lat: The latitude of the location required
lng: The longitude of the location required
zoom: The zoom level of the location required, ranges from 0 - 23
defaults to 12
"""
self._lat = lat
self._lng = lng
self._zoom = zoom
def get_image(self):
"""
Calls google static maps api to download satellite imagery at specified lat, long,
zoom, scale, height & width. Please use your own google maps apikey.
"""
global apikey
apikey = ""
width = 640
height = 400
image = Image.new('RGB', (width,height))
url = "https://maps.googleapis.com/maps/api/staticmap?maptype=satellite¢er=%s,%s&zoom=%s&size=%sx%s&scale=2&key=%s" \
% (self._lat, self._lng, self._zoom,width,height,apikey)
print("url: "+url)
request = Request(url)
try:
response = urlopen(request).read()
print("Received response.")
image = Image.open(io.BytesIO(response))
except URLError, e:
print 'No images. Got an error code:', str(e) +"."
return image
def main():
# Create a new instance of GoogleMap Downloader
latitude = 35.7976
longitude = 43.2932
gsid = GoogleSatelliteImageDownloader(latitude,longitude, 13)
try:
# Get the high resolution image
img = gsid.get_image()
except IOError:
print("Could not generate the image - try adjusting the zoom level and checking your coordinates.")
else:
#Save the image to disk
current_path = os.path.dirname(sys.argv[0])
img.save(current_path+"/images/satellite_image_"+str(latitude)+"_"+str(longitude)+".png")
print("The map has successfully been created.")
if __name__ == '__main__': main()
<file_sep>/exploration/Stanford CS 230 - 2018/README.md
# Stanford CS230 2018
In Spring 2018, we invited groups of Stanford students to explore this problematic using machine-learning approaches. Their work, exploration and code have been extremely useful in refining the problematic and understanding the challenges.
#### Team 1 - Building Detection CrowdAI & Application to Rohingya Camps
<NAME>, <NAME>, <NAME>
https://github.com/NichelleBot/CS230-Final-Project
#### Team 2 - Building Detection BuildNet
<NAME>, <NAME>, <NAME>
https://github.com/mananrai/BuildingNet
#### Team 3 - Road Detection
<NAME>, <NAME>, <NAME>
<file_sep>/exploration/README.md
# Exploration
The settlement monitoring is a long term initiative. We aim to explore different approaches and stay open to new opportunities, on the algorithm and data side.
In this folder, we will incoporate interesting work in the field as well as feature work from students and volunteers, who help create the building blocks making settlment monitoring a reality.
| 3cd5d5641dec038bbfb5ece40393a50fd49e471a | [
"Markdown",
"Python"
] | 4 | Markdown | benvolia/unicef-innovation-settlement-monitoring | 438559b028db7d2aec841dc9270f5b0bc7a67d4d | 663fa274977e1b7f5b24a9445261c21d6e7c1674 |
refs/heads/master | <file_sep>using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Ports;
using System.Text;
using System.Threading;
namespace DataSetCollector
{
class vector3d
{
public vector3d() { x = 0; y = 0; z = 0; }
public double x, y, z;
};
class NeuroLink
{
/*public static double hyperTanGrad(double x)
{
return 1 - x * x;
}*/
public static double SigmoidGrad(double x)
{
return ((1 - x) * x);
}
public static double Sigmoid(double x)
{
return 1 / (1 + Math.Exp(-x));
}
private class Neuron
{
public Neuron(int prk)
{
kf = new double[prk];
dkf = new double[prk];
}
//коэфециенты входящих синапсисов
public double[] kf, dkf;
public double output, delta, bias, dbias = 0;
public void update(Neuron[] neus)
{
output = bias;
for (int i = 0; i < neus.Length; i++) output += neus[i].output * kf[i];
output = Sigmoid(output);
}
public void findDelta(int pos, Neuron[] neus)
{
double sum = 0;
for (int i = 0; i < neus.Length; i++) sum += neus[i].kf[pos] * neus[i].delta;
delta = sum * SigmoidGrad(output);
}
public void findDelta(double cor)
{
delta = (cor - output) * SigmoidGrad(output);
}
public void correctWeights(Neuron[] neus)
{
for (int i = 0; i < kf.Length; i++)
{
double gradient = neus[i].output * delta;
double dw = E * gradient + A * dkf[i];
dkf[i] = dw;
kf[i] += dw;
}
{
double gradient = delta;
double dw = E * gradient + A * dbias;
dbias = dw;
bias += dw;
}
}
}
const int INP = 48, H1 = 65, H2 = 30, O = 10;
//E - обучаемость, A - инертность
const double E = 0.000005, A = 0.05;
//массив массивов нейронов. Нейроны распределны по массивам в соответсвии со слоем
Neuron[][] layouts = new Neuron[4][];
public NeuroLink()
{
layouts[0] = new Neuron[INP];
layouts[1] = new Neuron[H1];
layouts[2] = new Neuron[H2];
layouts[3] = new Neuron[O];
if (File.Exists("neurolink.txt"))
{
StreamReader sr = new StreamReader("neurolink.txt");
string[] kf = sr.ReadToEnd().Split(' ');
sr.Close();
int kk = 0;
for (int i = 0; i < layouts[0].Length; i++)
{
layouts[0][i] = new Neuron(0);
}
for (int i = 0; i < layouts[1].Length; i++)
{
layouts[1][i] = new Neuron(INP);
for (int j = 0; j < layouts[1][i].kf.Length; j++)
{
layouts[1][i].kf[j] = double.Parse(kf[kk]);
kk++;
}
layouts[1][i].bias = double.Parse(kf[kk]);
kk++;
}
for (int i = 0; i < layouts[2].Length; i++)
{
layouts[2][i] = new Neuron(H1);
for (int j = 0; j < layouts[2][i].kf.Length; j++)
{
layouts[2][i].kf[j] = double.Parse(kf[kk]);
kk++;
}
layouts[2][i].bias = double.Parse(kf[kk]);
kk++;
}
for (int i = 0; i < layouts[3].Length; i++)
{
layouts[3][i] = new Neuron(H2);
for (int j = 0; j < layouts[3][i].kf.Length; j++)
{
layouts[3][i].kf[j] = double.Parse(kf[kk]);
kk++;
}
layouts[3][i].bias = double.Parse(kf[kk]);
kk++;
}
}
else
{
Random r = new Random();
StreamWriter sw = new StreamWriter("neurolink.txt", false, System.Text.Encoding.Default);
for (int i = 0; i < layouts[0].Length; i++)
{
layouts[0][i] = new Neuron(0);
}
for (int i = 0; i < layouts[1].Length; i++)
{
layouts[1][i] = new Neuron(INP);
for (int j = 0; j < layouts[1][i].kf.Length; j++)
{
double ko = (r.NextDouble() * 5) - 2.5;
layouts[1][i].kf[j] = ko;
sw.Write("{0} ", ko);
}
layouts[1][i].bias = (r.NextDouble() * 5) - 2.5;
sw.Write("{0} ", layouts[1][i].bias);
}
for (int i = 0; i < layouts[2].Length; i++)
{
layouts[2][i] = new Neuron(H1);
for (int j = 0; j < layouts[2][i].kf.Length; j++)
{
double ko = (r.NextDouble() * 5) - 2.5;
layouts[2][i].kf[j] = ko;
sw.Write("{0} ", ko);
}
layouts[2][i].bias = (r.NextDouble() * 10) - 5;
sw.Write("{0} ", layouts[2][i].bias);
}
for (int i = 0; i < layouts[3].Length; i++)
{
layouts[3][i] = new Neuron(H2);
for (int j = 0; j < layouts[3][i].kf.Length; j++)
{
double ko = (r.NextDouble() * 5) - 2.5;
layouts[3][i].kf[j] = ko;
sw.Write("{0} ", ko);
}
layouts[3][i].bias = (r.NextDouble() * 5) - 2.5;
sw.Write("{0} ", layouts[3][i].bias);
}
sw.Close();
}
}
public void think(double[] data)
{
for (int i = 0; i < layouts[0].Length; i++)
layouts[0][i].output = Sigmoid(data[i]);
for (int j = 1; j < layouts.Length; j++)
for (int i = 0; i < layouts[j].Length; i++)
layouts[j][i].update(layouts[j - 1]);
}
public double[] result()
{
double[] uns = new double[O];
for (int i = 0; i < O; i++) uns[i] = layouts[layouts.Length - 1][i].output;
return uns;
}
public void learn(double[] correct)
{
for (int i = 0; i < O; i++)
layouts[layouts.Length - 1][i].findDelta(correct[i]);
for (int i = layouts.Length - 2; i > 0; i--)
{
for (int j = 0; j < layouts[i].Length; j++)
{
layouts[i][j].findDelta(j, layouts[i + 1]);
}
}
for (int i = layouts.Length - 1; i > 0; i--)
{
for (int j = 0; j < layouts[i].Length; j++)
{
layouts[i][j].correctWeights(layouts[i - 1]);
}
}
}
public double curError(double[] correct)
{
double un = 0;
for (int i = 0; i < layouts[layouts.Length - 1].Length; i++)
un += (correct[i] - layouts[layouts.Length - 1][i].output) * (correct[i] - layouts[layouts.Length - 1][i].output);
return un / layouts.Length;
}
public void saveToFile()
{
StreamWriter sw = new StreamWriter("neurolink.txt", false, System.Text.Encoding.Default);
for (int i = 0; i < layouts[1].Length; i++)
{
for (int j = 0; j < layouts[1][i].kf.Length; j++)
{
sw.Write("{0} ", layouts[1][i].kf[j]);
}
sw.Write("{0} ", layouts[1][i].bias);
}
for (int i = 0; i < layouts[2].Length; i++)
{
for (int j = 0; j < layouts[2][i].kf.Length; j++)
{
sw.Write("{0} ", layouts[2][i].kf[j]);
}
sw.Write("{0} ", layouts[2][i].bias);
}
for (int i = 0; i < layouts[3].Length; i++)
{
for (int j = 0; j < layouts[3][i].kf.Length; j++)
{
sw.Write("{0} ", layouts[3][i].kf[j]);
}
sw.Write("{0} ", layouts[3][i].bias);
}
sw.Close();
}
}
class ringBuffer
{
private vector3d[] data;
const int SIZE = 80;
private int head = 0;
public ringBuffer()
{
data = new vector3d[SIZE];
for (int i = 0; i < SIZE; i++) data[i] = new vector3d();
}
public void add(vector3d vec)
{
data[head++] = vec;
head %= SIZE;
}
public vector3d peek()
{
return (head > 0) ? data[head - 1] : data[SIZE - 1];
}
public vector3d[] getCopy()
{
vector3d[] copy = new vector3d[SIZE];
int h = head;
for (int i = 0; i < SIZE; i++)
{
copy[i] = data[h++];
h %= SIZE;
}
return copy;
}
}
class dataset
{
public double[] data = new double[48], result = new double[10];
public dataset(string path)
{
StreamReader sr = new StreamReader(path, Encoding.Default);
for (int i = 0; i < data.Length; i++)
{
data[i] = double.Parse(sr.ReadLine()) / 3;
}
for (int i = 0; i < result.Length; i++)
{
result[i] = double.Parse(sr.ReadLine());
}
sr.Close();
}
}
class Program
{
static double abs(double x) { return x >= 0 ? x : -x; }
static double hypot(vector3d V) { return Math.Sqrt(V.x * V.x + V.y * V.y + V.z * V.z); }
static double median(double a, double b, double c)
{
return Math.Max(Math.Min(a, b), Math.Min(Math.Max(a, b), c));
}
static void medianFilter3x(vector3d[] vec)
{
for (int i = 1; i < vec.Length - 1; i++)
{
vec[i].x = median(vec[i - 1].x, vec[i].x, vec[i + 1].x);
vec[i].y = median(vec[i - 1].y, vec[i].y, vec[i + 1].y);
vec[i].z = median(vec[i - 1].z, vec[i].z, vec[i + 1].z);
}
}
static SerialPort srp;
static ringBuffer stk = new ringBuffer();
static int Co = 0;
static System.Diagnostics.Stopwatch sw = new Stopwatch();
static bool SIGNAL = false, READY_READ = false, SO_POWERFUL = false;
static void dataRecived(object sender, SerialDataReceivedEventArgs e)
{
lock (srp)
{
while (srp.ReadByte() != 0xff) ;
while (srp.BytesToRead < 12) ;
// while (srp.BytesToRead > 11)
lock (stk)
{
vector3d V = new vector3d();
byte[] data = new byte[12];
srp.Read(data, 0, 12);
V.x = BitConverter.ToSingle(data, 0);
V.y = BitConverter.ToSingle(data, 4);
V.z = BitConverter.ToSingle(data, 8);
V.x /= 400;
V.y /= 400;
V.z /= 400;
stk.add(V);
if (!SIGNAL && !READY_READ && (abs(V.x) > 10.0 || abs(V.y) > 10.0 || abs(V.z) > 10.0))
{
SO_POWERFUL = false;
SIGNAL = true;
Co = 0;
sw.Restart();
// sw.Restart();
}
if (SIGNAL)
{
if (abs(V.x) > 60.0 || abs(V.y) > 60.0 || abs(V.z) > 60.0) SO_POWERFUL = true;
Co += 1;
if (Co >= 60)
{
READY_READ = true && !SO_POWERFUL;
SIGNAL = false;
// sw.Stop();
}
}
}
}
}
// static dataset[] DS1, DS2, DS3, DS4, DS5, DS6, DS7, DS8, DS9, DS0, TS1, TS2, TS3, TS4, TS5, TS6, TS7, TS8, TS9, TS0, DS_;
static void Main(string[] args)
{
/// Random rand = new Random();
NeuroLink link = new NeuroLink();
/*
StreamWriter logger = new StreamWriter("log.txt", true, Encoding.Default);
Console.WriteLine("loading datasets and testing samples");
logger.WriteLine("loading datasets and testing samples");
{
string[] files = Directory.GetFiles(@"l1\");
DS1 = new dataset[files.Length];
for (int i = 0; i < files.Length; i++)
DS1[i] = new dataset(files[i]);
}
{
string[] files = Directory.GetFiles(@"l2\");
DS2 = new dataset[files.Length];
for (int i = 0; i < files.Length; i++)
DS2[i] = new dataset(files[i]);
}
{
string[] files = Directory.GetFiles(@"l3\");
DS3 = new dataset[files.Length];
for (int i = 0; i < files.Length; i++)
DS3[i] = new dataset(files[i]);
}
{
string[] files = Directory.GetFiles(@"l4\");
DS4 = new dataset[files.Length];
for (int i = 0; i < files.Length; i++)
DS4[i] = new dataset(files[i]);
}
{
string[] files = Directory.GetFiles(@"l5\");
DS5 = new dataset[files.Length];
for (int i = 0; i < files.Length; i++)
DS5[i] = new dataset(files[i]);
}
{
string[] files = Directory.GetFiles(@"l6\");
DS6 = new dataset[files.Length];
for (int i = 0; i < files.Length; i++)
DS6[i] = new dataset(files[i]);
}
{
string[] files = Directory.GetFiles(@"l7\");
DS7 = new dataset[files.Length];
for (int i = 0; i < files.Length; i++)
DS7[i] = new dataset(files[i]);
}
{
string[] files = Directory.GetFiles(@"l8\");
DS8 = new dataset[files.Length];
for (int i = 0; i < files.Length; i++)
DS8[i] = new dataset(files[i]);
}
{
string[] files = Directory.GetFiles(@"l9\");
DS9 = new dataset[files.Length];
for (int i = 0; i < files.Length; i++)
DS9[i] = new dataset(files[i]);
}
{
string[] files = Directory.GetFiles(@"l0\");
DS0 = new dataset[files.Length];
for (int i = 0; i < files.Length; i++)
DS0[i] = new dataset(files[i]);
}
{
string[] files = Directory.GetFiles(@"_\");
DS_ = new dataset[files.Length];
for (int i = 0; i < files.Length; i++)
DS_[i] = new dataset(files[i]);
}
Console.WriteLine("Datasets Loaded");
logger.WriteLine("Datasets Loaded");
{
string[] files = Directory.GetFiles(@"t1\");
TS1 = new dataset[files.Length];
for (int i = 0; i < files.Length; i++)
TS1[i] = new dataset(files[i]);
}
{
string[] files = Directory.GetFiles(@"t2\");
TS2 = new dataset[files.Length];
for (int i = 0; i < files.Length; i++)
TS2[i] = new dataset(files[i]);
}
{
string[] files = Directory.GetFiles(@"t3\");
TS3 = new dataset[files.Length];
for (int i = 0; i < files.Length; i++)
TS3[i] = new dataset(files[i]);
}
{
string[] files = Directory.GetFiles(@"t4\");
TS4 = new dataset[files.Length];
for (int i = 0; i < files.Length; i++)
TS4[i] = new dataset(files[i]);
}
{
string[] files = Directory.GetFiles(@"t5\");
TS5 = new dataset[files.Length];
for (int i = 0; i < files.Length; i++)
TS5[i] = new dataset(files[i]);
}
{
string[] files = Directory.GetFiles(@"t6\");
TS6 = new dataset[files.Length];
for (int i = 0; i < files.Length; i++)
TS6[i] = new dataset(files[i]);
}
{
string[] files = Directory.GetFiles(@"t7\");
TS7 = new dataset[files.Length];
for (int i = 0; i < files.Length; i++)
TS7[i] = new dataset(files[i]);
}
{
string[] files = Directory.GetFiles(@"t8\");
TS8 = new dataset[files.Length];
for (int i = 0; i < files.Length; i++)
TS8[i] = new dataset(files[i]);
}
{
string[] files = Directory.GetFiles(@"t9\");
TS9 = new dataset[files.Length];
for (int i = 0; i < files.Length; i++)
TS9[i] = new dataset(files[i]);
}
{
string[] files = Directory.GetFiles(@"t0\");
TS0 = new dataset[files.Length];
for (int i = 0; i < files.Length; i++)
TS0[i] = new dataset(files[i]);
}
Console.WriteLine("Testing sets loaded");
Console.WriteLine("learning started");
logger.WriteLine("learning started");
Console.Beep();
for (int gen = 0; gen < 10000000; gen++)
{
if (Console.KeyAvailable && Console.ReadKey().Key == ConsoleKey.Escape) break;
for (int i = 0; i < 50; i++)
{
link.think(DS1[i].data);
link.learn(DS1[i].result);
link.think(DS2[i].data);
link.learn(DS2[i].result);
link.think(DS3[i].data);
link.learn(DS3[i].result);
link.think(DS4[i].data);
link.learn(DS4[i].result);
link.think(DS5[i].data);
link.learn(DS5[i].result);
link.think(DS6[i].data);
link.learn(DS6[i].result);
link.think(DS7[i].data);
link.learn(DS7[i].result);
link.think(DS8[i].data);
link.learn(DS8[i].result);
link.think(DS9[i].data);
link.learn(DS9[i].result);
link.think(DS0[i].data);
link.learn(DS0[i].result);
if (i % 5 == 1)
{
link.think(DS_[i / 5].data);
link.learn(DS_[i / 5].result);
}
}
if (gen % 1000 == 0)
{
double error = 0;
for (int i = 0; i < 10; i++)
{
link.think(TS1[i].data);
error += link.curError(TS1[i].result);
link.think(TS2[i].data);
error += link.curError(TS2[i].result);
link.think(TS3[i].data);
error += link.curError(TS3[i].result);
link.think(TS4[i].data);
error += link.curError(TS4[i].result);
link.think(TS5[i].data);
error += link.curError(TS5[i].result);
link.think(TS6[i].data);
error += link.curError(TS6[i].result);
link.think(TS7[i].data);
error += link.curError(TS7[i].result);
link.think(TS8[i].data);
error += link.curError(TS8[i].result);
link.think(TS9[i].data);
error += link.curError(TS9[i].result);
link.think(TS0[i].data);
error += link.curError(TS0[i].result);
}
error /= 100;
Console.WriteLine("Gen#{0}. Error: {1:f7}", gen, error);
logger.WriteLine("Gen#{0}. Error: {1:f7}", gen, error);
}
if (gen % 25000 == 0)
{
Console.WriteLine("Gen#{0}. Testing: ", gen);
logger.WriteLine("Gen#{0}. Testing: ", gen);
int a = rand.Next(0, 10);
link.think(TS1[a].data);
Console.WriteLine("tst '1'. Neu: '1':{0:f3};'2':{1:f3};'3':{2:f3};'4':{3:f3};'5':{4:f3};'6':{5:f3};'7':{6:f3};'8':{7:f3};'9':{8:f3};'0':{9:f3}", link.result()[0], link.result()[1], link.result()[2], link.result()[3], link.result()[4], link.result()[5], link.result()[6], link.result()[7], link.result()[8], link.result()[9]);
logger.WriteLine("tst '1'. Neu: '1':{0:f3};'2':{1:f3};'3':{2:f3};'4':{3:f3};'5':{4:f3};'6':{5:f3};'7':{6:f3};'8':{7:f3};'9':{8:f3};'0':{9:f3}", link.result()[0], link.result()[1], link.result()[2], link.result()[3], link.result()[4], link.result()[5], link.result()[6], link.result()[7], link.result()[8], link.result()[9]);
a = rand.Next(0, 10);
link.think(TS2[a].data);
Console.WriteLine("tst '2'. Neu: '1':{0:f3};'2':{1:f3};'3':{2:f3};'4':{3:f3};'5':{4:f3};'6':{5:f3};'7':{6:f3};'8':{7:f3};'9':{8:f3};'0':{9:f3}", link.result()[0], link.result()[1], link.result()[2], link.result()[3], link.result()[4], link.result()[5], link.result()[6], link.result()[7], link.result()[8], link.result()[9]);
logger.WriteLine("tst '2'. Neu: '1':{0:f3};'2':{1:f3};'3':{2:f3};'4':{3:f3};'5':{4:f3};'6':{5:f3};'7':{6:f3};'8':{7:f3};'9':{8:f3};'0':{9:f3}", link.result()[0], link.result()[1], link.result()[2], link.result()[3], link.result()[4], link.result()[5], link.result()[6], link.result()[7], link.result()[8], link.result()[9]);
a = rand.Next(0, 10);
link.think(TS3[a].data);
Console.WriteLine("tst '3'. Neu: '1':{0:f3};'2':{1:f3};'3':{2:f3};'4':{3:f3};'5':{4:f3};'6':{5:f3};'7':{6:f3};'8':{7:f3};'9':{8:f3};'0':{9:f3}", link.result()[0], link.result()[1], link.result()[2], link.result()[3], link.result()[4], link.result()[5], link.result()[6], link.result()[7], link.result()[8], link.result()[9]);
logger.WriteLine("tst '3'. Neu: '1':{0:f3};'2':{1:f3};'3':{2:f3};'4':{3:f3};'5':{4:f3};'6':{5:f3};'7':{6:f3};'8':{7:f3};'9':{8:f3};'0':{9:f3}", link.result()[0], link.result()[1], link.result()[2], link.result()[3], link.result()[4], link.result()[5], link.result()[6], link.result()[7], link.result()[8], link.result()[9]);
a = rand.Next(0, 10);
link.think(TS4[a].data);
Console.WriteLine("tst '4'. Neu: '1':{0:f3};'2':{1:f3};'3':{2:f3};'4':{3:f3};'5':{4:f3};'6':{5:f3};'7':{6:f3};'8':{7:f3};'9':{8:f3};'0':{9:f3}", link.result()[0], link.result()[1], link.result()[2], link.result()[3], link.result()[4], link.result()[5], link.result()[6], link.result()[7], link.result()[8], link.result()[9]);
logger.WriteLine("tst '4'. Neu: '1':{0:f3};'2':{1:f3};'3':{2:f3};'4':{3:f3};'5':{4:f3};'6':{5:f3};'7':{6:f3};'8':{7:f3};'9':{8:f3};'0':{9:f3}", link.result()[0], link.result()[1], link.result()[2], link.result()[3], link.result()[4], link.result()[5], link.result()[6], link.result()[7], link.result()[8], link.result()[9]);
a = rand.Next(0, 10);
link.think(TS5[a].data);
Console.WriteLine("tst '5'. Neu: '1':{0:f3};'2':{1:f3};'3':{2:f3};'4':{3:f3};'5':{4:f3};'6':{5:f3};'7':{6:f3};'8':{7:f3};'9':{8:f3};'0':{9:f3}", link.result()[0], link.result()[1], link.result()[2], link.result()[3], link.result()[4], link.result()[5], link.result()[6], link.result()[7], link.result()[8], link.result()[9]);
logger.WriteLine("tst '5'. Neu: '1':{0:f3};'2':{1:f3};'3':{2:f3};'4':{3:f3};'5':{4:f3};'6':{5:f3};'7':{6:f3};'8':{7:f3};'9':{8:f3};'0':{9:f3}", link.result()[0], link.result()[1], link.result()[2], link.result()[3], link.result()[4], link.result()[5], link.result()[6], link.result()[7], link.result()[8], link.result()[9]);
a = rand.Next(0, 10);
link.think(TS6[a].data);
Console.WriteLine("tst '6'. Neu: '1':{0:f3};'2':{1:f3};'3':{2:f3};'4':{3:f3};'5':{4:f3};'6':{5:f3};'7':{6:f3};'8':{7:f3};'9':{8:f3};'0':{9:f3}", link.result()[0], link.result()[1], link.result()[2], link.result()[3], link.result()[4], link.result()[5], link.result()[6], link.result()[7], link.result()[8], link.result()[9]);
logger.WriteLine("tst '6'. Neu: '1':{0:f3};'2':{1:f3};'3':{2:f3};'4':{3:f3};'5':{4:f3};'6':{5:f3};'7':{6:f3};'8':{7:f3};'9':{8:f3};'0':{9:f3}", link.result()[0], link.result()[1], link.result()[2], link.result()[3], link.result()[4], link.result()[5], link.result()[6], link.result()[7], link.result()[8], link.result()[9]);
a = rand.Next(0, 10);
link.think(TS7[a].data);
Console.WriteLine("tst '7'. Neu: '1':{0:f3};'2':{1:f3};'3':{2:f3};'4':{3:f3};'5':{4:f3};'6':{5:f3};'7':{6:f3};'8':{7:f3};'9':{8:f3};'0':{9:f3}", link.result()[0], link.result()[1], link.result()[2], link.result()[3], link.result()[4], link.result()[5], link.result()[6], link.result()[7], link.result()[8], link.result()[9]);
logger.WriteLine("tst '7'. Neu: '1':{0:f3};'2':{1:f3};'3':{2:f3};'4':{3:f3};'5':{4:f3};'6':{5:f3};'7':{6:f3};'8':{7:f3};'9':{8:f3};'0':{9:f3}", link.result()[0], link.result()[1], link.result()[2], link.result()[3], link.result()[4], link.result()[5], link.result()[6], link.result()[7], link.result()[8], link.result()[9]);
a = rand.Next(0, 10);
link.think(TS8[a].data);
Console.WriteLine("tst '8'. Neu: '1':{0:f3};'2':{1:f3};'3':{2:f3};'4':{3:f3};'5':{4:f3};'6':{5:f3};'7':{6:f3};'8':{7:f3};'9':{8:f3};'0':{9:f3}", link.result()[0], link.result()[1], link.result()[2], link.result()[3], link.result()[4], link.result()[5], link.result()[6], link.result()[7], link.result()[8], link.result()[9]);
logger.WriteLine("tst '8'. Neu: '1':{0:f3};'2':{1:f3};'3':{2:f3};'4':{3:f3};'5':{4:f3};'6':{5:f3};'7':{6:f3};'8':{7:f3};'9':{8:f3};'0':{9:f3}", link.result()[0], link.result()[1], link.result()[2], link.result()[3], link.result()[4], link.result()[5], link.result()[6], link.result()[7], link.result()[8], link.result()[9]);
a = rand.Next(0, 10);
link.think(TS9[a].data);
Console.WriteLine("tst '9'. Neu: '1':{0:f3};'2':{1:f3};'3':{2:f3};'4':{3:f3};'5':{4:f3};'6':{5:f3};'7':{6:f3};'8':{7:f3};'9':{8:f3};'0':{9:f3}", link.result()[0], link.result()[1], link.result()[2], link.result()[3], link.result()[4], link.result()[5], link.result()[6], link.result()[7], link.result()[8], link.result()[9]);
logger.WriteLine("tst '9'. Neu: '1':{0:f3};'2':{1:f3};'3':{2:f3};'4':{3:f3};'5':{4:f3};'6':{5:f3};'7':{6:f3};'8':{7:f3};'9':{8:f3};'0':{9:f3}", link.result()[0], link.result()[1], link.result()[2], link.result()[3], link.result()[4], link.result()[5], link.result()[6], link.result()[7], link.result()[8], link.result()[9]);
a = rand.Next(0, 10);
link.think(TS0[a].data);
Console.WriteLine("tst '0'. Neu: '1':{0:f3};'2':{1:f3};'3':{2:f3};'4':{3:f3};'5':{4:f3};'6':{5:f3};'7':{6:f3};'8':{7:f3};'9':{8:f3};'0':{9:f3}", link.result()[0], link.result()[1], link.result()[2], link.result()[3], link.result()[4], link.result()[5], link.result()[6], link.result()[7], link.result()[8], link.result()[9]);
logger.WriteLine("tst '0'. Neu: '1':{0:f3};'2':{1:f3};'3':{2:f3};'4':{3:f3};'5':{4:f3};'6':{5:f3};'7':{6:f3};'8':{7:f3};'9':{8:f3};'0':{9:f3}", link.result()[0], link.result()[1], link.result()[2], link.result()[3], link.result()[4], link.result()[5], link.result()[6], link.result()[7], link.result()[8], link.result()[9]);
}
if (gen % 5000 == 0) link.saveToFile();
}
link.saveToFile();
Console.WriteLine("Learning finished");
logger.WriteLine("Learning finished");
logger.Close();
Console.Beep();
Console.ReadKey();*/
////////////////////////////////////////////////////////////////////////////////////////
/*
string NUM = "_/";
Directory.CreateDirectory(NUM);
int cur = 0;
{
string[] fls = Directory.GetFiles(NUM);
foreach (string s in fls)
{
int tmp = int.Parse(s.Substring(2, s.Length - 6));
if (tmp+1 > cur) cur = tmp+1;
}
}
vector3d[] buff;
srp = new SerialPort("com8", 57600);
srp.DataReceived += dataRecived;
Console.WriteLine("3");
Thread.Sleep(500);
Console.WriteLine("2");
Thread.Sleep(500);
Console.WriteLine("1");
Thread.Sleep(300);
Console.WriteLine("Openning port");
try
{
srp.Open();
}
catch (Exception e) { Console.WriteLine(e.Message); Console.ReadKey(); return; }
Console.WriteLine("Port opened");
while (true)
{
if (READY_READ)
{
StreamWriter fw2 = new StreamWriter(NUM + cur + ".txt", false, Encoding.Default);
lock (stk)
buff = stk.getCopy();
medianFilter3x(buff);
READY_READ = false;
for (int i = 2; i < buff.Length; i += 5)
{
fw2.WriteLine((buff[i - 1].x + buff[i].x + buff[i + 1].x) / 3);
fw2.WriteLine((buff[i - 1].y + buff[i].y + buff[i + 1].y) / 3);
fw2.WriteLine((buff[i - 1].z + buff[i].z + buff[i + 1].z) / 3);
}
fw2.WriteLine("0\n0\n0\n0\n0\n0\n0\n0\n0\n0");
fw2.Close();
sw.Stop();
Console.WriteLine("#:{0}\tesc:{1}", cur, sw.ElapsedMilliseconds);
cur++;
System.GC.Collect();
}
Thread.Sleep(5);
if (Console.KeyAvailable && Console.ReadKey().Key == ConsoleKey.Escape) break;
}
lock (srp) srp.Close();*/
///////////////////////////////////////////////////////
Console.ForegroundColor = ConsoleColor.Green;
Console.SetBufferSize(170,40);
Console.SetWindowSize(170, 40);
Console.WriteLine("Welcome to proectnaya practika");
srp = new SerialPort("com8", 57600);
int C = 0;
srp.DataReceived += dataRecived;
try
{
srp.Open();
}
catch (Exception e) { Console.WriteLine(e.Message); Console.ReadKey(); return; }
Console.WriteLine("Connected");
vector3d[] buff;
double[] data = new double[48];
StringBuilder str = new StringBuilder();
int PP = 0;
while (true)
{
if (READY_READ)
{
lock (stk)
buff = stk.getCopy();
READY_READ = false;
medianFilter3x(buff);
for (int i = 2, j = 0; i < buff.Length; i += 5, j += 3)
{
data[j] = (buff[i - 1].x + buff[i].x + buff[i + 1].x) / 9;
data[j + 1] = (buff[i - 1].y + buff[i].y + buff[i + 1].y) / 9;
data[j + 2] = (buff[i - 1].z + buff[i].z + buff[i + 1].z) / 9;
}
link.think(data);
double[] res = link.result();
char ch = '_';
int mx = maxPos(res);
if (res[mx] >= 0.4)
switch (mx)
{
case 0:
ch = '1';
break;
case 1:
ch = '2';
break;
case 2:
ch = '3';
break;
case 3:
ch = '4';
break;
case 4:
ch = '5';
break;
case 5:
ch = '6';
break;
case 6:
ch = '7';
break;
case 7:
ch = '8';
break;
case 8:
ch = '9';
break;
case 9:
ch = '0';
break;
}
str.Append(ch);
Console.SetCursorPosition(0, 2);
Console.WriteLine(str);
Console.SetCursorPosition(0, 3+PP%20);
Console.WriteLine("#{10}:\t'1':{0:f3};\t'2':{1:f3};\t'3':{2:f3}\t'4':{3:f3}\t'5':{4:f3}\t'6':{5:f3}\t'7':{6:f3}\t'8':{7:f3}\t'9':{8:f3}\t'0':{9:f3}", res[0], res[1], res[2], res[3], res[4], res[5], res[6], res[7], res[8], res[9], PP);
PP++;
}
Thread.Sleep(20);
if (Console.KeyAvailable && Console.ReadKey().Key == ConsoleKey.Escape) break;
}
lock (srp)
srp.Close();
}
static int maxPos(double[] vect)
{
double max = 0; int pos = 0;
for (int i = 0; i < vect.Length; i++)
{
if (max < vect[i]) { max = vect[i]; pos = i; }
}
return pos;
}
}
}
<file_sep>using OpenTK;
using System;
using System.IO.Ports;
using OpenTK;
using OpenTK.Graphics;
using OpenTK.Graphics.OpenGL;
using OpenTK.Input;
using System.Drawing;
using System.Drawing.Imaging;
namespace openGL_Visualaser
{
class Program
{
static void data(object sender, SerialDataReceivedEventArgs e)
{
while (srp.ReadByte() != 0xFF) if (srp.BytesToRead <= 0) return;
while (srp.ReadByte() != 0x00) if (srp.BytesToRead <= 0) return;
string[] data = srp.ReadLine().Replace('.', ',').Split('\t');
alpha = float.Parse(data[0])/1000f;
beta = float.Parse(data[1])/1000f;
gamma = float.Parse(data[2])/1000f;
}
static float alpha, beta, gamma;
static SerialPort srp;
const float arm_len = 6f / 15f;
const float toDeg = 180f / (float)Math.PI;
[STAThread]
static void Main(string[] args)
{
while (true)
{
Console.WriteLine("Выберете порт из списка: ");
string[] ports = SerialPort.GetPortNames();
if (ports.Length == 1) try
{
srp = new SerialPort(ports[0], 57600);
srp.Open();
srp.DataReceived += data;
break;
}
catch (Exception e)
{
Console.WriteLine("Ошибка подключения: " + e.Message);
}
foreach (string s in ports) Console.WriteLine(s);
Console.WriteLine("Напишите refresh для обновления списка");
string port = Console.ReadLine();
if (port != "refresh")
{
try
{
srp = new SerialPort(port, 57600);
srp.Open();
srp.DataReceived += data;
break;
}
catch (Exception e)
{
Console.WriteLine("Ошибка подключения: " + e.Message);
}
}
Console.WriteLine();
}
Console.WriteLine("Успешно подключен");
const float PI_05 = (float)Math.PI / 2;
float t = 0;
Vector3 me = new Vector3(0, 5f, 0);
Vector3 up = Vector3.UnitY;
Vector3 at = new Vector3(0, 0, 10f);
const float dt = 1f / 60f;
int prevx = 200, prevy = 200;
Bitmap img = new Bitmap(400, 400);
for (int x = 0; x < 400; x++)
for (int y = 0; y < 400; y++)
img.SetPixel(x, y, Color.White);
using (var game = new GameWindow())
{
game.Load += (sender, e) =>
{
// setup settings, load textures, sounds
game.VSync = VSyncMode.On;
};
game.Resize += (sender, e) =>
{
GL.Viewport(0, 0, game.Width, game.Height);
};
game.RenderFrame += (sender, e) =>
{
Console.SetCursorPosition(0, 0);
//lock (key)
{
float gam = gamma - beta;
while (gam > Math.PI) gam -= (float)Math.PI * 2;
while (gam < -Math.PI) gam += (float)Math.PI * 2;
Console.WriteLine("{0:f4}\t{1:f4}\t{2:f4}\t{3:f2}", alpha * toDeg, beta * toDeg, gamma * toDeg, gam * toDeg);
// Console.WriteLine("{0:f3} \n{1:f3} ", ang1 * 180 / Math.PI, azim2 * 180 / Math.PI);
float l1 = arm_len * (float)Math.Tan(alpha);
float l2 = l1 - (float)Math.Sin(alpha);
int px = (int)(200 + l1 * 200 * Math.Cos(gam));
int pz = (int)(200 + l1 * 200 * Math.Sin(gam));
if (px > 398) px = 200;
else if (px < 1) px = 200;
if (pz > 398) pz = 200;
else if (pz < 1) pz = 200;
img.SetPixel(px, pz, Color.Black);
//Console.WriteLine("{0:f3}\t{1:f3}\t{2:f3} ", l1, l2, ay);
SetPerspectiveProjection(game.Width, game.Height, 70);
GL.ClearColor(0.3f, 0.3f, 0.3f, 1f);
GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);
/* me.X = 10 * (float)Math.Cos(t);
me.Z = 10 + 10 * (float)Math.Sin(t);*/
//t += 0.005f;
SetLookAtCamera(me, at, up);
GL.Begin(PrimitiveType.Quads);
GL.Color4(1f, 1f, 1f, 1f);
GL.Vertex3(-5f, 0f, 5f);
GL.Vertex3(5f, 0f, 5f);
GL.Vertex3(5f, 0f, 15f);
GL.Vertex3(-5f, 0f, 15f);
GL.End();
GL.Disable(EnableCap.Texture2D);
GL.LineWidth(5);
GL.Begin(PrimitiveType.Lines);
GL.Color3(0f, 1f, 0f);
GL.Vertex3(0, 0, 10f);
GL.Vertex3(0, arm_len * 2, 10f);
GL.Color3(1f, 0f, 0f);
GL.Vertex3(l1 * 2 * Math.Cos(gam), 0, 10f + l1 * 2 * Math.Sin(gam));
GL.Color3(0f, 0f, 1f);
GL.Vertex3(l2 * 2 * Math.Cos(gam), Math.Cos(alpha) * 2, 10f + l2 * 2 * Math.Sin(gam));
/*
GL.Color3(1f, 0f, 1f);
GL.Vertex3(l2 * 2, ay * 2, 5f);
GL.Vertex3(l2 * 2, ay * 2 + Math.Cos(ang1), 5f - Math.Sin(ang1));*/
GL.End();
prevx = px;
prevy = pz;
}
game.SwapBuffers();
};
// Run the game at 60 updates per second
Console.Clear();
game.Run(30.0);
}
img.Save(@"C:\Users\Спок\Desktop\pen\test.png");
}
private static void SetLookAtCamera(Vector3 position, Vector3 target, Vector3 up)
{
Matrix4 modelViewMatrix = Matrix4.LookAt(position, target, up);
GL.MatrixMode(MatrixMode.Modelview);
GL.LoadMatrix(ref modelViewMatrix);
}
static int LoadTexture(Bitmap bitmap)
{
int tex;
GL.Hint(HintTarget.PerspectiveCorrectionHint, HintMode.Nicest);
GL.GenTextures(1, out tex);
GL.BindTexture(TextureTarget.Texture2D, tex);
BitmapData data = bitmap.LockBits(new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height),
ImageLockMode.ReadOnly, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba, data.Width, data.Height, 0,
OpenTK.Graphics.OpenGL.PixelFormat.Bgra, PixelType.UnsignedByte, data.Scan0);
bitmap.UnlockBits(data);
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)TextureMinFilter.Linear);
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)TextureMagFilter.Linear);
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)TextureWrapMode.Repeat);
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)TextureWrapMode.Repeat);
return tex;
}
private static void SetPerspectiveProjection(int width, int height, float FOV)
{
Matrix4 projectionMatrix = Matrix4.CreatePerspectiveFieldOfView((float)Math.PI * (FOV / 180f), width / (float)height, 0.01f, 20f);
GL.MatrixMode(MatrixMode.Projection);
GL.LoadMatrix(ref projectionMatrix); // this replaces the old matrix, no need for GL.LoadIdentity()
GL.ShadeModel(ShadingModel.Smooth);
GL.Enable(EnableCap.DepthTest); // Разрешить тест глубины
GL.DepthFunc(DepthFunction.Lequal);
GL.Hint(HintTarget.PerspectiveCorrectionHint, HintMode.Nicest);
}
}
}
<file_sep>using System;
using System.Drawing;
using System.IO;
using System.IO.Ports;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace GUI_DataSetCollector
{
public partial class Form1 : Form
{
const int LERNINGS = 200, TESTINGS = 20;
static NeuroLink link = new NeuroLink();
static AppMode appMode = AppMode.COLLECTING;
static double abs(double x) { return x >= 0 ? x : -x; }
static double hypot(vector3d V) { return Math.Sqrt(V.x * V.x + V.y * V.y + V.z * V.z); }
static double median(double a, double b, double c)
{
return Math.Max(Math.Min(a, b), Math.Min(Math.Max(a, b), c));
}
static void medianFilter3x(vector3d[] vec)
{
for (int i = 1; i < vec.Length - 1; i++)
{
vec[i].x = median(vec[i - 1].x, vec[i].x, vec[i + 1].x);
vec[i].y = median(vec[i - 1].y, vec[i].y, vec[i + 1].y);
vec[i].z = median(vec[i - 1].z, vec[i].z, vec[i + 1].z);
}
}
static SerialPort srp;
static ringBuffer stk = new ringBuffer();
static int Co = 0;
static bool SIGNAL = false, READY_READ = false, SO_POWERFUL = false, IGNORE = false;
static bool isRuning = true, isLearning = false;
static vector3d[] toDraw;
static vector4d prevError = new vector4d(), curError = new vector4d();
static Panel panell;
static RadioButton lern, testing, collecting;
static Bitmap buferImage;
static StringBuilder STR = new StringBuilder();
static int maxPos(double[] vect)
{
double max = -2; int pos = 0;
for (int i = 0; i < vect.Length; i++)
{
if (max < vect[i]) { max = vect[i]; pos = i; }
}
return pos;
}
void Demiss()
{
if (appMode != AppMode.COLLECTING) return;
toDraw = null;
panel1.Refresh();
IGNORE = false;
}
void Accept()
{
if (appMode != AppMode.COLLECTING || !IGNORE || toDraw == null) return;
string path = (checkBox1.Checked ? "t" : "l") + numericUpDown1.Value + "/";
Directory.CreateDirectory(path);
string[] fls = Directory.GetFiles(path);
int nxtfl = 0;
foreach (string f in fls)
{
int tmp = int.Parse(f.Substring(3, f.Length - 7));
if (nxtfl < tmp + 1) nxtfl = tmp + 1;
}
StreamWriter sw = new StreamWriter(path + nxtfl + ".txt", false, Encoding.Default);
for (int i = 0; i < toDraw.Length; i++)
{
sw.WriteLine(toDraw[i].x);
sw.WriteLine(toDraw[i].y);
sw.WriteLine(toDraw[i].z);
}
for (int i = 0; i < 10; i++)
{
sw.WriteLine(i == numericUpDown1.Value ? 1.0 : 0.0);
}
sw.Close();
sw.Dispose();
IGNORE = false;
label2.Text = "уже собрано: " + (fls.Length + 1) + " из " + (checkBox1.Checked ? TESTINGS : LERNINGS);
}
Action dataRefr = new Action(() =>
{
vector3d[] buff;
while (isRuning)
{
if (READY_READ)
{
lock (stk)
buff = stk.getCopy();
READY_READ = false;
// IGNORE = true;
if (toDraw == null)
{
toDraw = new vector3d[33];
for (int i = 0; i < toDraw.Length; i++)
{
toDraw[i] = new vector3d();
}
}
medianFilter3x(buff);
for (int i = 1, j = 0; i < buff.Length; i += 3, j++)
{
toDraw[j].x = (buff[i - 1].x + buff[i].x + buff[i + 1].x) / 3;
toDraw[j].y = (buff[i - 1].y + buff[i].y + buff[i + 1].y) / 3;
toDraw[j].z = (buff[i - 1].z + buff[i].z + buff[i + 1].z) / 3;
}
if (appMode == AppMode.TESTING)
{
double[] buffr = new double[99];
for (int i = 0; i < toDraw.Length; i++)
{
buffr[3 * i] = toDraw[i].x;
buffr[3 * i + 1] = toDraw[i].y;
buffr[3 * i + 2] = toDraw[i].z;
}
link.think(buffr);
buffr = link.result();
char ch = '_';
int mx = maxPos(buffr);
if (buffr[mx] >= 0)
switch (mx)
{
case 0:
ch = '0';
break;
case 1:
ch = '1';
break;
case 2:
ch = '2';
break;
case 3:
ch = '3';
break;
case 4:
ch = '4';
break;
case 5:
ch = '5';
break;
case 6:
ch = '6';
break;
case 7:
ch = '7';
break;
case 8:
ch = '8';
break;
case 9:
ch = '9';
break;
}
STR.Append(ch);
}
panell.BeginInvoke((Action)(() =>
{
panell.Refresh();
}));
}
Thread.Sleep(10);
}
});
Action learnStatus = new Action(() =>
{
inited = false;
curError = new vector4d();
dataset[][] datasets = new dataset[10][];
dataset[][] testsets = new dataset[10][];
for (int i = 0; i < 10; i++)
{
string[] path = Directory.GetFiles("l" + i + "/");
datasets[i] = new dataset[LERNINGS];
for (int j = 0; j < LERNINGS; j++)
{
datasets[i][j] = new dataset(path[j]);
}
path = Directory.GetFiles("t" + i + "/");
testsets[i] = new dataset[TESTINGS];
for (int j = 0; j < TESTINGS; j++)
{
testsets[i][j] = new dataset(path[j]);
}
}
link.EpochInit();
for (; link.generation < 1000000; link.generation++)
{
if (!isLearning) break;
double learnError = 0;
for (int i = 0; i < LERNINGS; i++)
{
for (int n = 0; n < 10; n++)
{
link.think(datasets[n][i].data);
learnError += link.curError(datasets[n][i].result);
link.learn(datasets[n][i].result);
}
}
link.fixRProp();
if (link.generation % 500 == 0)
{
learnError /= (LERNINGS * 10);
double mindError = 0, corct = 0;
for (int i = 0; i < 10; i++)
{
for (int n = 0; n < 10; n++)
{
link.think(testsets[n][i].data);
mindError += link.curError(testsets[n][i].result);
int mx = maxPos(link.result());
if (mx == n && link.result()[n] > 0) corct++;
}
}
mindError /= (TESTINGS * 10);
corct /= (TESTINGS * 10);
prevError = curError;
curError = new vector4d();
curError.x = link.generation;
curError.y = mindError;
curError.z = learnError;
curError.t = corct;
StreamWriter sr = new StreamWriter("errors.csv", true, Encoding.Default);
sr.WriteLine("{0};{1};{2};{3}", link.generation, mindError, learnError, corct);
sr.Close();
panell.BeginInvoke((Action)(() =>
{
panell.Refresh();
}));
}
if (link.generation % 1000 == 0) { link.saveToFile(); link.saveToFileCopy(); }
}
Thread.Sleep(0);
});
Task refr, lernThr;
private void button1_Click(object sender, EventArgs e)
{
string[] ports = SerialPort.GetPortNames();
listView1.Items.Clear();
foreach (string s in ports) { listView1.Items.Add(s); }
}
static Pen pen = new Pen(Color.LightGray);
private void button3_Click(object sender, EventArgs e)
{
Demiss();
}
private void button4_Click(object sender, EventArgs e)
{
Accept();
}
private void numericUpDown1_ValueChanged(object sender, EventArgs e)
{
label2.Text = (Directory.Exists((checkBox1.Checked ? "t" : "l") + numericUpDown1.Value + "/") ? ("уже собрано: " + (Directory.GetFiles((checkBox1.Checked ? "t" : "l") + numericUpDown1.Value + "/").Length)) : ("уже собрано: 0")) + " из " + (checkBox1.Checked ? TESTINGS : LERNINGS);
}
private void Form1_KeyUp(object sender, KeyEventArgs e)
{
switch (e.KeyCode)
{
case Keys.A:
Accept();
e.Handled = true;
break;
case Keys.D:
Demiss();
e.Handled = true;
break;
case Keys.T:
checkBox1.Checked = !checkBox1.Checked;
e.Handled = true;
break;
}
}
private void radioButton2_CheckedChanged(object sender, EventArgs e)
{
if (radioButton1.Checked)
appMode = AppMode.COLLECTING;
if (radioButton2.Checked)
appMode = AppMode.LEARNING;
if (radioButton3.Checked)
appMode = AppMode.WATCHING_SIGNAL;
if (radioButton4.Checked)
appMode = AppMode.TESTING;
button3.Enabled = false;
button4.Enabled = false;
button5.Enabled = false;
switch (appMode)
{
case AppMode.COLLECTING:
button4.Enabled = true;
button3.Enabled = true;
if (refr == null)
{
isRuning = true;
refr = new Task(dataRefr);
refr.Start();
}
break;
case AppMode.LEARNING:
if (refr != null)
{
isRuning = false;
refr.Wait();
refr.Dispose();
refr = null;
}
button5.Enabled = true;
break;
}
}
private void button5_Click(object sender, EventArgs e)
{
isLearning = !isLearning;
if (isLearning)
{
radioButton1.Enabled = false;
radioButton2.Enabled = false;
radioButton3.Enabled = false;
radioButton4.Enabled = false;
button5.Text = "остановить обучение";
buferImage = new Bitmap(5000, 5000 * panel1.Height / panel1.Width);
lernThr = new Task(learnStatus, TaskCreationOptions.LongRunning);
lernThr.Start();
}
else
{
lernThr.Wait();
lernThr.Dispose();
lernThr = null;
radioButton1.Enabled = true;
radioButton2.Enabled = true;
radioButton3.Enabled = true;
radioButton4.Enabled = true;
buferImage = new Bitmap(1000, 1000 * panel1.Height / panel1.Width);
button5.Text = "начать обучение";
}
}
private void panel1_MouseDown(object sender, MouseEventArgs e)
{
PMX = e.X;
PMY = e.Y;
}
private void panel1_MouseUp(object sender, MouseEventArgs e)
{
DX = PDX + e.X - PMX;
DY = PDY + e.Y - PMY;
panel1.Refresh();
panel1.Update();
PDX = DX;
PDY = DY;
}
private void panel1_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
DX = PDX + e.X - PMX;
DY = PDY + e.Y - PMY;
panel1.Refresh();
}
}
private void panel1_MouseWheel(object sender, MouseEventArgs e)
{
SCALE += e.Delta * 0.0005f;
panel1.Refresh();
}
static bool inited = false;
static int DX, DY, PDX, PDY, PMX, PMY, prevGen = -1;
static float SCALE = 1;
private void panel1_Paint(object sender, PaintEventArgs e)
{
switch (appMode)
{
case AppMode.TESTING:
case AppMode.COLLECTING:
case AppMode.WATCHING_SIGNAL:
{
if (appMode == AppMode.TESTING)
richTextBox2.Text = STR.ToString();
Graphics g = Graphics.FromImage(buferImage);
g.Clear(Color.White);
float wd = buferImage.Width / 32;
pen.Color = Color.LightGray;
pen.Width = 1;
for (int x = 1; x < 33; x++)
{
g.DrawLine(pen, x * wd, 0, x * wd, buferImage.Height);
}
float hd = buferImage.Height / 23;
for (int y = 1; y < 24; y++)
{
g.DrawLine(pen, 0, y * hd, buferImage.Width, y * hd);
}
pen.Color = Color.Gray;
pen.Width = 2;
g.DrawLine(pen, 0, hd * 12, buferImage.Width, 12 * hd);
if (toDraw != null)
{
pen.Color = Color.Blue;
pen.Width = 1;
double py = toDraw[0].x;
for (int x = 1; x < 33; x++)
{
g.DrawLine(pen, (x - 1) * wd, buferImage.Height / 2 - (float)py * hd, x * wd, buferImage.Height / 2 - (float)toDraw[x].x * hd);
py = toDraw[x].x;
if (x % 5 == 0) g.DrawString("" + Math.Round(py, 2), System.Drawing.SystemFonts.DefaultFont, Brushes.Blue, x * wd, buferImage.Height / 2 - (float)py * hd);
}
pen.Color = Color.Red;
py = toDraw[0].y;
for (int x = 1; x < 33; x++)
{
g.DrawLine(pen, (x - 1) * wd, buferImage.Height / 2 - (float)py * hd, x * wd, buferImage.Height / 2 - (float)toDraw[x].y * hd);
py = toDraw[x].y;
if (x % 5 == 2) g.DrawString("" + Math.Round(py, 2), System.Drawing.SystemFonts.DefaultFont, Brushes.Red, x * wd, buferImage.Height / 2 - (float)py * hd);
}
pen.Color = Color.Green;
py = toDraw[0].z;
for (int x = 1; x < 33; x++)
{
g.DrawLine(pen, (x - 1) * wd, buferImage.Height / 2 - (float)py * hd, x * wd, buferImage.Height / 2 - (float)toDraw[x].z * hd);
py = toDraw[x].z;
if (x % 5 == 4) g.DrawString("" + Math.Round(py, 2), System.Drawing.SystemFonts.DefaultFont, Brushes.Green, x * wd, buferImage.Height / 2 - (float)py * hd);
}
}
e.Graphics.DrawImage(buferImage, DX, DY, buferImage.Width * SCALE, buferImage.Height * SCALE);
}
break;
case AppMode.LEARNING:
{
Graphics g = Graphics.FromImage(buferImage);
if (!inited)
{
inited = true;
g.Clear(Color.White);
float wd = buferImage.Width / 100;
float hd = buferImage.Height / 4;
pen.Color = Color.LightGray;
pen.Width = 1;
for (int x = 1; x < 110; x++)
{
g.DrawLine(pen, x * wd, 0, x * wd, buferImage.Height);
}
for (int y = 1; y < 5; y++)
{
g.DrawLine(pen, 0, y * hd, buferImage.Width, y * hd);
}
pen.Color = Color.Gray;
pen.Width = 2;
g.DrawLine(pen, 0, hd * 5, buferImage.Width, 5 * hd);
}
float kx = buferImage.Width / 1000000f, ky = buferImage.Height;
pen.Color = Color.Red;
pen.Width = 1;
g.DrawLine(pen, (float)prevError.x * kx, (1 - (float)prevError.y) * ky, (float)curError.x * kx, (1 - (float)curError.y) * ky);
pen.Color = Color.Green;
g.DrawLine(pen, (float)prevError.x * kx, (1 - (float)prevError.z) * ky, (float)curError.x * kx, (1 - (float)curError.z) * ky);
pen.Color = Color.Blue;
g.DrawLine(pen, (float)prevError.x * kx, (1 - (float)prevError.t) * ky, (float)curError.x * kx, (1 - (float)curError.t) * ky);
if (curError.x > prevGen)
{
richTextBox2.AppendText("gen#" + curError.x + "; ошибка обобщения: " + curError.y + "; ошибка обучения: " + curError.z + "; Степень распознания: " + curError.t + "\n");
richTextBox2.ScrollToCaret();
prevGen = (int)curError.x;
}
e.Graphics.DrawImage(buferImage, DX, DY, buferImage.Width * SCALE, buferImage.Height * SCALE);
}
break;
}
System.GC.Collect();
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
isRuning = false;
if (srp != null) lock (srp)
{
srp.Close();
srp.Dispose();
srp = null;
}
}
private void button2_Click(object sender, EventArgs e)
{
if (srp == null)
{
srp = new SerialPort(listView1.SelectedItems[0].Text, 57600);
srp.DataReceived += dataRecived;
try
{
srp.Open();
button2.Text = "отключить";
richTextBox1.AppendText("Ручка успешно подключена\n");
richTextBox1.ScrollToCaret();
}
catch (Exception ex)
{
button2.Text = "подключить";
srp.Close();
srp.Dispose();
srp = null;
richTextBox1.AppendText(ex.Message + "\n");
richTextBox1.ScrollToCaret();
}
}
else
lock (srp)
{
button2.Text = "подключить";
srp.Close();
srp.Dispose();
srp = null;
richTextBox1.AppendText("Ручка отключена\n");
richTextBox1.ScrollToCaret();
}
}
static void dataRecived(object sender, SerialDataReceivedEventArgs e)
{
lock (srp)
{
if (IGNORE) { while (srp.BytesToRead > 0) srp.ReadByte(); return; }
while (srp.ReadByte() != 0xff) ;
while (srp.BytesToRead < 12) ;
// while (srp.BytesToRead > 11)
lock (stk)
{
vector3d V = new vector3d();
byte[] data = new byte[12];
srp.Read(data, 0, 12);
V.x = BitConverter.ToSingle(data, 0);
V.y = BitConverter.ToSingle(data, 4);
V.z = BitConverter.ToSingle(data, 8);
V.x /= 1600;
V.y /= 1600;
V.z /= 1600;
stk.add(V);
if (!SIGNAL && !READY_READ && (abs(V.x) > 2.3 || abs(V.y) > 2.3 || abs(V.z) > 2.3))
{
SO_POWERFUL = false;
SIGNAL = true;
Co = 0;
}
if (SIGNAL)
{
if (abs(V.x) > 9 || abs(V.y) > 9 || abs(V.z) > 9) SO_POWERFUL = true;
Co += 1;
if (Co >= 71)
{
READY_READ = true && !SO_POWERFUL;
if (collecting.Checked) IGNORE = READY_READ;
SIGNAL = false;
}
}
}
}
}
public Form1()
{
InitializeComponent();
buferImage = new Bitmap(1000, 1000 * panel1.Height / panel1.Width);
SCALE = (float)panel1.Height / buferImage.Height;
label2.Text = (Directory.Exists((checkBox1.Checked ? "t" : "l") + numericUpDown1.Value + "/") ? ("уже собрано: " + (Directory.GetFiles((checkBox1.Checked ? "t" : "l") + numericUpDown1.Value + "/").Length)) : ("уже собрано: 0")) + " из " + (checkBox1.Checked ? TESTINGS : LERNINGS);
KeyPreview = true;
string[] ports = SerialPort.GetPortNames();
listView1.Items.Clear();
foreach (string s in ports) { listView1.Items.Add(s); }
panell = panel1;
collecting = radioButton1;
lern = radioButton2;
testing = radioButton3;
refr = new Task(dataRefr);
refr.Start();
}
}
class vector3d
{
public double x, y, z;
};
class vector4d
{
public double x, y, z, t;
};
class NeuroLink
{
/*
public static double SigmoidGrad(double x)
{
return ((1 - x) * x);
}
public static double Sigmoid(double x)
{
return 1 / (1 + Math.Exp(-x));
}*/
public static double TanhGrad(double fx)
{
return 1 - fx * fx;
}
private class Neuron
{
public Neuron(int prk)
{
kf = new double[prk];
dkf = new double[prk];
// далее только для упругого спуска
grad = new double[prk];
prevGrSig = new bool[prk];
dbias = 0.1;
for (int i = 0; i < prk; i++) dkf[i] = 0.1;
}
//коэфециенты входящих синапсисов
public double[] kf, dkf, grad;
bool[] prevGrSig;
bool prevBGrSig;
public double output, delta, bias, dbias, biasGrad;
public void initGrads()
{
for (int i = 0; i < grad.Length; i++)
grad[i] = 0;
biasGrad = 0;
}
public void update(Neuron[] neus)
{
output = bias;
for (int i = 0; i < neus.Length; i++) output += neus[i].output * kf[i];
output = Math.Tanh(output);
}
public void findDelta(int pos, Neuron[] neus)
{
double sum = 0;
for (int i = 0; i < neus.Length; i++) sum += neus[i].kf[pos] * neus[i].delta;
delta = sum * TanhGrad(output);
}
public void findDelta(double cor)
{
delta = (cor - output) * TanhGrad(output);
}
public void fixRProps()
{
for (int i = 0; i < grad.Length; i++)
{
if (grad[i] == 0) continue;
bool sign = grad[i] > 0;
dkf[i] *= (sign == prevGrSig[i]) ? N : n;
if (dkf[i] < 0.000000001) dkf[i] = 0.000000001;
else if (dkf[i] > 50) dkf[i] = 50;
kf[i] += grad[i] > 0 ? dkf[i] : -dkf[i];
grad[i] = 0;
prevGrSig[i] = sign;
}
{
if (biasGrad == 0) return;
bool sign = biasGrad > 0;
dbias *= (sign == prevBGrSig) ? N : n;
if (dbias < 0.000000001) dbias = 0.000000001;
else if (dbias > 50) dbias = 50;
bias += biasGrad > 0 ? dbias : -dbias;
biasGrad = 0;
prevBGrSig = sign;
}
}
public void correctWeights(Neuron[] neus)
{//Метод простого градентного спуска
/*
for (int i = 0; i < kf.Length; i++)
{
double gradient = neus[i].output * delta;
double dw = E * gradient + A * dkf[i];
dkf[i] = dw;
kf[i] += dw;
}
{
double gradient = delta;
double dw = E * gradient + A * dbias;
dbias = dw;
bias += dw;
}*/
//метод упругого спуска
for (int i = 0; i < kf.Length; i++)
{
grad[i] += neus[i].output * delta;
}
{
biasGrad += delta;
}
}
}
public int generation;
//const int INP = 99, H1 = 60, H2 = 30, O = 10;
//const int INP = 99, H1 = 150, H2 = 60, O = 10;
const int INP = 99, H1 = 100, H2 = 40, O = 10;
//E - обучаемость, A - инертность
const double E = 0.000005, A = 0.06;
//Изменение прироста коэффециентов в случаях с градиентом одного или разных знаков
const double n = 0.5, N = 1.2;
//массив массивов нейронов. Нейроны распределны по массивам в соответсвии со слоем
Neuron[][] layouts = new Neuron[4][];
string filepath;
public NeuroLink(string fl = "neurolink.txt")
{
filepath = fl;
layouts[0] = new Neuron[INP];
layouts[1] = new Neuron[H1];
layouts[2] = new Neuron[H2];
layouts[3] = new Neuron[O];
if (File.Exists(filepath))
{
StreamReader sr = new StreamReader(filepath);
string[] kf = sr.ReadToEnd().Split(' ');
sr.Close();
generation = int.Parse(kf[0]);
int kk = 1;
for (int i = 0; i < layouts[0].Length; i++)
{
layouts[0][i] = new Neuron(0);
}
for (int i = 0; i < layouts[1].Length; i++)
{
layouts[1][i] = new Neuron(INP);
for (int j = 0; j < layouts[1][i].kf.Length; j++)
{
layouts[1][i].kf[j] = double.Parse(kf[kk]);
kk++;
}
layouts[1][i].bias = double.Parse(kf[kk]);
kk++;
}
for (int i = 0; i < layouts[2].Length; i++)
{
layouts[2][i] = new Neuron(H1);
for (int j = 0; j < layouts[2][i].kf.Length; j++)
{
layouts[2][i].kf[j] = double.Parse(kf[kk]);
kk++;
}
layouts[2][i].bias = double.Parse(kf[kk]);
kk++;
}
for (int i = 0; i < layouts[3].Length; i++)
{
layouts[3][i] = new Neuron(H2);
for (int j = 0; j < layouts[3][i].kf.Length; j++)
{
layouts[3][i].kf[j] = double.Parse(kf[kk]);
kk++;
}
layouts[3][i].bias = double.Parse(kf[kk]);
kk++;
}
}
else
{
Random r = new Random();
StreamWriter sw = new StreamWriter(filepath, false, System.Text.Encoding.Default);
sw.Write("0 ");
for (int i = 0; i < layouts[0].Length; i++)
{
layouts[0][i] = new Neuron(0);
}
for (int i = 0; i < layouts[1].Length; i++)
{
layouts[1][i] = new Neuron(INP);
for (int j = 0; j < layouts[1][i].kf.Length; j++)
{
double ko = (r.NextDouble() * 10) - 5;
layouts[1][i].kf[j] = ko;
sw.Write("{0} ", ko);
}
layouts[1][i].bias = (r.NextDouble() * 5) - 2.5;
sw.Write("{0} ", layouts[1][i].bias);
}
for (int i = 0; i < layouts[2].Length; i++)
{
layouts[2][i] = new Neuron(H1);
for (int j = 0; j < layouts[2][i].kf.Length; j++)
{
double ko = (r.NextDouble() * 10) - 5;
layouts[2][i].kf[j] = ko;
sw.Write("{0} ", ko);
}
layouts[2][i].bias = (r.NextDouble() * 10) - 5;
sw.Write("{0} ", layouts[2][i].bias);
}
for (int i = 0; i < layouts[3].Length; i++)
{
layouts[3][i] = new Neuron(H2);
for (int j = 0; j < layouts[3][i].kf.Length; j++)
{
double ko = (r.NextDouble() * 10) - 5;
layouts[3][i].kf[j] = ko;
sw.Write("{0} ", ko);
}
layouts[3][i].bias = (r.NextDouble() * 5) - 2.5;
sw.Write("{0} ", layouts[3][i].bias);
}
sw.Close();
}
}
public void EpochInit()
{
for (int i = 0; i < layouts.Length; i++) for (int j = 0; j < layouts[i].Length; j++) layouts[i][j].initGrads();
}
public void think(double[] data)
{
for (int i = 0; i < layouts[0].Length; i++)
layouts[0][i].output = Math.Tanh(data[i]);
for (int j = 1; j < layouts.Length; j++)
for (int i = 0; i < layouts[j].Length; i++)
layouts[j][i].update(layouts[j - 1]);
}
public double[] result()
{
double[] uns = new double[O];
for (int i = 0; i < O; i++) uns[i] = layouts[layouts.Length - 1][i].output;
return uns;
}
public void learn(double[] correct)
{
for (int i = 0; i < O; i++)
layouts[layouts.Length - 1][i].findDelta(correct[i]);
for (int i = layouts.Length - 2; i > 0; i--)
{
int max = Math.Max(layouts[i].Length, layouts[i + 1].Length);
for (int j = 0; j < max; j++)
{
if (layouts[i].Length > j) layouts[i][j].findDelta(j, layouts[i + 1]);
if (layouts[i + 1].Length > j) layouts[i + 1][j].correctWeights(layouts[i]);
}
}
for (int j = 0; j < layouts[1].Length; j++)
layouts[1][j].correctWeights(layouts[0]);
}
public void fixRProp()
{
for (int i = 1; i < layouts.Length; i++) for (int j = 0; j < layouts[i].Length; j++) layouts[i][j].fixRProps();
}
public double curError(double[] correct)
{
double un = 0;
for (int i = 0; i < layouts[layouts.Length - 1].Length; i++)
un += (correct[i] - layouts[layouts.Length - 1][i].output) * (correct[i] - layouts[layouts.Length - 1][i].output);
return un / layouts[layouts.Length - 1].Length;
}
public void saveToFileCopy()
{
Directory.CreateDirectory("neuro_history");
File.Copy(filepath, "neuro_history/gen_" + generation + ".txt");
}
public void saveToFile()
{
StreamWriter sw = new StreamWriter(filepath, false, System.Text.Encoding.Default);
sw.Write("{0} ", generation);
for (int i = 0; i < layouts[1].Length; i++)
{
for (int j = 0; j < layouts[1][i].kf.Length; j++)
{
sw.Write("{0} ", layouts[1][i].kf[j]);
}
sw.Write("{0} ", layouts[1][i].bias);
}
for (int i = 0; i < layouts[2].Length; i++)
{
for (int j = 0; j < layouts[2][i].kf.Length; j++)
{
sw.Write("{0} ", layouts[2][i].kf[j]);
}
sw.Write("{0} ", layouts[2][i].bias);
}
for (int i = 0; i < layouts[3].Length; i++)
{
for (int j = 0; j < layouts[3][i].kf.Length; j++)
{
sw.Write("{0} ", layouts[3][i].kf[j]);
}
sw.Write("{0} ", layouts[3][i].bias);
}
sw.Close();
}
}
class ringBuffer
{
private vector3d[] data;
const int SIZE = 99;
private int head = 0;
public ringBuffer()
{
data = new vector3d[SIZE];
for (int i = 0; i < SIZE; i++) data[i] = new vector3d();
}
public void add(vector3d vec)
{
data[head++] = vec;
head %= SIZE;
}
public vector3d peek()
{
return (head > 0) ? data[head - 1] : data[SIZE - 1];
}
public vector3d[] getCopy()
{
vector3d[] copy = new vector3d[SIZE];
int h = head;
for (int i = 0; i < SIZE; i++)
{
copy[i] = data[h++];
h %= SIZE;
}
return copy;
}
}
class dataset
{
public double[] data = new double[99], result = new double[10];
public dataset(string path)
{
StreamReader sr = new StreamReader(path, Encoding.Default);
for (int i = 0; i < data.Length; i++)
{
data[i] = double.Parse(sr.ReadLine());
}
for (int i = 0; i < result.Length; i++)
{
result[i] = double.Parse(sr.ReadLine());
}
sr.Close();
}
}
enum AppMode { COLLECTING, LEARNING, WATCHING_SIGNAL, TESTING };
}
<file_sep>using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Windows.Forms;
namespace PenProject_test
{
public partial class Form1 : Form
{
List<string> data_s = new List<string>();
public Form1()
{
InitializeComponent();
string[] ports = SerialPort.GetPortNames();
comboBox1.Items.Clear();
comboBox1.Items.AddRange(ports);
}
void data(object sender, SerialDataReceivedEventArgs e)
{
while (port1.BytesToRead < 12) ;
byte[] arr = new byte[12];
port1.Read(arr, 0, 12);
short[] data = new short[6];
for (int i = 0; i < 6; i++)
{
data[i] = (short)((arr[i * 2] << 8) & 0xff00 | (arr[i * 2 + 1]));
}
this.BeginInvoke((Action)(() =>
{
richTextBox1.Text = "ax: " + data[0] + ", ay: " + data[1] + ", az: " + data[2];
richTextBox1.ScrollToCaret();
}));
}
private void button1_Click(object sender, EventArgs e)
{
string[] ports = SerialPort.GetPortNames();
comboBox1.Items.Clear();
comboBox1.Items.AddRange(ports);
}
SerialPort port1;
private void button2_Click(object sender, EventArgs e)
{
port1 = new SerialPort(comboBox1.SelectedItem.ToString(), 1000000);
port1.Open();
port1.DataReceived += data;
richTextBox1.Text += "connected\n";
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO.Ports;
using System.Threading;
namespace Canvas_pen
{
struct angles
{
public float alpha, beta, gamma;
};
class Point
{
public float x, y; public int count;
public Point(float nx, float ny) { x = nx; y = ny; count = 1; }
}
public partial class Form1 : Form
{
static Queue<angles> angls = new Queue<angles>();
static List<Point> points = new List<Point>();
void data(object sender, SerialDataReceivedEventArgs e)
{
while (srp.ReadByte() != 0xFF) if (srp.BytesToRead <= 0) return;
while (srp.ReadByte() != 0x00) if (srp.BytesToRead <= 0) return;
string[] data = srp.ReadLine().Replace('.', ',').Split('\t');
angles a = new angles();
a.alpha = float.Parse(data[0]) / 10000f;
a.beta = float.Parse(data[1]) / 10000f;
a.gamma = float.Parse(data[2]) / 10000f;
lock (angls)
angls.Enqueue(a);
}
const float PI_05 = (float)Math.PI / 2;
static float hypot(float x, float y) { return (float)Math.Sqrt(x * x + y * y); }
//const float K = 0.9f;
Task thread = new Task(() =>
{
while (true)
{
lock (angls)
while (angls.Count > 0)
{
angles a = angls.Dequeue();
float gam = PI_05 - a.gamma + a.beta;
//float gam = a.gamma;
// gam *= -1;
while (gam > Math.PI) gam -= (float)Math.PI * 2;
while (gam < -Math.PI) gam += (float)Math.PI * 2;
// Console.WriteLine("{0:f4}\t{1:f4}\t{2:f4}\t{3:f2}", alpha * toDeg, beta * toDeg, gamma * toDeg, gam * toDeg);
// Console.WriteLine("{0:f3} \n{1:f3} ", ang1 * 180 / Math.PI, azim2 * 180 / Math.PI);
float l1 = arm_len * (float)Math.Tan(a.alpha);
float l2 = l1 - (float)Math.Sin(a.alpha);
int px = (int)(200 + l1 * 250 * Math.Cos(gam));
int pz = (int)(200 + l1 * 250 * Math.Sin(gam));
if (px > 398 || pz > 398 || pz < 1 || px < 1) { px = 200; pz = 200; }
lock (points)
{
if (points.Count == 0) points.Add(new Point(px, pz));
else
{
Point p = points[points.Count - 1];
if (hypot(p.x - px, p.y - pz) <= 10)
{
float K = 1f / (p.count + 1);
p.x = K * p.count * p.x + K * px;
p.y = K * p.count * p.y + K * pz;
p.count++;
}
else if (p.count < 6)
{
points.RemoveAt(points.Count - 1);
points.Add(new Point(px, pz));
}
else points.Add(new Point(px, pz));
}
}
}
Thread.Sleep(10);
}
});
static Pen blackPen = new Pen(Color.Black, 2);
Task drawTh = new Task(() =>
{
int TIMER = 0;
while (true)
{
using (var graphics = Graphics.FromImage(img))
{
float px = 0, py = 0;
graphics.Clear(Color.White);
graphics.DrawRectangle(Pens.Red, 195, 195, 10, 10);
graphics.DrawString("count: " + points.Count, SystemFonts.DefaultFont, Brushes.Black, 10, 10);
lock (points)
for (int i = 0; i < points.Count; i++)
{
/* if (TIMER >= 5 && points[i].count < 10)
{
points.RemoveAt(i);
i--;
continue;
}*/
if (i > 0)
{
graphics.DrawLine(blackPen, px, py, points[i].x, points[i].y);
}
px = points[i].x;
py = points[i].y;
}
}
imbx.Image = img;
TIMER++;
if (TIMER > 5) TIMER = 0;
Thread.Sleep(60);
}
});
const float arm_len = 6.5f / 17f;
SerialPort srp;
public Form1()
{
InitializeComponent();
string[] coms = SerialPort.GetPortNames();
foreach (string a in coms)
listView1.Items.Add(a);
pictureBox1.Image = img;
imbx = pictureBox1;
thread.Start();
drawTh.Start();
}
static Bitmap img = new Bitmap(400, 400);
static PictureBox imbx;
private void button1_Click(object sender, EventArgs e)
{
if (srp == null || !srp.IsOpen)
{
try
{
button1.Enabled = false;
srp = new SerialPort(listView1.SelectedItems[0].Text, 57600);
srp.Open();
srp.DataReceived += data;
richTextBox1.Text = "Успешно подключен";
}
catch (Exception ex)
{
richTextBox1.Text = ex.Message;
button1.Enabled = true;
if (srp != null && srp.IsOpen) srp.Close();
}
}
}
private void button2_Click(object sender, EventArgs e)
{
listView1.Items.Clear();
string[] coms = SerialPort.GetPortNames();
foreach (string a in coms)
listView1.Items.Add(a);
}
private void button3_Click(object sender, EventArgs e)
{
lock (points) points.Clear();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace openGL_Visualaser
{
public class MadgwickAHR
{
public float beta = 0.2f, q0 = 1.0f, q1 = 0.0f, q2 = 0.0f, q3 = 0.0f;
public void MadgwickAHRSupdateIMU(float tdelta, float gx, float gy, float gz, float ax, float ay, float az)
{
float recipNorm;
float s0, s1, s2, s3;
float qDot1, qDot2, qDot3, qDot4;
float _2q0, _2q1, _2q2, _2q3, _4q0, _4q1, _4q2, _8q1, _8q2, q0q0, q1q1, q2q2, q3q3;
// Rate of change of quaternion from gyroscope
qDot1 = 0.5f * (-q1 * gx - q2 * gy - q3 * gz);
qDot2 = 0.5f * (q0 * gx + q2 * gz - q3 * gy);
qDot3 = 0.5f * (q0 * gy - q1 * gz + q3 * gx);
qDot4 = 0.5f * (q0 * gz + q1 * gy - q2 * gx);
// Compute feedback only if accelerometer measurement valid (avoids NaN in accelerometer normalisation)
if (!((ax == 0.0f) && (ay == 0.0f) && (az == 0.0f)))
{
// Normalise accelerometer measurement
recipNorm = invSqrt(ax * ax + ay * ay + az * az);
ax *= recipNorm;
ay *= recipNorm;
az *= recipNorm;
// Auxiliary variables to avoid repeated arithmetic
_2q0 = 2.0f * q0;
_2q1 = 2.0f * q1;
_2q2 = 2.0f * q2;
_2q3 = 2.0f * q3;
_4q0 = 4.0f * q0;
_4q1 = 4.0f * q1;
_4q2 = 4.0f * q2;
_8q1 = 8.0f * q1;
_8q2 = 8.0f * q2;
q0q0 = q0 * q0;
q1q1 = q1 * q1;
q2q2 = q2 * q2;
q3q3 = q3 * q3;
// Gradient decent algorithm corrective step
s0 = _4q0 * q2q2 + _2q2 * ax + _4q0 * q1q1 - _2q1 * ay;
s1 = _4q1 * q3q3 - _2q3 * ax + 4.0f * q0q0 * q1 - _2q0 * ay - _4q1 + _8q1 * q1q1 + _8q1 * q2q2 + _4q1 * az;
s2 = 4.0f * q0q0 * q2 + _2q0 * ax + _4q2 * q3q3 - _2q3 * ay - _4q2 + _8q2 * q1q1 + _8q2 * q2q2 + _4q2 * az;
s3 = 4.0f * q1q1 * q3 - _2q1 * ax + 4.0f * q2q2 * q3 - _2q2 * ay;
recipNorm = invSqrt(s0 * s0 + s1 * s1 + s2 * s2 + s3 * s3); // normalise step magnitude
s0 *= recipNorm;
s1 *= recipNorm;
s2 *= recipNorm;
s3 *= recipNorm;
// Apply feedback step
qDot1 -= beta * s0;
qDot2 -= beta * s1;
qDot3 -= beta * s2;
qDot4 -= beta * s3;
}
// Integrate rate of change of quaternion to yield quaternion
q0 += qDot1 * tdelta;
q1 += qDot2 * tdelta;
q2 += qDot3 * tdelta;
q3 += qDot4 * tdelta;
// Normalise quaternion
recipNorm = invSqrt(q0 * q0 + q1 * q1 + q2 * q2 + q3 * q3);
q0 *= recipNorm;
q1 *= recipNorm;
q2 *= recipNorm;
q3 *= recipNorm;
}
private float invSqrt(float x)
{
float halfx = 0.5f * x;
float y = x;
long i = (long)y;
i = 0x5f3759df - (i >> 1);
y = (float)i;
y = y * (1.5f - (halfx * y * y));
y = y * (1.5f - (halfx * y * y));
return y;
}
public float[] getEuler()
{
float[] e = new float[3];
float[] q = { q0, q1, q2, q3 };
double sqx = q[1] * q[1];
double sqy = q[2] * q[2];
double sqz = q[3] * q[3];
e[0] = (float)Math.Atan2(2.0f * (q[2] * q[3] + q[1] * q[0]), 1 - 2.0f * (sqx + sqy)); // -sqx - sqy + sqz + sqw);
e[1] = (float)Math.Asin(-2.0f * (q[1] * q[3] - q[2] * q[0]));
e[2] = (float)Math.Atan2(2.0f * (q[1] * q[2] + q[3] * q[0]), 1 - 2.0f * (sqy + sqz)); //sqx - sqy - sqz + sqw);
return e;
}
}
}
| 75b70ebe2da144825ac6bd178c304d78b468887e | [
"C#"
] | 6 | C# | Jawa-Programmer/DigitalPenProject | 1a6a345ac89def92b8e8a398b550feb4a0ce82de | a9bd7503d013cf8249b7958f29c6ed06c42ec73e |
refs/heads/main | <file_sep>#!/bin/bash
FA_FILE_GZ="../data/Reference_training/ensembl_GRCh38_cdna_ncrna_v99_noalt.fa.gz"
FA_FILE="../output_training/Reference_training/ensembl_GRCh38_cdna_ncrna_v99_noalt.fa"
GENE_MAP_FILE="../output_training/Reference_training/ensembl_GRCh38_v98_cdna_ncrna_v99_noalt_gene_map_training.txt"
## alternative: use zgrep if available to avoid decompressing
gunzip -c $FA_FILE_GZ > $FA_FILE
paste \
<(grep '^>' $FA_FILE | cut -d ' ' -f 1-7 | tr ' ' '\t' | \
sed -E 's/gene:|gene_symbol:|gene_biotype:|transcript_biotype:|chromosome:GRCh38:|scaffold:GRCh38://g' | \
sed -E 's/:[0-9]+:[0-9]+:1|:[0-9]+:[0-9]+:-1//g') \
<(grep '^>' $FA_FILE | cut -d ' ' -f 8- | sed -E 's/description:| \[Source:.*//g') \
| tr -d '>' > $GENE_MAP_FILE
rm $FA_FILE
<file_sep>#!/bin/bash
INPUT_DIR="../output_training/FastQC/FastQC_output_100K"
OUTPUT_DIR="../output_training/MultiQC_reports/"
mkdir -p $OUTPUT_DIR
multiqc -o $OUTPUT_DIR \
--title "FastQC training 100K" \
--filename "fastqc_report_training_100K" \
--cl_config "fastqc_config: { fastqc_theoretical_gc: hg38_txome }" \
--module fastqc \
--force \
$INPUT_DIR
<file_sep>#!/bin/bash
INPUT_DIR="../data/Fastq_files/Fastq_training_subsample_100K/"
OUTPUT_DIR="../output_training/FastQC/FastQC_output_100K"
mkdir -p $OUTPUT_DIR
for FASTQ_FILE in $INPUT_DIR*.fastq.gz;
do
echo $FASTQ_FILE
fastqc -o $OUTPUT_DIR -f fastq --noextract $FASTQ_FILE
done
<file_sep>---
title: "Introduction to RNA-seq data analysis"
author: "<NAME>"
date: "17 June 2021"
output:
html_document:
number_sections: yes
toc: yes
toc_float:
collapsed: no
smooth_scroll: yes
knit: (function(input_file, encoding) {
out_dir <- 'docs';
rmarkdown::render(input_file,
encoding=encoding,
output_file=file.path(dirname(input_file), out_dir, 'index.html'))})
---
***
# Notes
* this document is intended to give a practical introduction to the first main steps of bulk RNA-seq analysis
* starting from FASTQ files containing the sequencing reads from a sequencing machine
* the first steps using raw data are usually performed by external tools outside R/RStudio
* we will showcase how to run some of the external tools and you can run them too in the interactive live environment
* analysis is usually performed within R *after* the alignment of reads and generation of counts for each sample, which will be imported into R
***
* in the first part of this workshop we highlight the main steps outside R
* the Binder environment allows you to easily try those tools on a subset of the input data
* later on we will make use of this document in RStudio and run the individual code chunks as we go along
***
* individual code chunks can be run by clicking the green triangle in the upper right corner within RStudio
* note, that code chunks with the option `eval=FALSE` are **not** meant to be run here
* they just produce examples or (external) code to be shown in the output HTML file
* some of the code given in those code chunks might be helpful for you in the future
***
* the GitHub workshop repository contains a link to the output HTML file of this .Rmd file
* this file can be generated if you run/knit this whole .Rmd file
* i.e. if you clicked the `Knit` button in RStudio
***
**How to use this file**
1. using it via Binder
* this document can be run run and explored within the RStudio environment provided by [mybinder.org](https://mybinder.org)
* it means that you can interact with this document totally independent of your local R/RStudio setup using the remote RStudio environment in the cloud via your web browser
* all R package dependencies should be taken care of and external tools like FastQC are available
* note, launching RStudio and running the code via mybinder.org can be a bit slow or the service could go down temporarily
2. using it locally
* you can also run and explore this document on your local machine
* one simple way is to download the zip file from the GitHub repository (click on green button Code)
* it will give you the same files and folder hierarchy as the GitHub repository
* please make sure you have installed all the R packages in the chunk `setup`
* see also the notes below regarding the installation of R packages
* if necessary, please change the variable `input_dir` in chunk `training_files` to the path/location where you stored the training material (don't forget the last slash at the end)
***
* note, Windows only:
* there is an issue with finding the cached tximeta metadata folder on *Windows* (when calling `setTximetaBFC()`)
* it seems to require a specific folder, in which it will create a file pointing to the cached folder
* here in RStudio you can run the following code to create this directory structure
```{r windows_directory, eval=F}
dir.create(paste("C:/Users/", Sys.getenv("USERNAME"), "/AppData/Local/tximeta/tximeta/Cache", sep = ""), recursive=TRUE)
## or, if you know your username, you can manually specify your USERNAME:
## dir.create("C:/Users/USERNAME/AppData/Local/tximeta/tximeta/Cache", recursive=TRUE)
```
***
**External tools**
* we mention and showcase a few external tools
* those are often run on dedicated external computer clusters for larger datasets making use of computational resources not available on standard laptops or desktop machines
* you can also run them within the interactive Binder session
* for the future, it would be good to install those on your machines as a follow-up to this workshop
***
* external tools are often run via bash shell scripts (`.sh` files) provided as part of the training material
* in a shell (Terminal on MacOS), a command line interface, they are run by typing `bash script_name.sh`
* you can use the `Terminal` within RStudio itself (tab `Terminal` in the bottom left panel)
* some explanation of the external code is provided here to help you understand the code in the `.sh` files
* also this online tool might help to understand command line/shell script code: [explainshell.com](https://explainshell.com)
***
* some useful tools for initial RNA-seq data analysis:
+ [FastQC](https://www.bioinformatics.babraham.ac.uk/projects/fastqc/)
+ [MultiQC](https://multiqc.info)
+ [Salmon](https://github.com/COMBINE-lab/salmon)
* all tools can be installed via [conda/bioconda](http://bioconda.github.io/user/install.html)
* please follow the instructions to install Miniconda described in the link above
* note, Bioconda supports only 64-bit Linux and Mac OS
* the 3 tools can then be easily installed:
* `conda install -c bioconda fastqc`
* `conda install -c bioconda salmon`
* `conda install -c bioconda multiqc`
**R packages**
* please see the code chunk `setup` below
* if all packages in this chunk can be loaded then all code of this Rmd file should be executable
* [CRAN](https://cran.r-project.org) packages can be easily installed within RStudio
* click on `Packages` tab in the bottom right RStudio pane
* click on `install` button and search for a specific package and select from the list
* tick the box `Install dependencies` (should be the default)
* [Bioconductor](https://www.bioconductor.org) packages are installed via the R package [BiocManager](https://cran.r-project.org/web/packages/BiocManager/vignettes/BiocManager.html)
* install `BiocManager` first, as any other CRAN package as described above
* individual Bioconductor packages can be installed via: `BiocManager::install("DESeq2", dependencies=TRUE)`
***
# Setup
```{r setup, message=FALSE, warning=FALSE}
library(rmarkdown)
library(knitr)
library(ggplot2)
library(data.table) # read in data with fread()
library(DT) # create HTML tables with datatable()
library(readr) # read in data faster via tximport
library(tximport) # uses readr package for faster import if available
library(tximeta) # extends tximport
library(DESeq2) # differential expression analysis
library(genefilter) # rowVars(), imported by DESeq2
library(SummarizedExperiment) # colData()
library(EnhancedVolcano) # pretty volcano plots
## library(clusterProfiler) # GO analysis, issue with Do.db package version, see workaround later
library(org.Hs.eg.db) # annotation of human genes in many formats
## cache = TRUE - cache results (in a folder) for future knits - set TRUE for running on local machine
## caching avoids re-running code if unchanged
## echo = TRUE - display code in output document
knitr::opts_chunk$set(cache = TRUE, echo = TRUE) # set cache = FALSE for mybinder
## white background theme for all ggplot2 plots
theme_set(theme_bw())
```
* there are a number of files and folders as part of the training material
* **please change** `input_dir` to the corresponding path of your system if run your local machine
```{r training_files}
###### change accordingly if run on local machine ######
## folder with training material
# input_dir <- "/Users/USERNAME/Desktop/RNAseq_workshop/"
# input_dir <- "C:/Users/USERNAME/Desktop/Training_RNAseq_part_1/"
## use data saved on github folder 'data'
input_dir <- "./data/"
######
## samples metadata
samples_info_file <- paste0(input_dir,
"sample_annotation_training.txt")
## Salmon quantification output (all reads used)
salmon_quant_dir <- paste0(input_dir,
"Salmon_mapping/Salmon_quant_110_ensembl_v99_noalt_decoy_k31_all_reads")
## Salmon index
## NOTE: contains only 'info.json' (and duplicate_clusters.tsv), not the whole index!!
salmon_index <- paste0(input_dir,
"Salmon_index/salmon_idx_ensembl_GRCh38_cdna_ncrna_v99_noalt_decoy_k31")
## Salmon removes identical sequences from the reference and retains one
salmon_duplicates_file <- paste0(salmon_index,
"/duplicate_clusters.tsv")
## ensembl GTF gene annotation
gtf_file <- paste0(input_dir,
"Reference_training/Homo_sapiens.GRCh38.99.gtf.gz")
## transcript sequences used for Salmon index
salmon_fasta_input <- paste0(input_dir,
"Reference_training/ensembl_GRCh38_cdna_ncrna_v99_noalt.fa.gz")
## transcript to gene mapping table
t2g_file <- paste0(input_dir,
"Reference_training/ensembl_GRCh38_v98_cdna_ncrna_v99_noalt_gene_map.txt")
## tximeta BiocFileCache directory for accessing and saving TxDb sqlite files
## not used in workshop
tximeta_cache_folder <- paste0(input_dir,
"tximeta_cache_ensembl_v99_decoy")
## for tximeta, generated by makeLinkedTxome()
## not used in workshop
jsonFile <- paste0(tximeta_cache_folder,
"/ensembl_v99_cdna_ncrna_noalt_decoy.json")
## SummarizedExperiment on gene level file using tximeta for data import
## will be loaded here instead of being generated
gse_file <- paste0(input_dir, "gse_object_from_tximeta_import.rds")
```
# Initial quality control
## FASTQ files
* text-based files containing the final output from a sequencing machine
* serve as starting point for RNA-seq analysis
* usually one (single-end) or two (paired-end) FASTQ files per sample
* note, there can be more FASTQ files per sample if the library was run on multiple lanes of the sequencing machine
* usually with file extension `.fastq` or `.fq` and usually compressed `.fastq.gz`
* paired-end sequencing: read 1 in `1.fastq.gz` and read 2 in `2.fastq.gz`
***
* 4 lines per read
* read about the [FASTQ format](https://en.wikipedia.org/wiki/FASTQ_format)
* for example, read 1 and 2 of one read pair from `1.fastq.gz` and `2.fastq.gz`, respectively:
```{r fastq_example, eval=FALSE}
@K00198:129:HG7LHBBXX:8:2128:8521:47735 1:N:0:CGAGAGAG
GGAAAAGAATTGGGGAAGAAAACCAACAACTGCCTTATGCAGGGGTGGGGACAGGGAAGGAGGTAGGGCCAGGGA
+
AAFFFJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJFJJJJJJJJJJJJJJJJJ<JJJJJJJJJJ<
@K00198:129:HG7LHBBXX:8:2128:8521:47735 2:N:0:CGAGAGAG
GGTTCTCCTCTTAAGGCCAGTTGAAGATGGTCCCTTACAGCTTCCCAAGTTAGGTTAGTGATGTGAAATGCTCCT
+
AA<FFJJJJJJJJJJJJJJJJJJJJAJJJJJJJJJFFFJJJJJJFJJJJJJJJJFJJJFFJJJJJJ<FJJJJJJJ
```
## Training data
* bulk RNA-seq from 7 samples of iPSC-derived astrocytes:
* 4 samples from Parkinson's disease (PD) and 3 samples from healthy controls (CT)
* polyA+ enrichment, 75bp paired-end, Illumina HiSeq 4000
* sequencing data is available from Gene Expression Omnibus [GEO GSE120306](https://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc=GSE120306)
***
* the European Nucleotide Archive [ENA](https://www.ebi.ac.uk/ena/data/view/PRJNA492470) provides direct access to published FASTQ files
* a file report contains FTP links to easily download original FASTQ files
* for example, use the command `wget` (or `curl -O`) in your terminal/shell to download paired-end sequencing data of one sample from ENA to your current directory:
```{r fastq_download_example, eval=FALSE}
wget ftp://ftp.sra.ebi.ac.uk/vol1/fastq/SRR788/005/SRR7889835/SRR7889835_1.fastq.gz
wget ftp://ftp.sra.ebi.ac.uk/vol1/fastq/SRR788/005/SRR7889835/SRR7889835_2.fastq.gz
```
* note, for this training 100,000 read pairs were randomly selected from the original paired FASTQ files using [seqtk sample](https://github.com/lh3/seqtk)
* `seqtk` is a handy tool for processing FASTQ (and FASTA) files
* here, sub-sampled FASTQ files are provided in the folder `/data/Fastq_files/Fastq_training_subsample_100K`
## FastQC
* widely used first-line QC tool to assess raw (or pre-processed/trimmed) FASTQ files
* Java programme available from [Babraham Bioinformatics](https://www.bioinformatics.babraham.ac.uk/projects/fastqc/)
* can be installed via conda/bioconda: e.g. `conda install -c bioconda fastqc`
* run for every FASTQ file as input
* generates a HTML report for each FASTQ file
* here is a simple bash script to run FastQC for all FASTQ files in one input directory:
```{r, code = readLines("./shell_scripts/run_fastqc_training.sh"), eval=F}
```
**some explanation**
* it assumes that the `fastqc` command is known, i.e. the tool is installed
* `..` the double dot specifies the *parent directory* (one level up)
* `mkdir -p` make directory with `-p` option: no error if existing, make parent directories as needed
* `$NAME` the dollar sign `$` will access the value assigned (via `=`) to the variable `NAME`
* `for` iterates over all FASTQ files (ending with `.fastq.gz`) found in the input directory
* `*` a placeholder
* `echo` print text or values of a variable
***
* note, mutiple files can be specified as input to FastQC, best to use multiple threads in that case (`-t` argument)
* type this command in your terminal to see all options: `fastqc --help`
***
**tasks:**
1.
open a terminal/shell and change into the folder `shell_scripts` using the `cd` command, press the `Tab` key for auto-completion of names you have started to type
2.
run FastQC on sub-sampled FASTQ files with 100K reads by typing: `bash run_fastqc_training.sh`, or modify the shell script to check your own FASTQ files
3.
check the contents of the output folder `output_training`
***
* the FastQC HTML report for each FASTQ file contains a number of summary plots to quickly assess your data
* the individual QC tests come with a flag: pass, warn or failure
* note that warnings or failures can happen even in perfectly fine sequencing datasets
* for example, RNA-seq data usually fails in the `Per Base Sequence Content` check because of a known bias at the start of the sequences, see [here](https://sequencing.qcfail.com/articles/positional-sequence-bias-in-random-primed-libraries/) for more information about this
* help and explanation of different FASTQC analysis modules: [FastQC Help](https://www.bioinformatics.babraham.ac.uk/projects/fastqc/Help/)
* also see a [good](https://www.bioinformatics.babraham.ac.uk/projects/fastqc/good_sequence_short_fastqc.html) and a [bad](https://www.bioinformatics.babraham.ac.uk/projects/fastqc/bad_sequence_fastqc.html) example on the FastQC website
## MultiQC
* very useful [reporting tool](https://multiqc.info) to merge summary statistics from [many bioinformatics tools](https://multiqc.info/docs/#multiqc-modules), including FastQC
* can be [installed](https://multiqc.info/docs/#installing-multiqc) via conda/bioconda: e.g. `conda install -c bioconda fastqc`
* recursively searches through any provided file directories and finds files that it recognises
* provides convenient HTML report files
* here is an example bash script to run MultiQC summarising our FastQC results:
```{r code = readLines("./shell_scripts/run_multiqc_training.sh"), eval=F}
```
**some explanation**
* it assumes that the `multiqc` command is known
* a backslash `\` (directly followed by a linebreak) means the command continuous in the next line
* `--cl_config` allows module-specific config values to be set, e.g. add a theoretical distribution of GC content
* type this command in your terminal to see all options: `multiqc --help`
***
**Task:** run MultiQC to summarise FastQC results: `bash run_multiqc_training.sh`
***
* multiple QC modules from many different tools can be combined into one large report
* here is an [example report for RNA-seq data](https://multiqc.info/examples/rna-seq/multiqc_report.html) combining results from multiple RNA-seq tools
* the training material contains the MultiQC report of FastQC results based on all reads: `/data/MultiQC_reports/fastqc_report_all_reads.html`
## Optional steps
* upon initial inspection it may be necessary to pre-process the raw FASTQ files before proceeding
* for example, FastQC results might reveal adapter sequence contamination or very low-quality read ends
* several tools are available for adapter removal and/or quality trimming
* for example, [cutadapt](https://cutadapt.readthedocs.io/en/stable/) or [fastp](https://github.com/OpenGene/fastp)
# Alignment and quantification
* general task: find the origin of reads within the genome/transcriptome and quantify transcript/gene expression
* here we use [Salmon](https://github.com/COMBINE-lab/salmon) as a *transcript quantification tool*
* Salmon aligns reads to a reference transcriptome and estimates transcript-level abundances
* can be installed via conda/bioconda: e.g. `conda install -c bioconda salmon`
* pre-compiled [binary releases](https://github.com/COMBINE-lab/salmon/releases) are available for linux environments
***
* other common tools for RNA-seq data:
+ [Kallisto](https://pachterlab.github.io/kallisto/about.html) (similar to Salmon, another 'lightweight quantifier')
+ [STAR](https://github.com/alexdobin/STAR) (general purpose splice-aware aligner)
+ [HISAT2](https://daehwankimlab.github.io/hisat2/) (another splice-aware aligner, less memory demand than STAR)
* STAR and HISAT2 produce output files in [SAM/BAM format](https://samtools.github.io/hts-specs/SAMv1.pdf)
* the alignment information contained in those (usually large) files can be used by additional tools to perform transcript quantification
* in fact, alignments (to the transcriptome) reported by STAR (or other aligners) can be used as input to Salmon (instead of providing the raw sequencing reads) to obtain transcript abundances [Salmon's alignment-based mode](https://salmon.readthedocs.io/en/latest/salmon.html#quantifying-in-alignment-based-mode)
* here we use Salmon in the mapping-based mode directly processing reads
* this requires a specific data structure of the transcriptome - an index
## Transcriptome
* we need an organism-specific reference, human in our case
* get a reference set of (spliced) transcripts from [ensembl](https://www.ensembl.org/info/data/ftp/index.html) or [GENCODE](https://www.gencodegenes.org/)
* ensembl provides two FASTA files for coding (cDNA) and non-coding (ncRNA) transcript sequences
* it is recommended to use *both* types of transcripts for more accurate quantification
***
* download (`wget` or `curl -O`) cDNA and ncRNA transcript sequences from ensembl
* combine/concatenate the two FASTA files using the `cat` command
* also we exclude alternative (or alternate) transcript sequences with ensembl location `CHR_H*`, which are allelic sequences (haplotypes and novel patches) or assembly fix patches, and are not part of the primary assembly
* here is example code for those steps to obtain the transcriptome from ensembl (no need to run):
```{r ensembl_reference, eval=FALSE}
wget ftp://ftp.ensembl.org/pub/release-99/fasta/homo_sapiens/cdna/Homo_sapiens.GRCh38.cdna.all.fa.gz
wget ftp://ftp.ensembl.org/pub/release-99/fasta/homo_sapiens/ncrna/Homo_sapiens.GRCh38.ncrna.fa.gz
cat Homo_sapiens.GRCh38.cdna.all.fa.gz Homo_sapiens.GRCh38.ncrna.fa.gz \
> ensembl_GRCh38_cdna_ncrna_v99.fa.gz
gunzip -c ensembl_GRCh38_cdna_ncrna_v99.fa.gz | grep '^>' | grep -v 'CHR_H' | tr -d '>' \
> non_alt_seq_names.txt
## this takes a minute or so, linebreak at 80 bases
seqtk subseq -l 80 \
ensembl_GRCh38_cdna_ncrna_v99.fa.gz non_alt_seq_names.txt | \
gzip -c > ensembl_GRCh38_cdna_ncrna_v99_noalt.fa.gz
```
**some explanation:**
* `gunzip -c` expand the `.gz` FASTA file
* `|` the pipe takes the output from one command and uses it as the input to the next command
* `grep 'pattern'` print lines matching a pattern
* `grep '^>'` print lines starting with `>` (FASTA sequence headers always start with a `>`)
* `grep -v CHR_H` print non-matching lines
* `tr -d '>'` simply delete the '>' character
* `>` redirect the output to the specified file
* `seqtk subseq` is used to extract those sequences with matching names in `non_alt_seq_names.txt`
* `gzip -c` compress the FASTA file
* note, for any command line tool you can get help (manual page) by typing `man` followed by the tool name e.g. `man grep` or `man tr`
* leave the man page by pressing `Q` on your keyboard
***
* note, in some cases more transcript sequences need to be added to the reference transcriptome
* for example, if [ERCC RNA Spike-In Mix](https://www.thermofisher.com/order/catalog/product/4456740#/4456740) was used, also add the 92 ERCC sequences to the transcriptome
* the FASTA file of ERCCs can be obtained from [here](https://tools.thermofisher.com/content/sfs/manuals/ERCC92.zip)
## Index transcriptome
* first step to run Salmon means *indexing* the transcriptome as it is needed for efficient search
* this step is totally *independent* of your sequencing reads
* needs to be done only once for that specific reference and can be re-used for future runs/experiments
* build the Salmon index for the reference transcriptome (cDNA plus ncRNA):
```{r salmon_index_transcriptome, eval=F}
salmon index \
-t ensembl_GRCh38_cdna_ncrna_v99_noalt.fa.gz \
-i salmon_idx_ensembl_GRCh38_cdna_ncrna_v99_noalt_k31 \
-p 24
```
* creates an index directory as specified by `-i`
* the indexing step takes a little while, if possible make use of multiple threads (`-p`) to speed it up
* note, the default k-mer size (31) was used, which specifies the minimum match length used when searching for alignments
* having reads shorter than 75bp, e.g. 50bp or many reads trimmed (e.g. down to 30bp), a lower value is recommended, e.g. (`-k 23`)
* type this command in your terminal to see all Salmon index options: `salmon index --help`
## Index decoy-aware transcriptome
* recommended to build a decoy-aware transcriptome to improve accuracy of transcript quantification
* deal with reads that could originate from un-annotated genomic locus that is sequence-similar to an annotated (i.e. known) transcript
* helps to prevent reads from spuriously aligning to the transcriptome
* more information about this can be found in this [paper](https://genomebiology.biomedcentral.com/articles/10.1186/s13059-020-02151-8) and this [blog post](https://combine-lab.github.io/alevin-tutorial/2019/selective-alignment/)
* see also [Salmon documentation](https://salmon.readthedocs.io/en/latest/salmon.html)
* most comprehensive solution: use the *whole genome* as decoy
* a read (fragment) is discarded if it aligns *better*(!) to a decoy genome sequence rather than a transcript sequence
***
* download (`wget` or `curl -O`) the genomic sequences
* extract sequence names of genome targets (decoys) as a list of chromosome names saved in a text file called `decoys_ensembl_v99_primary.txt`:
```{r ensembl_reference_decoy, eval=F}
wget ftp://ftp.ensembl.org/pub/release-99/fasta/homo_sapiens/dna/Homo_sapiens.GRCh38.dna.primary_assembly.fa.gz
gunzip -c Homo_sapiens.GRCh38.dna.primary_assembly.fa.gz | \
grep '^>' | \
cut -d ' ' -f1 | \
tr -d '>' \
> decoys_ensembl_v99_primary.txt
```
**some explanation**
* `cut -d ' ' -f1` specify a space character as a field delimiter and extract the first field/string (before the first space)
* basically the code extracts and converts all FASTA headers to give us all chromosome/contig names
* e.g. for chromsome 1 with the FASTA header `>1 dna:chromosome chromosome:GRCh38:1:1:248956422:1 REF`, it simply extracts `1` and stores it as one line in the output file, the same is done for chromosome 2 etc. and all other contigs
***
* GRCh38 primary assembly (all top-level sequence regions excluding haplotypes & patches) has 194 genome sequences:
* 1-22 autosomes, X, Y, MT, 16 GL\*, 153 KI\* (unlocalised and unplaced scaffolds/contigs)
* these 194 sequence names are listed in `decoys_ensembl_v99_primary.txt`
* next, concatenate (`cat`) the transcriptome and genome FASTA files and build a decoy-aware Salmon index
```{r salmon_index_decoy, eval=F}
cat ensembl_GRCh38_cdna_ncrna_v99_noalt.fa.gz Homo_sapiens.GRCh38.dna.primary_assembly.fa.gz \
> ensembl_GRCh38_cdna_ncrna_v99_noalt_gentrome.fa.gz
salmon index \
-t ensembl_GRCh38_cdna_ncrna_v99_noalt_gentrome.fa.gz \
-d decoys_ensembl_v99_primary.txt \
-i salmon_idx_ensembl_GRCh38_cdna_ncrna_v99_noalt_decoy_k31 \
-p 24
```
* again, this takes a while, needs some memory resources and will produce an index of about 18GB(!)
* pre-computed salmon indices for some common organisms are available from [refgenie](http://refgenomes.databio.org)
## Salmon quant
* now that we have an index, let's align our 100,000 reads and quantify
* i.e. run Salmon to estimate transcript-level abundances using the transcriptome index
* note, for this training, we use a Salmon index *without* genome decoys and using only transcripts from chr10
* running `salmon quant` will generate a separate directory for each sample in the specified output directory
* here is an example bash script to run Salmon for alignment and quantification:
```{r code = readLines("./shell_scripts/run_salmon_training.sh"), eval=F}
```
**some explanation**
* the script assumes that the `salmon` command is known
* similarly to `run_fastqc_training.sh` the code loops over all FASTQ files
* `find` find all FASTQ files (pathnames) with read 1 of the paired reads (i.e. files ending with `1.fastq.gz`), saved in variable `R1`
* `1.fastq.gz` in `$R1` is replaced by `2.fastq.gz` to get the path of the FASTQ file with the corresponding read 2 (of the same sample)
* `sed 's/SEARCH/REPLACE/'` search and replace strings
* `basename` strip directory and suffix from filenames, e.g. `basename /path/to/dir/filename.txt .txt` gives `filename`
* here, each Salmon output directory will be named after the filename of the input FASTQ file
***
**Task:** run Salmon on sub-sampled FASTQ files with 100K reads: `bash run_salmon_training.sh`
***
* note, it is recommended to use the decoy-aware Salmon index
* simply not used during the training since the total index files are rather larger (18GB) (might be smaller in newer versions of Salmon)
* the folder `data/Salmon_mapping/Salmon_quant_110_ensembl_v99_noalt_decoy_k31_all_reads/` contains the Salmon quantification results, where all reads and the complete decoy-aware index were used
* we will import these transcript-level quantifications into R for our downstream analyses
# Import quantifications
* import transcript-level estimates from Salmon into R
* two useful R packages facilitate this task:
+ [tximport](https://bioconductor.org/packages/release/bioc/html/tximport.html)
+ [tximeta](https://www.bioconductor.org/packages/release/bioc/html/tximeta.html)
* tximeta extends tximport: automatic addition of annotation metadata for commonly used transcriptomes
* also imports more metadata of the mapping and quantification process
* here, we show how to use both packages
* later we want to perform gene-level analysis (differential gene expression, as compared to e.g. differential transcript usage)
* hence, need to summarise transcript-level abundances to the gene-level
* requires a mapping of transcripts to corresponding genes
***
* first things first
* analysis in R usually starts with reading a table containing information about individual samples:
```{r samples_info, cache=FALSE}
samples_meta <- fread(samples_info_file, sep = '\t')
samples_meta %>% DT::datatable(caption="Samples overview", escape=F, rownames = F)
```
* add location of Salmon quantification folders (each sample with its own folder):
```{r samples_info_2}
quant_dirs <- list.dirs(salmon_quant_dir, full.names = TRUE, recursive = FALSE)
quant_dirs_short <- list.dirs(salmon_quant_dir, full.names = FALSE, recursive = FALSE)
quant_dirs_table <- data.table(sample = quant_dirs_short, path = quant_dirs)
samples_meta <- merge(samples_meta, quant_dirs_table, by = "sample")
```
## tximport
* here, we extract gene information from the headers of the transcript sequences used as a reference for Salmon
* the fields in the header are delimited by spaces, beware of spaces in the gene description part
* here is an example header of one transcript of GAPDH:
```{r transcript_seq_header_example, eval=FALSE}
>ENST00000396856.5 cdna chromosome:GRCh38:12:6534532:6538340:1 gene:ENSG00000111640.15 gene_biotype:protein_coding transcript_biotype:protein_coding gene_symbol:GAPDH description:glyceraldehyde-3-phosphate dehydrogenase [Source:HGNC Symbol;Acc:HGNC:4141]
```
* the script `extract_gene_mapping_training.sh` can be used to parse the transcript to gene information into a TAB-delimited text file:
```{r code = readLines("./shell_scripts/extract_gene_mapping_training.sh"), eval=F}
```
* the output of this script, the transcript to gene mapping table, is in the training material: `/data/Reference_training/ensembl_GRCh38_v98_cdna_ncrna_v99_noalt_gene_map.txt`
* read transcript to gene mapping table:
```{r t2g_annotation}
t2g <- fread(t2g_file, header=F, sep = '\t')
setnames(t2g, c("target_id", "seqtype", "location", "ens_gene", "gene_type", "tx_type", "ext_gene", "desc"))
# remove version number from ensembl gene IDs
t2g <- t2g[, ens_gene := gsub('\\..*', '', ens_gene, perl = T)]
# remove duplicates identified by Salmon
salmon_duplicates <- fread(salmon_duplicates_file)
t2g <- t2g[!(target_id %in% salmon_duplicates[, DuplicateRef]), ]
# unique ensembl gene IDs
t2g_genes <- unique(t2g, by = "ens_gene")
```
* `t2g` is used to summarise Salmon transcript abundances at the gene level (ensembl transcript and gene IDs columns)
* `quant.sf` is the main quantification file produced by Salmon for every sample
* `txi` is simply a list of matrices
```{r run_tximport}
files_tximport <- paste0(samples_meta[, path], "/", "quant.sf")
names(files_tximport) <- samples_meta[, sample] ## names of individual Salmon quant folders
txi <- tximport(files_tximport, type = "salmon",
tx2gene = t2g[, .(target_id, ens_gene)],
dropInfReps = TRUE)
```
## tximeta
* tximeta makes use of a GTF (Gene Transfer Format) gene annotation file
* here, we link the transcriptome of the Salmon index to a locally saved GTF file from ensembl
* note, that it is recommended to specify a remote GTF source instead
* see the [tximeta vignette](https://www.bioconductor.org/packages/release/bioc/vignettes/tximeta/inst/doc/tximeta.html)
* however, if additional transcripts were added to the standard set of transcripts (e.g. ERCC sequences), those need to be manually added to the standard GTF file
* here, we make use of so called *linked transcriptomes*, where standard (*known*) transcriptomes have been modified
* remember, that we filtered the standard set of transcripts by removing alternative sequences
```{r get_ensembl_GTF, eval=FALSE}
wget ftp://ftp.ensembl.org/pub/release-99/gtf/homo_sapiens/Homo_sapiens.GRCh38.99.gtf.gz
```
* this annotation file is already available in the training material folder `/data/Reference_training`
* the code below demonstrates how to set up tximeta and creates relevant files in the tximeta cache folder
* **no need to run this code chunk as part of the training**
```{r makeLinkedTxome, eval=FALSE}
setTximetaBFC(dir = tximeta_cache_folder)
makeLinkedTxome(indexDir = salmon_index,
source = "Ensembl",
organism = "Homo sapiens",
release = "99",
genome = "GRCh38",
fasta = salmon_fasta_input,
gtf = gtf_file,
jsonFile = jsonFile)
## tximeta expects 2 columns: files and names
samples_meta <- samples_meta[, files := paste0(samples_meta[, path], "/", "quant.sf")]
samples_meta <- samples_meta[, names := sample]
## import data for the FIRST time to generate metadata
se <- tximeta(samples_meta, type = "salmon")
```
* import Salmon data and use cached version (`tximeta_cache_folder`) of the metadata and transcript ranges
* usually you run this code block, making use of the tximeta cache
* not used during training, simply to avoid uploading a sqlite database
* tximeta returns a *SummarizedExperiment* object (different to tximport)
```{r run_tximeta}
## workaround for Windows:
## dir.create("C:/Users/YOUR_USERNAME/AppData/Local/tximeta/tximeta/Cache", recursive=TRUE)
# setTximetaBFC(dir = tximeta_cache_folder)
#
# ## tximeta expects 2 columns: 'files' and 'names'
# samples_meta <- samples_meta[, files := paste0(samples_meta[, path], "/", "quant.sf")]
# samples_meta <- samples_meta[, names := sample]
# ## remove 'path' column
# samples_meta <- samples_meta[, path := NULL]
#
# se <- tximeta(samples_meta, type = "salmon")
# se
```
* summarise transcript-level quantifications to the gene-level
* with tximeta, the transcript to gene mapping table is automatically created
```{r summarise_to_gene}
###### usually run this line of code using the se generated above
# gse <- summarizeToGene(se) ## makes use of local tximeta database, uses transcript-to-gene mapping from database
## save 'gse' object for loading as part of workshop to avoid usage of larger sqlite database on github
# saveRDS(gse, gse_file, compress = TRUE)
#######
## read gene summarized object as computed from the code block above
gse <- readRDS(gse_file)
gse
colData(gse)
```
***
* note, we should have the same information obtained via tximport or tximeta:
```{r check_tximport_vs_tximeta}
# check genes
all.equal(rownames(txi$counts), rownames(gse))
all.equal(assays(gse)[["counts"]], txi$counts)
all.equal(assays(gse)[["abundance"]], txi$abundance)
all.equal(assays(gse)[["length"]], txi$length)
## alternative syntax to get counts:
## assay(gse, "counts")
## all.equal(assays(gse)[["counts"]], assay(gse, "counts"))
```
# Quality control
* one advantage of using tximeta is that metadata from Salmon are also automatically imported
* allows to quickly check a few overall QC metrics
```{r extract_quantInfo}
quant_meta <- metadata(gse)[["quantInfo"]]
quant_meta_dt <-
data.table(
sample = colData(gse)$sample,
name = colData(gse)$name,
type = colData(gse)$type,
sex = colData(gse)$sex,
lib = quant_meta$library_types,
num_proc = quant_meta$num_processed,
num_map = quant_meta$num_mapped,
pct_map = round(quant_meta$percent_mapped, 2),
pct_decoy = round(100 * quant_meta$num_decoy_fragments / quant_meta$num_processed, 2),
pct_filt = round(100 * quant_meta$num_fragments_filtered_vm / quant_meta$num_processed, 2),
pct_dovetail = round(100 * quant_meta$num_dovetail_fragments / quant_meta$num_processed, 2))
```
* the code below is a bit cumbersome, but it allows you to have buttons to quickly copy table content
* more information about the useful [DT package](https://rstudio.github.io/DT/)
```{r quantInfo_table, cache=F}
quant_meta_dt %>%
DT::datatable(caption = "Salmon quantInfo overview",
escape = F,
rownames = F,
extensions = 'Buttons',
options = list(dom = 'Blfrtip',
buttons = list('colvis',
list(extend = 'copy', exportOptions = list(columns=':visible')),
list(extend = 'csv', exportOptions = list(columns=':visible')),
list(extend = 'excel', exportOptions = list(columns=':visible'))))) %>%
formatCurrency(c("num_proc", "num_map"), digits=0, currency='')
```
***
* lib: fragement library type, see an explanation [here](https://salmon.readthedocs.io/en/latest/library_type.html)
* num_proc: number of fragments (paired reads) analysed
* num_map: number of mapped fragments
* pct_map: percentage of mapped fragments
* pct_filt: percentage of fragments that had a mapping to the transcriptome, but which were discarded because none of the mappings for the fragments exceeded the minimum selective alignment score
* pct_decoy: percentage of fragments that were discarded from quantification because they best-aligned to a decoy target rather than a valid transcript
* pct_dovetail: percentage of fragments that have only dovetailing mappings, considered as discordant and discarded by default, see an explaination of [dovetail](http://bowtie-bio.sourceforge.net/bowtie2/manual.shtml#bowtie2-options-dovetail)
***
## Overview plots
* graph the Salmon metrics from above
* future versions of tximeta might facilitate such plots as mentioned in the Next steps of the [tximeta vignette](https://www.bioconductor.org/packages/release/bioc/vignettes/tximeta/inst/doc/tximeta.html#Next_steps)
* note, if you have many samples (>20) it is probably better to use boxplots/beeswarm plots instead of barplots
```{r overview_plots_1, fig.width=9, fig.height=3}
plot_data_1 <- melt(quant_meta_dt,
id.vars = c("name", "type", "sex"),
measure.vars = c("num_proc", "num_map"))
p <- ggplot(plot_data_1, aes(x = name, y = value))
p <- p + geom_bar(stat = "identity", position = "dodge")
p <- p + facet_wrap(~variable, scales = "fixed", ncol = 2)
p
```
* having used the full genome as decoy allows you to check how many reads were discarded because they map better to a decoy sequence
* may give you and indication if you have many reads from intronic or intergenic regions
```{r overview_plots_2, fig.width=9, fig.height=5}
plot_data_2 <- melt(quant_meta_dt,
id.vars = c("name", "type", "sex"),
measure.vars = c("pct_map", "pct_decoy", "pct_filt", "pct_dovetail"))
p <- ggplot(plot_data_2, aes(x = name, y = value))
p <- p + geom_bar(stat="identity", position="dodge")
p <- p + facet_wrap(~variable, scales = "free_y", ncol=2)
p <- p + geom_text(aes(label = value), position=position_dodge(width = 0.9), vjust = -0.2, size = 2)
p
```
## Sex check
* sample swaps can happen at some stage
* if you have male and female samples, one way to quickly double check the sex identity is by looking at the expression of XIST against some Y-chromosomal genes
* X-inactive specific transcript (XIST) is involved in the X-chromosome inactivation process in mammalian females and is expressed from the inactive X chromosome
* here, two female samples have lower expression of XIST, indicating a potential erosion of X chromosome
```{r XIST_vs_Y_expression, fig.width=5, fig.height=3.5}
dds <- DESeqDataSet(gse, ~1)
dds <- estimateSizeFactors(dds)
genes_x <- c("XIST")
genes_y <- c("USP9Y", "UTY", "NLGN4Y", "RPS4Y1", "TXLNGY")
genes_x <- t2g_genes[ext_gene %in% genes_x, ens_gene]
genes_y <- t2g_genes[ext_gene %in% genes_y, ens_gene]
counts_x <- counts(dds, normalized = TRUE)[genes_x, ]
counts_y <- counts(dds, normalized = TRUE)[genes_y, ]
counts_y <- apply(counts_y, 2, sum)
plot_data <- data.table(sample = names(counts_x),
XIST_logcounts = log2(counts_x),
Y_logcounts = log2(counts_y))
plot_data <- merge(plot_data, samples_meta, by = "sample")
p <- ggplot(data = plot_data, aes(x = XIST_logcounts, y = Y_logcounts, colour = sex))
p <- p + geom_point(size = 2, alpha = 0.7)
p
```
## Genotype check
* probably the best check for sample identity is possible if samples were previously genotyped (e.g. by genotyping arrays)
* variants can be identified from the RNA-seq data and compared to genotyping data
* if there are multiple samples from the same donor within the dataset, this could be double checked even without genotyping data by checking the percentage of identical variant calls from pairwise RNA-seq samples
* below is an example showing the fraction of identical variant calls from genotyping data and RNA-seq data
* note that patients PD1 and PD2 are siblings
```{r fig_genotype_heatmap}
knitr::include_graphics("./data/astro_identity_heatmap.png")
```
## PCA
* a common way to globally visualise sample gene expression profiles is by using dimensionality reduction techniques such as principal components analysis (PCA)
* it also allows to check which samples are similar to each other and spot individual outliers in the dataset
* DESeq2 comes with a basic function (`plotPCA`, which calls `prcomp`) to plot the first two principal components (PC1 and PC2), which explain most of the variance in the gene expression data
* the percentage of the total variance that is explained by each PC (direction) is included in the axes labels
* by default it uses 500 genes with the highest variance across samples (i.e. highest row variance)
***
* for more sophisticated PCA you could try, for example, the Bioconductor packages [pcaExplorer](http://bioconductor.org/packages/release/bioc/html/pcaExplorer.html) or [PCAtools](https://www.bioconductor.org/packages/release/bioc/html/PCAtools.html)
* examples of other dimensionality reduction techniques are multidimensional scaling (MDS), and especially for single-cell RNA-seq, uniform manifold approximation and projection (UMAP) and t-distributed stochastic neighbor embedding (t-SNE)
***
* note, for exploratory analysis, such as PCA, it is recommended to transform the counts to stabilize the variance across the mean so that genes with low or high counts do not overly contribute to sample-sample distances
* DESeq2 offers the variance stabilizing transformation (`vst`) and regularized-logarithm transformation (`rlog`)
```{r PCA_plots, fig.width=5, fig.height=3.5}
vsd <- vst(dds)
class(vsd)
DESeq2::plotPCA(vsd, intgroup = c("type"))
DESeq2::plotPCA(vsd, intgroup = c("sex"))
DESeq2::plotPCA(vsd, intgroup = c("name"))
```
* for example, here, you can see that sample PD1 appears as an outlier
* you can also see that sex is a factor driving sample separation along PC2
* further evaluation showed that sample PD1 shows residual pluripotency, e.g. indicated by increased expression of POU5F1 (OCT4, ENSG00000204531)
* PD1 was excluded from further analyses:
```{r exclude_sample}
gse <- gse[, samples_meta[name != "PD1", sample]]
gse
```
# Differential expression analysis
* here, we use the Bioconductor package [DESeq2](https://www.bioconductor.org/packages/release/bioc/html/DESeq2.html)
* please see the [DESeq2 vignette](https://www.bioconductor.org/packages/release/bioc/vignettes/DESeq2/inst/doc/DESeq2.html) for more details about differential expression analysis using DESeq2
* other popular methods to perform differential gene expression analysis:
+ [edgeR](https://www.bioconductor.org/packages/release/bioc/html/edgeR.html)
+ [limma with the voom method](https://www.bioconductor.org/packages/release/bioc/html/limma.html)
* first, we construct a `DESeqDataSet` object (a specific class of object used by DESeq2) from the imported and gene-level summarised data (`gse`), and using only the protein-coding genes
```{r DESeqDataSet_setup}
## select protein-coding genes
gene_info <- as.data.frame(rowData(gse))
gse <- gse[gene_info$gene_biotype == "protein_coding", ]
## correct design formula will be assigned later
dds <- DESeqDataSet(gse, design = ~1)
## the equivalent command for tximport data import:
# stopifnot(all.equal(colnames(txi$counts), samples_meta[, sample]))
# dds <- DESeqDataSetFromTximport(txi, colData = samples_meta, design = ~1)
```
* it is common to exclude lowly-expressed genes
* there are many genes (rows) with no or very few counts, with a low signal-to-noise ratio (not informative)
* here, keep genes with at least 5 counts across all samples
```{r dds_pre_filter}
# at least 5 counts across all samples
expression_cutoff <- 5
## estimate size factors to account for sequencing depth
## note, adjustment for differing library sizes does not depend on the design formula
dds <- estimateSizeFactors(dds)
cat("Number of lowly-expressed genes excluded: ",
sum(rowSums(counts(dds, normalized = TRUE)) < expression_cutoff), fill=T)
cat("Number of genes before filtering: ", nrow(dds), fill=T)
dds <- dds[rowSums(counts(dds, normalized = TRUE)) >= expression_cutoff, ]
cat("Number of genes after filtering: ", nrow(dds), fill=T)
```
## Find DEGs
* need to specify a *design formula* describing how counts depend on experimental variables
* the design formula tells which columns in the sample information table (`colData`) specify the experimental design and how these factors should be used in the analysis
* the simplest design formula would be `~ type` for the effect of disease (comparing controls vs PD cases)
* note that `type` is a column in colData(dds)
* here, we also include `sex` as an additional covariate: test for the effect of disease (type) whilst controlling for the effect of different sex
* note that DESeq2 uses the same formula notation as the `lm` function of base R to fit linear models
* a formula starts with a tilde `~` followed by the variables with plus signs between them
* variables for experimental design are encoded as factors
* by default, the last variable in the formula is used for building results tables
* it is recommended to use the reference level (control or untreated samples) as first level of a factor (here, `CT` as the reference level of the factor `type`)
```{r dds_design}
dds$type <- factor(dds$type, levels = c("CT", "PD"))
dds$sex <- factor(dds$sex)
d <- "~ sex + type"
design(dds) <- formula(d)
```
* run the standard differential expression analysis by calling `DESeq`:
```{r run_DESeq}
dds <- DESeq(dds)
```
* get the results table via `results()` for a pecified a significance threshold
* the comparison we are interested in is specified by the `contrast` argument
```{r get_results}
# adjusted p-value threshold (padj), 5% significance level, FDR level of 5%
alpha_cutoff <- 0.05
res <- results(dds, alpha = alpha_cutoff, contrast = c("type", "PD", "CT"))
## add shrunken LFCs to results table, "apeglm", "ashr" require extra packages
## apeglm is the new default
res <- lfcShrink(dds, contrast = c("type", "PD", "CT"), res = res, type = "normal")
summary(res)
```
* the object containing the results (`res`, a *DataFrame* object) contains a number of columns:
```{r results_columns}
res_columns <- as.data.frame(mcols(res, use.names = TRUE))
res_columns
```
* baseMean: average of the (normalised) count values, divided by the size factors, taken over *all* samples
* log2FoldChange: effect size estimate on log2 scale
* log2 FC = 1 means the gene’s expression is increased by a factor of 2
* log2 FC = -1 means the gene’s expression is decreased by a factor of 2 (multiplicative change of 0.5)
## DEGs table
* it is useful to report the list of DEGs based on a significance threshold
* again we use `DT::datatable` to have a table we can easily search, sort and copy
```{r deg_table, cache=F}
res_dt <- as.data.table(res)
res_dt <- res_dt[, ens_gene := rownames(res)]
res_dt <- res_dt[padj < alpha_cutoff, ]
res_dt <- res_dt[, c("lfcSE", "stat") := NULL]
res_dt <- merge(res_dt, t2g_genes[, .(ens_gene, ext_gene, desc)], by = "ens_gene")
res_dt <- res_dt[, c("log2FoldChange", "pvalue", "padj") :=
list(signif(log2FoldChange, 3), signif(pvalue, 3), signif(padj, 3))]
res_dt <- res_dt[, baseMean := round(baseMean, digits=1)]
setcolorder(res_dt, c("ens_gene", "ext_gene", "log2FoldChange", "pvalue", "padj", "baseMean", "desc"))
setnames(res_dt, "desc", "______________gene_description______________")
setnames(res_dt, "log2FoldChange", "log2FC")
setnames(res_dt, "padj", "pval_adj")
res_dt <- res_dt[order(pval_adj)]
res_dt %>%
DT::datatable(caption = "DESeq PD vs CT",
escape = F,
rownames = F,
extensions = 'Buttons',
options = list(dom = 'Blfrtip',
buttons = list('colvis',
list(extend = 'copy', exportOptions = list(columns=':visible')),
list(extend = 'csv', exportOptions = list(columns=':visible')),
list(extend = 'excel', exportOptions = list(columns=':visible')))))
```
## PCA based on DEGs
* performing PCA on the DEGs should separate the samples by type:
```{r PCA_using_DEGs, fig.width=5, fig.height=3.5}
vsd <- vst(dds)
vsd_subset <- vsd[(rownames(vsd) %in% res_dt[, ens_gene]), ]
plotPCA(vsd_subset, intgroup = c("type"))
```
## Pot top DEGs
* check the expression levels of the top DEGs
* DESeq2 provides a simple function `plotCounts` for single genes:
```{r plot_DEGs, fig.width=4, fig.height=4}
plotCounts(dds, gene = "ENSG00000164692", intgroup = c("type"))
```
* plot top 10 down-regulated genes
* showing gene symbols instead of ensembl IDs (gene symbols shown alphabetically)
```{r top_10_down, fig.width=9, fig.height=5}
res_dt <- res_dt[order(pval_adj)]
plot_genes <- res_dt[log2FC < 0, ens_gene][1:10]
counts_dt <- data.table(log2(counts(dds[plot_genes, ], normalized = TRUE) + 1),
keep.rownames = TRUE)
setnames(counts_dt, "rn", "ens_gene")
counts_dt <- melt(counts_dt, id.vars = "ens_gene")
counts_dt <- merge(counts_dt, samples_meta[, .(sample, type, sex)],
by.x = "variable", by.y = "sample")
counts_dt <- merge(counts_dt, t2g_genes[, .(ens_gene, ext_gene)],
by = "ens_gene")
p <- ggplot(data = counts_dt, aes(x = type, y = value, color = sex))
p <- p + geom_violin(aes(group = type), alpha = 0, colour = "gray60", scale = "width")
p <- p + geom_point(position = position_jitterdodge(), size = 2, alpha=0.7)
p <- p + facet_wrap(~ext_gene, scales = "free_y", ncol = 5)
p <- p + xlab(NULL) + ylab("log2(normalised counts + 1)")
p <- p + theme(legend.position="top")
p
```
* and the top 10 up-regulated genes
```{r top_10_up, fig.width=9, fig.height=5}
plot_genes <- res_dt[log2FC > 0, ens_gene][1:10]
counts_dt <- data.table(log2(counts(dds[plot_genes, ], normalized = TRUE) + 1),
keep.rownames = TRUE)
setnames(counts_dt, "rn", "ens_gene")
counts_dt <- melt(counts_dt, id.vars = "ens_gene")
counts_dt <- merge(counts_dt, samples_meta[, .(sample, type, sex)],
by.x = "variable", by.y = "sample")
counts_dt <- merge(counts_dt, t2g_genes[, .(ens_gene, ext_gene)],
by = "ens_gene")
p <- ggplot(data = counts_dt, aes(x = type, y = value, color = sex))
p <- p + geom_violin(aes(group = type), alpha = 0, colour = "gray60", scale = "width")
p <- p + geom_point(position = position_jitterdodge(), size = 2, alpha=0.7)
p <- p + facet_wrap(~ext_gene, scales = "free_y", ncol = 5)
p <- p + xlab(NULL) + ylab("log2(normalised counts + 1)")
p <- p + theme(legend.position="top")
p
```
***
## Volcano plot
* a typical global visualisation of differential expression results is a *volcano plot*
* log2 fold changes are plotted on the x-axis against log transformed p-values on the y-axis (i.e. effect size vs statistical signficance)
* for advanced volcano plots [EnhancedVolcano](https://bioconductor.org/packages/release/bioc/html/EnhancedVolcano.html) can be used
* it comes with many configuration options, see the [vignette](https://bioconductor.org/packages/release/bioc/vignettes/EnhancedVolcano/inst/doc/EnhancedVolcano.html) for further details
```{r enhanced_volcano_1, fig.width=7, fig.height=7}
EnhancedVolcano(res,
lab = rownames(res),
x = 'log2FoldChange',
y = 'pvalue')
```
* it's probably better to use gene symbols:
```{r enhanced_volcano_2, fig.width=7, fig.height=7}
res_dt_all <- as.data.table(res)
res_dt_all <- res_dt_all[, ens_gene := rownames(res)]
res_dt_all <- merge(res_dt_all, t2g_genes[, .(ens_gene, ext_gene, desc)], by = "ens_gene")
EnhancedVolcano(res_dt_all,
lab = res_dt_all$ext_gene,
x = 'log2FoldChange',
y = 'pvalue')
```
***
## Gene Ontology enrichment
* a common functional analysis step is the enrichment analysis for Gene Ontology terms
* there are several R packages that could be used for over-representation analysis, for example [topGO](https://bioconductor.org/packages/release/bioc/html/topGO.html) or [clusterProfiler](https://bioconductor.org/packages/release/bioc/html/clusterProfiler.html)
* here, use package clusterProfiler with all DEGs as input
* background (gene universe): all genes not filtered by DESeq2
***
* note, there is an issue with loading clusterProfiler in the Binder environment:
>Error: package 'DO.db' was installed before R 4.0.0: please re-install it
* force the installation of the `DO.db` package, after that clusterProfiler should work
* **however, R session errors come up in Binder running `enrichGO()`, so probably something for you to explore on your local machines**
* please see the HTML output file for table and plot from clusterProfiler
```{r clusterProfiler_workaround_binder}
# Error: package or namespace load failed for 'clusterProfiler':
# package 'DO.db' was installed before R 4.0.0: please re-install it
# BiocManager::install("DO.db", force = TRUE)
# library(clusterProfiler)
```
```{r clusterProfiler}
library(clusterProfiler)
## background of expressed genes
genes_universe <- res_dt_all[!(is.na(padj)), ens_gene]
## use all DEGs, could be filtered by direction (up vs down) or minimum absolute log2FC
genes_test <- res_dt$ens_gene
## takes a minute or two to run
go_enrich <-
enrichGO(
gene = genes_test,
universe = genes_universe,
keyType = "ENSEMBL",
OrgDb = "org.Hs.eg.db",
ont = "BP",
pAdjustMethod = "BH",
pvalueCutoff = 0.05,
qvalueCutoff = 0.05,
maxGSSize = 500
)
## show all signficant terms in a table
go_enrich_print <- data.table(data.frame(go_enrich))
go_enrich_print <- go_enrich_print[, .(ID, qvalue, GeneRatio, BgRatio, Description)]
go_enrich_print <- go_enrich_print[, qvalue := signif(qvalue, 3)]
go_enrich_print %>%
DT::datatable(caption = "GO:BP enrichment",
escape = F,
rownames = F,
extensions = 'Buttons',
options = list(dom = 'Blfrtip',
buttons = list('colvis',
list(extend = 'copy', exportOptions = list(columns=':visible')),
list(extend = 'csv', exportOptions = list(columns=':visible')),
list(extend = 'excel', exportOptions = list(columns=':visible')))))
```
* enrichment results can be visualised by a dot plot showing the most enriched pathways:
```{r plot_enrichment_results, fig.width=9, fig.height=3.5}
dotplot(go_enrich, showCategory = 10)
```
## Other tools
* there are also many online tools for gene set or ontology analysis
* here are some examples:
+ [DAVID](https://david.ncifcrf.gov)
+ [GORilla](http://cbl-gorilla.cs.technion.ac.il)
+ [GeneTrail](https://genetrail.bioinf.uni-sb.de/start.html)
+ [g:Profiler](https://biit.cs.ut.ee/gprofiler/gost]), also comes with an R interface [grprofiler2](https://cran.r-project.org/web/packages/gprofiler2/index.html)
# SessionInfo
```{r session_info, cache=F}
sessionInfo()
## devtools::session_info()
```<file_sep>#!/bin/bash
INPUT_DIR="../data/Fastq_files/Fastq_training_subsample_100K/"
OUTPUT_DIR="../output_training/Salmon_mapping/Salmon_quant_110_ensembl_v99_noalt_k31_100K_chr10/"
SALMON_IDX="../data/Salmon_index/salmon_idx_ensembl_GRCh38_cdna_ncrna_v99_noalt_k31_chr10"
mkdir -p $OUTPUT_DIR
for R1 in $INPUT_DIR*1.fastq.gz;
do
R2=$(echo $R1 | sed 's/1.fastq.gz/2.fastq.gz/')
OUT=$OUTPUT_DIR""$(basename $R1 '_1.fastq.gz')
salmon quant -i $SALMON_IDX \
--libType A \
-1 $R1 \
-2 $R2 \
-o $OUT \
-p 2
done
<file_sep># Workshop: Introduction to bulk RNA-seq data analysis
The main document of the workshop is written in R Markdown producing an HTML file as output.
Some shell scripts are also provided as part of the workshop material highlighting the use of some external tools before entering R for data analysis.
Here is the output HTML: https://frankwessely.github.io/RNAseq_workshop/
Please open the link below in a new tab to run RStudio via mybinder.org and access the R Markdown file by clicking on `Intro_RNAseq.Rmd` in the bottom right pane.
It my take a few minutes to launch RStudio.
<!-- badges: start -->
[](https://mybinder.org/v2/gh/frankwessely/RNAseq_workshop/main?urlpath=rstudio)
<!-- badges: end -->
| a99c39683d8095e2df907dc9c3a7bc0264a42328 | [
"Markdown",
"RMarkdown",
"Shell"
] | 6 | Shell | frankwessely/RNAseq_workshop | 2666240546b3f794096a72f194adf92a6b46a003 | 4df216095cef6d055cca9e8e70754320c6f2a31b |
refs/heads/master | <file_sep>package com.inboundrx.paulsensbeaconsapp.sourceCode.ui;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import com.inboundrx.paulsensbeaconsapp.R;
import butterknife.Bind;
import butterknife.ButterKnife;
public class UserActivity extends AppCompatActivity implements View.OnClickListener{
@Bind(R.id.aboutButton) ImageView mAboutButton;
@Bind(R.id.homeButton) ImageView mHomeButton;
@Bind(R.id.rewardsButton) ImageView mRewardsButton;
@Bind(R.id.historyButton) ImageView mHistoryButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user);
ButterKnife.bind(this);
mAboutButton.setOnClickListener(this);
mHomeButton.setOnClickListener(this);
mRewardsButton.setOnClickListener(this);
mHistoryButton.setOnClickListener(this);
}
@Override
public void onClick(View v){
if (v == mAboutButton){
Intent intent = new Intent(UserActivity.this, AboutActivity.class);
startActivity(intent);
}
if (v == mRewardsButton){
Intent intent = new Intent(UserActivity.this, RewardsActivity.class);
startActivity(intent);
}
if (v == mHistoryButton){
Intent intent = new Intent(UserActivity.this, HistoryActivity.class);
startActivity(intent);
}
if (v == mHomeButton){
Intent intent = new Intent(UserActivity.this, LandingActivity.class);
startActivity(intent);
}
}
}
<file_sep>package com.inboundrx.paulsensbeaconsapp.sourceCode.ui;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.inboundrx.paulsensbeaconsapp.R;
import com.inboundrx.paulsensbeaconsapp.sourceCode.StringConstants;
import butterknife.Bind;
import butterknife.ButterKnife;
public class AboutActivity extends AppCompatActivity implements View.OnClickListener {
@Bind(R.id.aboutButton) ImageView mAboutButton;
@Bind(R.id.homeButton) ImageView mHomeButton;
@Bind(R.id.rewardsButton) ImageView mRewardsButton;
@Bind(R.id.historyButton) ImageView mHistoryButton;
@Bind(R.id.paulsensInfo) TextView mPaulsensInfo;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_about);
ButterKnife.bind(this);
mAboutButton.setOnClickListener(this);
mHomeButton.setOnClickListener(this);
mRewardsButton.setOnClickListener(this);
mHistoryButton.setOnClickListener(this);
mPaulsensInfo.setText(StringConstants.PAULSENS_BIO
+ StringConstants.PAULSENS_HOURS
+ StringConstants.PAULSENS_WEBSITE
+ StringConstants.PAULSENS_ADDRESS
+ StringConstants.PAULSENS_PHONE);
}
@Override
public void onClick(View v){
if (v == mAboutButton){
Intent intent = new Intent(AboutActivity.this, AboutActivity.class);
startActivity(intent);
}
if (v == mRewardsButton){
Intent intent = new Intent(AboutActivity.this, RewardsActivity.class);
startActivity(intent);
}
if (v == mHistoryButton){
Intent intent = new Intent(AboutActivity.this, HistoryActivity.class);
startActivity(intent);
}
if (v == mHomeButton){
Intent intent = new Intent(AboutActivity.this, LandingActivity.class);
startActivity(intent);
}
}
}
<file_sep>package com.inboundrx.paulsensbeaconsapp.sourceCode.ui;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.inboundrx.paulsensbeaconsapp.R;
import com.inboundrx.paulsensbeaconsapp.sourceCode.managers.BeaconRangingManager;
public class RewardsActivity extends AppCompatActivity {
private BeaconRangingManager beaconFinder = new BeaconRangingManager();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rewards);
beaconFinder.findBeacon(this);
}
}
<file_sep>package com.inboundrx.paulsensbeaconsapp.sourceCode;
import com.inboundrx.paulsensbeaconsapp.BuildConfig;
/**
* Created by arlen on 7/12/17.
*/
public class BaseConstants {
public static final String BEACON_UUID = BuildConfig.BEACON_UUID;
}
<file_sep>package com.inboundrx.paulsensbeaconsapp.sourceCode.ui;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.estimote.sdk.BeaconManager;
import com.estimote.sdk.Region;
import com.estimote.sdk.SystemRequirementsChecker;
import com.inboundrx.paulsensbeaconsapp.R;
import com.inboundrx.paulsensbeaconsapp.sourceCode.interfaces.BeaconCallback;
import com.inboundrx.paulsensbeaconsapp.sourceCode.managers.BeaconRangingManager;
import butterknife.Bind;
import butterknife.ButterKnife;
public class LandingActivity extends AppCompatActivity implements View.OnClickListener, BeaconCallback{
@Bind(R.id.aboutButton) ImageView mAboutButton;
@Bind(R.id.homeButton) ImageView mHomeButton;
@Bind(R.id.rewardsButton) ImageView mRewardsButton;
@Bind(R.id.historyButton) ImageView mHistoryButton;
private BeaconRangingManager beaconFinder = new BeaconRangingManager();
private BeaconManager beaconManager;
private Region region;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_landing);
ButterKnife.bind(this);
mAboutButton.setOnClickListener(this);
mHomeButton.setOnClickListener(this);
mRewardsButton.setOnClickListener(this);
mHistoryButton.setOnClickListener(this);
beaconFinder.findBeacon(this);
}
public void beaconCallBack() {
System.out.println("I've been called back");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.user_account_menu, menu);
return super.onCreateOptionsMenu(menu);
}
public boolean onOptionsItemSelected(MenuItem item){
int id = item.getItemId();
if (id == R.id.action_user){
Intent intent = new Intent(LandingActivity.this, UserActivity.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onClick(View v){
if (v == mAboutButton){
Intent intent = new Intent(LandingActivity.this, AboutActivity.class);
startActivity(intent);
}
if (v == mRewardsButton){
Intent intent = new Intent(LandingActivity.this, RewardsActivity.class);
startActivity(intent);
}
if (v == mHistoryButton){
Intent intent = new Intent(LandingActivity.this, HistoryActivity.class);
startActivity(intent);
}
if (v == mHomeButton){
Intent intent = new Intent(LandingActivity.this, LandingActivity.class);
startActivity(intent);
}
}
@Override
protected void onPause(){
beaconFinder.beaconPause();
super.onPause();
}
@Override
protected void onResume() {
super.onResume();
beaconFinder.beaconResume();
SystemRequirementsChecker.checkWithDefaultDialogs(this);
}
}
<file_sep>package com.inboundrx.paulsensbeaconsapp.sourceCode.managers;
import android.content.Context;
import android.util.Log;
import com.estimote.sdk.Beacon;
import com.estimote.sdk.BeaconManager;
import com.estimote.sdk.Region;
import com.inboundrx.paulsensbeaconsapp.sourceCode.BaseConstants;
import com.inboundrx.paulsensbeaconsapp.sourceCode.interfaces.BeaconCallback;
import com.inboundrx.paulsensbeaconsapp.sourceCode.interfaces.Caller;
import com.inboundrx.paulsensbeaconsapp.sourceCode.ui.LandingActivity;
import java.util.List;
import java.util.UUID;
/**
* Created by arlen on 7/17/17.
*/
public class BeaconRangingManager {
private LandingActivity landingActivity;
private BeaconManager beaconManager;
private Caller caller;
private Region region;
private boolean stringDecider;
private String foundBeacon;
public void findBeacon(Context context){
beaconManager = new BeaconManager(context);
beaconManager.setRangingListener(new BeaconManager.RangingListener() {
@Override
public void onBeaconsDiscovered(Region region, List<Beacon> list) {
if (!list.isEmpty()) {
final String[] beacons = new String[]{"Found Beacon", "No Beacon"};
Log.d("Paulsons Beaon App: ", BaseConstants.BEACON_UUID);
Caller.main(beacons);
}
}
});
region = new Region("ranged region", UUID.fromString(BaseConstants.BEACON_UUID), null, null);
}
public void beaconResume(){
beaconManager.connect(new BeaconManager.ServiceReadyCallback(){
@Override
public void onServiceReady(){
beaconManager.startRanging(region);
}
});
}
public void beaconPause(){
beaconManager.stopRanging(region);
}
}
<file_sep>package com.inboundrx.paulsensbeaconsapp.sourceCode.services;
/**
* Created by arlen on 7/12/17.
*/
public class WebRequest {
// public static void dataRequest(String /*placeholder*/, Callback callback){
// OkHttpClient client = new OkHttpClient.Builder().build();
// HttpUrl.Builder urlBuilder = HttpUrl.parse(BaseConstants.BASE_URL).newBuilder();
// urlBuilder.addQueryParameter(StringConstants.ENDPOINT_QUERY, /*placeholder*/)
// .addQueryParameter(StringConstants.ENDPOINT_KEYWORD, StringConstants.ENDPOINT_TYPE)
// .addQueryParameter(StringConstants.KEY_PARAM, StringConstants.);
// String url = urlBuilder.build().toString();
// Request request = new Request.Builder().url(url).build();
// Call call = client.newCall(request);
// call.enqueue(callback);
// }
// public ArrayList</*placeholder*/> processResults(Response response){
// ArrayList</*placeholder*/> beers = new ArrayList<>();
//
// try{
// String jsonData = response.body().string();
// if (response.isSuccessful()){
// JSONObject allDataJSON = new JSONObject(jsonData);
// JSONArray resultsJSON = allDataJSON.getJSONArray("data");
// for (int i = 0; i < resultsJSON.length(); i++){
// JSONObject dataJSON = resultsJSON.getJSONObject(i);
// }
// }
// } catch (IOException e) {
// e.printStackTrace();
// } catch (JSONException e) {
// e.printStackTrace();
// }
// return /*placeholder*/;
// }
}
| 6b3fe41726a2783a69f0fbe847bdeb928b37836c | [
"Java"
] | 7 | Java | BurtonArlen/PaulsonsAppAndroid | 8e13efe926acb797b37a65d562e1023123aa02a1 | 3b6e8ac461c485c11863a2e9ed6d200816171da1 |
refs/heads/Stratos_series | <repo_name>Atomix85/LinkNet<file_sep>/LinkNet Series/src/org/piwel/linknet/mlp/NeuralSystem.java
package org.piwel.linknet.mlp;
import java.text.DecimalFormat;
import org.piwel.linknet.graphic.Window;
import org.piwel.linknet.parser.header.HeaderHandler;
import org.piwel.linknet.parser.header.HeaderEvaluationException;
public class NeuralSystem implements Runnable {
DataCollection data;
DataPoint currentDataPoint;
NeuralNetwork network;
String[] header;
HeaderHandler headerHandler;
IHM ihm;
public boolean isRunning = true;
public int i;
Window win;
int nbOutputs;
double learningRate = 1f;
double maxError = 0.005;
int maxIterations = 10001;
double errorRate = Double.POSITIVE_INFINITY;
/**
*
* @return L'exemple en train d'être testé par le programme
*/
public DataPoint getCurrentDataPoint() {
return currentDataPoint;
}
/**
*
* @return Le taux d'erreur actuel
*/
public double getErrorRate() {
return errorRate;
}
/**
*
* @return Le réseau de neurone
*/
public NeuralNetwork getNeuralNetwork() {
return network;
}
/**
*
* @return L'ensemble des exemples
*/
public DataCollection getDataCollection() {
return data;
}
/**
*
*
* @param nbInputs Nombre de neurones d'entrée
* @param nbHidden Nombre de neurones dans le calque caché
* @param nbOutputs Nombre de neurones de sortie
* @param data Les lignes de l'exemple à utiliser
* @param trainingRatio Le ratio d'entrainement
* @param ihm IHM à utiliser
*/
public NeuralSystem(int nbInputs, int[] nbHidden, int nbOutputs, DataCollection datapoints, double trainingRatio)
{
IHM.info("Making Neural System...");
long time = System.currentTimeMillis();
this.nbOutputs = nbOutputs;
network = new NeuralNetwork(nbInputs, nbHidden, nbOutputs);
this.data = datapoints;
IHM.info("Neural System done in "+ (int) (System.currentTimeMillis() - time) +" ms !");
}
/**
* Change le taux d'apprentissage du système
*
* @param rate Le nouveau taux d'apprentissage
*/
public void learningRate(double rate)
{
learningRate = rate;
}
/**
*
* Change le taux d'erreur maximal où le programme s'arrêtera par défaut
*
* @param error Nouveau taux d'erreur maximal
*/
public void maximumError(double error)
{
maxError = error;
}
/**
*
* Change le nombre d'itération maximal où le programme pourra s'arrêter
*
* @param iterations Nouveau nombre d'itération maximal
*/
public void maximumIterations(int iterations)
{
maxIterations = iterations;
}
/**
*
* Ajoute au système un header pour indiquer les paramètres et le nom des neurones d'entrée/sortie
*
* @param head Ligne du header
*/
public void addHeaderFile(String[] head)
{
header = head;
try {
headerHandler = new HeaderHandler(head);
} catch (HeaderEvaluationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
*
* Lie une interface Window au système neural (facultatif)
*
* @param win Interface Window
*/
public void addWindow(Window win) {
this.win = win;
}
/**
*
* Change toutes les secondes l'exemple à tester. Tout le système neural sera actualisé mais l'apprentissage
* est empêché pour éviter la généralisation.
*
*/
public void testInput() {
try {
while(true) {
for (DataPoint point : data.points())
{
if(win != null && !win.autoMode) {
return;
}
currentDataPoint = point;
if(win != null) {
win.reDraw();
}
Thread.sleep(1000);
}
}
}catch(InterruptedException ex) {}
}
/**
*
* Actualise tout le sytème neural selon l'exemple donné en paramètre
*
* @param value Ligne contenant les entrées (et sorties) de l'exemple
*/
public void testInput(double[] value) {
DataPoint point = new DataPoint(value, this.nbOutputs);
double[] outputs = network.evaluate(point);
currentDataPoint = point;
String msg = "";
for(int i = 0; i < point.getInputs().length; i++)
{
msg += "Input " + (i+1) + "="+ point.getInputs()[i] + "\t"; //Deprecated
}
msg += "\n";
for(int i = 0; i < outputs.length; i++)
{
msg += "Output " + (i+1) + "="+ outputs[i] + "\t"; //Deprecated
}
//msg += "Output " + header[header.length - nbOutputs/8 + outNb] + "=" + heaviside(error); //Deprecated
IHM.info(msg);
}
/**
*
* Permet d'obtenir les valeurs de sortie pour chaque exemple donné selon le système neural formé
*
* @param isApplyHeavyside Est-ce que la valeur de sortie est arrondie selon heavyside
*/
@Deprecated
public void test(boolean isApplyHeavyside)
{
for (DataPoint point : data.points())
{
double[] outputs = network.evaluate(point);
for (int outNb = 0; outNb < outputs.length; outNb++)
{
double error = outputs[outNb];
String msg = "";
for(int i = 0; i < point.getInputs().length; i++)
{
msg += "Input " + (i+1) + "="+ point.getInputs()[i] + "\t";
}
if (isApplyHeavyside)
{
msg += "Output " + header[header.length - nbOutputs + outNb] + "=" + heaviside(error);
}
else
{
msg += "Output " + header[header.length - nbOutputs + outNb] + "=" + error;
}
IHM.info(msg);
}
}
}
/**
*
* Arrondie la valeur en paramètre
*
* @param value Valeur à tester
* @return Valeur entière retourné
*/
@Deprecated
private int heaviside(double value)
{
if(value >= 0.5)
{
return 1;
}
else
{
return 0;
}
}
/**
*
* Permet au système neural d'apprendre selon les exemples fournis. Les poids des neurones seront ainsi adapter pour
* diminuer les erreurs au minimum
*
*/
@SuppressWarnings("deprecation")
public void run()
{
try {
i = 0;
double totalError = Double.POSITIVE_INFINITY;
double oldError = Double.POSITIVE_INFINITY;
double totalGeneralisationError = Double.POSITIVE_INFINITY;
double oldGeneratlisationError = Double.POSITIVE_INFINITY;
boolean betterGeneralisation = true;
while(i < this.maxIterations && totalError > maxError && betterGeneralisation)
{
long time = System.nanoTime();
oldError = totalError;
totalError = 0;
oldGeneratlisationError = totalGeneralisationError;
totalGeneralisationError = 0;
currentDataPoint = data.points()[data.points().length-1];
for(DataPoint point : data.points())
{
double[] outputs = network.evaluate(point);
for(int outNb = 0; outNb < outputs.length; outNb++)
{
double error = point.getOutputs()[outNb] - outputs[outNb];
totalError += (error * error);
}
network.adjustWeight(point, learningRate);
}
for(DataPoint point : data.generalisationPoints())
{
double[] outputs = network.evaluate(point);
for(int outNb = 0; outNb < outputs.length; outNb++)
{
double error = point.getOutputs()[outNb] - outputs[outNb];
totalGeneralisationError += (error * error);
}
}
if(totalGeneralisationError > oldGeneratlisationError)
{
betterGeneralisation = false;
}
if(totalError >= oldError)
{
learningRate = learningRate / 2;
}
errorRate = Math.sqrt(totalError / data.points().length) * 100;
IHM.info("Iteration n°" + i + " - In "+(int)(System.nanoTime()-time)+" ms - Rate " + learningRate + " - Mean : " + new DecimalFormat("#.##").format(errorRate) + " %");
i++;
if(i % 10 == 0) {
if(win != null)
win.reDraw();
}
}
Thread.sleep(10);
isRunning = false;
IHM.info("Test image 1 " + network.getOutputNeurons()[0].getOutput() + " - " + network.getOutputNeurons()[1].getOutput());
}catch(Exception ex) {
ex.printStackTrace();
}
}
}
<file_sep>/LinkNet Series/src/org/piwel/linknet/parser/header/HeaderEvaluationException.java
package org.piwel.linknet.parser.header;
public class HeaderEvaluationException extends Throwable {
}
<file_sep>/LinkNet Series/src/org/piwel/linknet/mlp/DataCollection.java
package org.piwel.linknet.mlp;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
/**
*
* @author Atomix
*
* Cette classe encapsule certains (ou tous les) exemples DataPoint depuis le taux d'entrainement
* Ces valeurs seront ainsi rangées dans un ordre aléatoire
*
*
*/
public class DataCollection {
private DataPoint[] trainingPoints;
private DataPoint[] generalisationPoints;
/**
*
* @return Tableau des exemples d'entrainement
*/
public DataPoint[] points()
{
return trainingPoints;
}
/**
* @deprecated
* @return Tableau des exemples de généralisation (inutilisé depuis LN-2)
*/
@Deprecated
public DataPoint[] generalisationPoints()
{
return generalisationPoints;
}
/**
* Constructeur de la classe. Il permet de sélectionner un taux d'exemples et de les répartir aléatoirement dans trainingPoint
*
* @param content Contenu du fichier (header homis)
* @param outputNb Nombre de valeurs de sortie (masque de séparation I/O)
* @param trainingRatio Taux d'exemple à tester par génération (ex : 0.2 : 1/5 des exemples de contenu; 1 : tous les exemples de contenu)
*/
public DataCollection(double[][] content, int outputNb, double trainingRatio)
{
int nbLines = content.length;
List<DataPoint> points = new ArrayList<DataPoint>();
for(int i = 0; i < nbLines; i++)
{
DataPoint dp = new DataPoint(content[i], outputNb);
points.add(dp);
}
int nbTrainingPoints = (int)(trainingRatio * nbLines);
trainingPoints = new DataPoint[nbTrainingPoints];
Random rand = new Random();
for(int i = 0; i < nbTrainingPoints; i++)
{
int index = rand.nextInt(points.size());
trainingPoints[i] = points.get(index);
points.remove(index);
}
generalisationPoints = points.toArray(new DataPoint[0]);
}
}
<file_sep>/LinkNet Series/src/org/piwel/linknet/LinkNet.java
package org.piwel.linknet;
import org.piwel.linknet.mlp.NeuralSystem;
import org.piwel.linknet.util.DatasetFileProvider;
import org.piwel.linknet.data.SimpleData;
import org.piwel.linknet.data.image.BMPFormatter;
import org.piwel.linknet.graphic.Window;
import org.piwel.linknet.mlp.IHM;
public class LinkNet{
private final String version = "alpha-3.0";
private static String filename;
Window win;
//L'appel du programme
private LinkNet() {
IHM.info("Init Stratos " + version);
}
public static void main(String[] args) {
filename = args[0];
//BMPFormatter format = new BMPFormatter("datasets/test.bmp");
LinkNet linkNet = new LinkNet();
linkNet.run();
}
private void run()
{
DatasetFileProvider dataset = new DatasetFileProvider(filename);
SimpleData datas = dataset.getDatas();
NeuralSystem system = new NeuralSystem(datas.nbNeuronIn,datas.nbMiddleHiddenNeuron,datas.nbNeuronOut , datas.getDatapoints(), 1);
//win = new Window("Stratos Graphic");
//win.linkToMLP(system);
//win.setVisible(true);
//system.addWindow(win);
system.run();
}
}
<file_sep>/LinkNet Series/src/org/piwel/linknet/mlp/IHM.java
package org.piwel.linknet.mlp;
import java.util.Date;
/**
*
* @author Atomix
*
*Cette interface permet de gérer les flux de sortie.
*
*/
public class IHM {
/**
*
* @param msg Chaine de caractère à afficher ou enregistrer
*/
@SuppressWarnings("deprecation")
public static void info(String msg) {
System.out.println("["+(new Date()).toGMTString()+"] [INFO] - " + msg);
}
}
<file_sep>/LinkNet Series/src/org/piwel/linknet/data/SimpleData.java
package org.piwel.linknet.data;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.piwel.linknet.mlp.DataCollection;
import org.piwel.linknet.mlp.IHM;
import org.piwel.linknet.util.ParserUtil;
public abstract class SimpleData {
public final String name;
public int nbNeuronIn;
public int nbNeuronOut;
public final int[] nbMiddleHiddenNeuron;
protected DataCollection datapoints;
public SimpleData(JSONObject json) {
this.name = json.get("name").toString();
JSONArray array = (JSONArray) json.get("nbHN");
this.nbMiddleHiddenNeuron = new int[array.size()];
for(int i = 0; i < array.size();i++) {
this.nbMiddleHiddenNeuron[i] = ParserUtil.objectToInt(array.get(i));
}
this.nbNeuronIn = ParserUtil.objectToInt(json.get("nbIN"));
this.nbNeuronOut = ParserUtil.objectToInt(json.get("nbOUT"));
long time = System.currentTimeMillis();
IHM.info("Entrance MakeDataPoint of " + name + " of type "+this.getClass());
makeDataPoint((JSONArray) json.get("datas"));
IHM.info("Exit MakeDataPoint in "+ (int) (System.currentTimeMillis()-time) + " ms");
}
public abstract void makeDataPoint(JSONArray array);
public DataCollection getDatapoints() {
return datapoints;
}
}
| 435c738db868a33738818c001bede41544759be6 | [
"Java"
] | 6 | Java | Atomix85/LinkNet | b0d4253aed766ba9f259d7d544c2e2edd11221c9 | a457ebf84cae773c1570a3749ff6ac8353b9795b |
refs/heads/master | <repo_name>absaw/Surface-Water-Quality-Data-Anomaly-Detection<file_sep>/Code/Dissolved Oxygen.py
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 17 10:53:52 2020
@author: admin
"""
#%%
import numpy as np
import matplotlib.pyplot as mp
import pandas as pd
from pandas import datetime
from sklearn.preprocessing import Imputer
from pandas.plotting import autocorrelation_plot
from matplotlib import pyplot
from statsmodels.tsa.arima_model import ARIMA
from sklearn.model_selection import train_test_split as tts
from statsmodels.tsa.stattools import adfuller
from statsmodels.tsa.stattools import acf, pacf
from statsmodels.tsa.seasonal import seasonal_decompose
import matplotlib.pylab as plt #for visualization
from sklearn.metrics import mean_squared_error
#%%
def input_data():
def parser(x):
return datetime.strptime(x,'%Y-%m-%d %H:%M')
dataset = pd.read_csv('Data8.csv',header=0, delimiter=',',index_col=0, parse_dates=[0], date_parser=parser)
dataset = dataset.fillna(method ='pad')
do = dataset.filter(['DO(mg/L)'], axis=1)
train_size,test_size = 1000, 1396
do_train,do_test = tts(do,test_size = test_size, random_state=0, shuffle=False)
#dataset.fillna(method ='bfill')
#%%
def check_adfuller(att):
#Perform Augmented Dickey–Fuller test:
print('Results of Dickey Fuller Test:')
print("--------For a stationary time series Test statistic is less than critical values-----------")
dftest = adfuller(att, autolag='AIC')
dfoutput = pd.Series(dftest[0:4], index=['Test Statistic','p-value','#Lags Used','Number of Observations Used'])
for key,value in dftest[4].items():
dfoutput['Critical Value (%s)'%key] = value
print(dfoutput)
#%%
def check_mean_std(ts, name):
rolmean = ts.rolling(window=192).mean()
rolstd = ts.rolling(window=192).std()
plt.figure(figsize=(12,8))
print(name)
orig = plt.plot(ts, color='red',label='Original')
mean = plt.plot(rolmean, color='black', label='Rolling Mean')
std = plt.plot(rolstd, color='green', label = 'Rolling Std')
plt.xlabel("Date")
plt.ylabel("Dissolved Oxygen")
plt.title('Rolling Mean & Standard Deviation')
plt.legend()
plt.show()
#%%
def acf_pacf_plots(dataset):
ts_diff = dataset - dataset.shift()
ts_diff.dropna(inplace=True)
lag_acf = acf(ts_diff, nlags=20)
lag_pacf = pacf(ts_diff, nlags=20, method='ols')
# ACF
plt.figure(figsize=(22,10))
plt.subplot(121)
plt.plot(lag_acf)
plt.axhline(y=0.4,linestyle='--',color='gray')
plt.axhline(y=0.3,linestyle='--',color='gray')
plt.axhline(y=0.2,linestyle='--',color='gray')
plt.title('Autocorrelation Function')
# PACF
plt.subplot(122)
plt.plot(lag_pacf)
plt.axhline(y=0.4,linestyle='--',color='gray')
plt.axhline(y=0.3,linestyle='--',color='gray')
plt.axhline(y=0.2,linestyle='--',color='gray')
plt.title('Partial Autocorrelation Function')
plt.tight_layout()
#%%
def arima_model(ts, order):
# fit model
model = ARIMA(ts, order=order) # (ARMA) = (p,d,q)
model_fit = model.fit(disp=0)
# predict
forecast = model_fit.predict(start=1000, end=2396)
# visualization
plt.figure(figsize=(12,8))
plt.plot(do_test,label = "original")
plt.figure(figsize=(12,8))
plt.plot(forecast,label = "predicted")
plt.title("Dissolved Oxygen Time Series Forecast")
plt.xlabel("Date")
plt.ylabel("Dissolve Oxygen(FNU)")
plt.legend()
plt.show()
#%%
# Moving average method for DISSOLVED OXYGEN
def moving_average():
#do_logScale = np.log(do)
#plt.plot(do_logScale)
do_ma = do.rolling(window=192).mean() #window size 12 denotes 12 months, giving rolling mean at yearly level
#sc_movingSTD = sc_logScale.rolling(window=192).std()
# plt.plot(sc_logScale)
#plt.plot(sc_moving_Average, color='blue')
plt.figure(figsize=(12,8))
plt.plot(do, color = "red",label = "Original")
plt.plot(do_ma, color='black', label = "DO moving_avg_mean")
plt.title("Dissolved Oxygen Rolling mean(mg/L) of Potomac River")
plt.xlabel("Date")
plt.ylabel("DO(mg/L)")
plt.legend()
plt.show()
do_ma_diff = do - do_ma
#sc_LogScaleMinusMovingAverage.head(100)
do_ma_diff.dropna(inplace=True)
#print(sc_rolmean,sc_rolstd)
check_adfuller(do_ma_diff['DO(mg/L)'])
check_mean_std(do_ma_diff, 'Dissolved Oxygen(mg/L)')
#%%
#series = read_csv('', header=0, parse_dates=[0], index_col=0, squeeze=True, date_parser=parser)
#%%
#X = series.values
diss_train, diss_test = do_train.values, do_test.values
history_do = [x for x in diss_train]
do_predictions = list()
for t in range(len(diss_test)):
model = ARIMA(history_do, order=(1,0,1))
model_fit = model.fit(disp=0)
output = model_fit.forecast()
yhat = output[0]
do_predictions.append(yhat)
obs = diss_test[t]
history_do.append(obs)
print('predicted=%f, expected=%f' % (yhat, obs))
#do_test1, do_test2 = tts(do_test,test_size = 298, random_state=0, shuffle=False)
error = mean_squared_error(diss_test, do_predictions)
print('Test MSE: %.3f' % error)
# plot
plt.figure(figsize=(12,8))
pyplot.plot(diss_test, label = "Original")
pyplot.plot(do_predictions, color='red',label='Predicted')
plt.xlabel("Datatime Index ")
plt.ylabel("Dissolved Oxygen Values")
plt.title('Dissolved Oxygen Forecast')
plt.legend()
plt.show()
#%%
def main():
input_data()
check_adfuller(dataset['DO(mg/L)'])
check_mean_std(dataset['DO(mg/L)'],'\n\nDissolved Oxygen')
acf_pacf_plots(do)
arima_model(do_test,(1,0,1))
moving_average()
<file_sep>/Code/Specific Conductance.py
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 17 12:09:53 2020
@author: admin
"""
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 17 10:53:52 2020
@author: admin
"""
#%%
import numpy as np
import matplotlib.pyplot as mp
import pandas as pd
from pandas import datetime
from sklearn.preprocessing import Imputer
from pandas.plotting import autocorrelation_plot
from matplotlib import pyplot
from statsmodels.tsa.arima_model import ARIMA
from sklearn.model_selection import train_test_split as tts
from statsmodels.tsa.stattools import adfuller
from statsmodels.tsa.stattools import acf, pacf
from statsmodels.tsa.seasonal import seasonal_decompose
import matplotlib.pylab as plt #for visualization
#%%
def input_data():
def parser(x):
return datetime.strptime(x,'%Y-%m-%d %H:%M')
dataset = pd.read_csv('Data7.csv',header=0, delimiter=',',index_col=0, parse_dates=[0], date_parser=parser)
dataset = dataset.fillna(method ='pad')
turb = dataset.filter(['Turb(FNU)'], axis=1)
train_size,test_size = 1000, 1396
turb_train,turb_test = tts(turb,test_size = test_size, random_state=0, shuffle=False)
#dataset.fillna(method ='bfill')
#%%
def check_adfuller(att):
#Perform Augmented Dickey–Fuller test:
print('Results of Dickey Fuller Test:')
print("--------For a stationary time series Test statistic is less than critical values-----------")
dftest = adfuller(att, autolag='AIC')
dfoutput = pd.Series(dftest[0:4], index=['Test Statistic','p-value','#Lags Used','Number of Observations Used'])
for key,value in dftest[4].items():
dfoutput['Critical Value (%s)'%key] = value
print(dfoutput)
#%%
def check_mean_std(ts, name):
rolmean = ts.rolling(window=192).mean()
rolstd = ts.rolling(window=192).std()
plt.figure(figsize=(12,8))
print(name)
orig = plt.plot(ts, color='red',label='Original')
mean = plt.plot(rolmean, color='black', label='Rolling Mean')
std = plt.plot(rolstd, color='green', label = 'Rolling Std')
plt.xlabel("Date")
plt.ylabel("Turbidity")
plt.title('Rolling Mean & Standard Deviation')
plt.legend()
plt.show()
#%%
def acf_pacf_plots(dataset):
ts_diff = dataset - dataset.shift()
ts_diff.dropna(inplace=True)
lag_acf = acf(ts_diff, nlags=20)
lag_pacf = pacf(ts_diff, nlags=20, method='ols')
# ACF
plt.figure(figsize=(22,10))
plt.subplot(121)
plt.plot(lag_acf)
plt.axhline(y=0,linestyle='--',color='gray')
plt.axhline(y=-1.96/np.sqrt(len(ts_diff)),linestyle='--',color='gray')
plt.axhline(y=1.96/np.sqrt(len(ts_diff)),linestyle='--',color='gray')
plt.title('Autocorrelation Function')
# PACF
plt.subplot(122)
plt.plot(lag_pacf)
plt.axhline(y=0,linestyle='--',color='gray')
plt.axhline(y=-1.96/np.sqrt(len(ts_diff)),linestyle='--',color='gray')
plt.axhline(y=1.96/np.sqrt(len(ts_diff)),linestyle='--',color='gray')
plt.title('Partial Autocorrelation Function')
plt.tight_layout()
#%%
def arima_model(ts, order):
# fit model
model = ARIMA(ts, order=order) # (ARMA) = (p,d,q)
model_fit = model.fit(disp=0)
# predict
forecast = model_fit.predict(start=1000, end=2396)
# visualization
plt.figure(figsize=(12,8))
plt.plot(turb_test,label = "original")
plt.figure(figsize=(12,8))
plt.plot(forecast,label = "predicted")
plt.title("Turbidity Time Series Forecast")
plt.xlabel("Date")
plt.ylabel("Dissolve Oxygen(FNU)")
plt.legend()
plt.show()
#%%
# Moving average method for Turbidity
def moving_average():
#turb_logScale = np.log(turb)
#plt.plot(turb_logScale)
turb_ma = turb.rolling(window=192).mean() #window size 12 denotes 12 months, giving rolling mean at yearly level
#sc_movingSTD = sc_logScale.rolling(window=192).std()
# plt.plot(sc_logScale)
#plt.plot(sc_moving_Average, color='blue')
plt.figure(figsize=(12,8))
plt.plot(turb, color = "red",label = "Original")
plt.plot(turb_ma, color='black', label = "turb moving_avg_mean")
plt.title("Turbidity Rolling mean(mg/L) of Potomac River")
plt.xlabel("Date")
plt.ylabel("Turb(FNU)")
plt.legend()
plt.show()
turb_ma_diff = turb - turb_ma
#sc_LogScaleMinusMovingAverage.head(100)
turb_ma_diff.dropna(inplace=True)
#print(sc_rolmean,sc_rolstd)
check_adfuller(turb_ma_diff['turb(uS)'])
check_mean_std(turb_ma_diff, 'Turb(FNU)')
#%%
def main():
input_data()
check_adfuller(dataset['Turb(FNU)'])
check_mean_std(dataset['Turb(FNU)'],'\n\nTurbidity')
acf_pacf_plots(turb)
arima_model(turb_test,(1,0,1))
moving_average()
<file_sep>/Code/Turbidity.py
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 17 12:09:53 2020
@author: admin
"""
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 17 10:53:52 2020
@author: admin
"""
#%%
import numpy as np
import matplotlib.pyplot as mp
import pandas as pd
from pandas import datetime
from pandas.plotting import autocorrelation_plot
from matplotlib import pyplot
from statsmodels.tsa.arima_model import ARIMA
from sklearn.model_selection import train_test_split as tts
from statsmodels.tsa.stattools import adfuller
from statsmodels.tsa.stattools import acf, pacf
from statsmodels.tsa.seasonal import seasonal_decompose
import matplotlib.pylab as plt #for visualization
from sklearn.metrics import mean_squared_error
from sklearn.metrics import accuracy_score
from sklearn.ensemble import IsolationForest
#%%
#def input_data():
def parser(x):
return datetime.strptime(x,'%Y-%m-%d %H:%M')
dataset = pd.read_csv('./Dataset/Data7.csv',header=0, delimiter=',',index_col=0, parse_dates=[0], date_parser=parser)
dataset = dataset.fillna(method ='pad')
turb = dataset.filter(['Turb(FNU)'], axis=1)
train_size,test_size = 1920, 3251#in paper given as 3169
#train_size,test_size = 1000, 1396
turb_train,turb_test = tts(turb,train_size = train_size, random_state=0, shuffle=False)
#dataset.fillna(method ='bfill')
#%%
def check_adfuller(att):
print('Results of Dickey Fuller Test:')
print("--------For a stationary time series Test statistic is less than critical values-----------")
dftest = adfuller(att, autolag='AIC')
dfoutput = pd.Series(dftest[0:4], index=['Test Statistic','p-value','#Lags Used','Number of Observations Used'])
for key,value in dftest[4].items():
dfoutput['Critical Value (%s)'%key] = value
print(dfoutput)
#%%
def check_mean_std(ts, name):
rolmean = ts.rolling(window=192).mean()
rolstd = ts.rolling(window=192).std()
plt.figure(figsize=(12,8))
print(name)
orig = plt.plot(ts, color='red',label='Original')
mean = plt.plot(rolmean, color='black', label='Rolling Mean')
std = plt.plot(rolstd, color='green', label = 'Rolling Std')
plt.xlabel("Date")
plt.ylabel("Turbidity")
plt.title('Rolling Mean & Standard Deviation')
plt.legend()
plt.show()
#%%
def acf_pacf_plots(dataset):
ts_diff = dataset - dataset.shift()
ts_diff.dropna(inplace=True)
lag_acf = acf(ts_diff, nlags=20)
lag_pacf = pacf(ts_diff, nlags=20, method='ols')
# ACF
plt.figure(figsize=(22,10))
plt.subplot(121)
plt.plot(lag_acf)
plt.axhline(y=0,linestyle='--',color='gray')
plt.axhline(y=-1.96/np.sqrt(len(ts_diff)),linestyle='--',color='gray')
plt.axhline(y=1.96/np.sqrt(len(ts_diff)),linestyle='--',color='gray')
plt.title('Autocorrelation Function')
# PACF
plt.subplot(122)
plt.plot(lag_pacf)
plt.axhline(y=0,linestyle='--',color='gray')
plt.axhline(y=-1.96/np.sqrt(len(ts_diff)),linestyle='--',color='gray')
plt.axhline(y=1.96/np.sqrt(len(ts_diff)),linestyle='--',color='gray')
plt.title('Partial Autocorrelation Function')
plt.tight_layout()
#%%
def arima_model(ts, order):
# fit model
ts = turb_train
order=(1,0,1)
model = ARIMA(ts, order=order) # (ARMA) = (p,d,q)
model_fit = model.fit(disp=0)
#print summary of fit model
print(model_fit.summary())
# predict
#forecast = model_fit.forecast()[0]
forecast2 = model_fit.predict(start=1000, end=2396)
# visualization
plt.figure(figsize=(12,8))
plt.plot(turb_test,label = "original")
#plt.figure(figsize=(12,8))
plt.plot(forecast2,label = "predicted")
plt.title("Turbidity Time Series Forecast")
plt.xlabel("Date")
plt.ylabel("Dissolve Oxygen(FNU)")
plt.legend()
plt.show()
#%%
# Moving average method for Turbidity
def moving_average():
#turb_logScale = np.log(turb)
#plt.plot(turb_logScale)
turb_ma = turb.rolling(window=192).mean() #window size 12 denotes 12 months, giving rolling mean at yearly level
#sc_movingSTD = sc_logScale.rolling(window=192).std()
# plt.plot(sc_logScale)
#plt.plot(sc_moving_Average, color='blue')
plt.figure(figsize=(12,8))
plt.plot(turb, color = "red",label = "Original")
plt.plot(turb_ma, color='black', label = "turb moving_avg_mean")
plt.title("Turbidity Rolling mean(mg/L) of Potomac River")
plt.xlabel("Date")
plt.ylabel("Turb(FNU)")
plt.legend()
plt.show()
turb_ma_diff = turb - turb_ma
#sc_LogScaleMinusMovingAverage.head(100)
turb_ma_diff.dropna(inplace=True)
#print(sc_rolmean,sc_rolstd)
check_adfuller(turb_ma_diff['turb(uS)'])
check_mean_std(turb_ma_diff, 'Turb(FNU)')
#%%
#X = series.values
train, test = turb_train.values, turb_test.values
turb_history = [x for x in train]
turb_predictions = list()
turb_diff = list()
k = 1921
for t in range(len(test)):
model = ARIMA(turb_history, order=(1,0,1))
model_fit = model.fit(disp=0)
output = model_fit.forecast()
yhat = output[0]
turb_predictions.append(yhat)
obs = test[t]
turb_history.append(obs)
diff = obs-yhat
turb_diff.append(diff)
print('TurbParameter Index= %d, predicted=%f, expected=%f, difference = %f' % (k, yhat, obs,diff))
k=k+1
if(k==3000):
break
#test1, test2 = tts(test,test_size = 337, random_state=0, shuffle=False)
error = mean_squared_error(test1, predictions)
print('Test MSE: %.3f' % error)
# plot
plt.figure(figsize=(12,8))
pyplot.plot(test1, label = "Original")
pyplot.plot(predictions, color='red',label='Predicted')
plt.xlabel("Datatime Index ")
plt.ylabel("Turbidity Values")
plt.title('Turbidity Forecast')
plt.legend()
plt.show()
#%%
# SARIMA example
from statsmodels.tsa.statespace.sarimax import SARIMAX
from random import random
# fit model
model = SARIMAX(turb_test, order=(1, 1, 1), seasonal_order=(1, 1, 1, 1))
model_fit = model.fit(disp=False)
# make prediction
print(model_fit.summary().tables[1])
#Prediction plot
model_fit.plot_diagnostics(figsize=(18, 8))
plt.show()
yhat = model_fit.predict(len(turb_test), len(turb_test))
print(yhat)
pred = model_fit.get_prediction(start=1500, dynamic=False)
pred_ci = pred.conf_int()
plt.figure(figsize=(20,10))
ax = turb_test.plot(label='observed')
pred.predicted_mean.plot(ax=ax, label='One-step ahead Forecast', alpha=.7, figsize=(14, 4))
ax.fill_between(pred_ci.index,
pred_ci.iloc[:, 0],
pred_ci.iloc[:, 1], color='k', alpha=.2)
ax.set_xlabel('Date')
ax.set_ylabel('Retail_sold')
plt.legend()
plt.show()
y_forecasted = pred.predicted_mean
y_truth = y['2018-06-01':]
mse = ((y_forecasted - y_truth) ** 2).mean()
print('The Mean Squared Error is {}'.format(round(mse, 2)))
print('The Root Mean Squared Error is {}'.format(round(np.sqrt(mse), 2)))
#%%
#Isolation Forest Model Prediction
model= IsolationForest(n_estimators=100, max_samples=256)
#model = IsolationForest(behaviour = 'new')
model.fit(turb_train)
turb_pred = model.predict(turb_test)
print("Valid cases accuracy:", list(turb_pred).count(1)/turb_pred.shape[0])
Fraud_pred = model.predict(turb_test)
#%%
plt.figure(figsize=(12,8))
plt.hist(test, normed=True)
plt.xlim([-1, 10])
plt.show()
#%%
train, test = turb_train.values, turb_test.values
isolation_forest = IsolationForest(n_estimators=100)
isolation_forest.fit(train.reshape(-1, 1))
#xx = np.linspace(-6, 6, 100).reshape(-1,1)
xx = test.reshape(-1,1)
anomaly_score = isolation_forest.decision_function(xx)
outlier = isolation_forest.predict(xx)
plt.figure(figsize=(12,8))
plt.plot(xx, anomaly_score, label='anomaly score')
plt.fill_between(xx.T[0], np.min(anomaly_score), np.max(anomaly_score), where=outlier==-1, color='r', label='outlier region')
plt.legend()
plt.ylabel('anomaly score')
plt.xlabel('Turbidity Value Frequency')
plt.xlim([-1, 10])
plt.show()
#%%
def main():
#input_data()
check_adfuller(dataset['Turb(FNU)'])
check_mean_std(dataset['Turb(FNU)'],'\n\nTurbidity')
acf_pacf_plots(turb)
arima_model(turb_test,(1,0,1))
moving_average()
<file_sep>/README.md
# Surface-Water-Quality-Data-Anomaly-Detection
Surface water quality data analysis and prediction of Potomac River, West Virginia, USA. Using time series forecasting, and anomaly detection : ARIMA, SARIMA, Isolation Forest, OCSVM and Gaussian Distribution
There exists an imperious need for development of schemes to analyse constantly monitored environmental data i.e. information about the various aspects of the ecosystem such as Surface Water Quality Parameters such as Dissolved Oxygen, Turbidity, Specific Conductance of water and analyse them for unnatural increase in their general values above predetermined standard levels to detect environmental anomalies that cause such increase. These parameters reflect the absolute state of the ecosystem of a particular geographical area, and thus help us to access any present or future discrepancies which can cause environmental degradation by direct or indirect activities of man in the geographical area.
This process is done using Time Series forecasting techniques ARIMA and Seasonal ARIMA and anomaly detection techniques which are Isolation Forest, Gaussian Distribution, OneclassSVM.
<p>
<h1> Working of Project:</h1>
<img src="https://github.com/absaw/Surface-Water-Quality-Data-Anomaly-Detection/blob/master/Images/Formulae/Flowchart%20Major.png">
<h3>Stationarity of Dataset</h3>
<ol>
<li>
<h4>1. Augmented Dickey Fuller Test</h4>
<img src="https://github.com/absaw/Surface-Water-Quality-Data-Anomaly-Detection/blob/master/Results/1/ADF%20Test%20Turb.JPG">
<h4>2. Rolling Mean Plot</h4>
<img src="https://github.com/absaw/Surface-Water-Quality-Data-Anomaly-Detection/blob/master/Results/1/Rolling%20Mean%20and%20STD%20Plot%20Turb.png">
</li>
</ol>
<h3>Time Series Forecasting with : ARIMA</h3>
<img src="https://github.com/absaw/Surface-Water-Quality-Data-Anomaly-Detection/blob/master/Images/Flowchart/arima%20flow.png">
<h4> Result : ARIMA </h4>
<img src="https://github.com/absaw/Surface-Water-Quality-Data-Anomaly-Detection/blob/master/Results/1/ARIMA%20Original%20vs%20Predicted.png">
<h4> Result : Seasonal ARIMA with window = 192(Daily number of observations)</h4>
<img src="https://github.com/absaw/Surface-Water-Quality-Data-Anomaly-Detection/blob/master/Results/1/Differenced%20ARIMA%20Original%20vs%20Predicted%202.png">
<h4>Time Series Forecast Result Analysis</h4>
<img src="https://github.com/absaw/Surface-Water-Quality-Data-Anomaly-Detection/blob/master/Results/1/Time%20Series%20Error%20Analysis.JPG">
<hr>
<h3>Isolation Forest Anomaly Detection</h3>
<h4> iTree Generation and Anomaly Score Calculation<h4>
<img src="https://github.com/absaw/Surface-Water-Quality-Data-Anomaly-Detection/blob/master/Images/Flowchart/Isolation%20Tree%20working.jpeg">
<h4>Isolation Forest</h4>
<img src="https://github.com/absaw/Surface-Water-Quality-Data-Anomaly-Detection/blob/master/Images/Flowchart/iForest.jpeg">
<h4> Result : iForest Anomaly Detection </h4>
<img src="https://github.com/absaw/Surface-Water-Quality-Data-Anomaly-Detection/blob/master/Results/1/iForest%20Anomaly%20Detection%20New.png">
<hr>
<h3>OneClassSVM</h3>
<img src="https://github.com/absaw/Surface-Water-Quality-Data-Anomaly-Detection/blob/master/Images/Flowchart/OCSVM%202.jpeg">
<h4> Result : OneClassSVM </h4>
<img src="https://github.com/absaw/Surface-Water-Quality-Data-Anomaly-Detection/blob/master/Results/1/OCSVM%20Anomaly%20Detection.png">
<hr>
<h3>Gaussian Distribution</h3>
<h4> Result </h4>
<img src="https://github.com/absaw/Surface-Water-Quality-Data-Anomaly-Detection/blob/master/Results/1/Gaussian%20Anomaly%20Detection.png">
<hr>
<h3>Anomaly Detection Result Analysis</h3>
<img src="https://github.com/absaw/Surface-Water-Quality-Data-Anomaly-Detection/blob/master/Results/1/Anomalies%20Detected%20Analysis%20New.JPG">
The above graph shows that isolation forest may be detecting a lot more false positives than the other approaches or it might be over measuring the result. All other methods give similar result with anomaly percentage ranging from 9 to 20 %. The Anomaly graph predictions shown earlier indicate that most anomalies occur on 29 January, 2017 and also on 22 March, 2017. These anomalies can be acknowledged by the fact that these dates had actually shown intensity rainfalls on the monitoring site.
</p>
<file_sep>/Code/DataPreprocessing.py
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 22 12:12:59 2020
@author: admin
"""
#%%
import numpy as np
import matplotlib.pyplot as mp
import pandas as pd
#%%
from pandas import DataFrame
df = DataFrame.from_csv("Data4.tsv", sep="\t")
#%%
#Creating a dataset variable and importing the dataset.csv file with it
dataset = pd.read_csv('Data5.tsv', delimiter="\t", header=0, encoding='utf-8')
#%%
dataset = pd.read_csv('Data7.csv',header=0, delimiter=',')
#%%
dataset.plot()
dataset.show()
#%%
'''
Extra knowledge
pd.set_option('display.max_columns', 5) - To set displayed no. of columns
data = pd.read_csv('file1.csv', error_bad_lines=False) - To ignore error ridden lines
'''
#%%
#Creating separate matrices for x - indep, y- dep
x = dataset.iloc[ : , 0].values
y = dataset.iloc[ : , 1:].values
#x is a matrix while y is a vector
#for defining x - specify a range so the resultant x is a matrix(10,1)
#for defining y - just specify the index of the reqd column directly to make it
# a vector(10,)
#%%
#ELIMINATING THE MISSING VALUES
from sklearn.preprocessing import Imputer
#creating function variable using Imputer
imputer = Imputer(missing_values='NaN', strategy='mean', axis=0)
#attaching the variable imputer to our matrix y
imputer = imputer.fit(y[:,:])
#now we apply our imputer variable on matrix to fill in the
#missing values will be filled with the strategy we picked
#fit() used to apply changes on a temp var in memory
#transform() used to commit the changes to the said variable
#fit_transform() for doing both together
y=imputer.transform(y)
#%%
#Splitting dataset to training and test set
'''
Training Set- from which the model will learn from
Test -with which it will compare itself and check itself
'''
from sklearn.model_selection import train_test_split as tts
y_train,y_test = tts(y,test_size = 0.2, random_state=0)
#%%
#Feature Scaling- it scales the entries so that all columns are comparable to
#same scale
from sklearn.preprocessing import StandardScaler as ss
sc_x = ss()
x_train = sc_x.fit_transform(x_train)
x_test = sc_x.transform(x_test)
<file_sep>/Code/turb_LSTM.py
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 26 18:53:44 2020
@author: admin
"""
#%%
import pandas as pd
from matplotlib import pyplot
from sklearn.model_selection import train_test_split as tts
from pandas import DataFrame
from pandas import Series
from pandas import concat
from pandas import read_csv
from pandas import datetime
from sklearn.metrics import mean_squared_error
from sklearn.preprocessing import MinMaxScaler
from keras.preprocessing.sequence import TimeseriesGenerator
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
from keras.layers import Dropout
from math import sqrt
import numpy
#%%
#def input_data():
def parser(x):
return datetime.strptime(x,'%Y-%m-%d %H:%M')
dataset = pd.read_csv('./Dataset/Data7.csv',header=0, delimiter=',',index_col=0, parse_dates=[0], date_parser=parser)
dataset = dataset.fillna(method ='pad')
turb = dataset.filter(['Turb(FNU)'], axis=1)
train_size,test_size = 1920, 3251#in paper given as 3169
#train_size,test_size = 1000, 1396
turb_train,turb_test = tts(turb,train_size = train_size, random_state=0, shuffle=False)
#dataset.fillna(method ='bfill')
#%%
from pandas import read_csv
from pandas import datetime
from pandas import DataFrame
from pandas import concat
# frame a sequence as a supervised learning problem
def timeseries_to_supervised(data, lag=1):
df = DataFrame(data)
columns = [df.shift(i) for i in range(1, lag+1)]
columns.append(df)
df = concat(columns, axis=1)
df.fillna(0, inplace=True)
return df
# load dataset
def parser(x):
return datetime.strptime(x,'%Y-%m-%d %H:%M')
#series = read_csv('shampoo-sales.csv', header=0, parse_dates=[0], index_col=0, squeeze=True, date_parser=parser)
dataset = pd.read_csv('./Dataset/Data7.csv',header=0, delimiter=',',index_col=0, parse_dates=[0], date_parser=parser)
dataset = dataset.fillna(method ='pad')
turb = dataset.filter(['Turb(FNU)'], axis=1)
# transform to supervised learning
X = turb.values
supervised = timeseries_to_supervised(X, 1)
print(supervised.head())
#%%
# frame a sequence as a supervised learning problem
def timeseries_to_supervised(data, lag=1):
df = DataFrame(data)
columns = [df.shift(i) for i in range(1, lag+1)]
columns.append(df)
df = concat(columns, axis=1)
df.fillna(0, inplace=True)
return df
'''
# create a differenced series
def difference(dataset, interval=1):
diff = list()
for i in range(interval, len(dataset)):
value = dataset[i] - dataset[i - interval]
diff.append(value)
return Series(diff)
# invert differenced value
def inverse_difference(history, yhat, interval=1):
return yhat + history[-interval]
'''
# scale train and test data to [-1, 1]
def scale(train, test):
# fit scaler
scaler = MinMaxScaler(feature_range=(-1, 1))
scaler = scaler.fit(train)
# transform train
#train = train.reshape(train.shape[0], train.shape[1])
train_scaled = scaler.transform(train)
# transform test
#test = test.reshape(test.shape[0], test.shape[1])
test_scaled = scaler.transform(test)
return scaler, train_scaled, test_scaled
# inverse scaling for a forecasted value
def invert_scale(scaler, X, value):
new_row = [x for x in X] + [value]
array = numpy.array(new_row)
array = array.reshape(1, len(array))
inverted = scaler.inverse_transform(array)
return inverted[0, -1]
# fit an LSTM network to training data
def fit_lstm(train):
#X, y = train[:, 0:-1], train[:, -1]
#X = X.reshape(X.shape[0], 1, X.shape[1])
batch_size = 96 #batch_size:no of entries sampled in one go
#epoch = 3000
neurons = 200
n_input = 12
n_features =
generator = TimeseriesGenerator(train, train, length = n_input, batch_size = batch_size)
model = Sequential()
#model.add(LSTM(neurons, batch_input_shape=(batch_size, X.shape[1], X.shape[2]), stateful=True))
model.add(LSTM(neurons, activation='relu', input_shape=(n_input, n_features)))
model.add(Dropout(0.15))
model.add(Dense(1))
model.compile(loss='mean_squared_error', optimizer='adam')
'''
for i in range(nb_epoch):
model.fit(X, y, epochs=1, batch_size=batch_size, verbose=0, shuffle=False)
model.reset_states()
'''
model.fit_generator(generator, epochs=180)
return model
# make a one-step forecast
def forecast_lstm(model, batch_size, X):
X = X.reshape(1, 1, len(X))
yhat = model.predict(X, batch_size=batch_size)
return yhat[0,0]
# load dataset
def parser(x):
return datetime.strptime(x,'%Y-%m-%d %H:%M')
#series = read_csv('shampoo-sales.csv', header=0, parse_dates=[0], index_col=0, squeeze=True, date_parser=parser)
dataset = pd.read_csv('./Dataset/Data7.csv',header=0, delimiter=',',index_col=0, parse_dates=[0], date_parser=parser)
dataset = dataset.fillna(method ='pad')
turb = dataset.filter(['Turb(FNU)'], axis=1)
# transform to supervised learning
X = turb.values
supervised = timeseries_to_supervised(X, 1)
supervised_values = supervised.values
print(supervised.head())
'''
# transform data to be stationary
raw_values = series.values
diff_values = difference(raw_values, 1)
'''
# split data into train and test-sets
#train, test = supervised_values[0:-12], supervised_values[-12:]
train_size,test_size = 4000, 1171#in paper given as 3169
#train_size,test_size = 1000, 1396
turb_train,turb_test = tts(turb,train_size = train_size, random_state=0, shuffle=False)
turb_train = turb_train.values
turb_test = turb_test.values
# transform the scale of the data
scaler, train_scaled, test_scaled = scale(turb_train, turb_test)
# fit the model
lstm_model = fit_lstm(train_scaled)#96 entries of one day
# forecast the entire training dataset to build up state for forecasting
train_reshaped = train_scaled[:, 0].reshape(len(train_scaled), 1, 1)
lstm_model.predict(train_reshaped, batch_size=1)<file_sep>/Code/arima.py
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 22 12:12:59 2020
@author: admin
"""
#%%
import numpy as np
import matplotlib.pyplot as mp
import pandas as pd
from pandas import datetime
from sklearn.preprocessing import Imputer
from pandas.plotting import autocorrelation_plot
from matplotlib import pyplot
from statsmodels.tsa.arima_model import ARIMA
from sklearn.model_selection import train_test_split as tts
from statsmodels.tsa.stattools import adfuller
from statsmodels.tsa.stattools import acf, pacf
from statsmodels.tsa.seasonal import seasonal_decompose
import matplotlib.pylab as plt #for visualization
from sklearn.metrics import mean_squared_error
#%%
def parser(x):
return datetime.strptime(x,'%Y-%m-%d %H:%M')
dataset = pd.read_csv('Data7.csv',header=0, delimiter=',',index_col=0, parse_dates=[0], date_parser=parser)
dataset = dataset.fillna(method ='pad')
#dataset.fillna(method ='bfill')
#%%
dataset.plot()
dataset.show()
#%%
def check_adfuller(att):
#Perform Augmented Dickey–Fuller test:
print('Results of Dickey Fuller Test:')
print("--------For a stationary time series Test statistic is less than critical values-----------")
dftest = adfuller(att, autolag='AIC')
dfoutput = pd.Series(dftest[0:4], index=['Test Statistic','p-value','#Lags Used','Number of Observations Used'])
for key,value in dftest[4].items():
dfoutput['Critical Value (%s)'%key] = value
print(dfoutput)
#%%
check_adfuller(dataset['SC(uS)'])
check_adfuller(dataset['Turb(FNU)'])
check_adfuller(dataset['DO(mg/L)'])
#%%
sc = dataset.filter(['SC(uS)'], axis=1)
turb = dataset.filter(['Turb(FNU)'], axis=1)
do = dataset.filter(['DO(mg/L)'], axis=1)
#%%
def check_mean_std(ts, name):
rolmean = ts.rolling(window=96).mean()
rolstd = ts.rolling(window=96).std()
plt.figure(figsize=(22,10))
print(name)
orig = plt.plot(ts, color='red',label='Original')
mean = plt.plot(rolmean, color='black', label='Rolling Mean')
std = plt.plot(rolstd, color='green', label = 'Rolling Std')
plt.xlabel("Date")
plt.ylabel("Mean Temperature")
plt.title('Rolling Mean & Standard Deviation')
plt.legend()
plt.show()
#%%
def acf_pacf_plots(datset):
dataset = sc
ts_diff = dataset - dataset.shift()
ts_diff.dropna(inplace=True)
lag_acf = acf(ts_diff, nlags=20)
lag_pacf = pacf(ts_diff, nlags=20, method='ols')
# ACF
plt.figure(figsize=(22,10))
plt.subplot(121)
plt.plot(lag_acf)
plt.axhline(y=0,linestyle='--',color='gray')
plt.axhline(y=-1.96/np.sqrt(len(ts_diff)),linestyle='--',color='gray')
plt.axhline(y=1.96/np.sqrt(len(ts_diff)),linestyle='--',color='gray')
plt.title('Autocorrelation Function')
# PACF
plt.subplot(122)
plt.plot(lag_pacf)
plt.axhline(y=0,linestyle='--',color='gray')
plt.axhline(y=-1.96/np.sqrt(len(ts_diff)),linestyle='--',color='gray')
plt.axhline(y=1.96/np.sqrt(len(ts_diff)),linestyle='--',color='gray')
plt.title('Partial Autocorrelation Function')
plt.tight_layout()
#%%
def arima_model(ts, order):
# fit model
ts = sc_train
model = ARIMA(ts, order=(1,0,1)) # (ARMA) = (p,d,q)
model_fit = model.fit(disp=0)
# predict
forecast = model_fit.predict(start=1919, end=5171)
# visualization
plt.figure(figsize=(12,8))
plt.plot(sc_test,label = "original")
plt.figure(figsize=(12,8))
plt.plot(forecast,label = "predicted")
plt.title("Turbidity Time Series Forecast")
plt.xlabel("Date")
plt.ylabel("Turbidity(FNU)")
plt.legend()
plt.show()
#%%
#X = series.values
sp_train, sp_test = sc_train.values, sc_test.values
history_sc = [x for x in train]
sc_predictions = list()
for t in range(len(sp_test)):
model = ARIMA(history_sc, order=(1,0,1))
model_fit = model.fit(disp=0)
output = model_fit.forecast()
yhat = output[0]
sc_predictions.append(yhat)
obs = sp_test[t]
history_sc.append(obs)
print('predicted=%f, expected=%f' % (yhat, obs))
sp_test1, sp_test2 = tts(sc_test,test_size = 3232, random_state=0, shuffle=False)
error = mean_squared_error(do_test1, do_predictions)
print('Test MSE: %.3f' % error)
# plot
plt.figure(figsize=(12,8))
pyplot.plot(test1, label = "Original")
pyplot.plot(predictions, color='red',label='Predicted')
plt.xlabel("Datatime Index ")
plt.ylabel("Dissolved Oxygen Values")
plt.title('Dissolved Oxygen Forecast')
plt.legend()
plt.show()
#%%
# Moving average method for TURBIDITY
window_size = 192
turb_ma = turb.rolling(window=window_size).mean()
plt.figure(figsize=(22,10))
plt.plot(turb, color = "red",label = "Original")
plt.plot(turb_ma, color='black', label = "moving_avg_mean")
plt.title("Turbidity(FNU) of Potomac River")
plt.xlabel("Date")
plt.ylabel("Turbidity")
plt.legend()
plt.show()
turb_moving_avg_diff = turb - turb_ma
turb_moving_avg_diff.dropna(inplace=True) # first 6 is nan value due to window size
# check stationary: mean, variance(std)and adfuller test
check_mean_std(turb_moving_avg_diff, "Turbidity")
check_adfuller(turb_moving_avg_diff['Turb(FNU)'])
#p and q for turbidity
acf_pacf_plots(turb)
#%%
check_adfuller(sc['SC(uS)'])
check_mean_std(sc['SC(uS)'])
#%%
# Moving average method for Specific Conductance
#sc_logScale = np.log(sc)
#plt.plot(sc_logScale)
sc_ma = sc.rolling(window=192).mean() #window size 12 denotes 12 months, giving rolling mean at yearly level
#sc_movingSTD = sc_logScale.rolling(window=192).std()
#plt.plot(sc_logScale)
#plt.plot(sc_moving_Average, color='blue')
plt.figure(figsize=(22,10))
plt.plot(sc, color = "red",label = "Original")
plt.plot(sc_ma, color='black', label = "moving_avg_mean")
plt.title("Specific Conductance(uS) of Potomac River")
plt.xlabel("Date")
plt.ylabel("Specific Conductance")
plt.legend()
plt.show()
sc_ma_diff = sc - sc_ma
#sc_LogScaleMinusMovingAverage.head(100)
sc_ma_diff.dropna(inplace=True)
#print(sc_rolmean,sc_rolstd)
check_adfuller(sc_ma_diff['SC(uS)'])
check_mean_std(sc_ma_diff, "SC(uS)")
#%%
# Moving average method for DISSOLVED OXYGEN
do_ma = do.rolling(window=192).mean()
plt.figure(figsize=(22,10))
plt.plot(do, color = "red",label = "Original")
plt.plot(do_ma, color='black', label = "DO moving_avg_mean")
plt.title("Dissolved Oxygen (mg/L) of Potomac River")
plt.xlabel("Date")
plt.ylabel("DO(mg/L)")
plt.legend()
plt.show()
#do_ma_diff = do - do_ma
#sc_LogScaleMinusMovingAverage.head(100)
do_ma_diff.dropna(inplace=True)
#print(sc_rolmean,sc_rolstd)
check_adfuller(do_ma_diff['DO(mg/L)'])
check_mean_std(sc_ma_diff, 'Dissolved Oxygen(mg/L)')
#%%
#Determine rolling statistics
sc_rolmean = sc.rolling(window=96).mean() #window size 12 denotes 12 months
sc_rolstd = sc.rolling(window=96).std()
print(sc_rolmean,sc_rolstd)
orig = plt.plot(sc, color='blue', label='Original')
mean = plt.plot(sc_rolmean, color='red', label='Rolling Mean')
std = plt.plot(sc_rolstd, color='black', label='Rolling Std')
plt.legend(loc='best')
plt.title('Rolling Mean & Standard Deviation')
plt.show(block=False)
#%%
#PLotting all individual variables
plt.figure(figsize=(17,8))
plt.plot(sc,label="Specific Conductance(uS) of Potomac River",color='red')
plt.plot(turb,label="Turbidity(FNU) of Potomac River",color='black')
plt.plot(do,label="Dissolved Oxygen(mg/L)",color='green')
plt.title("Dataset (mg/L) of Potomac River")
plt.xlabel("Date")
plt.ylabel("DO(mg/L)")
plt.legend()
plt.show()
plt.show()
#%%
#Auto Correlation Plots
autocorrelation_plot(sc)
pyplot.show()
autocorrelation_plot(turb)
pyplot.show()
autocorrelation_plot(do)
pyplot.show()
#%%
#Auto Correlation
from pandas.plotting import lag_plot
lag_plot(sc)
pyplot.show()
lag_plot(turb)
pyplot.show()
lag_plot(do)
pyplot.show()
#%%
#ACF Plots
from statsmodels.graphics.tsaplots import plot_acf
plot_acf(sc)
plot_acf(turb, label="Turbidity")
plot_acf(do)
#%%
'''
Extra knowledge
pd.set_option('display.max_columns', 5) - To set displayed no. of columns
data = pd.read_csv('file1.csv', error_bad_lines=False) - To ignore error ridden lines
'''
#%%
sc_v = sc.values
turb_v = turb.values
do_v = do.values
#%%
from scipy.stats import zscore
sc_z = sc.apply(zscore)
turb_z = turb.apply(zscore)
#%%
#ELIMINATING THE MISSING VALUES
imputer = Imputer(missing_values='NaN', strategy='mean', axis=0)
imputer = imputer.fit(sc_v[:,:])
sc_v=imputer.transform(sc_v)
imputer = imputer.fit(turb_v[:,:])
turb_v=imputer.transform(turb_v)
#%%
#Splitting dataset to training and test set
'''
Training Set- from which the model will learn from
Test -with which it will compare itself and check itself
'''
#from sklearn.model_selection import train_test_split as tts
train_size = 1920
test_size = 3252
sc_train,sc_test = tts(sc,test_size = test_size, random_state=0, shuffle=False)
do_train,do_test = tts(do,test_size = test_size, random_state=0, shuffle=False)
turb_train,turb_test = tts(turb,test_size =test_size, random_state=0, shuffle=False)
#sc_train, sc_test = sc_v[0:train_size,:], sc_v[train_size:5171,:]
#%%
#p,d,q p = periods taken for autoregressive model
#d -> Integrated order, difference
# q periods in moving average model
sc_arima = ARIMA(sc_train,order=(12,0,0))
sc_arima_fit = sc_arima.fit(disp=-1)
plt.plot(sc_train, color = 'blue')
plt.plot(sc_arima_fit.fittedvalues, color = 'red', figsize=(20,20))
print(sc_arima_fit.aic)
#%%
# predict
start_index = parser("2017-02-16 00:00")
end_index = "2017-03-21 23:45"
forecast = sc_arima_fit.predict(start=1919, end=4000)
plt.figure(figsize=(22,10))
plt.plot(sc_test,label = "original")
plt.plot(forecast,label = "predicted", color = 'red')
#%%
predictions = sc_arima_fit.predict(start=1919, end=3000)
print(predictions)
#%%
import itertools
p=d=q=range(0,5)
pdq = list(itertools.product(p,d,q))
#%%
import warnings
warnings.filterwarnings('ignore')
for param in pdq:
try:
sc_arima = ARIMA(sc_train,order=param)
sc_arima_fit = sc_arima.fit()
print(param, sc_arima_fit.aic)
'''
model_arima = ARIMA(train,order=param)
model_arima_fit = model_arima.fit()
print(param,model_arima_fit.aic)
'''
except:
continue
#%%
mp.plot(sc_test)
mp.plot(forecast,color='red')
#%%
from statsmodels.tsa.ar_model import AR
from sklearn.metrics import mean_squared_error
sc_ar = AR(sc_train)
sc_ar_fit = sc_ar.fit()
predictions = sc_ar_fit.predict(start=train_size, end=5171)
#%%
import warnings
warnings.filterwarnings('ignore')
for param in pdq:
try:
turb_arima = ARIMA(turb_train,order=param)
turb_arima_fit = turb_arima.fit()
print(param, turb_arima_fit.aic)
'''
model_arima = ARIMA(train,order=param)
model_arima_fit = model_arima.fit()
print(param,model_arima_fit.aic)
'''
except:
continue
#%%
import warnings
warnings.filterwarnings('ignore')
for param in pdq:
try:
do_arima = ARIMA(do_train,order=param)
turb_arima_fit = do_arima.fit()
print(param, turb_arima_fit.aic)
'''
model_arima = ARIMA(train,order=param)
model_arima_fit = model_arima.fit()
print(param,model_arima_fit.aic)
'''
except:
continue
| 669a92de35b92a614190d9673f9cc33b11d490f8 | [
"Markdown",
"Python"
] | 7 | Python | absaw/Surface-Water-Quality-Data-Anomaly-Detection | 9840d051d5ed518f53d834ecec1d82b567c959b1 | ce176a84497f785e525d336b655b09b93ecc4299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.