branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/master
<file_sep>from django.db import models # Create your models here. class Blog(models.Model): sno = models.AutoField(primary_key = True) title = models.CharField(max_length=200) content = models.TextField() slug = models.CharField(max_length=100) time = models.DateField(auto_now_add=True) def __str__(self) -> str: return self.title<file_sep># Django_First_Blog This is the first blog created with the help of Django <file_sep>from blog.models import Blog from django.http.response import HttpResponse from django.shortcuts import render # Create your views here. def home(request): return render(request,'index.html') def blog(request): blogs = Blog.objects.all context = {'blogs':blogs} return render(request,'bloghome.html',context) def blogpost(request,slug): blogs = Blog.objects.filter(slug = slug).first() context = {'blogs': blogs} return render(request,'blogpost.html',context) def contact(request): return render(request,'contact.html') def search(request): return render(request,'search.html')<file_sep> let sc = document.createElement('script'); sc.attribute( 'src', "https://cdn.tiny.cloud/1/0f460m1mt2m84vjkilkckq1hwis426ep690z9d68f3jk10v1/tinymce/5/tinymce.min.js"); referrerpolicy="origin"; document.head.appendChild(sc);<file_sep>from django.contrib import admin from django.urls import path from django.urls.conf import include from blog import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.home, name='home'), path('home/', views.home, name='home'), path('blog/', views.blog, name='blog'), path('blogpost/<str:slug>', views.blogpost, name='blog'), path('contact/', views.contact, name='contact'), path('search/', views.search, name='search'), ]
c5cc9c443121c4d1fccbf8f2d2fa9686eb57c7cb
[ "Markdown", "Python", "JavaScript" ]
5
Python
sagarnakade96/Django_First_Blog
b04fcbd7c704cd73a71e49d4ba007a31badc1e74
b8139df8b52280972e589a00f822fc6535f2b710
refs/heads/master
<file_sep>package controlador; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import modelo.Producto; import javax.servlet.ServletContext; 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 javax.servlet.http.HttpSession; import java.io.IOException; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; @WebServlet(name = "eliminarCarrito", urlPatterns = {"/eliminarCarrito"}) public class eliminarCarrito extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { HttpSession session = request.getSession(); int idProducto = Integer.parseInt(request.getParameter("id")); String ruta = (String) session.getAttribute("ruta"); session.setAttribute("ruta",""); String json = (String) session.getAttribute("carrito"); Gson gson = new Gson(); ArrayList<Producto> carrito = null; if (json!=null){ Type listType = new TypeToken<ArrayList<Producto>>(){}.getType(); carrito = gson.fromJson(json, listType); int pos = verificarCarrito(idProducto, carrito); if (pos !=-1 ){ carrito.remove(pos); } String carritoJson = gson.toJson(carrito); session.setAttribute("carrito", carritoJson); session.setAttribute("mensaje", "Se elimino del carrito"); }else{ session.setAttribute("mensaje", "Ese producto no esta en el carrito"); } ServletContext contexto=request.getServletContext(); response.sendRedirect(ruta); } public int verificarCarrito(int idProducto, List<Producto> productos){ for (int i = 0; i < productos.size(); i++) { if (productos.get(i).getIdProducto() == idProducto){ return i; } } return -1; } } <file_sep> $(document).ready(function(){ var rutaRelativa = window.location.href; $.post(rutaRelativa+"productos",{}, function(response){ response.forEach(function (producto) { $("#cards").append('<div class="card ml-3 mt-2 float-left" style="width: 18rem;">\n' + ' <div class="card-body">\n' + ' <h5 class="card-title">'+producto.nombreProducto+'</h5>\n' + ' </div>\n' + ' <ul class="list-group list-group-flush">\n' + ' <li class="list-group-item">Precio: $ '+producto.valorProducto+'</li>\n' + ' </ul>\n' + ' <div class="card-body">\n' + ' <form action="'+rutaRelativa+'adicionar" method="get"><input type="text" name="id" value="'+producto.idProducto+'" style="display: none;"><input type="submit" class="btn btn-primary card-link" value="Añadir al carrito">\n' + ' <input type="number" name="cantidad" min="1" style="width: 40px;" value="1"></form>\n' + ' </div>\n' + ' </div>') }) }) if (carrito != undefined){ let total = 0; for (let i = 0; i < carrito.length; i++) { $("#carrito").append('<tr><td><h5>'+carrito[i].nombreProducto+'</h5><p>Precio: $'+carrito[i].valorProducto+'</p><p>Cantidad: '+carrito[i].cantidad+'</p></td><td><a href="'+rutaRelativa+'eliminarCarrito?id='+carrito[i].idProducto+'" class="btn btn-danger">Eliminar</a></td></tr>') total += carrito[i].valorProducto * carrito[i].cantidad; } $("#total").append("Total: $"+total) } $('#shoopingCart').click(function () { $("#divCarrito").toggle('normal'); if ($(this).attr("operation") == "ocultar") { $(this).html("Mostrar Carrito"); $(this).removeAttr("operation"); $(this).attr("operation", "mostrar") }else{ $(this).html("Ocultar Carrito"); $(this).removeAttr("operation"); $(this).attr("operation", "ocultar"); } }) $("#myBtn").click(function(){ $("#myModal").modal(); }); });<file_sep>package controlador; import javax.servlet.RequestDispatcher; 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 javax.servlet.http.HttpSession; import java.io.IOException; @WebServlet(name="close", urlPatterns = {"/close"}) public class cerrarSesion extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { HttpSession session = request.getSession(); session.invalidate(); response.sendRedirect(request.getContextPath()); } } <file_sep>package controlador; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import modelo.Producto; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.*; import java.io.IOException; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Arrays; import java.util.List; @WebServlet(name = "controlador.adicionarCarrito", urlPatterns = {"/adicionar"}) public class adicionarCarrito extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { HttpSession session = request.getSession(); int idProducto = Integer.parseInt(request.getParameter("id")); int cantidad = Integer.parseInt(request.getParameter("cantidad")); Producto producto = new Producto(idProducto,cantidad); if (producto.consultar()){ String json = (String) session.getAttribute("carrito"); Gson gson = new Gson(); ArrayList<Producto> carrito = null; if (json!=null){ Type listType = new TypeToken<ArrayList<Producto>>(){}.getType(); carrito = gson.fromJson(json, listType); int pos = verificarCarrito(producto, carrito); if (pos !=-1 ){ carrito.get(pos).aumentarCantidad(cantidad); }else{ carrito.add(producto); } }else{ carrito = new ArrayList<Producto>(); carrito.add(producto); } String carritoJson = gson.toJson(carrito); session.setAttribute("carrito", carritoJson); session.setAttribute("mensaje", "Se agrego al carrito"); }else{ session.setAttribute("mensaje", "No existe dicho producto"); } response.sendRedirect(request.getContextPath()); } public int verificarCarrito(Producto producto, List<Producto> productos){ for (int i = 0; i < productos.size(); i++) { if (productos.get(i).getIdProducto() == producto.getIdProducto()){ return i; } } return -1; } } <file_sep>package modelo; import java.sql.ResultSet; public class Usuario { private int idUsuario; private String usuario; private String password; public Usuario(){} public Usuario(String usuario, String password) { this.usuario = usuario; this.password = password; } public int getIdUsuario() { return idUsuario; } public void setIdUsuario(int idUsuario) { this.idUsuario = idUsuario; } public String getUsuario() { return usuario; } public void setUsuario(String usuario) { this.usuario = usuario; } public String getPassword(String s) { return password; } public void setPassword(String password) { this.password = password; } public boolean insertar(){ String INSERT = "INSERT INTO usuario(usuario, password) VALUES ('"+this.usuario+"','"+this.password+"')"; Conexion oConexion = new Conexion(); oConexion.setSQL(INSERT); return oConexion.ejecutarSentencia(); } public boolean consultar(){ String SELECT = "SELECT * FROM `usuario` WHERE `usuario` = '"+this.usuario+"' AND `password` = '"+this.password+"'"; Conexion oConexion = new Conexion(); oConexion.setSQL(SELECT); if (oConexion.ejecutarConsulta()){ try{ ResultSet rs = oConexion.getoResultSet(); if (rs.next()){ this.idUsuario = Integer.parseInt(rs.getString(1)); oConexion.desconectar(); return true; }else{ oConexion.desconectar(); return false; } }catch(Exception e){ oConexion.desconectar(); System.out.println("ERROR " + e.getMessage()); return false; } } return false; } } <file_sep>$(document).ready(function(){ if (carrito != undefined){ let total = 0; for (let i = 0; i < carrito.length; i++) { $("#carrito").append('<tr><td><h5>'+carrito[i].nombreProducto+'</h5><p>Precio: $'+carrito[i].valorProducto+'</p><p>Cantidad: '+carrito[i].cantidad+'</p></td><td><a href="'+ruta+'/eliminarCarrito?id='+carrito[i].idProducto+'" class="btn btn-danger">Eliminar</a></td></tr>') total += carrito[i].valorProducto * carrito[i].cantidad; } $("#total").append("Total: $"+total) } }); <file_sep>-- phpMyAdmin SQL Dump -- version 4.9.0.1 -- https://www.phpmyadmin.net/ -- -- Servidor: 127.0.0.1 -- Tiempo de generación: 01-08-2019 a las 14:46:37 -- Versión del servidor: 10.3.16-MariaDB -- Versión de PHP: 7.3.7 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Base de datos: `store` -- -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `compra` -- CREATE TABLE `compra` ( `idCompra` int(11) NOT NULL, `idUsuario` int(11) NOT NULL, `fecha` varchar(30) NOT NULL, `medioPago` varchar(30) NOT NULL, `productos` mediumtext NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Volcado de datos para la tabla `compra` -- INSERT INTO `compra` (`idCompra`, `idUsuario`, `fecha`, `medioPago`, `productos`) VALUES (1, 1, '29-07-2019', 'PSE', '[{\"idProducto\":3,\"valorProducto\":30.0,\"nombreProducto\":\"Nintendo\",\"cantidad\":1},{\"idProducto\":6,\"valorProducto\":22.6,\"nombreProducto\":\"Xbox 360\",\"cantidad\":1}]'), (2, 2, '30-07-2019', 'PayPal', '[{\"idProducto\":3,\"valorProducto\":30.0,\"nombreProducto\":\"Nintendo\",\"cantidad\":1},{\"idProducto\":2,\"valorProducto\":30.0,\"nombreProducto\":\"Play Station 4\",\"cantidad\":1}]'), (3, 1, '30-06-2019', 'Tarjeta de Credito', '[{\"idProducto\":4,\"valorProducto\":12.0,\"nombreProducto\":\"PSP Vita\",\"cantidad\":1}]'), (4, 1, '31-07-2019', 'PSE', '[{\"idProducto\":2,\"valorProducto\":30.0,\"nombreProducto\":\"Play Station 4\",\"cantidad\":1}]'), (5, 2, '31-07-2019', 'PayPal', '[{\"idProducto\":1,\"valorProducto\":25.0,\"nombreProducto\":\"Xbox One S\",\"cantidad\":1}]'); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `producto` -- CREATE TABLE `producto` ( `idProducto` int(11) NOT NULL, `nombreProdcuto` varchar(40) DEFAULT NULL, `valorProducto` double DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Volcado de datos para la tabla `producto` -- INSERT INTO `producto` (`idProducto`, `nombreProdcuto`, `valorProducto`) VALUES (1, 'Xbox One S', 25), (2, 'Play Station 4', 30), (3, 'Nintendo', 30), (4, 'PSP Vita', 12), (5, 'Play Station 1', 12.6), (6, 'Xbox 360', 22.6); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `usuario` -- CREATE TABLE `usuario` ( `idUsuario` int(11) NOT NULL, `usuario` varchar(10) NOT NULL, `password` varchar(20) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Volcado de datos para la tabla `usuario` -- INSERT INTO `usuario` (`idUsuario`, `usuario`, `password`) VALUES (1, 'egutierrez', '<PASSWORD>'), (2, 'esteguri', '321'); -- -- Índices para tablas volcadas -- -- -- Indices de la tabla `compra` -- ALTER TABLE `compra` ADD PRIMARY KEY (`idCompra`), ADD KEY `fk_idUsuario` (`idUsuario`); -- -- Indices de la tabla `producto` -- ALTER TABLE `producto` ADD PRIMARY KEY (`idProducto`); -- -- Indices de la tabla `usuario` -- ALTER TABLE `usuario` ADD PRIMARY KEY (`idUsuario`); -- -- AUTO_INCREMENT de las tablas volcadas -- -- -- AUTO_INCREMENT de la tabla `compra` -- ALTER TABLE `compra` MODIFY `idCompra` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=6; -- -- AUTO_INCREMENT de la tabla `producto` -- ALTER TABLE `producto` MODIFY `idProducto` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7; -- -- AUTO_INCREMENT de la tabla `usuario` -- ALTER TABLE `usuario` MODIFY `idUsuario` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3; -- -- Restricciones para tablas volcadas -- -- -- Filtros para la tabla `compra` -- ALTER TABLE `compra` ADD CONSTRAINT `fk_idUsuario` FOREIGN KEY (`idUsuario`) REFERENCES `usuario` (`idUsuario`); COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; <file_sep>package modelo; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List; public class Compra { private int idCompra, idUsuario; private String fecha, medioPago, productos; public Compra() { } public Compra(int idUsuario) { this.idUsuario = idUsuario; } public Compra(int idUsuario, String fecha, String medioPago, String productos) { this.idUsuario = idUsuario; this.fecha = fecha; this.medioPago = medioPago; this.productos = productos; } public Compra(int idCompra, int idUsuario, String fecha, String medioPago, String productos) { this.idCompra = idCompra; this.idUsuario = idUsuario; this.fecha = fecha; this.medioPago = medioPago; this.productos = productos; } public int getIdCompra() { return idCompra; } public void setIdCompra(int idCompra) { this.idCompra = idCompra; } public int getIdUsuario() { return idUsuario; } public void setIdUsuario(int idUsuario) { this.idUsuario = idUsuario; } public String getFecha() { return fecha; } public void setFecha(String fecha) { this.fecha = fecha; } public String getMedioPago() { return medioPago; } public void setMedioPago(String medioPago) { this.medioPago = medioPago; } public String getProductos() { return productos; } public void setProductos(String productos) { this.productos = productos; } public boolean insertar(){ String INSERT = "INSERT INTO `compra`( `idUsuario`, `fecha`, `medioPago`, `productos`) VALUES ("+idUsuario+",'"+fecha+"','"+medioPago+"','"+productos+"')"; Conexion oConexion = new Conexion(); oConexion.setSQL(INSERT); return oConexion.ejecutarSentencia(); } public List<Compra> consultarAll(){ String SELECT = "SELECT * FROM `compra` WHERE idUsuario="+idUsuario; Conexion oConexion = new Conexion(); oConexion.setSQL(SELECT); if (oConexion.ejecutarConsulta()){ try{ ResultSet rs = oConexion.getoResultSet(); List<Compra> compras = new ArrayList<Compra>(); while (rs.next()){ Compra compra = new Compra(rs.getInt(1),this.idUsuario,rs.getString(3),rs.getString(4), rs.getString(5)); compras.add(compra); } oConexion.desconectar(); return compras; }catch(Exception e){ oConexion.desconectar(); System.out.println("ERROR " + e.getMessage()); return null; } } return null; } public boolean consultar(){ String SELECT = "SELECT * FROM `compra` WHERE idUsuario="+idUsuario; Conexion oConexion = new Conexion(); oConexion.setSQL(SELECT); if (oConexion.ejecutarConsulta()){ try{ ResultSet rs = oConexion.getoResultSet(); if (rs.next()){ this.idCompra = Integer.parseInt(rs.getString(1)); this.fecha = rs.getString(3); this.medioPago = rs.getString(4); this.productos = rs.getString(5); oConexion.desconectar(); return true; }else{ oConexion.desconectar(); return false; } }catch(Exception e){ oConexion.desconectar(); System.out.println("ERROR " + e.getMessage()); return false; } } return false; } }
0bd5e33783dad92bb9f27daa87e4d0aa42c8b25e
[ "JavaScript", "Java", "SQL" ]
8
Java
esteguri/carrito_de_compras
0b3007b3934ac1830e4f7a68cdc8252cc3364484
0d62f7df8b46cfeabadd54b95ac7b91324d72893
refs/heads/master
<repo_name>JeethJJ/LaravelDev<file_sep>/README.md # LaravelDev A web application built on laravel <file_sep>/notepad/app/Http/Controllers/HomeController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; class HomeController extends Controller { public function list(){ $names=["Jihan","Jeeth","Jafeer"]; return view("contact",["contacts"=>$names]); } } <file_sep>/notepad/routes/web.php <?php /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ Route::get('/', function () { return view('welcome'); }); // Route::get('/contact',function(){ // $names=["Jihan","Jeeth","Jafeer"]; // return view("contact",["contacts"=>$names]); // }); Route::get('/contact','HomeController@list'); Route::get('/home',function(){ return view("home.home"); }); // we can use . or / to write the folder heirachy Route::get('/about',function(){ return view("about",["title"=>"Page"]); }); Route::get('/about',function(){ return view("about",["title"=>"Page"]); }); Route::get('/',function(){ return view("layouts.index"); }); Route::resource('student','StudentController');
62361159c64f6bed8356c0fa296b427b2649ec55
[ "Markdown", "PHP" ]
3
Markdown
JeethJJ/LaravelDev
f429c5fbda46d8e671cb385611cde0072ffff0a8
059e9550007337d49e62cec631260de75dc3098c
refs/heads/master
<file_sep>import redis import uuid import time import multiprocessing class RedisLock(object): def __init__(self, lock_key, redis_host='localhost', redis_port=6379): self._lock_value = str(uuid.uuid4()) self._lock_key = "lock_{}".format(lock_key) self._client = None self._make_redis_client(redis_host, redis_port) def acquire(self, timeout=10): while True: value = self._client.set(self._lock_key, self._lock_value, nx=True, ex=timeout) if value: print('lock success') return self._lock_value time.sleep(1) def release(self): cmd = 'if redis.call("get",KEYS[1]) == ARGV[1] then\n return redis.call("del",KEYS[1])\nelse\n return 0\nend' exe = self._client.register_script(cmd) exe(keys=[self._lock_key], args=[self._lock_value]) print('lock_failed') # old_value = self._client.get(self._lock_key) # if old_value == self._lock_value: # return self._client.delete(self._lock_key) def _make_redis_client(self, host, port): cache_connection_url = 'redis://{}:{}'.format(host, port) \ if host is not None and port is not None else 'redis://localhost:6379' connection_pool = redis.ConnectionPool.from_url(cache_connection_url) self._client = redis.StrictRedis(connection_pool=connection_pool, decode_responses=True) def test_func(): lock = RedisLock('test','localhost',6987) lock.acquire(timeout=10) time.sleep(5) lock.release() if __name__ == "__main__": for i in range(10): p1 = multiprocessing.Process(name=str(i), target=test_func) p1.start() # test_func()<file_sep>import redis import uuid import time import multiprocessing class RedisLock(object): def __init__(self, lock_key, redis_host='localhost', redis_port=6379): self._lock_value = str(uuid.uuid4()) self._lock_key = "lock_{}".format(lock_key) self._client = None self._make_redis_client(redis_host, redis_port) def acquire(self, timeout=10): while True: value = self._client.set(self._lock_key, self._lock_value, nx=True, ex=timeout) if value: print('lock success'+self._lock_value+';'+str(time.time())) return self._lock_value time.sleep(1) def release(self): pipe = self._client.pipeline(True) while True: try: pipe.watch(self._lock_key) # value = pipe.get(self._lock_key) if pipe.get(self._lock_key).decode(encoding='utf-8') == self._lock_value: pipe.multi() pipe.delete(self._lock_key) print('unlock success'+self._lock_value+';'+str(time.time())) pipe.execute() return True pipe.unwatch() break except redis.exceptions.WatchError: pass return False def _make_redis_client(self, host, port): cache_connection_url = 'redis://{}:{}'.format(host, port) \ if host is not None and port is not None else 'redis://localhost:6379' connection_pool = redis.ConnectionPool.from_url(cache_connection_url) self._client = redis.StrictRedis(connection_pool=connection_pool, decode_responses=True) def test_func(): lock = RedisLock('test','localhost',6379) lock.acquire(timeout=10) time.sleep(3) lock.release() if __name__ == "__main__": # test_func() for i in range(5): p1 = multiprocessing.Process(name=str(i), target=test_func) p1.start()
bef8a82ec8caae26049a4f7b1d408e165c33014e
[ "Python" ]
2
Python
airlovelq/distribute-lock
96a65d248d5d19c31ae388d8badf81be1a13a6d4
d74bf27a7c7ae0356bf893e66203f46316e0888b
refs/heads/master
<repo_name>nchan8150/MKS22X<file_sep>/02NQueens/Driver.java public class Driver{ public static void main(String[] args){ QueenBoard b = new QueenBoard(16); System.out.println(b.countSolutions()); // b.addQueen(2,4); // b.addQueen(1,1); // b.addQueen(3,4); // b.removeQueen(1,1); //System.out.println(b.solve()); //System.out.println(b); // System.out.println(b.solve()); } } <file_sep>/09StackCalculator/Calculator.java //got operations.contains(str) idea from Amit. import java.util.*; import java.lang.*; public class Calculator { public static double eval(String s) { Stack stack = new Stack(); String operations = "+-*/%"; //LinkedList<Double> stack = new LinkedList<>(); String[] arr = s.split(" "); for (int x = 0; x < arr.length; x++) { String str = arr[x]; if (operations.contains(str)) { if (str.equals("+")) { double num1 = stack.pop(); double num2 = stack.pop(); stack.push(num1+num2); } else if(str.equals("-")) { double num1 = stack.pop(); double num2 = stack.pop(); stack.push(num2-num1); } else if (str.equals("*")) { double num1 = stack.pop(); double num2 = stack.pop(); stack.push(num1*num2); } else if (str.equals("/")) { double num1 = stack.pop(); double num2 = stack.pop(); stack.push(num2/num1); } else if (str.equals("%")) { double num1 = stack.pop(); double num2 = stack.pop(); stack.push(num1%num2); } } else { Double d = Double.parseDouble(str); stack.push(d); } } return stack.peek(); } public static void main(String[] args) { System.out.println(eval("5 4 +")); //Should be 9 System.out.println(eval("5 4 -")); //1 System.out.println(eval("8 4 /")); // 2 System.out.println(eval("10 2.0 +")); //12 System.out.println(eval("11 3 - 4 + 2.5 *")); //30 System.out.println(eval("8 2 + 99 9 - * 2 + 9 -")); //893 } } <file_sep>/05USACO/USACO.java //had help from Raisa import java.io.*; import java.util.*; public class USACO { public static int bronze(String filename){ try { File text = new File(filename); Scanner input = new Scanner(text); int R = input.nextInt(); int C = input.nextInt(); int E = input.nextInt(); int N = input.nextInt(); int[][] lake = new int[R][C]; for (int r = 0; r < R; r++){ for (int c = 0; c < C; c++){ lake[r][c] = input.nextInt(); } } for (int n = N; n > 0; n--){ int R_s = input.nextInt() -1; int C_s = input.nextInt() -1; int D_s = input.nextInt(); int[][] cowLocations = new int[][] { {0,0}, {0,1}, {0,2}, {1,0}, {1,1}, {1,2}, {2,0}, {2,1}, {2,2} }; for (int d = D_s; d > 0; d--){ int max = 0; for (int i[]: cowLocations){ if (lake[R_s + i[0]][C_s + i[1]] > max){ max = lake[R_s + i[0]][C_s + i[1]]; } } for (int i[]: cowLocations){ if (lake[R_s + i[0]][C_s + i[1]] == max){ lake[R_s + i[0]][C_s + i[1]]--; } } } } int totalDepth = 0; for (int r = 0; r < R; r ++){ for (int c = 0; c < C; c++){ if (E > lake[r][c]){ totalDepth += E - lake[r][c]; } } } return totalDepth * 72 *72; }catch(Exception e){System.exit(1);} return 0; } public static int silver(String filename) throws FileNotFoundException{ File text = new File(filename); Scanner inf = new Scanner(text); int row = inf.nextInt(); int col = inf.nextInt(); int steps = inf.nextInt(); inf.nextLine(); char[][] map = new char[row][col]; for (int x = 0; x < row; x++) { String line = inf.nextLine(); for (int y = 0; y < col; y++){ map[x][y] = line.charAt(y); } } int startRow = inf.nextInt(); int startCol = inf.nextInt(); int endRow = inf.nextInt(); int endCol = inf.nextInt(); int[][] allPath = new int[row][col]; allPath[startRow - 1][startCol - 1] = 1; int CT = 0; while (CT < steps){ int[][] currentPath = new int[row][col]; for (int x = 0; x < row; x++){ for (int y = 0; y < col; y++){ if (map[x][y] != '*'){ if ((x+1) < row){ currentPath[x][y] = currentPath[x][y] + allPath[x+1][y]; } if ((x-1) >= 0){ currentPath[x][y] = currentPath[x][y] + allPath[x-1][y]; } if ((y+1) < col){ currentPath[x][y] = currentPath[x][y] + allPath[x][y+1]; } if ((y-1) >= 0){ currentPath[x][y] = currentPath[x][y] + allPath[x][y-1]; } } } } for (int x = 0; x < row; x++){ for (int y = 0; y < col; y++){ allPath[x][y] = currentPath[x][y]; } } CT = CT + 1; } return allPath[endRow - 1][endCol - 1]; } } <file_sep>/09StackCalculator/Stack.java import java.util.*; public class Stack { private LinkedList<Double> stack; public Stack() { stack = new LinkedList<Double>(); } public Double pop() { return stack.remove(stack.size()-1); } public Double peek() { return stack.get(stack.size()-1); } public void push(Double d) { stack.add(d); } } <file_sep>/08LinkedList/MyLinkedList.java public class MyLinkedList { private Node first, last; private int length; public String toString() { String ans = "["; Node temp = first; while(temp != null) { ans += temp; if(temp.getNext() != null) { ans += ", "; } temp = temp.getNext(); } ans += "]"; return ans; } public Integer get(int index) { return getNode(index).getValue(); } public void set(int index, Integer value) { if(index >= length || index < 0) { throw new IndexOutOfBoundsException(); } Node temp = getNode(index); temp.setValue(value); } public int size() { return length; } public boolean add(Integer value) { Node create = new Node(value); if (length == 0) { first = last = create; length = 1; return true; } last.setNext(create); create.setPrev(last); length ++; last = create; return true; } public void add(int index, Integer value) { Node created = new Node(value); if(index > length || index < 0) { throw new IndexOutOfBoundsException(); } else if(index == length) { add(value); return; } else if (index == 0) { first.setPrev(created); created.setNext(first); first = created; } else { created.setNext(getNode(index)); created.setPrev(created.getNext().getPrev()); created.getNext().setPrev(created); created.getPrev().setNext(created); } length++; } public Integer remove(int index) { if (index > length || index < 0) { throw new IndexOutOfBoundsException(); } Node temp = getNode(index); Integer removed = temp.getValue(); if (index == 0){ first = first.getNext(); first.setPrev(null); } else if (index == length -1){ last = last.getPrev(); last.setNext(null); } else{ temp.getPrev().setNext(temp.getNext()); temp.getNext().setPrev(temp.getPrev()); } length--; return removed; } public boolean remove(Integer value) { int x = indexOf(value); if (x == -1) { return false; } else { remove(x); return true; } } public int indexOf(Integer value){ Node chosen = first; for (int x = 0; x < length; x++){ if (chosen.getValue().equals(value)){ return x; } chosen = chosen.getNext(); } return -1; } private Node getNode(int index){ if(index >= length || index < 0){ throw new IndexOutOfBoundsException(); } Node gotti = first; for (int x = 0; x < index; x++){ gotti = gotti.getNext(); } return gotti; } public void clear() { first = null; last = null; length = 0; } public MyLinkedList() { first = null; last = null; length = 0; } private class Node { private Node next, prev; private Integer data; public Node getNext() { return next; } public Node getPrev() { return prev; } public Integer getValue() { return data; } public void setValue(Integer value) { data = value; } public void setNext(Node newN) { next = newN; } public void setPrev(Node newN) { prev = newN; } public String toString() { return data + ""; } private Node(Integer value) { data = value; next = null; prev = null; } } } <file_sep>/02NQueens/QueenBoard.java //JAVAC BOTH AND RUN DRIVER THEN GO FROM THERE. //size 2 and 3 wont work //negatives wont work //cant call solve twice bc its not 0 anymore //put 1 in each coloumn //rewrite add and remove lmao //runtime? how slow is this really public class QueenBoard { private int[][]board; public QueenBoard (int size) { board = new int[size][size]; } private boolean addQueen(int r, int c) { if (board[r][c] != 0) { return false; } for(int x = r; x < board.length; x++) { board[x][c] += 1; } for(int y = c; y < board[r].length; y++) { board[r][y] += 1; } int diagDown = 0; for(int z = r; z < board.length && c + diagDown < board.length; z++) { board[z][c + diagDown] += 1; diagDown += 1; } int diagUp = 0; for(int i = r; i >= 0 && c + diagUp < board.length; i--) { board[i][c + diagUp] += 1; diagUp += 1; } board[r][c] = -1; return true; } private boolean removeQueen(int r, int c) { if (board[r][c] != -1) { return false; } for(int x = r; x < board.length; x++) { board[x][c] -= 1; } for(int y = c; y < board[r].length; y++) { board[r][y] -= 1; } int diagDown = 0; for(int z = r; z < board.length && c + diagDown < board.length; z++) { board[z][c + diagDown] -= 1; diagDown += 1; } int diagUp = 0; for(int i = r; i >= 0 && c + diagUp < board.length; i--) { board[i][c + diagUp] -= 1; diagUp += 1; } board[r][c] = 0; return true; } public String toString() { String bb = ""; for(int x = 0; x < board.length; x++) { for (int y = 0; y < board[x].length; y++) { if (board[x][y] == -1) { bb += "Q "; } else bb += "_ "; //board[x][y] + " "; } bb += "\n"; } return bb; } public boolean solve() { for(int x = 0; x < board.length; x++) { for(int y = 0; y < board[x].length; y++) { if(board[x][y] != 0) { throw new IllegalStateException(); } } } return solver(0); } public boolean solver(int col) { if(col >= board.length) { return true; } for(int x = 0; x < board.length; x++) { if(addQueen(x, col)) { if(solver(col+1)) { return true; } else { removeQueen(x, col); } } } return false; } public int countSolutions() { for(int x = 0; x < board.length; x++) { for(int y = 0; y < board[x].length; y++) { if(board[x][y] != 0) { throw new IllegalStateException(); } } } return countSolutionsHelp(0); } public int countSolutionsHelp(int col) { if(col >= board.length) { return 1; } int total = 0; for(int x = 0; x < board.length; x++) { if(addQueen(x, col)) { total += countSolutionsHelp(col+1); removeQueen(x,col); } } return total; } } <file_sep>/01Recursion/Recursion.java public class Recursion { public int fact(int n) { if (n < 0) { throw new IllegalArgumentException(); } if (n == 0) { return 1; } return n * fact(n - 1); } public int fib(int n) { return fibHelp(n, 0, 0, 1); } public int fibHelp(int n, int count, int twoBefore, int oneBefore) { if (n < 0) { throw new IllegalArgumentException(); } if (n == count) { return twoBefore; } return fibHelp(n, count + 1, oneBefore, oneBefore + twoBefore); } public double sqrt(double n) { return sqrtHelp(n, n / 2); } public double sqrtHelp(double n, double guess) { if (n < 0) { throw new IllegalArgumentException(); } if (n == 0) { return 0; } if (((n * 1.000001) > (guess * guess)) && ((n * 0.99999) < (guess * guess))) { return guess; } return sqrtHelp(n, (n / guess + guess) / 2); } /* public static void main(String[] args) { System.out.println(fact(0)); //should be 1 System.out.println(fact(5)); //should be 120 //System.out.println(fact(-50)); //error System.out.println(fib(0)); //should be 0 System.out.println(fib(1)); //should be 1 System.out.println(fib(6)); //should be 8 //System.out.println(fib(1000)); //System.out.println(fib(-50)); //error System.out.println(sqrt(0)); //should be 0 System.out.println(sqrt(1)); //should be 1 System.out.println(sqrt(4)); //should be 2 System.out.println(sqrt(.1111111)); //should be .3333333 System.out.println(sqrt(10)); //should be 3.16 //System.out.println(sqrt(-4)); //error } */ } <file_sep>/14Frontier/MazeSolver.java public class MazeSolver{ private Maze maze; private Frontier frontier; public MazeSolver(String mazeText){ maze = new Maze(mazeText); } //Default to BFS public boolean solve(){ return solve(0); } //mode: required to allow for alternate solve modes. //0: BFS //1: DFS public boolean solve(int mode){ //initialize your frontier //while there is stuff in the frontier: // get the next location // process the location to find the locations (use the maze to do this) // check if any locations are the end, if you found the end just return true! // add all the locations to the frontier //when there are no more values in the frontier return false if (mode == 0){ frontier = new FrontierQueue(); } if (mode == 1){ frontier = new FrontierStack(); } if (mode == 2){ frontier = new FrontierPriorityQueue(); } else{ frontier = new FrontierPriorityQueue(); maze.setAStar(true); } frontier.add(maze.getStart()); while (frontier.hasNext()){ Location n = frontier.next(); if (!(n.equals(maze.getStart()))){ maze.set(n.getx(), n.gety(), '.'); } Location[] locs = maze.getNeighbors(n); for (Location l : locs){ if (l != null){ if (l.equals(maze.getEnd())){ while (!(n.equals(maze.getStart()))){ maze.set(n.getx(), n.gety(), '@'); n = n.getprev(); } return true; } frontier.add(l); maze.set(l.getx(), l.gety(), '?'); } } } return false; } public String toString(){ return maze.toString(); } }<file_sep>/12MyHeap/Sorts.java import java.util.*; public class Sorts extends MyHeap{ public static void heapsort(int[] data){ MyHeap<Integer> heap = new MyHeap<Integer>(false); for (int x = 0; x < data.length; x++){ heap.add(data[x]); } for (int x = 0; x < data.length; x++){ data[x] = heap.peek(); heap.remove(); } } /* public static void main(String[] args){ int[] reg = new int[25]; int[] heap = new int[25]; for(int i = 0; i < 25; i ++){ int temp = (int)(Math.random() * 1000); reg[i] = temp; heap[i] = temp; } Arrays.sort(reg); Sorts.heapsort(heap); for(int i = 0; i < 25; i++){ if(reg[i] != heap[i]){ System.out.println("There is an error at index " + i); System.out.println("reg: " + Arrays.toString(reg)); System.out.println("hea: " + Arrays.toString(heap)); } } } */ }
ff796d3ca8fe49959212244fa6556040972b80cf
[ "Java" ]
9
Java
nchan8150/MKS22X
edd563fd7ff57936618aeed331971f3bca661a4c
5a9575275e51b9531e65e870a0f1255267c373f5
refs/heads/master
<repo_name>ilziramoiseeva/NPSService<file_sep>/src/Main.java public class Main { public static void main(String[] args) { NPSService service = new NPSService(); System.out.println(service.nps(new int[]{1, 2, 3, 4,7,10,9,1,8,10,11})); } }
67d2d06669af0b79c3097773572e6676686c86b0
[ "Java" ]
1
Java
ilziramoiseeva/NPSService
9e67829d9820b96b26af899df1518d22b0a30130
7a8903f3b64b939f4283e16ec6dd9c68159d6426
refs/heads/master
<repo_name>Allanksr/Android<file_sep>/Firebase Crashlytics/Crashlytics/app/src/main/java/allanksr/crashlytics/MainActivity.kt package allanksr.crashlytics import android.os.Bundle import android.text.InputFilter import com.google.android.material.snackbar.Snackbar import androidx.appcompat.app.AppCompatActivity import android.view.Menu import android.view.MenuItem import android.widget.Toast import com.google.firebase.crashlytics.FirebaseCrashlytics import kotlinx.android.synthetic.main.activity_main.* import kotlinx.android.synthetic.main.content_main.* class MainActivity : AppCompatActivity() { private lateinit var mCrash: FirebaseCrashlytics private var from = "" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) setSupportActionBar(toolbar) from = packageName.toString() mCrash = FirebaseCrashlytics.getInstance() edtTofatalTest.filters = arrayOf<InputFilter>(InputFilter.LengthFilter(20)) edtTofatalTestCustom.filters = arrayOf<InputFilter>(InputFilter.LengthFilter(20)) edtTofatalTest.hint = "IllegalArgumentException fatalTest" fatalTest.setOnClickListener{ if(edtTofatalTest.text.toString().isNotEmpty()){ throw IllegalArgumentException("IllegalArgumentException Text : ${edtTofatalTest.text.toString()}") } } edtTofatalTestCustom.hint = "IllegalArgumentException fatalTestCustom" fatalTestCustom.setOnClickListener{ if(edtTofatalTestCustom.text.toString().isNotEmpty()){ mCrash.setUserId(from) mCrash.setCustomKey("fatalTestCustom",edtTofatalTestCustom.text.toString()) throw IllegalArgumentException("IllegalArgumentException Text : ${edtTofatalTestCustom.text.toString()}") } } fab.setOnClickListener { view -> Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) .setAction("Action", null).show() } } override fun onCreateOptionsMenu(menu: Menu): Boolean { // Inflate the menu; this adds items to the action bar if it is present. menuInflater.inflate(R.menu.menu_main, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. return when (item.itemId) { R.id.action_settings -> true else -> super.onOptionsItemSelected(item) } } } <file_sep>/Firebase Crashlytics/README.md # Implementação do Firebase Crashlytics Android Antes de prosseguir, é extremamente importante você assistir esse vídeo : **[Assistir YouTube](https://www.youtube.com/watch?v=a-XgoJSNx-k)**<br><br> <img src="https://raw.githubusercontent.com/Allanksr/Android/master/Firebase%20Crashlytics/firebase.gif" width="200"> <img src="https://raw.githubusercontent.com/Allanksr/Android/master/Firebase%20Crashlytics/firebase_crashlytics_installed.gif" width="200"> <a href="https://www.youtube.com/watch?v=a-XgoJSNx-k"> <img src="https://raw.githubusercontent.com/Allanksr/Android/master/Firebase%20Crashlytics/capa.png" width="200"> </a> <file_sep>/Firebase Crashlytics/Crashlytics/settings.gradle include ':app' rootProject.name='Crashlytics'
aef6022c6781a8280e392e6173ece5ba85c874bb
[ "Markdown", "Kotlin", "Gradle" ]
3
Kotlin
Allanksr/Android
a12c46e8e65d0bf76b2fa5758e781fda820e5e53
9abde72b08951df524e922439fc994ae464f2316
refs/heads/main
<repo_name>nishantsethi/MonthBar-Twitter<file_sep>/Progress_bar.py #Responsible for Creating the Progress import datetime import calendar def ProgressBar(): fill = "▓" empty ="░" now = datetime.datetime.now() current_date = now.day total_days = calendar.monthrange(now.year, now.month)[1] percentage = round(current_date/total_days,2) bar = "" to_fill = int(percentage*15) to_empty = 15 - to_fill for i in range(to_fill): bar += fill for j in range(to_empty): bar += empty full_bar = bar + " " + str(int(percentage*100)) + "%" + " of " + calendar.month_name[now.month] + " is Complete!" return full_bar <file_sep>/README.md # MonthBar-Twitter A Twitter bot that Tweets a progress bar every day Bot can be access by visiting [@MonthBar](https://twitter.com/MonthBar) on Twitter ## Bot in Action: ![@MonthBar on Twitter](https://raw.githubusercontent.com/nishantsethi/MonthBar-Twitter/main/common/01.png)<file_sep>/app.py import tweepy from Credentials.Keys import api_key,api_secret_key,access_token,access_token_secret from Progress_bar import ProgressBar #Auth auth = tweepy.OAuthHandler(api_key, api_secret_key) auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth) api.update_status(ProgressBar())
fde405f5a1270fd5a88057576a6e59beb8c79a5b
[ "Markdown", "Python" ]
3
Python
nishantsethi/MonthBar-Twitter
e684276e04b6af0e43a1a41180ede8db9d34d427
b2b64d9f9dd6e9910c2fac92ce4e4459ece7c180
refs/heads/master
<file_sep><?php require_once 'libs/Frex/Frex.php'; // initialize the app $app = new Frex(); /* set routes */ // without pass any controller method $app->set('/'); // current secrets $app->set('/secrets', 'SecretsController:getSecrets'); // login to app $app->set('/login', 'UserController:loginToApp'); // check for token if it's match $app->set('/checkForToken', 'UserController:checkForToken'); // register to app $app->set('/register', 'UserController:registerNewUser'); // run the app! $app->run(); ?> <file_sep><?php Class BlogController extends Controller { public function setting_data() { // set type of content (json) Presentation::presentation_type('application/json'); // get setting data $setting_data = BlogModel::get_setting_data(); // output setting data in json format Presentation::present_data($setting_data, 'application/json'); } public function setting_key_value($data) { // set type of content (json) Presentation::presentation_type('application/json'); // get setting key value $setting_key_value = BlogModel::get_setting_value_by_key($data['key']); // output setting key value in json format Presentation::present_data($setting_key_value, 'application/json'); } } ?> <file_sep>-- phpMyAdmin SQL Dump -- version 4.2.5 -- http://www.phpmyadmin.net -- -- Host: localhost:8889 -- Generation Time: Mar 19, 2015 at 11:13 PM -- Server version: 5.5.38 -- PHP Version: 5.5.14 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; -- -- Database: `boax_blog` -- -- -------------------------------------------------------- -- -- Table structure for table `posts` -- CREATE TABLE `posts` ( `post_id` int(11) NOT NULL, `post_name` varchar(100) COLLATE utf8_unicode_ci NOT NULL, `post_title` varchar(200) COLLATE utf8_unicode_ci NOT NULL, `post_content` text COLLATE utf8_unicode_ci NOT NULL, `post_created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, `post_author` varchar(40) COLLATE utf8_unicode_ci NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=12 ; -- -- Dumping data for table `posts` -- INSERT INTO `posts` (`post_id`, `post_name`, `post_title`, `post_content`, `post_created_at`, `post_author`) VALUES (1, 'first_post', 'First Post', '<p>This is a content for a post</p>', '2015-03-11 20:13:30', '<NAME>'), (2, 'another_post', 'Another post', '<p>This is another post content!</p>\r\n\r\n<p>However, you can edit this area.</p>', '2015-03-11 20:53:21', '<NAME>'), (3, 'the-game-is-out', 'The game is out!', 'Your game is out!', '0000-00-00 00:00:00', '<NAME>'), (4, 'tic-tac-toe.2-beta-0-3-6-released', 'Tic Tac Toe 2beta.0.3.6 is released', '<p>Just released the beta version</p>\n<strong>Download from GitHub!</strong>', '2015-03-18 20:04:23', '<NAME>'), (5, 'demo-topic', 'Demo topic', '<p>This is a testing topic</p>', '2015-03-18 20:08:07', '<NAME>'), (6, 'another-demo', 'Another demo', '...', '2015-03-18 20:09:09', '<NAME>'), (7, 'testing', 'Testing', 'Just a post', '2015-03-19 21:51:55', 'John'), (8, 'just-a-post', 'Just a post', 'nothing!', '2015-03-19 22:10:01', 'John'); -- -------------------------------------------------------- -- -- Table structure for table `setting` -- CREATE TABLE `setting` ( `setting_id` int(11) NOT NULL, `setting_key` varchar(100) COLLATE utf8_unicode_ci NOT NULL, `setting_value` text COLLATE utf8_unicode_ci NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=2 ; -- -- Dumping data for table `setting` -- INSERT INTO `setting` (`setting_id`, `setting_key`, `setting_value`) VALUES (1, 'blog_title', 'Boax Blog'); -- -- Indexes for dumped tables -- -- -- Indexes for table `posts` -- ALTER TABLE `posts` ADD PRIMARY KEY (`post_id`); -- -- Indexes for table `setting` -- ALTER TABLE `setting` ADD PRIMARY KEY (`setting_id`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `posts` -- ALTER TABLE `posts` MODIFY `post_id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=12; -- -- AUTO_INCREMENT for table `setting` -- ALTER TABLE `setting` MODIFY `setting_id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=2; <file_sep>-- phpMyAdmin SQL Dump -- version 4.2.5 -- http://www.phpmyadmin.net -- -- Host: localhost:8889 -- Generation Time: Mar 23, 2015 at 12:35 AM -- Server version: 5.5.38 -- PHP Version: 5.5.14 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; -- -- Database: `fex_app` -- -- -------------------------------------------------------- -- -- Table structure for table `secrets` -- CREATE TABLE `secrets` ( `secret_id` int(11) NOT NULL, `secret_content` text COLLATE utf8_unicode_ci NOT NULL, `secret_created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=2 ; -- -- Dumping data for table `secrets` -- INSERT INTO `secrets` (`secret_id`, `secret_content`, `secret_created_at`) VALUES (1, 'You are awesome!', '2015-03-20 00:22:15'); -- -------------------------------------------------------- -- -- Table structure for table `users` -- CREATE TABLE `users` ( `user_id` int(11) NOT NULL, `user_email` varchar(150) COLLATE utf8_unicode_ci NOT NULL, `user_pass` varchar(200) COLLATE utf8_unicode_ci NOT NULL, `user_token` varchar(100) COLLATE utf8_unicode_ci NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=3 ; -- -- Dumping data for table `users` -- INSERT INTO `users` (`user_id`, `user_email`, `user_pass`, `user_token`) VALUES (1, '<EMAIL>', '<PASSWORD>', 'otw97fl91nv6h5ya6ewpcp8xfk6eogdpmac2qtldj6lrqrifmx'), (2, '<EMAIL>', '<PASSWORD>', 'otw97fl91nv6h5ya6ewpcp8xfk6eogdpmac2qtldj6lrqrifmx'); -- -- Indexes for dumped tables -- -- -- Indexes for table `secrets` -- ALTER TABLE `secrets` ADD PRIMARY KEY (`secret_id`); -- -- Indexes for table `users` -- ALTER TABLE `users` ADD PRIMARY KEY (`user_id`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `secrets` -- ALTER TABLE `secrets` MODIFY `secret_id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=2; -- -- AUTO_INCREMENT for table `users` -- ALTER TABLE `users` MODIFY `user_id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=3; <file_sep> // auth controller authApp.controller('AuthController', function($scope, $localStorage) { //console.log($localStorage.isAuthorized); if ($localStorage.isAuthorized == undefined) { $scope.isAuthorized = false; } }); // login controller authApp.controller('LoginController', function($scope, $http, $localStorage, $window) { var backEndUrl = 'http://vserver/learning-angular-examples/fex-secret/back-end'; $scope.loginSubmit = function() { if ($scope.loginForm.$valid) { $http.post(backEndUrl+'/login',{ 'user_email': $scope.email, 'user_pass': <PASSWORD> }).success(function(data) { if (data.isValid) { $scope.incorrectData = false; // add the token to local storage $localStorage.user_token = data.user_token; $localStorage.isAuthorized = true; if ($localStorage.user_token != undefined && $localStorage.isAuthorized != undefined) { // redirect to app (simple dashboard) setTimeout(function() { $window.location.href = 'index.html'; }, 300); } } else { alert('Username or password is incorrect'); $scope.incorrectData = true; } //console.log(data); }); } } }); // register controller authApp.controller('RegisterController', function($scope, $http, $localStorage, $window) { var backEndUrl = 'http://vserver/learning-angular-examples/fex-secret/back-end'; $scope.registerSubmit = function() { if ($scope.registerForm.$valid) { $http.post(backEndUrl+'/register',{ 'user_email': $scope.email, 'user_pass': $<PASSWORD> }).success(function(data) { //console.log(data); if (data.isExist == false) { $scope.registed = true; // add the token to local storage $localStorage.user_token = data.user_token; $localStorage.isAuthorized = true; if ($localStorage.user_token != undefined && $localStorage.isAuthorized != undefined) { // redirect to app (simple dashboard) setTimeout(function() { $window.location.href = 'index.html'; }, 300); } } else { alert("Your email is exist already!"); } }); } } }); <file_sep>var app = angular.module('fex-secret',['ngStorage']); <file_sep><?php Class PostsController extends Controller { public function lastPosts() { // set type of content (json) Presentation::presentation_type('application/json'); // get last posts $last_posts = PostsModel::get_last_posts(); // output last posts in json format Presentation::present_data($last_posts, 'application/json'); } public function addNewPost() { // set type content (json) Presentation::presentation_type('application/json'); // set POST input values $input_data = Presentation::input_data_as_json(); // insert new post to database PostsModel::add_new_post($input_data->post_title, $input_data->post_name, $input_data->post_author, $input_data->post_content); } } ?> <file_sep><?php class PostSingleController extends Controller { public function singlePost($data) { // set output type to json Presentation::presentation_type('application/json'); // get single post $single_post = PostSingleModel::getSinglePostById($data['id']); // return single post as json format Presentation::present_data($single_post, 'application/json'); } } ?><file_sep><?php Class PostSingleModel extends Model { public function getSinglePostById($id) { // connect with database $database = new Database(); // get single post $single_post_data = $database->query_assoc("SELECT * FROM posts WHERE post_id = '$id'"); // close database connection $database->close(); // return single post return $single_post_data; } } ?> <file_sep><?php Class SecretsModel extends Model { public function getSecrets($request) { if ($request == 'secrets') { $database = new Database(); $secrets = $database->query_assoc("SELECT * FROM secrets"); $database->close(); return $secrets; } return false; } } ?> <file_sep><?php /** * Class: Presentation Class * Handling presentation in Frex micro-framework **/ Class Presentation { // change presentation type public function presentation_type($presentation_type) { /* Content-types: plain-text application/json application/xml text/html */ header('Content-type: '. $presentation_type); } // present data in specific presentation type public function present_data($data, $presentation_type) { // present in JSON format if ($presentation_type == 'application/json') { echo json_encode($data); // present in Plain/text format } else if ($presentation_type == 'plain/text') { echo trim(strip_tags($data)); // present in XML format } else if ($presentation_type == 'application/xml') { $xml = new SimpleXMLElement('<root/>'); array_walk_recursive($data, array($xml, 'addChild')); print $xml->asXML(); // present in HTML format } else if ($presentation_type == 'text/html') { print_r($data); } } // include php input data in specific format public function input_data_as_json() { // set input data $input_data = file_get_contents('php://input'); if (strlen($input_data) > 2) { // return input data in JSON format return json_decode($input_data); } } } ?> <file_sep><?php Class UserModel extends Model { public function randomToken($length) { $key = ''; $keys = array_merge(range(0, 9), range('a', 'z')); for ($i = 0; $i < $length; $i++) { $key .= $keys[array_rand($keys)]; } return $key; } public function checkForLoginProcess($email, $password) { if ($email != null && $password != null) { $database = new Database(); $email = $database->validate($email); $password = $database->validate($password); $get_token = $database->query_assoc("SELECT user_token FROM users WHERE user_email = '$email' AND user_pass = MD5('$<PASSWORD>')"); if (count($get_token) != 0) { $user_token = UserModel::randomToken(50); $update_token = $database->query("UPDATE users SET user_token='$user_token'"); $get_token = $database->query_assoc("SELECT user_token FROM users WHERE user_email = '$email' AND user_pass = MD5('$<PASSWORD>')"); } $database->close(); return $get_token; } return; } public function registerNewUser($email, $password) { if ($email != null && $password != null) { $database = new Database(); $email = $database->validate($email); $password = $database->validate($password); $checkEmailIfExist = $database->query_assoc("SELECT * FROM users WHERE user_email = '$email'"); if (count($checkEmailIfExist) != 0) { $database->close(); return array('isExist' => true); } else { $user_token = UserModel::randomToken(50); $registerNewUser = $database->query("INSERT INTO users (user_email, user_pass, user_token) VALUE ('$email', MD5('$password'), '$user_token')"); $database->close(); return array('isExist' => false, 'user_token' => $user_token); } } return; } public function checkForTokenMatch($token) { if ($token != null) { $database = new Database(); $token = $database->validate($token); $get_token = $database->query_assoc("SELECT user_token FROM users WHERE user_token = '$token'"); $database->close(); return $get_token; } return; } } ?> <file_sep><?php Class PostsModel extends Model { public function get_last_posts() { // connect with database $database = new Database(); // get last posts $last_posts = $database->query_assoc("SELECT * FROM posts Order By post_created_at DESC"); // close database connection $database->close(); // return last posts return $last_posts; } public function add_new_post($post_title, $post_name, $post_author, $post_content) { // connect with database $database = new Database(); // validate all input values $post_title = $database->validate($post_title); $post_name = $database->validate($post_name); $post_author = $database->validate($post_author); $post_content = $database->validate($post_content); // check if all input is not empty if ($post_title != null && $post_name != null && $post_author != null && $post_content != null) { // insert new post $insert_post = $database->query("INSERT INTO posts (post_title, post_name, post_author, post_content) VALUES ('$post_title', '$post_name', '$post_author', '$post_content')"); // output json response of result echo Presentation::present_data($insert_post, 'application/json'); } // close database connection $database->close(); } } ?> <file_sep>// app controller app.controller('AppController', function($http, $scope, $localStorage, $window ) { var backEndUrl = 'http://vserver/learning-angular-examples/fex-secret/back-end'; if ($localStorage.user_token == undefined && $localStorage.isAuthorized == undefined) { $scope.isAuthorized = false; $window.location.href = "auth.html"; } else if ($localStorage.isAuthorized == true && $localStorage.user_token != null) { $scope.isAuthorized = true; // $http.post(backEndUrl+'/checkForToken', {'user_token': $localStorage.user_token}).success(function(data) { // if ($localStorage.user_token == data.user_token) { // $scope.isAuthorized = true; // } else { // $scope.isAuthorized = false; // } // }); } $scope.logoutFromApp = function() { $localStorage.$reset(); setTimeout(function() { $window.location.href = 'auth.html'; }, 300); } }); // secrets controller app.controller('SecretsController', function($scope, $http) { var backEndUrl = 'http://vserver/learning-angular-examples/fex-secret/back-end'; if ($scope.isAuthorized == true) { $scope.secrets = []; $http.post(backEndUrl+'/secrets', {request: 'secrets'}).success(function(data) { $scope.secrets = data; }); } }); <file_sep><?php Class BlogModel extends Model { public function get_setting_data() { // connect with database $database = new Database(); // get setting data $setting_data = $database->query_assoc("SELECT * FROM setting"); // close database connection $database->close(); // return setting data return $setting_data; } public function get_setting_value_by_key($key) { // connect with database $database = new Database(); // get setting single value $setting_key_value = $database->query_assoc("SELECT setting_value FROM setting WHERE setting_key='$key'"); // close database connection $database->close(); // return setting single value return $setting_key_value; } } ?> <file_sep><?php Class UserController extends Controller { public function loginToApp() { Presentation::presentation_type('application/json'); $input_data = Presentation::input_data_as_json(); $login_result = UserModel::checkForLoginProcess($input_data->user_email, $input_data->user_pass); if ($login_result == '') { echo 'Access denied'; } else { if ($login_result == null) { $login_result[0]['isValid'] = false; } else { $login_result[0]['isValid'] = true; } Presentation::present_data($login_result[0], 'application/json'); } } public function checkForToken() { Presentation::presentation_type('application/json'); $input_data = Presentation::input_data_as_json(); $isTokenMatch = UserModel::checkForTokenMatch($input_data->user_token); if ($isTokenMatch == '') { echo 'Access denied'; } else { Presentation::present_data($isTokenMatch[0], 'application/json'); } } public function registerNewUser() { Presentation::presentation_type('application/json'); $input_data = Presentation::input_data_as_json(); $toRegisterNewUser = UserModel::registerNewUser($input_data->user_email, $input_data->user_pass); if ($toRegisterNewUser == '') { echo 'Access denied'; } else { Presentation::present_data($toRegisterNewUser, 'application/json'); } } } ?> <file_sep><?php Class SecretsController extends Controller { public function getSecrets() { Presentation::presentation_type('application/json'); $input_data = Presentation::input_data_as_json(); $secrets = SecretsModel::getSecrets($input_data->request); if ($secrets != false) { Presentation::present_data($secrets, 'application/json'); } else { echo 'Access denied'; } } } ?> <file_sep>// url of back-end stuff var backend_url = 'http://vserver/learning-angular-examples/boaxBlog/back-end/'; // angular app var app = angular.module('boaxBlog', ['ngSanitize', 'ngRoute']); /* App Route */ app.config(['$routeProvider', function($routeProvider) { $routeProvider .when('/', { templateUrl: 'articles.html', controller: 'content' }) .when('/add', { templateUrl: 'add-new-post.html', controller: 'AddNewPostController' }) .otherwise({ redirectTo: '/' }); }]); /* Controllers */ // blog header controller app.controller('blogHeader', function($scope, $http) { // set blog name variable $scope.blog_name = ''; // get blog name $http.get(backend_url+'blog/setting/blog_title').success(function(data){ $scope.blog_name = data[0].setting_value; }); }) // content controller app.controller('content', function($scope, $http) { // set last posts object $scope.last_posts = []; // get last posts object $http.get(backend_url+'blog/posts').success(function(data) { $scope.last_posts = data; }); }) // add new post controller app.controller('AddNewPostController', function($scope, $http,$location) { // initial scope attributes $scope.isSubmitted = false; $scope.post_title; $scope.post_name; $scope.post_author; $scope.post_content; // add new post method $scope.addNewPost = function() { // the form is submitted $scope.isSubmitted = true; if ($scope.addNewPostForm.$valid) { // insert new post $http.post(backend_url+'blog/posts/add', { post_title: $scope.post_title, post_name: $scope.post_name, post_author: $scope.post_author, post_content: $scope.post_content }). success(function(data) { console.log(data); // set form status to default $scope.isSubmitted = false; $scope.addNewPostForm.$submitted = false; // clear all input values $scope.post_title = ''; $scope.post_name = ''; $scope.post_author = ''; $scope.post_content = ''; }). error(function(data) { console.log(data); }); } else { $scope.isSubmitted = false; $scope.addNewPostForm.$submitted = false; } } // cancel adding the post $scope.cancelAddPost = function() { $location.path('/'); } }); <file_sep><?php require_once 'libs/Frex/Frex.php'; // initialize the app $app = new Frex(); /* set routes */ // blog setting route $app->set('/blog/setting', 'BlogController:setting_data'); // blog setting key value route $app->set('/blog/setting/:key', 'BlogController:setting_key_value'); // posts route $app->set('/blog/posts', 'PostsController:lastPosts'); // single post route $app->set('/blog/posts/single/:id', 'PostSingleController:singlePost'); // add new post route $app->set('/blog/posts/add','PostsController:addNewPost'); // run the app! $app->run(); ?>
17b50049707c1554ba9036c0999ab9c0f133bb47
[ "JavaScript", "SQL", "PHP" ]
19
PHP
aakatheeri/learning-angular-examples
52401796d7f53f02599746e4c59e0dfdc042bc7f
4272171f566b9d2b457d29f86b2097ef29704c7d
refs/heads/master
<repo_name>PabloLSF/Teste-para-vaga-de-estagiario<file_sep>/Desafio Fron-Back-end/database/CreateDataBase.sql CREATE DATABASE `PostdataBase` <file_sep>/README.md # Teste para vaga de estagiário por <NAME> ## Desafios realizados. ### Lista de exercícios: 1- Foi realizado todos os exercícios em um único arquivo. #### Execução do código 1. Execute o arquivo `FuctionsTest.js` que se localiza no diretorio `/Desafio JS` 2. Execute atravez do pront de comando ou pelo site `jsbin.com` ### Exercício de front-end e Back-end: 1. Instalar [Node.JS](https://nodejs.org/en/download/package-manager/) ultima versão 2. Instalar MySql 3. Clonar este repositorio 4. Crie o banco de dados: - CREATE USER `root` WITH PASSWORD `<PASSWORD>` - CREATE DATABASE `PostdataBasev` #### Execução do código 1. Execute o arquivo index.js em `/Desfio Fron-Back-end/index.js` 2. Abra o navegador na url `http://localhost:8080/` 3. Crie um novo Post em `Postar`. 4. Localize o novo Post. 5. Click em `Ver Post` . 6. Realize um comentário em `Comentar` 7. Click no símbolos do `Nave.rs` para voltar a Home Page. ## Estrutura do Diretorio ``` ├── /Desfio Fron-Back-end | ├── /database | ├── /node_modules | ├── /public | ├── /views | | ├── /partil ├── /Desfio Js ``` <file_sep>/Desafio Fron-Back-end/database/Comment.js const Sequelize = require("sequelize"); const connection = require("./database"); const Comment= connection.define("comment",{ body:{ type: Sequelize.TEXT, allowNull:false, }, postId: { type: Sequelize.INTEGER, allowNull: false } }); Comment.sync({force: false}); module.exports= Comment; <file_sep>/Desafio JS/FuctionsTest.js // arry para o proximo exercicio var arry = [ {id: 1, nome: 'juca', sobrenome: '<NAME>', idade: 42}, {id: 2, nome: 'daniel', sobrenome: 'gonçalves', idade: 21}, {id:3, nome: 'matheus', sobrenome: 'garcia', idade: 28}, {id: 4, nome: 'gabriel', sobrenome: 'pinheiro', idade: 21} ]; //E.1 Crie uma função que recebe dois argumentos string e retorna o de maior comprimento. function returnBiggerString(string1,string2){ if(string1.length>string2.length){ return string1 }else{ return string2 } } //E.2 Crie uma função que recebe três argumentos, uma função e duas string, aplique a função nas duas string e imprima o resultado. function returnFunctionDoubleString(func,string1,string2){ var funct = func(string1,string2); return funct; } //E.3 Crie uma função que recebe vários argumentos do tipo string e imprime todos juntos function concatFunction( arg1,...args) { var str=arg1; for(var i=0;i<args.length;i++){ str= str +' '+ args[i]; } return str; } //E.4 Dado a seguinte string 'teste 1 de 2 string 3', substitua todas as ocorrências de números pelo valor '[removido]'. function returnNumString(){ str='teste 1 de 2 string 3'; var aux=''; for(var i=0;i< str.length;i++){ var c=str.charAt(i); switch(c) { case '0': aux=aux+'zero'; break; case '1': aux=aux+'um'; break; case '2': aux=aux+'dois'; break; case '3': aux=aux+'três'; break; case '4': aux=aux+'quatro'; break; case '5': aux=aux+'cinco'; break; case '6': aux=aux+'seis'; break; case '7': aux=aux+'sete'; break; case '8': aux=aux+'oito'; break; case '9': aux=aux+'nove'; break; default: aux=aux+str.charAt(i); } } return aux; } //E.5 Dado o dicionário {4: 'a', 3: 'e', 1: 'i', 5: 's'} substitua os números na frase 'T35t3 d3 35t4g1o' conforme o dicionário. function codeString(){ str='T35t3 d3 35t4g1o'; var aux=''; for(var i=0;i< str.length;i++){ var c=str.charAt(i); switch(c) { case '1': aux=aux+'i'; break; case '3': aux=aux+'e'; break; case '4': aux=aux+'a'; break; case '5': aux=aux+'s'; break; default: aux=aux+str.charAt(i); } } return aux; } //E.6 Utilizando a api da viacep (https://viacep.com.br/) e o seu cep como entrada imprima o seu endereço no formato 'ENDERECO, NUMERO, CIDADE/ESTADO'. //gerado em https://viacep.com.br/ws/96085-470/json/ var ender={ "cep": "96085-470", "logradouro": "Avenida Domingos José de Almeida", "complemento": "", "bairro": "Areal", "localidade": "Pelotas", "uf": "RS", "unidade": "", "ibge": "4314407", "gia": "583" }; function findCep(obj){ var ender={"endereco":"", "numero":"", "cidade":"", "estado":""}; ender.endereco=obj.logradouro; ender.numero=obj.gia; ender.cidade=obj.localidade; ender.estado=obj.uf; return ender; } //E.7 Imprima uma mensagem de saudação com o nome completo para cada um dos objetos. O nome deve ter a primeira letra maiúscula. function printName(arry){ for(var i=0;i<arry.length;i++){ console.log("olá "+arry[i].nome+' '+arry[i].sobrenome+'!'); } } //E.8 Imprima a soma das idades (dica: utilize reduce) function sumAge(arry){ var sum=0; for(var i=0;i<arry.length;i++){ sum=sum+arry[i].idade } return sum; } //E.9 Imprima o objeto se existir alguem com menos 25 anos. function ifLowAge(arry){ var ageLow=false; for(var i=0;i<arry.length;i++){ if(arry[i].idade<25){ ageLow=true; } } if(ageLow){ console.log(arry) } } //E.10 Imprima todos os elementos em que a idade é menor que 30 anos. function findLowAge(arry){ for(var i=0;i<arry.length;i++){ if(arry[i].idade<30){ console.log('id: '+arry[i].id+'\n'+'Nome: '+arry[i].nome+' '+arry[i].sobrenome+'\n'+'Idade: '+arry[i].idade); } } } //E.11 Ordene o array de forma decrescente por idade, em caso de empate o desempate é pelo id. function decOrdern(arry){ var swapp; var n = arry.length; do { swapp = false; for (var i=0; i < n-1; i++) { if (arry[i].idade < arry[i+1].idade) { var temp = arry[i]; arry[i] = arry[i+1]; arry[i+1] = temp; swapp = true; }else if(arry[i].idade == arry[i+1].idade){ if(arry[i].id < arry[i+1].id){ var temp = arry[i]; arry[i] = arry[i+1]; arry[i+1] = temp; swapp = true; } } } n--; } while (swapp); return arry; } // Chamada das functions console.log('E.1'); var bigger =returnBiggerString('the bigger string it is','not bigger'); console.log(bigger); console.log('E.2'); var testFunc =returnFunctionDoubleString(returnBiggerString,'the bigger string it is','not bigger'); console.log(testFunc); console.log('E.3'); var arr = concatFunction('helo','world','testing','this','function'); console.log(arr); console.log('E.4'); console.log(returnNumString()); console.log('E.5'); console.log(codeString()); console.log('E.6'); console.log(findCep(ender)); console.log('E.7'); printName(arry); console.log('E.8'); var sum= sumAge(arry); console.log(sum); console.log('E.9'); ifLowAge(arry); console.log('E.10'); findLowAge(arry); console.log('E.11'); var dec=decOrdern(arry); console.log(dec); <file_sep>/Desafio Fron-Back-end/index.js const express = require("express"); const app= express(); const bodyParser = require("body-parser"); const connection =require("./database/database"); const Post = require("./database/Post"); const Comment = require("./database/Comment"); connection .authenticate() .then(()=>{ console.log("conexao realizaoda") }) .catch((msgErro)=>{ console.log(msgErro); }) app.set('view engine','ejs'); app.use(express.static('public')); app.use(bodyParser.urlencoded({extended: false})); app.use(bodyParser.json()); app.get("/",(req,res)=>{ Post.findAll({raw: true,order:[ ['title','ASC'] ]}).then(posts=>{ res.render("index",{ posts : posts }); }); }); app.get("/posting",(req,res)=>{ res.render("posting"); }); app.get("/post/view/:id",(req,res)=>{ var id = req.params.id; Post.findOne({ where:{id: id} }).then(post => { if(post != undefined){ Comment.findAll({ where: {postId: post.id}, order: [ ['id','DESC'] ] }).then(comments=> { res.render("postViews",{ post: post, comments: comments }); }); }else{ res.redirect("/"); } }); }); app.post("/savePost",(req,res)=>{ var title= req.body.title; var desc= req.body.desc; Post.create({ title:title, desc: desc }).then(()=>{ res.redirect("/"); }); }); app.post("/commenting",(req, res)=> { var body= req.body.body; var postId =req.body.post; Comment.create({ body: body, postId: postId }).then(()=>{ res.redirect("/post/view/"+postId); }); }); app.listen(8080,()=>{ console.log("API rodando");});
2fc42f45b5ca7e182f0000d584b68ee58cf971dc
[ "Markdown", "SQL", "JavaScript" ]
5
SQL
PabloLSF/Teste-para-vaga-de-estagiario
fe8aa1aa9d0af34375427d515a4a9e0550dff729
8939666b4630a8105570c19556e3c1d12a1a091f
refs/heads/master
<repo_name>deniso4ka/Web-Frameworks<file_sep>/README.md # Web-Frameworks Silex Project passwords and logins are follows: admin : id - 1 , password <PASSWORD> supervisor : id 2 , password <PASSWORD> supervisor : id 3 , password <PASSWORD> student: id 4 , password <PASSWORD> student: id 5 , password <PASSWORD><file_sep>/ProductTest.php <?php class ProductTest extends \PHPUnit_Framework_TestCase { public function testOnePlusOne(){ $this->assertEquals(1+1,2); } }
001153cd0eae83c6fa8236329762576f86cb8720
[ "Markdown", "PHP" ]
2
Markdown
deniso4ka/Web-Frameworks
8799b5e4d6d0dcafcb8679858c6e51b5a5c7ba58
a0f8e582707678aa534d345d915228650f10f82c
refs/heads/main
<file_sep>import { CylinderGeometry, HemisphereLight, Mesh, MeshPhongMaterial, Scene, WebGLRenderer, XRFrame } from 'three'; import { PerspectiveCamera } from 'three'; import { ARButton } from 'three/examples/jsm/webxr/ARButton'; window.addEventListener('resize', () => { camera.aspect = window.innerWidth / window.innerHeight; camera.updateProjectionMatrix(); renderer.setSize(window.innerWidth, window.innerHeight); }); const scene = new Scene(); const camera = new PerspectiveCamera(70, window.innerWidth / window.innerHeight, 0.01, 20);; const renderer = new WebGLRenderer({ antialias: true, alpha: true }); renderer.setPixelRatio(window.devicePixelRatio); renderer.setSize(window.innerWidth, window.innerHeight); renderer.xr.enabled = true; document.body.appendChild(renderer.domElement); document.body.appendChild(ARButton.createButton(renderer, { optionalFeatures: [ 'dom-overlay', 'dom-overlay-for-handheld-ar' ], domOverlay: { root: document.body }, })); const light = new HemisphereLight(0xffffff, 0xbbbbff, 1); light.position.set(0.5, 1, 0.25); scene.add(light); const controller = renderer.xr.getController(0); controller.addEventListener('select', () => { const geometry = new CylinderGeometry(0, 0.05, 0.2, 32).rotateX(Math.PI / 2); const material = new MeshPhongMaterial({ color: 0xffffff * Math.random() }); const mesh = new Mesh(geometry, material); mesh.position.set(0, 0, - 0.3).applyMatrix4(controller.matrixWorld); mesh.quaternion.setFromRotationMatrix(controller.matrixWorld); scene.add(mesh); }); scene.add(controller); renderer.setAnimationLoop((timestamp: number, frame: XRFrame | undefined) => { renderer.render(scene, camera); }); const uiContainer = document.getElementById('uiContainer') as HTMLDivElement; const rightMenu = document.getElementById('rightMenu') as HTMLDivElement; const button1 = document.getElementById('button1') as HTMLButtonElement; button1.addEventListener('click', (evt) => { rightMenu.innerHTML = '<p>Button 1 clicked!</p>'; evt.stopPropagation(); }); const button2 = document.getElementById('button2') as HTMLButtonElement; button2.addEventListener('click', (evt) => { rightMenu.innerHTML = '<p>Button 2 clicked!</p>'; evt.stopPropagation(); });
e62f46c96d35533c2abfba6c972288795169f436
[ "TypeScript" ]
1
TypeScript
MichaelLangbein/webxrExperiments
0f408f464568a3f3bd96e63219145506bba1d199
60965a98292329aaa23de414ec16d94c659c63f6
refs/heads/master
<repo_name>zakkies/table-maker<file_sep>/README.md # table-maker <file_sep>/src/data/staff-duties.js import uuid from './../uuid' import staffs from './staffs' import duties from './duties' export default staffs.map(staff => duties.map(duty => ( { id: uuid(), staffId: staff.id, dutyId: duty.id } )) ).reduce((a, b) => a.concat(b)) <file_sep>/src/data/staffs.js import uuid from './../uuid' export default [ // { id: uuid(), name: '御書 康一' }, // { id: uuid(), name: '初馬 本子' }, // { id: uuid(), name: '夏梅 光三' }, // { id: uuid(), name: '斉京 安樹子' }, // { id: uuid(), name: '仙名 尚博' }, // { id: uuid(), name: '菜月 敬大' }, // { id: uuid(), name: '落海 一城' }, // { id: uuid(), name: '藤ノ原 磨里子' }, // { id: uuid(), name: '與古田 みらの' }, // { id: uuid(), name: '揚 忠篤' }, // { id: uuid(), name: '兼保 良将' }, // { id: uuid(), name: '覚田 涼' }, // { id: uuid(), name: '隈田原 正子' }, // { id: uuid(), name: '板元 将子' }, // { id: uuid(), name: '名郷 尚伸' }, // { id: uuid(), name: '拝原 萌葉' }, // { id: uuid(), name: '部流 勝也' }, // { id: uuid(), name: '三野原 信喜' }, // { id: uuid(), name: '兼口 次夫' }, // { id: uuid(), name: '間吾 きぬよ' }, // { id: uuid(), name: '原口 森彦' }, // { id: uuid(), name: '平宮 真岐' }, // { id: uuid(), name: '神事 優生' }, // { id: uuid(), name: '極 照太' }, // { id: uuid(), name: '羽根川 伸年' }, // { id: uuid(), name: '海北 規幸' }, // { id: uuid(), name: '海援隊 莉夏' }, // { id: uuid(), name: '井坂 令菜' }, // { id: uuid(), name: '脊古 孝真' }, // { id: uuid(), name: '阿賀嶺 想子' }, // { id: uuid(), name: '鹿子嶋 准' }, // { id: uuid(), name: '九富 友文' }, // { id: uuid(), name: '実本 紳一朗' }, // { id: uuid(), name: '友信 幹仁' }, // { id: uuid(), name: '沢安 旬' }, // { id: uuid(), name: '部谷 憲二郎' }, // { id: uuid(), name: '越前屋 莉香子' }, // { id: uuid(), name: '太田島 島' }, // { id: uuid(), name: '竹ノ子 菜歩' }, // { id: uuid(), name: '下原 治世' }, // { id: uuid(), name: '安瀬 智絵' }, // { id: uuid(), name: '加集 理夏子' }, // { id: uuid(), name: '美淋 莉名' }, // { id: uuid(), name: '与十田 靖昌' }, // { id: uuid(), name: '生山 公美子' }, // { id: uuid(), name: '鶴屋 佳徳' }, // { id: uuid(), name: '彦惣 真佐樹' }, // { id: uuid(), name: '安形 心太郎' }, // { id: uuid(), name: '長埜 光季' }, // { id: uuid(), name: '夜咲 善人' }, // { id: uuid(), name: '由木 麻生' }, // { id: uuid(), name: '殷 美千穂' }, // { id: uuid(), name: '仙川 直靖' }, // { id: uuid(), name: '<NAME>子' }, // { id: uuid(), name: '帆場 果恵' }, // { id: uuid(), name: '師崎 好久' }, // { id: uuid(), name: '小屋原 千誉' }, // { id: uuid(), name: '波里 練' }, // { id: uuid(), name: '小伊勢 善嗣' }, // { id: uuid(), name: '小和口 なち' }, // { id: uuid(), name: '久原 伸典' }, // { id: uuid(), name: '魏 和興' }, // { id: uuid(), name: '与古田 智' }, // { id: uuid(), name: '七久保 奈美紀' }, // { id: uuid(), name: '利見 匡' }, // { id: uuid(), name: '葉田野 安行' }, // { id: uuid(), name: '百地 泰' }, // { id: uuid(), name: '畳谷 華梨' }, // { id: uuid(), name: '井出川 日出人' }, // { id: uuid(), name: '薬王寺 薫子' }, // { id: uuid(), name: '土佐野 李果' }, // { id: uuid(), name: '笹氣 亜衣莉' }, // { id: uuid(), name: '吉楽 盛一郎' }, // { id: uuid(), name: '荒記 淳男' }, // { id: uuid(), name: '本重 珠妃' }, // { id: uuid(), name: '小駒 梨会' }, // { id: uuid(), name: '峠舘 曉子' }, // { id: uuid(), name: '萩崎 貴朗' }, // { id: uuid(), name: '五井 沙綾子' }, // { id: uuid(), name: '図師田 桂衣' }, { id: uuid(), name: '種清 未麻' }, { id: uuid(), name: '能上 昌彦' }, { id: uuid(), name: '見野 将大' }, { id: uuid(), name: '光橋 六郎' }, { id: uuid(), name: '葉名 梨英子' }, { id: uuid(), name: '塘田 祐里江' }, { id: uuid(), name: '砂澤 敦宏' }, { id: uuid(), name: '柳沢屋 凛香' }, { id: uuid(), name: '中所 治喜' }, { id: uuid(), name: '道譯 ヨシヒロ' }, { id: uuid(), name: '猪爪 翔' }, { id: uuid(), name: '門手 知沙都' }, { id: uuid(), name: '濵坂 史孝' }, { id: uuid(), name: '宇貫 幸嗣' }, { id: uuid(), name: '長門石 正保' }, { id: uuid(), name: '鹿本 柚奈' }, { id: uuid(), name: '天摩 丈浩' }, { id: uuid(), name: '古美門 厚仁' }, { id: uuid(), name: '八百枝 紫緒里' }, { id: uuid(), name: '伊折 由起' } ] <file_sep>/src/data/minimum-numbers-of-duties-for-every-day.js import duties from './duties' export default [ { dutyId: duties.find(duty => duty.name === '2F夜').id, number: 2 }, { dutyId: duties.find(duty => duty.name === '3F夜').id, number: 2 }, { dutyId: duties.find(duty => duty.name === '2FB').id, number: 2 }, { dutyId: duties.find(duty => duty.name === '3FB').id, number: 2 }, { dutyId: duties.find(duty => duty.name === '2FC2').id, number: 1 }, { dutyId: duties.find(duty => duty.name === '3FC2').id, number: 1 }, { dutyId: duties.find(duty => duty.name === '2FC3').id, number: 2 }, { dutyId: duties.find(duty => duty.name === '3FC3').id, number: 2 }, { dutyId: duties.find(duty => duty.name === '2FC1').id, number: 2 }, { dutyId: duties.find(duty => duty.name === '3FC1').id, number: 2 } ] <file_sep>/src/data/duties.js import uuid from './../uuid' export default [ { id: uuid(), name: '2F夜' }, { id: uuid(), name: '3F夜' }, { id: uuid(), name: '休' }, { id: uuid(), name: '有' }, { id: uuid(), name: '2FB' }, { id: uuid(), name: '3FB' }, { id: uuid(), name: '2FC2' }, { id: uuid(), name: '3FC2' }, { id: uuid(), name: '2FC3' }, { id: uuid(), name: '3FC3' }, { id: uuid(), name: '2FC1' }, { id: uuid(), name: '3FC1' }, { id: uuid(), name: 'A' } ] <file_sep>/src/evaluate-assignments.js export default ( assignments, { days = [], staffs = [], minimumNumbersOfDutiesForEveryDay = [], maximumNumbersOfDutiesForEveryStaff = [] } ) => { const assignmentsGroupedByDay = days.map(day => { const assignmentsFilteredByDay = assignments.filter(assignment => assignment.day === day ) return { day, assignments: assignmentsFilteredByDay } }) const assignmentsGroupedByStaff = staffs.map(staff => { const staffId = staff.id const assignmentsFilteredByStaffId = assignments.filter(assignment => assignment.staffId === staffId ) return { staffId, assignments: assignmentsFilteredByStaffId } }) const errors = [] const fitness = minimumNumbersOfDutiesForEveryDay.reduce( (fitness, minimumNumberOfDuties) => { const dutyId = minimumNumberOfDuties.dutyId const minimumNumber = minimumNumberOfDuties.number return fitness + assignmentsGroupedByDay.reduce( (fitness, assignmentsAndDay) => { const day = assignmentsAndDay.day const assignments = assignmentsAndDay.assignments const number = assignments.reduce((number, assignment) => number + (assignment.dutyId === dutyId ? 1 : 0) , 0) if (number >= minimumNumber) { return fitness } const unfitness = minimumNumber - number errors.push({ day, dutyId, unfitness, constraint: 'minimumNumbersOfDutiesForEveryDay' }) return fitness - unfitness }, 0) }, 0) + maximumNumbersOfDutiesForEveryStaff.reduce( (fitness, maximumNumberOfDuties) => { const dutyId = maximumNumberOfDuties.dutyId const maximumNumber = maximumNumberOfDuties.number return fitness + assignmentsGroupedByStaff.reduce( (fitness, assignmentsAndStaff) => { const staffId = assignmentsAndStaff.staffId const assignments = assignmentsAndStaff.assignments const number = assignments.reduce((number, assignment) => number + (assignment.dutyId === dutyId ? 1 : 0) , 0) if (number <= maximumNumber) { return fitness } const unfitness = number - maximumNumber errors.push({ staffId, dutyId, unfitness, constraint: 'maximumNumbersOfDutiesForEveryStaff' }) return fitness - unfitness }, 0) }, 0) return { fitness, errors } } <file_sep>/src/data/maximum-numbers-of-duties-for-every-staff.js import duties from './duties' export default [ { dutyId: duties.find(duty => duty.name === '休').id, number: 2 } ] <file_sep>/src/write-assignments.js import csv from 'csv' import fs from 'fs' export default (assignments, { days, staffs, duties }) => { const head = [[''].concat(days)] const rows = head.concat(staffs.map(staff => { const staffAssignments = assignments.filter(assignment => assignment.staffId === staff.id ) const staffAssignmentsSortedByDay = days.map(day => staffAssignments.find(assignment => assignment.day === day) ) const staffDutyNames = staffAssignmentsSortedByDay.map(assignment => duties.find(duty => duty.id === assignment.dutyId).name ) return [staff.name].concat(staffDutyNames) })) csv.stringify(rows, (err, string) => fs.writeFile('assignments.csv', string)) return rows }
63411ef5d3f9d41e1a7e2a97b705333192c801d8
[ "Markdown", "JavaScript" ]
8
Markdown
zakkies/table-maker
229a7d4499f43c79b68f98823920cbdf1dc31dd6
5c371afd1b4c084ec02106a1b60eec361c049b40
refs/heads/main
<file_sep>import { Component, OnInit, TemplateRef } from '@angular/core'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { BsModalRef, BsModalService } from 'ngx-bootstrap/modal'; import { Aluno } from '../models/Aluno'; @Component({ selector: 'app-alunos', templateUrl: './alunos.component.html', styleUrls: ['./alunos.component.css'] }) export class AlunosComponent implements OnInit { public modalRef?: BsModalRef; public alunoForm!: FormGroup; public titulo = 'Alunos'; public alunoSelecionado: Aluno | null | undefined; public textoSimples: string | undefined; public alunos = [ { id: 1, nome: 'Amanda', sobrenome: 'Kent', telefone: 321321, }, { id: 2, nome: 'Fernando', sobrenome: 'Augusto', telefone: 159159, }, { id: 3, nome: 'Gabriela', sobrenome: 'Tedezco', telefone: 156156, }, { id: 4, nome: 'Marquinhos', sobrenome: 'Relampago', telefone: 741741, }, { id: 5, nome: 'Nayra', sobrenome: 'Nira', telefone: 954954, }, { id: 6, nome: 'Older', sobrenome: 'Young', telefone: 658658, }, { id: 7, nome: 'Wilson', sobrenome: 'Afonso', telefone: 656565, } ] openModal(template: TemplateRef<any>) { this.modalRef = this.modalService.show(template); } constructor(private fb: FormBuilder, private modalService: BsModalService) { this.criarForm(); } ngOnInit() { } criarForm() { this.alunoForm = this.fb.group({ nome: ['', Validators.required], sobrenome: ['', Validators.required], telefone: ['', Validators.required] }); } alunoSubmit() { console.log(this.alunoForm?.value); } alunoSelect(aluno: Aluno) { this.alunoSelecionado = aluno; this.alunoForm.patchValue(aluno); } voltar() { this.alunoSelecionado = null; } } <file_sep>import { Component, OnInit, TemplateRef } from '@angular/core'; import { BsModalRef, BsModalService } from 'ngx-bootstrap/modal'; import { Professor } from '../models/Professor'; @Component({ selector: 'app-professores', templateUrl: './professores.component.html', styleUrls: ['./professores.component.css'] }) export class ProfessoresComponent implements OnInit { public modalRef?: BsModalRef; public titulo = "Professores" public professorSelecionado: Professor | null | undefined; public professores = [ { id: 1, nome: "Arlindo", disciplina: 'Matemática' }, { id: 2, nome: "Abigaiu", disciplina: 'Física' }, { id: 3, nome: "Clotilde", disciplina: 'Português' }, { id: 4, nome: "Fabiano", disciplina: 'Inglês' }, { id: 5, nome: "Mariafalda", disciplina: 'Espanhol' }, { id: 6, nome: "Paulinea", disciplina: 'Filosofia' }, { id: 7, nome: "<NAME>", disciplina: 'História' }, ] constructor(private modalService: BsModalService) { } openModal(template: TemplateRef<any>) { this.modalRef = this.modalService.show(template); } professorSelect(professor: Professor) { this.professorSelecionado = professor; } voltar() { this.professorSelecionado = null; } ngOnInit() { } }
ce6e0fccd81f95c24b53aa9fe35fd4abb929acdb
[ "TypeScript" ]
2
TypeScript
fernandoasg/angular-net-core-spa
3e5b31bd6f26858f36d2deba3e95cf6f7cf72327
a9797107009d584814e0f5fac2a74b544c96c913
refs/heads/master
<repo_name>jakerutter/ClockPractice<file_sep>/clockProblemLogic.js //this script will handle creating problems and answers for the clock game function getClockProblem(){ //create empty clockProblem object var clockProblem = new ClockProblem(0, 0, 0, 0, 0, "", "", "", "", "", "", 0, [], 0); //get question format // 1) what time does this clock show ? (answer will be digital clock style): "guessTime" // 2) which clock shows x' oClock ? (answer will be clicking on one of 4 clocks): "pickClock" || "guessText" // 3) how many minutes between these two clocks ? (answer will be to evaluate the time in both and return the difference in time): "timeDiff" // 4) trivia - how many minutes are in a half hour? (answer will be appropriate for question): "trivia" // 5) time word problems: "wordProblem" // 6) set the clock to show x' oClock ? (answer will be user setting analog clock hands to correct position): "setTime" getQuestionFormat(clockProblem); testClockProblemQuestionFormat(clockProblem); //get the hour, minute, and text of the problem createQuestionWithFormat(clockProblem); //get the position the correct answer will be placed in //not needed for questions that will have a numerical answer if(clockProblem.format == "guessTime" || clockProblem.format == "guessText" || clockProblem.format == "pickClock"){ getCorrectAnswerPosition(clockProblem); testClockProblemCorrectAnswerPosition(clockProblem); } //set UI setUI(clockProblem); //start timer / score tracker if (!(document.getElementById("letsPracticeBtn").classList.contains("hidden"))){ beginTimerAndScoreTracking(); } //hide "Lets Practice button" document.getElementById("letsPracticeBtn").classList.add("hidden"); } //create empty clock problem function ClockProblem(hour, minute, secondHour, secondMinute, time, question, format, slang, secondSlang, ampm, secondampm, correctPosition, notAnswerArray, timeDiffAnswer){ this.hour = hour; this.minute = minute; this.secondHour = secondHour; this.secondMinute = secondMinute; this.time = time; this.question = question; this.format = format; this.slang = slang; this.secondSlang = secondSlang; this.ampm = ampm; this.secondampm = secondampm; this.correctPosition = correctPosition; this.notAnswerArray = notAnswerArray; this.timeDiffAnswer = timeDiffAnswer; } //gets either "guessTime" or "pickClock" as game types and hydrates clockProblem.format function getQuestionFormat(clockProblem){ //var questionFormat = 4; //timeDiff for testing var questionFormat = getRandomInt(0, 5); clockProblem.format = getQuestionFormatString(questionFormat); return clockProblem; } function getQuestionFormatString(questionFormat){ var formatString; if (questionFormat === 0){ formatString = "guessTime"; } else if(questionFormat === 1){ formatString = "pickClock"; } else if(questionFormat === 2){ formatString = "guessText"; } else if(questionFormat === 3){ formatString = "trivia"; } else if(questionFormat === 4){ formatString = "timeDiff"; } else if(questionFormat === 5){ formatString = "wordProblem"; } else if(questionFormat === 6){ formatString = "setTime"; } console.log(formatString); return formatString; } function createQuestionWithFormat(clockProblem) { //get hour and minute clockProblem.hour = getRandomInt(1, 12); testClockProblemHour(clockProblem); clockProblem.minute = getMinute(); testClockProblemMinute(clockProblem); //get second hour and second minute clockProblem.secondHour = getRandomInt(1, 12); testClockProblemSecondHour(clockProblem); clockProblem.secondMinute = getMinute(); testClockProblemSecondMinute(clockProblem); //get slang term for minute (like quarter til or half past) clockProblem.slangTerm = getSlangTerm(clockProblem.minute); //get second slang term for second minute clockProblem.secondSlangTerm = getSlangTerm(clockProblem.secondMinute); //get AMPM value clockProblem.ampm = getAMPM(); //get second AMPM vlaue clockProblem.secondampm = getAMPM(); //get the text for the clock problem (what time does this clock show) getClockQuestionText(clockProblem); return clockProblem; } //get the slang term function getSlangTerm(minute){ var slang; if (minute == 00){ slang = "o'clock"; } else if (minute == 05){ slang = "five after"; } else if (minute == 10){ slang = "ten after"; } else if (minute == 15){ slang = "a quarter after"; } else if (minute == 20){ slang = "twenty after" } else if (minute == 25){ slang = "twenty-five after" } else if (minute == 30){ slang = "half past"; } else if (minute == 35){ slang = "twenty-five til"; } else if (minute == 40){ slang = "twenty til"; } else if (minute == 45){ slang = "a quarter til"; } else if (minute == 50){ slang = "ten til"; } else if (minute == 55){ slang = "five til"; } return slang; } //get ampm value function getAMPM(){ var randomInt = getRandomInt(0, 2); return randomInt == 0 ? "A.M." : "P.M."; } //get the question text (what time does this clock show?) function getClockQuestionText(clockProblem){ //what time does this clock show ? (answer will be digital clock style) if ((clockProblem.format === "guessTime") || (clockProblem.format === "guessText")){ clockProblem.question = "What time is shown?"; } //which clock shows x' oClock ? (answer will be clicking on one of 4 clocks) else if (clockProblem.format === "pickClock"){ var questionText = "Which clock shows "; //handle the 00 minute if (clockProblem.minute === 00){ questionText += clockProblem.hour + " " + clockProblem.slangTerm + "?"; } else if (clockProblem.minute > 30 && clockProblem.minute != 45){ questionText += clockProblem.slangTerm + " " + getHourPlusOne(clockProblem.hour) + "?"; } else if (clockProblem.minute != 45){ questionText += clockProblem.slangTerm + " " + clockProblem.hour + "?"; } else if (clockProblem.minute == 45){ questionText += clockProblem.slangTerm + " " + getHourPlusOne(clockProblem.hour) + "?"; } clockProblem.question = questionText; // timeDiff questions - show two clocks and ask the difference between the two } else if (clockProblem.format === "timeDiff") { clockProblem.question = "What is the difference in time in hours and minutes?"; clockProblem.timeDiffAnswer = getTimeDiffAnswer(clockProblem); } else if (clockProblem.format === "trivia") { var randomInt = getRandomInt(0, 7); clockProblem.question = getTriviaQuestion(randomInt); clockProblem.answer = getTriviaAnswer(randomInt); } else if (clockProblem.format === "wordProblem") { console.log('----------> haven\'t coded word problem'); getClockProblem(); } else if (clockProblem.format === "setTime") { console.log('----------> haven\'t coded set time'); getClockProblem(); }else { alert('Encountered an error with the question format. Error 1.'); } //add test for logging 13 hour issue that has arisen testClockProblemHourForThirteen(clockProblem); return clockProblem; } //get the integer that represents the position the correct answer will be placed in (random 1-4) function getCorrectAnswerPosition(clockProblem){ clockProblem.correctPosition = getRandomInt(1, 4); //will need these for placing the clocks that are not the answer var notAnswerArray = [1, 2, 3, 4]; removeItemFromArrayByValue(notAnswerArray, clockProblem.correctPosition); clockProblem.notAnswerArray = notAnswerArray; return clockProblem; } // set the appropriate UI elements, clear or hide the others function setUI(clockProblem){ clearUI(); // only draw analog clocks if needed if(clockProblem.format === "guessTime" || clockProblem.format === "guessText" || clockProblem.format === "pickClock"){ // save the correct answer location to hidden field document.getElementById("hiddenField").innerHTML = clockProblem.correctPosition; // draw the clock displays drawAnalogClocks(clockProblem); } // if format is guessTime need to draw digital clocks as well // unhide the guessTime div if (clockProblem.format === "guessTime"){ drawDigitalClocks(clockProblem); document.getElementById("guessTime").classList.remove("hidden"); document.getElementById("guessTimeText").innerText = clockProblem.question; // unhide pickClock div } else if (clockProblem.format === "pickClock") { document.getElementById("pickClock").classList.remove("hidden"); document.getElementById("pickClockText").innerText = clockProblem.question; // unhide guessText div } else if (clockProblem.format === "guessText") { document.getElementById("guessText").classList.remove("hidden"); getTextAnswers(clockProblem); document.getElementById("guessTextText").innerText = clockProblem.question; // unhide triviaSection div } else if (clockProblem.format === "trivia"){ document.getElementById("triviaSection").classList.remove("hidden"); document.getElementById("triviaQuestion").innerText = clockProblem.question; // save the correct answer to hidden field document.getElementById("hiddenField").innerHTML = clockProblem.answer; document.getElementById("triviaInput").focus(); } // unhide timeDiffSection div else if (clockProblem.format === "timeDiff"){ drawDigitalClocks(clockProblem); document.getElementById("timeDiffSection").classList.remove("hidden"); document.getElementById("timeDiffQuestion").innerText = clockProblem.question; // save the correct answer to hidden field document.getElementById("hiddenField").innerHTML = clockProblem.timeDiffAnswer; document.getElementById("timeDiffHours").focus(); } } //create timer and set initial score values function beginTimerAndScoreTracking(){ document.getElementById("timeAndScore").classList.remove("hidden"); document.getElementById("correctAnswers").innerHTML = 0; document.getElementById("incorrectAnswers").innerHTML = 0; setInterval(countTime, 1000); } function countTime(counter){ var counter = Number(document.getElementById("timeDisplay").innerHTML); counter += 1; document.getElementById("timeDisplay").innerHTML = counter; return counter; } // get the analog clock displays function drawAnalogClocks(clockProblem){ // what time does this clock show? (need 1 analog clock for the question clock, 4 digital for answers) if (clockProblem.format == "guessTime"){ getAnalogClock('clockQuestion', clockProblem.hour, clockProblem.minute); } // which clock shows x o'Clock? (need 4 analog clocks) else if (clockProblem.format == "pickClock"){ getAnalogClock('pickCanvas'+clockProblem.correctPosition, clockProblem.hour, clockProblem.minute); // Cranking up the difficulty. Purposefully spoofing answers closer to the actual answer getAnalogClock('pickCanvas'+clockProblem.notAnswerArray[0], clockProblem.hour, getRandomMinuteWithException(clockProblem.minute)); getAnalogClock('pickCanvas'+clockProblem.notAnswerArray[1], getHourPlusOne(clockProblem.hour), getMinute()); getAnalogClock('pickCanvas'+clockProblem.notAnswerArray[2], getHourMinusOne(clockProblem.hour), getMinute()); } else { // need 1 analog clock for question clock. 4 text times for answers getAnalogClock("clockQuestion2", clockProblem.hour, clockProblem.minute); } } // get the digital clock displays function drawDigitalClocks(clockProblem){ // handle all cases that are not timeDiff if(clockProblem.format !== "timeDiff"){ getDigitalClock('guessCanvas'+clockProblem.correctPosition, clockProblem.hour, clockProblem.minute); // Cranking up the difficulty. Purposefully spoofing answers closer to the actual answer getDigitalClock('guessCanvas'+clockProblem.notAnswerArray[0], clockProblem.hour, getRandomMinuteWithException(clockProblem.minute)); getDigitalClock('guessCanvas'+clockProblem.notAnswerArray[1], getHourPlusOne(clockProblem.hour), getMinute()); getDigitalClock('guessCanvas'+clockProblem.notAnswerArray[2], getHourMinusOne(clockProblem.hour), getMinute()); } else { // Draw digital clocks for time diff getDigitalClock("timeDiff1", clockProblem.hour, clockProblem.minute); getDigitalClock("timeDiff2", clockProblem.secondHour, clockProblem.secondMinute); // Write out "A.M." or "P.M." document.getElementById("timeDiff1").innerText += " " + clockProblem.ampm; document.getElementById("timeDiff2").innerText += " " + clockProblem.secondampm; } } function clearUI(){ //get id and correctPosition to clear the green border if present if (document.getElementById("hdnID")){ var id = document.getElementById("hdnID").innerHTML; if (document.getElementById("hiddenField")){ var correctPosition = document.getElementById("hiddenField").innerHTML; if(document.getElementById(id+correctPosition)){ document.getElementById(id+correctPosition).classList.remove("green-border"); } } } //clear hidden field and results label clearInnerHtml("hiddenField"); clearInnerHtml("hdnID"); clearInnerHtml("resultsLabel"); //clear the canvases clearCanvas("clockQuestion"); clearCanvas("clockQuestion2"); clearInnerHtml("guessCanvas1"); clearInnerHtml("guessCanvas2"); clearInnerHtml("guessCanvas3"); clearInnerHtml("guessCanvas4"); clearInnerHtml("text1"); clearInnerHtml("text2"); clearInnerHtml("text3"); clearInnerHtml("text4"); clearCanvas("pickCanvas1"); clearCanvas("pickCanvas2"); clearCanvas("pickCanvas3"); clearCanvas("pickCanvas4"); //hide all UI divs document.getElementById("guessTime").classList.add("hidden"); document.getElementById("pickClock").classList.add("hidden"); document.getElementById("guessText").classList.add("hidden"); document.getElementById("triviaSection").classList.add("hidden"); document.getElementById("timeDiffSection").classList.add("hidden"); //clear trivia border classes document.getElementById("triviaInput").classList.remove("green-border-thin"); document.getElementById("triviaInput").classList.remove("red-border-thin"); //clear time diff border classes document.getElementById("timeDiffHours").classList.remove("green-border-thin"); document.getElementById("timeDiffMinutes").classList.remove("green-border-thin"); } // check the user's input versus the correct answer function checkAnswer(input, id){ document.getElementById("hdnID").innerHTML = id; var correctPosition = document.getElementById("hiddenField").innerHTML; if (input == correctPosition) { console.log('You got it correct.'); document.getElementById("resultsLabel").innerHTML = "Correct!"; var correct = document.getElementById("correctAnswers").innerHTML; correct = Number(correct)+1; document.getElementById("correctAnswers").innerHTML = correct; document.activeElement.blur(); setTimeout(getClockProblem, 1000); } else { console.log('Incorrect. Log this as a missed question.'); document.getElementById("resultsLabel").innerHTML = "Nope, that wasn't the right choice."; var incorrect = document.getElementById("incorrectAnswers").innerHTML; incorrect = Number(incorrect)+1; document.getElementById("incorrectAnswers").innerHTML = incorrect; document.getElementById(id+correctPosition).classList.add("green-border"); } } // check the user's trivia answer function submitTriviaAnswer(){ //remove trivia input border class document.getElementById("triviaInput").classList.remove("red-border-thin"); var correctAnswer = document.getElementById("hiddenField").innerHTML; var submittedAnswer = document.getElementById("triviaInput").value; //correct if (Number(submittedAnswer) === Number(correctAnswer)){ console.log('You got it correct.'); document.getElementById("resultsLabel").innerHTML = "Correct!"; var correct = document.getElementById("correctAnswers").innerHTML; correct = Number(correct)+1; document.getElementById("correctAnswers").innerHTML = correct; document.activeElement.blur(); document.getElementById("triviaInput").value = ""; document.getElementById("triviaInput").classList.add("green-border-thin"); setTimeout(getClockProblem, 1000); } else { //incorrect console.log('Incorrect. Log this as a missed question.'); document.getElementById("resultsLabel").innerHTML = "Nope, that is not correct."; var incorrect = document.getElementById("incorrectAnswers").innerHTML; incorrect = Number(incorrect)+1; document.getElementById("incorrectAnswers").innerHTML = incorrect; document.getElementById("triviaInput").classList.add("red-border-thin"); document.getElementById("triviaInput").value = ""; document.getElementById("triviaInput").focus(); } } // convert and check the user's time diff answer function submitTimeDiffInput(){ // remove timeDiff input border class document.getElementById("timeDiffHours").classList.remove("red-border-thin"); document.getElementById("timeDiffMinutes").classList.remove("red-border-thin"); var correctAnswer = document.getElementById("hiddenField").innerHTML; var submittedAnswer; var submittedHours = document.getElementById("timeDiffHours").value; var submittedMinutes = document.getElementById("timeDiffMinutes").value; // convert hours and minutes to minutes only submittedAnswer = Number((submittedHours * 60) + Number(submittedMinutes)); //console.log('submitted answer is ' + submittedAnswer); // hours correct - add green border for hours if (Math.floor(Number(submittedAnswer / 60)) === Math.floor(Number(correctAnswer / 60))){ document.getElementById("timeDiffHours").classList.add("green-border-thin"); } else if(Number(correctAnswer) < 60 && submittedHours === 0){ document.getElementById("timeDiffHours").classList.add("green-border-thin"); } else { //console.log(submittedAnswer + ' is submitted answer. Correct answer is ' + correctAnswer); document.getElementById("timeDiffHours").classList.add("red-border-thin"); } // minutes correct - add green border for minutes if ((Number(submittedAnswer) % 60) === (Number(correctAnswer) % 60)){ document.getElementById("timeDiffMinutes").classList.add("green-border-thin"); } else { //console.log(submittedAnswer + ' is submitted answer. Correct answer is ' + correctAnswer); //console.log('answer % 60 = '+ Number(correctAnswer % 60)); document.getElementById("timeDiffMinutes").classList.add("red-border-thin"); } // answer is correct if (Number(correctAnswer) === Number(submittedHours * 60) + Number(submittedMinutes)){ console.log('You got it correct.'); document.getElementById("resultsLabel").innerHTML = "Correct!"; var correct = document.getElementById("correctAnswers").innerHTML; correct = Number(correct)+1; document.getElementById("correctAnswers").innerHTML = correct; document.activeElement.blur(); document.getElementById("timeDiffHours").value = ""; document.getElementById("timeDiffMinutes").value = ""; setTimeout(getClockProblem, 1000); } else { //incorrect console.log('Incorrect. Log this as a missed question.'); document.getElementById("resultsLabel").innerHTML = "Nope, that is not correct."; var incorrect = document.getElementById("incorrectAnswers").innerHTML; incorrect = Number(incorrect)+1; document.getElementById("incorrectAnswers").innerHTML = incorrect; } } // clear the innerhtml from an item function clearInnerHtml(id){ document.getElementById(id).innerHTML = ""; } function getTextAnswers(clockProblem){ document.getElementById("text"+clockProblem.correctPosition).innerHTML = getCorrectAnswerText(clockProblem); document.getElementById("text"+clockProblem.notAnswerArray[0]).innerHTML = getTextForWrongAnswers(clockProblem, 0); document.getElementById("text"+clockProblem.notAnswerArray[1]).innerHTML = getTextForWrongAnswers(clockProblem, 1); document.getElementById("text"+clockProblem.notAnswerArray[2]).innerHTML = getTextForWrongAnswers(clockProblem, 2); } function getCorrectAnswerText(clockProblem){ var answerText = getHourInEnglish(clockProblem.hour) + " " + getMinuteInEnglish(clockProblem.minute); return answerText; } function getTextForWrongAnswers(clockProblem, value){ var answerText; var hours = [clockProblem.hour, getHourPlusOne(clockProblem.hour), getHourMinusOne(clockProblem.hour)]; //going to allow the same hour but enforce different minutes var hour = getHourInEnglish(hours[value]); var minute; minute = value == 0 ? minute = getRandomMinuteInEnglishWithException(clockProblem.minute) : getMinuteInEnglish(clockProblem.minute); // var minute = getRandomMinuteInEnglishWithException(clockProblem.minute); answerText = hour + " " + minute; return answerText; } function getHourInEnglish(hour){ var hourText; if (hour == 1){ hourText = "One"; } else if (hour == 2){ hourText = "Two"; } else if (hour == 3){ hourText = "Three"; } else if (hour == 4){ hourText = "Four"; } else if (hour == 5){ hourText = "Five"; } else if (hour == 6){ hourText = "Six"; } else if (hour == 7){ hourText = "Seven"; } else if (hour == 8){ hourText = "Eight"; } else if (hour == 9){ hourText = "Nine"; } else if (hour == 10){ hourText = "Ten"; } else if (hour == 11){ hourText = "Eleven"; } else if (hour == 12){ hourText = "Twelve"; } else{ console.log("Error encountered. Hour to english conversion failed. Hour came in as "+hour+". Error 6."); alert("Error 6."); } return hourText; } // get the minutes. the options are 0 to 60 in 5 min increments function getMinute(){ var minuteArray = [00,05,10,15,20,25,30,35,40,45,50,55]; var minute = minuteArray[getRandomInt(0,12)]; return minute; } // Get minute that doesn't match the minute passed in function getRandomMinuteWithException(minute){ //create array off all possible minutes var minuteArray = [00,05,10,15,20,25,30,35,40,45,50,55]; //remove the correct minute removeItemFromArrayByValue(minuteArray, minute); //get english version of the randomly selected minute var min = minuteArray[getRandomInt(0, minuteArray.length)]; return min; } function getMinuteInEnglish(minute){ var minuteText; if (minute == 00){ minuteText = "o'clock"; } else if (minute == 05){ minuteText = "o' five"; } else if (minute == 10){ minuteText = "ten"; } else if (minute == 15){ minuteText = "fifteen"; } else if (minute == 20){ minuteText = "twenty"; } else if (minute == 25){ minuteText = "twenty-five"; } else if (minute == 30){ minuteText = "thirty"; } else if (minute == 35){ minuteText = "thirty-five"; } else if (minute == 40){ minuteText = "forty"; } else if (minute == 45){ minuteText = "forty-five"; } else if (minute == 50){ minuteText = "fifty"; } else if (minute == 55){ minuteText = "fifty-five"; } else { console.log('Error encountered. Get minute in english conversion failed. Error 7.'); console.log(minute + "<--- that is minute"); alert('Error 7'); } return minuteText; } // Get minute (in English) that doesn't match the minute passed in function getRandomMinuteInEnglishWithException(minute){ //create array off all possible minutes var minuteArray = [00,05,10,15,20,25,30,35,40,45,50,55]; //remove the correct minute removeItemFromArrayByValue(minuteArray, minute); //get english version of the randomly selected minute var minuteText = getMinuteInEnglish(minuteArray[getRandomInt(0, minuteArray.length)]); return minuteText; } function getHourPlusOne(hour){ // if hour is 11 or fewer, return hour plus one // if hour is 12, return 1 hour = hour <= 11 ? hour +=1 : 1; return hour; } function getHourMinusOne(hour){ // if hour is 2 or greater, return hour minus one // if hour is 1, return 12 hour = hour >= 2 ? hour -= 1 : 12; return hour; } function getTimeDiffAnswer(clockProblem){ var timeOneInMinutes; var timeTwoInMinutes; // convert first time to minutes past midnight if(clockProblem.ampm === "A.M."){ timeOneInMinutes = Number((clockProblem.hour * 60) + clockProblem.minute); } else { timeOneInMinutes = Number((clockProblem.hour * 60) + clockProblem.minute + 720); } // convert second time to minutes past midnight if(clockProblem.secondampm === "A.M."){ timeTwoInMinutes = Number((clockProblem.secondHour * 60) + clockProblem.secondMinute); } else { timeTwoInMinutes = Number((clockProblem.secondHour * 60) + clockProblem.secondMinute + 720); } // return the difference between the two times if (timeOneInMinutes > timeTwoInMinutes){ console.log(timeOneInMinutes + ' is time one, ' + timeTwoInMinutes + ' is time two. Answer is ' + Number(timeOneInMinutes - timeTwoInMinutes)); return timeOneInMinutes - timeTwoInMinutes; } else if(timeTwoInMinutes > timeOneInMinutes){ console.log(timeTwoInMinutes + ' is time two, ' + timeOneInMinutes + ' is time one. Answer is ' + Number(timeTwoInMinutes - timeOneInMinutes)); return timeTwoInMinutes - timeOneInMinutes; } else { console.log('time is same? remove message after testing pass'); return 0; } }<file_sep>/README.md # ClockPractice An application for practicing reading time and learning facts about time. ## Question Types There are questions that display a single analog clock with randomized time (5 min increments) where the user has to select the correct answer from multiple choice digital clock read out. There are questions that display a single analog clock with randomized time (5 min increments) where the user has to select the correct answer from multiple choice time written in English. There are questions that display four analog clocks with different times and a question written in English asking the user to identify the clock displaying a specific time. There are time-related trivia questions. There are questions that show two different digital clocks and ask the user to determine the difference from the time earlier a day to the later time. The answer should be in hours and minutes. ## Recently Added Recently added a simple score keeping system & timer displaying amount of time played in seconds. Recently added two new question types. ## Feature Roadmap Cutover app to use bootstrap Imrove score keeping stats Consider adding quiz with timer functionality Improve color & UX Add military time setting choice. (Toggle between military or standard 12 hour time) ### Known Bugs There are currently no known bugs in this application. <file_sep>/userDefinedClock.js //ANALOG CLOCK SECTION function getAnalogClock(elementName, hour, minute){ var element = document.getElementById(elementName); var graphic = element.getContext("2d"); var radius = element.height / 2; var widthByTwo = element.width / 2; graphic.translate(widthByTwo, radius); //JTR - this line controls the size of the clock //radius = radius * .90 startClock(graphic, radius, hour, minute); } function startClock(graphic, radius, hour, minute) { drawFace(graphic, radius); drawNumbers(graphic, radius); drawTime(graphic, radius, hour, minute); } function drawFace(graphic, radius) { var grad; graphic.beginPath(); graphic.arc(0, 0, radius, 0, 2*Math.PI); graphic.fillStyle = 'white'; graphic.fill(); graphic.stroke(); graphic.beginPath(); graphic.arc(0, 0, radius*0.1, 0, 2*Math.PI); graphic.fillStyle = '#333'; graphic.fill(); } function drawNumbers(graphic, radius) { var angle; var number; graphic.font = radius*0.15 + "px arial"; graphic.textBaseline="middle"; graphic.textAlign="center"; for(number = 1; number < 13; number++){ angle = number * Math.PI / 6; graphic.rotate(angle); graphic.translate(0, -radius*0.85); graphic.rotate(-angle); graphic.fillText(number.toString(), 0, 0); graphic.rotate(angle); graphic.translate(0, radius*0.85); graphic.rotate(-angle); } } function drawTime(graphic, radius, hour, minute){ var hour = hour; var minute = minute; var second = 0; //JTR - passing in time // var currentTime = new Date(); // var hour = currentTime.getHours(); // var minute = currentTime.getMinutes(); // var second = currentTime.getSeconds(); hour=hour%12; hour=(hour*Math.PI/6)+(minute*Math.PI/(6*60))+(second*Math.PI/(360*60)); minute=(minute*Math.PI/30)+(second*Math.PI/(30*60)); drawHand(graphic, minute, radius*0.75, radius*0.07, "#8B0000"); //MINUTE hand -- dark red drawHand(graphic, hour, radius*0.5, radius*0.07, "#00008B"); //HOUR hand -- dark blue // JTR decided not to show second hand for now //second=(second*Math.PI/30); //drawHand(graphic, second, radius*0.9, radius*0.02); } function drawHand(graphic, position, length, width, color) { color = color == "" ? "#000000" : color; graphic.beginPath(); graphic.lineWidth = width; graphic.lineCap = "round"; graphic.moveTo(0,0); graphic.rotate(position); graphic.lineTo(0, -length); graphic.strokeStyle = color; graphic.stroke(); graphic.rotate(-position); } //clear all the canvases if they exist function clearCanvas(element){ var canvas = document.getElementById(element); if (canvas){ var graphic = canvas.getContext("2d"); //JTR - this is the correct way to clear canvas, but it wasn't working //graphic.clearRect(0, 0, canvas.width, canvas.height); canvas.width = canvas.width; } } //DIGITAL CLOCK SECTION function getDigitalClock(elementName, hour, minute) { var element = document.getElementById(elementName); //ensure minute is two digits if (minute == 0){ minute = "00"; } else if (minute == 5){ minute = "05"; } element.innerHTML = hour + ":" + minute; }
911e72d9670ddfb0828f264f7609603d63ef2cd2
[ "JavaScript", "Markdown" ]
3
JavaScript
jakerutter/ClockPractice
5d775f47d545d7e6517ed4708ff9c7e4048d1928
8cd8462aa2650f664ba2e1347ad6933bd9313712
refs/heads/master
<repo_name>aayushkothari11/People-position-heatmap<file_sep>/heat_map.py import numpy as np import cv2 import time cap = cv2.VideoCapture("vtest.avi") ret,frame = cap.read() width = np.size(frame, 1) height = np.size(frame, 0) frame_size=(height, width) res = np.zeros((height, width), np.uint8) fgbg = cv2.createBackgroundSubtractorMOG2(history=1, varThreshold=100,detectShadows=True) kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (13, 13)) while True: ret, frame = cap.read() if not ret: break fgmask = fgbg.apply(frame, None, 0.01) fgmask = cv2.morphologyEx(fgmask, cv2.MORPH_CLOSE, kernel) gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) gray = cv2.GaussianBlur(gray, (11, 11), 2, 2) thresh = 2 maxValue = 2 ret, th1 = cv2.threshold(fgmask, thresh, maxValue, cv2.THRESH_BINARY) res = cv2.add(res, th1) color_image = cv2.applyColorMap(res, cv2.COLORMAP_JET) result_overlay = cv2.addWeighted(frame, 0.5, color_image, 40, 0) cv2.imshow('Final', result_overlay) k = cv2.waitKey(30) & 0xff if k == 27: break cv2.imshow('Final', result_overlay) time.sleep(100000) cap.release() cv2.destroyAllWindows() <file_sep>/README.md # People-position-heatmap Test video - https://github.com/opencv/opencv/blob/master/samples/data/vtest.avi Generated HeatMap - ![Screenshot from 2019-06-26 01-58-17](https://user-images.githubusercontent.com/29770201/60131075-1db8c080-97b6-11e9-9867-f386108d76a7.png)
58def55ff5345472f932d95c920bc0102e04a0b6
[ "Markdown", "Python" ]
2
Python
aayushkothari11/People-position-heatmap
e14b4244ffbbb1963c866777f16f75590c16c7a3
acc8770695ddc4681c4f9679b1aebda5a39522ee
refs/heads/master
<file_sep># MI-PDP.16 This repository contains Parallel and Distributed Programming (MI-PDP.16) course homework from CTU FIT. * [task1.cpp](src/task1.cpp) – sequential algorithm * [task2.cpp](src/task2.cpp) – OpenMP task parallelism * [task3.cpp](src/task3.cpp) – OpenMP data parallelism * [task4.cpp](src/task4.cpp) – MPI ## How to compile, execute and run tests You can take advantage of prepared Makefile recipes, which ease the whole process. ### Compilation ``` bash make compile${NUMBER} ``` ### Compilation for Debugging ``` bash make debug${NUMBER} ``` ### Execute (without input) Runs compilation automatically. ``` bash make task${NUMBER} ``` ### Run Tests Runs compilation automatically and uses [tests](tests) directory files as an input. ``` bash make tests${NUMBER} ``` `${NUMBER}` is a task number you want to run a particular recipe for. Example (tests for task 2): ``` bash make tests2 ``` ### Notes * There are prepared only `compile` and `tests` recipes for [task4.cpp](src/task4.cpp). * By default, [task4.cpp](src/task4.cpp) is executed using `mpic++` utility. * Default number of MPI processes (-np) is `3`. * To change this value, run the makefile `tests` recipe like this: ``` bash make NP=<number_of_processes> tests4 ``` * For example, to use 4 processes you run it like this: ``` bash make NP=4 tests4 ``` * By default, [task4.cpp](src/task4.cpp) is executed without defining `OMP_NUM_THREADS`. * To change this behavior, follow the steps from the previous example, e.g.: ``` bash make OMP_NUM_THREADS=<number_of_threads> tests4 ``` ## License This project is licensed under the MIT License – see the [LICENSE](LICENSE) file for details. <file_sep>#include <iostream> #include <string> #include <sstream> #include <fstream> #include <vector> #include <array> #include <queue> #include <iterator> #include <chrono> #include <climits> #include <omp.h> #include <mpi.h> #include <cstddef> #include <stdexcept> #define INST_SIZE 160 using namespace std; using namespace chrono; typedef vector<vector<pair<int, double>>> graph; /** * Represents a state of problem we want to solve. State consists of price, * depth (current bit in vector) and a static array of bits. */ struct State { double price; int depth; array<int, INST_SIZE> vec; }; /** * Is responsible for creating graph represenation of a problem and solving this * problem. */ class MECSolver { public: /** * Default constructor */ MECSolver() = default; /** * Constructor used to initialize all of the essential variables. */ MECSolver(int n, int k, int b, int threadNum, int instNum): m_n(n), m_k(k), m_b(b), m_threadNum(threadNum), m_instNum(instNum), m_graph(graph(m_n, vector<pair<int, double>>())), m_exclusionPairs(vector<int>(m_n, -1)) {} /** * Returns graph representation. */ graph getGraph() { return m_graph; } /** * Inserts edge between nodes u and v with the weight w to the graph. */ void insertEdge(int u, int v, double w) { m_graph.at(u).push_back(make_pair(v, w)); m_graph.at(v).push_back(make_pair(u, w)); } /** * Inserts a new exclusion pair between u and v. */ void insertExclusionPair(int u, int v) { m_exclusionPairs.at(v) = u; } /** * Generates initial states(instances) of the problem using BFS algorithm. */ void generateStates(queue<State>& q) { State s0; initState(s0); q.push(s0); while(q.size() <= size_t(m_instNum / m_n) && !q.empty()) { State state = q.front(); q.pop(); if ((state.depth + 1) == m_n) break; if (m_exclusionPairs.at(state.depth + 1) != -1) { int next = !state.vec.at(m_exclusionPairs.at(state.depth + 1)); updateState(state, next); q.push(state); } else { int depth = state.depth; double price = state.price; updateState(state, 0); q.push(state); state.depth = depth; state.price = price; updateState(state, 1); q.push(state); } } } /** * Solves the problem using OpenMP and task parallelism technique. Returns * the best solution. */ State solve(State& state) { m_bestState.price = INT_MAX; #pragma omp parallel { #pragma omp single solveProblem(state); } return m_bestState; } private: int m_n, m_k, m_b, m_threadNum, m_instNum; State m_bestState; graph m_graph; vector<int> m_exclusionPairs; void solveProblem(State& state) { int it = state.depth + 1; if (it == m_n) { if (state.price < m_bestState.price) { #pragma omp critical { if (state.price < m_bestState.price) m_bestState = state; } } return; } if (m_exclusionPairs.at(it) != -1) { updateState(state, !state.vec.at(m_exclusionPairs.at(it))); if (state.price < m_bestState.price) { #pragma omp task shared (state) if ((it - 1) < m_threadNum) solveProblem(state); } } else { state.vec.at(it) = 0; double price0 = recalculatePrice(it, state.price, state.vec); if (price0 < m_bestState.price) { State state0 = state; updateState(state0, price0); #pragma omp task if ((it - 1) < m_threadNum) solveProblem(state0); } state.vec.at(it) = 1; double price1 = recalculatePrice(it, state.price, state.vec); if (price1 < m_bestState.price) { State state1 = state; updateState(state1, price1); #pragma omp task if ((it - 1) < m_threadNum) solveProblem(state1); } } #pragma omp taskwait } void updateState(State& state, int next) { state.depth++; state.vec.at(state.depth) = next; state.price = recalculatePrice(state.depth, state.price, state.vec); } void updateState(State& state, double newPrice) { state.depth++; state.price = newPrice; } double recalculatePrice(int u, double price, const array<int, INST_SIZE>& vec) { for (auto n: m_graph.at(u)) if (vec.at(n.first) != -1 && vec.at(n.first) != vec.at(u)) price += n.second; return price; } void initState(State& state) { state.price = 0; state.depth = 0; for (int i = 0; i < m_n; i++) state.vec.at(i) = -1; state.vec.at(0) = 0; } }; /** * Responsible for handling MPI communication. Divides work between master and * slave processes. Makes sure that passed messages are received and processed * by a correct process. */ class ProcessHandler { public: /** * Constructor which initializes MPI, solver class, and custom structured * MPI type based on the State structure. */ ProcessHandler(int argc, char **argv) { initMPI(argc, argv); initSolver(stoi(argv[1]), stoi(argv[2]), argv[3]); initStateType(); } /** * Divides work between master and slave processes and solves the problem * by calling appropriate functions. */ void solveProblem() { if (m_procNum == 0) { auto start = high_resolution_clock::now(); doMasterWork(); auto stop = high_resolution_clock::now(); printSolution((double) duration_cast<milliseconds>(stop - start).count() / 1000); } else { doSlaveWork(); } MPI_Finalize (); } private: int m_provided, m_required, m_numProcs, m_procNum, m_threadNum, m_n; MECSolver m_solver; State m_bestState; MPI_Datatype m_stateType; static const int tag_work = 0; static const int tag_done = 1; static const int tag_finished = 2; void initMPI(int argc, char **argv) { m_provided = MPI_THREAD_FUNNELED; m_required = MPI_THREAD_FUNNELED; MPI_Init_thread(&argc, &argv, m_required, &m_provided); if (m_provided < m_required) throw runtime_error("MPI library does not provide required threading support"); MPI_Comm_size(MPI_COMM_WORLD, &m_numProcs); MPI_Comm_rank(MPI_COMM_WORLD, &m_procNum); } void initSolver(const int& threadNum, const int& instNum, const string& fileName) { string rawInput; ifstream inFile(fileName); getline(inFile, rawInput); vector<int> inits = split<int>(rawInput); m_solver = MECSolver(inits.at(0), inits.at(1), inits.at(2), threadNum, instNum); m_n = inits.at(0); int edgesNum = inits.at(0) * inits.at(1) / 2; for (int i = 0; i < edgesNum; i++) { getline(inFile, rawInput); vector<double> nums = split<double>(rawInput); m_solver.insertEdge(int(nums.at(0)), int(nums.at(1)), nums.at(2)); } for (int i = 0; i < inits.at(2); i++) { getline(inFile, rawInput); vector<int> nums = split<int>(rawInput); m_solver.insertExclusionPair(nums.at(0), nums.at(1)); } } void initStateType() { const MPI_Aint displacements[3] = {offsetof(State, price), offsetof(State, depth), offsetof(State, vec)}; const int lengths[3] = {1, 1, INST_SIZE}; MPI_Datatype types[3] = {MPI_DOUBLE, MPI_INT, MPI_INT}; MPI_Type_create_struct(3, lengths, displacements, types, &m_stateType); MPI_Type_commit(&m_stateType); } void doMasterWork() { MPI_Status status; queue<State> q; m_bestState.price = INT_MAX; m_solver.generateStates(q); for (int dest = 1; dest < m_numProcs; dest++) { if (!q.empty()) { State state = q.front(); q.pop(); MPI_Send(&state, 1, m_stateType, dest, tag_work, MPI_COMM_WORLD); } else { break; } } int workingSlaves = m_numProcs - 1; while (workingSlaves > 0) { State state; MPI_Recv(&state, 1, m_stateType, MPI_ANY_SOURCE, tag_done, MPI_COMM_WORLD, &status); if (state.price < m_bestState.price) m_bestState = state; if (!q.empty()) { state = q.front(); q.pop(); MPI_Send(&state, 1, m_stateType, status.MPI_SOURCE, tag_work, MPI_COMM_WORLD); } else { MPI_Send(&state, 1, m_stateType, status.MPI_SOURCE, tag_finished, MPI_COMM_WORLD); workingSlaves--; } } } void doSlaveWork() { MPI_Status status; while (true) { State state; MPI_Recv(&state, 1, m_stateType, 0, MPI_ANY_TAG, MPI_COMM_WORLD, &status); if (status.MPI_TAG == tag_finished) { break; } else if (status.MPI_TAG == tag_work) { State bestState = m_solver.solve(state); MPI_Send(&bestState, 1, m_stateType, 0, tag_done, MPI_COMM_WORLD); } else { throw runtime_error("Unknown tag received"); } } } void printSolution(double duration) { auto graph = m_solver.getGraph(); auto price = m_bestState.price; auto vec = m_bestState.vec; cout << "Price: " << price << endl; cout << "-------------------------" << endl; cout << "Execution time: " << duration << endl; cout << "-------------------------" << endl; cout << "Set X: "; for (int i = 0; i < m_n; i++) if (vec.at(i) == 0) cout << i << " "; cout << endl; cout << "Set Y: "; for (int i = 0; i < m_n; i++) if (vec.at(i) == 1) cout << i << " "; cout << endl; cout << "-------------------------" << endl; cout << "Edges included in cut:" << endl; for (int i = 0; i < m_n; i++) { for (auto it: graph[i]) { if (vec[it.first] != vec[i] && (int) i < it.first) cout << "(" << i << ", " << it.first << ") "; } } cout << endl; } template<typename T> vector<T> split(const string& line) { istringstream is(line); return vector<T>(istream_iterator<T>(is), istream_iterator<T>()); } }; int main(int argc, char **argv) { ProcessHandler processHandler(argc, argv); processHandler.solveProblem(); return 0; } <file_sep>#include <iostream> #include <string> #include <sstream> #include <vector> #include <iterator> #include <chrono> #include <omp.h> #include <stdexcept> using namespace std; using namespace chrono; /** * Serves as a placeholder for a solution variables. Solution consists of best * price, number of recursive calls, execution time of B&B DFS algorithm, and * the vector with nodes that are separated into two disjoint sets. */ class Solution { public: /** * Default constructor. */ Solution(double price, vector<int> vec, double duration) { m_price = price; m_vec = vec; m_duration = duration; } /** * Returns best price. */ double getPrice() { return m_price; } /** * Returns vector with nodes separated into two disjoint sets. */ vector<int> getVec() { return m_vec; } /** * Returns execution time. */ double getDuration() { return m_duration; } private: double m_price, m_duration; vector<int> m_vec; }; /** * Represents the graph and includes methods to construct the graph and to solve * the minimum exclusion cut. */ class Graph { public: /** * Default constructor. */ Graph(int n, int k, int b, int limit): m_n(n), m_k(k), m_b(b), m_limit(limit) { for (int i = 0; i < n; i++) { vector<pair<int, double>> v; m_graph.push_back(v); } m_bestPrice = n * k / 2; m_exclusionPairs = vector<int>(m_n, -1); } /** * Returns number of nodes in the graph. */ int getN() { return m_n; } /** * Returns avarage degree of a node. */ int getK() { return m_k; } /** * Returns number of exclusion pairs. */ int getB() { return m_b; } /** * Returns graph representation. */ vector<vector<pair<int, double>>> getGraph() { return m_graph; } /** * Inserts edge between nodes u and v with the weight w to the graph. */ void insertEdge(int u, int v, double w) { m_graph.at(u).push_back(make_pair(v, w)); m_graph.at(v).push_back(make_pair(u, w)); } /** * Inserts a new exclusion pair between u and v. */ void insertExclusionPair(int u, int v) { m_exclusionPairs[v] = u; } /** * Solves the exclusion graph cut problem and returns solution. */ Solution solveProblem() { vector<int> vec(m_n, -1); vec.at(0) = 0; auto start = high_resolution_clock::now(); #pragma omp parallel { #pragma omp single bbDFS(0, 0.0, vec); } auto stop = high_resolution_clock::now(); double duration = (double) duration_cast<milliseconds>(stop - start).count() / 1000; return Solution(m_bestPrice, m_bestVec, duration); } private: int m_n, m_k, m_b, m_limit; double m_bestPrice; vector<int> m_bestVec; vector<vector<pair<int, double>>> m_graph; vector<int> m_exclusionPairs; void bbDFS(int u, double price, vector<int>& vec) { int next = u + 1; if (next == m_n) { if (price < m_bestPrice) { #pragma omp critical { if (price < m_bestPrice) { m_bestPrice = price; m_bestVec = vec; } } } return; } double newPrice; if (m_exclusionPairs.at(next) != -1) { vec.at(next) = !vec.at(m_exclusionPairs.at(next)); newPrice = recalculatePrice(next, price, vec); if (newPrice < m_bestPrice) { #pragma omp task shared(vec) if (u < m_limit) bbDFS(next, newPrice, vec); } } else { vector<int> newVec; vec.at(next) = 0; newPrice = recalculatePrice(next, price, vec); if (newPrice < m_bestPrice) { newVec = vec; #pragma omp task shared(vec) if (u < m_limit) bbDFS(next, newPrice, newVec); } vec.at(next) = 1; newPrice = recalculatePrice(next, price, vec); if (newPrice < m_bestPrice) { newVec = vec; #pragma omp task shared(vec) if (u < m_limit) bbDFS(next, newPrice, newVec); } } #pragma omp taskwait } double recalculatePrice(int u, double price, const vector<int>& vec) { for (auto n: m_graph.at(u)) if (vec.at(n.first) != -1 && vec.at(n.first) != vec.at(u)) price += n.second; return price; } }; /** * Helper function which splits a string through a whitespace and adds the * results to the vector. */ template<typename T> vector<T> split(const string& line) { istringstream is(line); return vector<T>(istream_iterator<T>(is), istream_iterator<T>()); } /** * Helper function which reads the input from the stdin and constructs a new * graph. */ Graph constructGraph(int limit) { string rawInput; getline(cin, rawInput); vector<int> inits = split<int>(rawInput); Graph g(inits.at(0), inits.at(1), inits.at(2), limit); int edgesNum = g.getN() * g.getK() / 2; for (int i = 0; i < edgesNum; i++) { getline(cin, rawInput); vector<double> nums = split<double>(rawInput); g.insertEdge(int(nums.at(0)), int(nums.at(1)), nums.at(2)); } for (int i = 0; i < g.getB(); i++) { getline(cin, rawInput); vector<int> nums = split<int>(rawInput); g.insertExclusionPair(nums.at(0), nums.at(1)); } return g; } /** * Helper function which prints a solution in the human readable format. */ void printSolution(Solution& s, Graph& g) { auto graph = g.getGraph(); auto vec = s.getVec(); cout << "Price: " << s.getPrice() << endl; cout << "-------------------------" << endl; cout << "Execution time: " << s.getDuration() << endl; cout << "-------------------------" << endl; cout << "Set X: "; for (size_t i = 0; i < vec.size(); i++) if (vec.at(i) == 0) cout << i << " "; cout << endl; cout << "Set Y: "; for (size_t i = 0; i < vec.size(); i++) if (vec.at(i) == 1) cout << i << " "; cout << endl; cout << "-------------------------" << endl; cout << "Edges included in cut:" << endl; for (size_t i = 0; i < vec.size(); i++) { for (auto it: graph[i]) { if (vec[it.first] != vec[i] && (int) i < it.first) cout << "(" << i << ", " << it.first << ") "; } } cout << endl; } /** * Helper function to process input command line arguments */ int processArgs(int argc, char **argv) { if (argc != 2) { cerr << "Invalid number of arguments" << endl; return -1; } int x; string arg = argv[1]; try { size_t pos; x = stoi(arg, &pos); if (pos < arg.size()) { cerr << "Trailing characters after number: " << arg << endl; return -1; } } catch (invalid_argument const &ex) { cerr << "Invalid number: " << arg << endl; return -1; } catch (out_of_range const &ex) { cerr << "Number out of range: " << arg << endl; return -1; } return x; } int main(int argc, char **argv) { int l = processArgs(argc, argv); if (l == -1) return 1; Graph g = constructGraph(l); Solution s = g.solveProblem(); printSolution(s, g); return 0; } <file_sep>#include <iostream> #include <string> #include <sstream> #include <vector> #include <queue> #include <iterator> #include <chrono> #include <omp.h> #include <stdexcept> using namespace std; using namespace chrono; typedef vector<vector<pair<int, double>>> graph; /** * Represents a state of problem we want to solve. State consists of price, * depth (current bit in vector) and vector of bits. */ struct State { /** * Default constructor. */ State() = default; /** * Constructor used to create an initial state of the problem. */ State(int size): price(0), depth(0), vec(vector<int>(size, -1)) { vec.at(0) = 0; } /** * Sets value of next bit and updates depth. */ void updateState(int next) { depth++; vec.at(depth) = next; } /** * Updates price and depth. */ void updateState(double newPrice) { depth++; price = newPrice; } double price; int depth; vector<int> vec; }; /** * Serves as a placeholder for a solution variables. Solution consists of best * instance of state and execution time of B&B DFS algorithm. */ struct Solution { /** * Default constructor. */ Solution() = default; /** * Constructor used to create an initial ("worst") solution. */ Solution(int size, double initPrice): m_state(State(size)) { m_state.price = initPrice; } State m_state; double m_duration; }; /** * Is responsible for creating graph represenation of a problem and solving this * problem. */ class Problem { public: /** * Constructor used to initialize all of the essential variables. */ Problem(int n, int k, int b, int mlpCons): m_n(n), m_k(k), m_b(b), m_mlpCons(mlpCons), m_bestPrice(n * k / 2), m_graph(graph(m_n, vector<pair<int, double>>())), m_exclusionPairs(vector<int>(m_n, -1)) {} /** * Returns number of nodes in the graph. */ int getN() { return m_n; } /** * Returns avarage degree of a node. */ int getK() { return m_k; } /** * Returns number of exclusion pairs. */ int getB() { return m_b; } /** * Returns graph representation. */ graph getGraph() { return m_graph; } /** * Inserts edge between nodes u and v with the weight w to the graph. */ void insertEdge(int u, int v, double w) { m_graph.at(u).push_back(make_pair(v, w)); m_graph.at(v).push_back(make_pair(u, w)); } /** * Inserts a new exclusion pair between u and v. */ void insertExclusionPair(int u, int v) { m_exclusionPairs.at(v) = u; } /** * Solves the problem using OpenMP and data parallelism technique. Returns * the final solution. */ Solution solveProblem() { auto start = high_resolution_clock::now(); Solution bestSol; double initPrice = m_bestPrice; generateStates(); #pragma omp parallel for for (size_t i = 0; i < m_states.size(); i++) { Solution sol(m_n, initPrice); solve(m_states[i], sol); #pragma omp critical if (sol.m_state.price < m_bestPrice && (sol.m_state.depth + 1) == m_n) { bestSol = sol; m_bestPrice = sol.m_state.price; } } auto stop = high_resolution_clock::now(); bestSol.m_duration = (double) duration_cast<milliseconds>(stop - start).count() / 1000; return bestSol; } private: int m_n, m_k, m_b, m_mlpCons; double m_bestPrice; graph m_graph; vector<int> m_exclusionPairs; vector<State> m_states; void generateStates() { State s0(m_n); queue<State> q; q.push(s0); while(q.size() <= size_t(m_mlpCons / m_n) && !q.empty()) { State state = q.front(); q.pop(); if ((state.depth + 1) == m_n) break; if (m_exclusionPairs.at(state.depth + 1) != -1) { int next = !state.vec.at(m_exclusionPairs.at(state.depth + 1)); state.updateState(next); state.price = recalculatePrice(state.depth, state.price, state.vec); q.push(state); } else { int depth = state.depth; double price = state.price; state.updateState(0); state.price = recalculatePrice(state.depth, state.price, state.vec); q.push(state); state.depth = depth; state.price = price; state.updateState(1); state.price = recalculatePrice(state.depth, state.price, state.vec); q.push(state); } } while (!q.empty()) { m_states.push_back(q.front()); q.pop(); } } void solve(State& state, Solution& sol) { int it = state.depth + 1; if (it == m_n) { if (state.price < sol.m_state.price) sol.m_state = state; return; } if (m_exclusionPairs.at(it) != -1) { int next = !state.vec.at(m_exclusionPairs.at(it)); state.updateState(next); state.price = recalculatePrice(state.depth, state.price, state.vec); if (state.price < sol.m_state.price) solve(state, sol); } else { state.vec.at(it) = 0; double price0 = recalculatePrice(it, state.price, state.vec); if (price0 < sol.m_state.price) { State state0 = state; state0.updateState(price0); solve(state0, sol); } state.vec.at(it) = 1; double price1 = recalculatePrice(it, state.price, state.vec); if (price1 < sol.m_state.price) { State state1 = state; state1.updateState(price1); solve(state1, sol); } } } double recalculatePrice(int u, double price, const vector<int>& vec) { for (auto n: m_graph.at(u)) if (vec.at(n.first) != -1 && vec.at(n.first) != vec.at(u)) price += n.second; return price; } }; /** * Helper function which splits a string through a whitespace and adds the * results to the vector. */ template<typename T> vector<T> split(const string& line) { istringstream is(line); return vector<T>(istream_iterator<T>(is), istream_iterator<T>()); } /** * Helper function which reads the input from the stdin and constructs a new * problem. */ Problem generateProblem(int mlpCons) { string rawInput; getline(cin, rawInput); vector<int> inits = split<int>(rawInput); Problem p(inits.at(0), inits.at(1), inits.at(2), mlpCons); int edgesNum = p.getN() * p.getK() / 2; for (int i = 0; i < edgesNum; i++) { getline(cin, rawInput); vector<double> nums = split<double>(rawInput); p.insertEdge(int(nums.at(0)), int(nums.at(1)), nums.at(2)); } for (int i = 0; i < p.getB(); i++) { getline(cin, rawInput); vector<int> nums = split<int>(rawInput); p.insertExclusionPair(nums.at(0), nums.at(1)); } return p; } /** * Helper function which prints a solution in the human readable format. */ void printSolution(Solution& s, Problem& p) { auto graph = p.getGraph(); auto vec = s.m_state.vec; cout << "Price: " << s.m_state.price << endl; cout << "-------------------------" << endl; cout << "Execution time: " << s.m_duration << endl; cout << "-------------------------" << endl; cout << "Set X: "; for (size_t i = 0; i < vec.size(); i++) if (vec.at(i) == 0) cout << i << " "; cout << endl; cout << "Set Y: "; for (size_t i = 0; i < vec.size(); i++) if (vec.at(i) == 1) cout << i << " "; cout << endl; cout << "-------------------------" << endl; cout << "Edges included in cut:" << endl; for (size_t i = 0; i < vec.size(); i++) { for (auto it: graph[i]) { if (vec[it.first] != vec[i] && (int) i < it.first) cout << "(" << i << ", " << it.first << ") "; } } cout << endl; } /** * Helper function to process input command line arguments */ int processArgs(int argc, char **argv) { if (argc != 2) { cerr << "Invalid number of arguments" << endl; return -1; } int x; string arg = argv[1]; try { size_t pos; x = stoi(arg, &pos); if (pos < arg.size()) { cerr << "Trailing characters after number: " << arg << endl; return -1; } } catch (invalid_argument const &ex) { cerr << "Invalid number: " << arg << endl; return -1; } catch (out_of_range const &ex) { cerr << "Number out of range: " << arg << endl; return -1; } return x; } int main(int argc, char **argv) { int mlpCons = processArgs(argc, argv); if (mlpCons == -1) return 1; Problem p = generateProblem(mlpCons); Solution s = p.solveProblem(); printSolution(s, p); return 0; } <file_sep>CXX=g++ CXXFLAGS=-std=c++11 -Wall -pedantic CXXSET=$(CXX) $(CXXFLAGS) COMPILE_SEQ=$(CXXSET) -Ofast COMPILE_PAR=$(CXXSET) -Ofast -fopenmp COMPILE_MPI=OMPI_CXX=g++ mpic++ -fopenmp -Ofast $(CXXFLAGS) DEBUG_SEQ=$(CXXSET) -g DEBUG_PAR=$(CXXSET) -g -fopenmp NAME1=task1 NAME2=task2 NAME3=task3 NAME4=task4 NP=3 define tests for file in test/*.txt; do \ echo "$$file\n"; \ out/$(1).out $(2) < "$$file"; \ echo "--------------------"; \ done endef define tests_mpi for file in test/*.txt; do \ echo "$$file\n"; \ if [[ ${INFINIBAND} = "true" ]]; then \ mpirun -np $(2) out/$(1).out $(3) $(4) "$$file"; \ else \ mpirun --mca btl tcp,self -np $(2) out/$(1).out $(3) $(4) "$$file"; \ fi; \ echo "--------------------"; \ done endef task1: compile1 out/$(NAME1).out compile1: $(COMPILE_SEQ) src/$(NAME1).cpp -o out/$(NAME1).out debug1: $(DEBUG_SEQ) src/$(NAME1).cpp -o out/$(NAME1).out tests1: compile1 $(call tests,$(NAME1)) task2: compile2 out/$(NAME2).out 15 compile2: $(COMPILE_PAR) src/$(NAME2).cpp -o out/$(NAME2).out debug2: $(DEBUG_PAR) src/$(NAME2).cpp -o out/$(NAME2).out tests2: compile2 $(call tests,$(NAME2),15) task3: compile3 out/$(NAME3).out 1000 compile3: $(COMPILE_PAR) src/$(NAME3).cpp -o out/$(NAME3).out debug3: $(DEBUG_PAR) src/$(NAME3).cpp -o out/$(NAME3).out tests3: compile3 $(call tests,$(NAME3),1000) compile4: $(COMPILE_MPI) src/$(NAME4).cpp -o out/$(NAME4).out tests4: compile4 $(call tests_mpi,$(NAME4),$(NP),15,1000) clean: rm -rf out/*
1c49f16960b16d192ef878f75465da4fc8b2f712
[ "Markdown", "Makefile", "C++" ]
5
Markdown
patrotom/pdp
95c3321560d009dd55f8488994dc776df290e4af
8c4d99e6b4a0899e55ca314cb2316200c1974a23
refs/heads/master
<repo_name>neener/sneakerpimps<file_sep>/src/js/runner.js var App = require('./App.js'); var domReady = require('domready'); domReady(function(){ var app; if (window.innerWidth >= 768 && ( function () { try { var canvas = document.createElement( 'canvas' ); return !! ( window.WebGLRenderingContext && ( canvas.getContext( 'webgl' ) || canvas.getContext( 'experimental-webgl' ) ) ); } catch ( e ) { return false; } } )()){ app = new App(); } });<file_sep>/README.md # karaoke-subtitling <file_sep>/gulpfile.js 'use strict'; var browserify = require('browserify'); var gulp = require('gulp'); var source = require('vinyl-source-stream'); var buffer = require('vinyl-buffer'); var uglify = require('gulp-uglify'); var sourcemaps = require('gulp-sourcemaps'); gulp.task('browserify', function() { var bundler = browserify({ entries: ['./src/js/runner.js'], debug: true }); var bundle = function() { return bundler .bundle() .pipe(source('application.js')) .pipe(buffer()) .pipe(sourcemaps.init({loadMaps: true})) // .pipe(uglify()) .pipe(sourcemaps.write('./maps')) .pipe(gulp.dest('./dist/js/')); }; return bundle(); }); var jshint = require('gulp-jshint'); var stylish = require('jshint-stylish'); gulp.task('lint', function() { return gulp.src(['./src/js/**/*.js', '!./src/js/*Loader.js']) .pipe( jshint() ) .pipe( jshint.reporter( stylish ) ) .pipe(jshint.reporter('fail')); }); gulp.task('html', function(){ return gulp.src('./src/*.html') .pipe( gulp.dest('./dist') ); }); gulp.task('css', function(){ return gulp.src('./src/css/*.css') .pipe( gulp.dest('./dist/css') ); }); gulp.task('textures', function(){ return gulp.src('./src/textures/**/*') .pipe( gulp.dest('./dist/textures')); }); gulp.task('build', ['lint', 'browserify', 'html', 'css', 'textures']); gulp.task('watch', function(){ gulp.watch('./src/js/**/*.js', ['lint', 'browserify']); gulp.watch('./src/*.html', ['html']); gulp.watch('./src/css/*.css', ['css']); gulp.watch('./src/textures/**/*', ['textures']); });
68203829f838b2325a3ed7263d957a18a10ebe7f
[ "JavaScript", "Markdown" ]
3
JavaScript
neener/sneakerpimps
d3454f2f4038909ae6bec9add997905c8a23a24f
93c1ce3db55a5e5d60fcf8512567efa199b2bb20
refs/heads/master
<repo_name>daweijia/Pricing-Analysis-using-Linear-Regression-and-Neural-Network<file_sep>/README.md # Pricing-using-Linear-Regression-and-Neural-Network Using linear regression and neural network to do pricing analysis # Data source The dataset has 8 columns. units refers to the total units purchased, weekInYearNum refers to which week within a particular year the purchased was made, overallWeekNum refers to overall week a purchase was made, totalCost refers to the total price that a consumer paid, storeNum is a categorical variable that represents which store the purchase was made at, productNum is a categorical variable that represents which product was sold, and isFeature and isDisplay are Boolean variables representing if the product was featured (in a mail out) or separately displayed in the store. <file_sep>/pricing with lm and nnet.R # <NAME> MSMA setwd("/Users/jiadawei/Desktop/Market Analytics") HW4DB <- read.csv("Homework 4 Student Data.csv") ## Part1: Pricing with LM # a) most popular productNum units_by_productNum <- aggregate(units~productNum,data = HW4DB, sum) which.max(units_by_productNum$units) # no.89 is most popular product # b) build upcfile upcFile <- HW4DB[which(HW4DB$productNum==89),] # c) regression aggUPCFile <- aggregate(cbind(totalCost,units)~weekInYearNum+overallWeekNum+ storeNum+isFeature+isDisplay,data=upcFile,FUN = sum) aggUPCFile$pricePerCan <- aggUPCFile$totalCost/aggUPCFile$units model1 <- lm(log(units)~pricePerCan+isFeature+isDisplay+poly(weekInYearNum,4)+ factor(storeNum),data=aggUPCFile) # d) newdata dataset possiblePrices <- data.frame(price = seq(0,10,.01)) possiblePrices$demand <- NA newData <- data.frame(weekInYearNum=1,overallWeekNum=1,storeNum=1,isFeature=FALSE, isDisplay=FALSE,pricePerCan=possiblePrices$price) # e) predict demand predicted_demand <- exp(predict(model1,newData)) # f) expected profit expected_profit <- predicted_demand*(newData$pricePerCan-0.3) # g) optimal price which.max(expected_profit) #no.106 expected_profit[106]#2.083353 optimal expected profit newData$pricePerCan[106] #1.05 optimal price # h) repeat 1c-1g model2 = lm(log(units)~pricePerCan+poly(weekInYearNum,4),data=aggUPCFile) predicted_demand2 <- exp(predict(model2,newData)) expected_profit2 <- predicted_demand2*(newData$pricePerCan-0.3) which.max(expected_profit2) #no.58 expected_profit2[58] #3.185952 optimal expected profit newData$pricePerCan[58] #0.57 optimal price ## Part2: Pricing with nnet # a) nnt models library('nnet') set.seed(1) nnet1 = nnet(log(units)~pricePerCan+isFeature+isDisplay+poly(weekInYearNum,4)+ factor(storeNum),data=aggUPCFile,skip=TRUE,size=3,linout=1,maxit=10000) nnet2 = nnet(log(units)~pricePerCan+poly(weekInYearNum,4),data=aggUPCFile, skip=TRUE,size=3,linout=1,maxit=10000) # b) predict demand nnt1_predict_50 <- exp(predict(nnet1,newData[which(newData$pricePerCan==0.50),])) # demand = 8.352401 nnt2_predict_50 <- exp(predict(nnet2,newData[which(newData$pricePerCan==0.50),])) # demand = 11.78383 nnt1_predict_100 <- exp(predict(nnet1,newData[which(newData$pricePerCan==1),])) # demand = 2.438454 nnt2_predict_100 <- exp(predict(nnet2,newData[which(newData$pricePerCan==1),])) # demand = 2.056536 nnt1_predict_50-nnt1_predict_100 #difference 5.913947 nnt2_predict_50-nnt2_predict_100 #difference 9.727299 # c) predict expected profit #nnt1 predicted_demand_nnt1 <- exp(predict(nnet1,newData)) expected_profit_nnt1 <- predicted_demand_nnt1*(newData$pricePerCan-0.3) which.max(expected_profit_nnt1) #no.1001 expected_profit_nnt1[1001] #291737.7 optimal expected profit newData$pricePerCan[1001] #10 optimal price # strange output #nnt2 predicted_demand_nnt2 <- exp(predict(nnet2,newData)) expected_profit_nnt2 <- predicted_demand_nnt2*(newData$pricePerCan-0.3) which.max(expected_profit_nnt2) #no.72 expected_profit_nnt2[72] #4.52583 optimal expected profit newData$pricePerCan[72] #0.71 optimal price # d) strang output plot(newData$pricePerCan,expected_profit_nnt1) plot(newData$pricePerCan,expected_profit_nnt2) min(aggUPCFile$pricePerCan) #minimun is 0.29 max(aggUPCFile$pricePerCan) #maximun is 1.19 min(newData$pricePerCan) #minimun is 0 max(newData$pricePerCan) #maximun is 10 # fix the strange output newData2 <- newData[30:120,] predicted_demand_nnt1_2 <- exp(predict(nnet1,newData2)) expected_profit_nnt1_2 <- predicted_demand_nnt1_2*(newData2$pricePerCan-0.3) which.max(expected_profit_nnt1_2) #no.39 expected_profit_nnt1_2[39] #3.354292 optimal expected profit newData2$pricePerCan[39] #0.67 optimal price plot(newData2$pricePerCan,expected_profit_nnt1_2)
e9f15c7a29f81b8690535241bfbdaf6553a6daea
[ "Markdown", "R" ]
2
Markdown
daweijia/Pricing-Analysis-using-Linear-Regression-and-Neural-Network
f1078383ca1c49b8b908325a7cd75282732b64e0
945a8c4ab07ff9633d3dc6b45e0f4b484f12b1f5
refs/heads/master
<repo_name>sethvincent/millrun-editor<file_sep>/example/index.js var css = require('sheetify') var createEditor = require('../index') css('./style.css', { global: true }) var editor = createEditor() var state = { content: '# new draft '} var tree = editor(state, function (action, data) { console.log(action, data) }) document.body.appendChild(tree) <file_sep>/index.js var assert = require('assert') var html = require('yo-yo') var css = require('sheetify') var codemirror = require('codemirror') require('codemirror/addon/mode/overlay') require('codemirror/addon/edit/continuelist') require('codemirror/mode/javascript/javascript') require('codemirror/mode/markdown/markdown') require('codemirror/mode/gfm/gfm') require('codemirror/mode/xml/xml') require('codemirror/mode/htmlmixed/htmlmixed') var format = require('./format') module.exports = function createEditor (options) { css('codemirror/lib/codemirror.css', { global: true }) css('./style.css', { global: true }) var prefix = css` :host { height: 100%; } #editor { height: 100%; } ` var el = html`<div id="editor"></div>` var editor = codemirror(el, { theme: 'millrun', mode: 'gfm', autofocus: true, lineNumbers: false, matchBrackets: true, lineWrapping: true, extraKeys: { 'Enter': 'newlineAndIndentContinueMarkdownList' } }) function render (params) { assert.ok(params) assert.ok(params.onChange) var onChange = params.onChange var element = html`<div class="editor-wrapper ${prefix}" onload=${onload} onunload=${onunload}> ${el} </div>` function change () { var value = editor.getValue() if (value.length) { onChange(format({ key: params.key, value: value, firstLine: editor.getLine(0), lineCount: editor.lineCount() })) } } function onload (el) { editor.on('change', change) } function onunload (el) { editor.off('change', change) } if (params.content) { editor.setValue(params.content) } setTimeout(function () { editor.refresh() }, 0) editor.containerEl = element return element } render.editor = editor return render } <file_sep>/README.md # millrun-editor Basic markdown editor component created for [millrun](https://github.com/cityarcade/millrun). ## Usage ```js var createEditor = require('millrun-editor') var editor = createEditor() var state = { content: '# new draft '} var tree = editor(state, function (action, data) { console.log(action, data) }) document.body.appendChild(tree) ```
baf03ecf71373b7da8147c2a1e850f533abc2fd8
[ "JavaScript", "Markdown" ]
3
JavaScript
sethvincent/millrun-editor
33d42dcfe537d8558368d94903b870054c3a34f4
a0f849bafbedcd9aeb919e4b434954467bc99ecc
refs/heads/master
<file_sep>/** Based on stm32h7xx_hal_eth.c from STM32H7 HAL lib v.1.10 (Cube H7 package v 1.9.0) ****************************************************************************** * @file stm32h7xx_hal_eth.c * @author * @brief ETH "middleware" layer on top of the ETH HAL driver @verbatim ============================================================================== ##### How to use this driver ##### ============================================================================== [..] (#) Ethernet data reception is asynchronous, so call the following API to start the listening mode: (##) HAL_ETH_Start(): This API starts the MAC and DMA transmission and reception process, without enabling end of transfer interrupts, in this mode user has to poll for data availability by calling HAL_ETH_IsRxDataAvailable() (##) HAL_ETH_Start_IT(): This API starts the MAC and DMA transmission and reception process, end of transfer interrupts are enabled in this mode, HAL_ETH_RxCpltCallback() will be executed when an Ethernet packet is received (#) When data is received (HAL_ETH_IsRxDataAvailable() returns 1 or Rx interrupt occurred), user can call the following APIs to get received data: (##) HAL_ETH_GetRxDataBuffer(): Get buffer address of received frame (##) HAL_ETH_GetRxDataLength(): Get received frame length (##) HAL_ETH_GetRxDataInfo(): Get received frame additional info, please refer to ETH_RxPacketInfo typedef structure (#) For transmission path, two APIs are available: (##) HAL_ETH_Transmit(): Transmit an ETH frame in blocking mode (##) HAL_ETH_Transmit_IT(): Transmit an ETH frame in interrupt mode, HAL_ETH_TxCpltCallback() will be executed when end of transfer occur @endverbatim */ /* Includes ------------------------------------------------------------------*/ #include "stm32h7xx_hal.h" #ifdef HAL_ETH_MODULE_ENABLED #error Cannot use both this and ST HAL library eth driver. Choose one. #endif #include "stm32h7xx_eth_MW.h" #include <string.h> /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /* Private macros ------------------------------------------------------------*/ /** @defgroup ETH_Private_Macros ETH Private Macros * @{ */ /* Helper macros for TX descriptor handling */ #define INCR_TX_DESC_INDEX(inx, offset) do {\ (inx) += (offset);\ if ((inx) >= (uint32_t)ETH_TX_DESC_CNT){\ (inx) = ((inx) - (uint32_t)ETH_TX_DESC_CNT);}\ } while (0) /* Helper macros for RX descriptor handling */ #define INCR_RX_DESC_INDEX(inx, offset) do {\ (inx) += (offset);\ if ((inx) >= (uint32_t)ETH_RX_DESC_CNT){\ (inx) = ((inx) - (uint32_t)ETH_RX_DESC_CNT);}\ } while (0) /** * @} */ /* Private function prototypes -----------------------------------------------*/ static uint32_t ETHx_Prepare_Tx_Descriptors(ETH_HandleTypeDef *heth, ETH_TxPacketConfig *pTxConfig, ETH_BufferTypeDef *txbuffer, uint32_t ItMode); // Static data - pa03 TODO put in some context struct -> link to heth ETH_TxDescListTypeDef g_TxDescList; ETH_RxDescListTypeDef g_RxDescList; /** * @brief Assign memory buffers to a DMA Rx descriptor * @param heth: pointer to a ETH_HandleTypeDef structure that contains * the configuration information for ETHERNET module * @param Index : index of the DMA Rx descriptor * this parameter can be a value from 0x0 to (ETH_RX_DESC_CNT -1) * @param pBuffer1: address of buffer 1 * @param pBuffer2: address of buffer 2 if available * @retval HAL status */ HAL_StatusTypeDef ETHx_DescAssignMemory(ETH_HandleTypeDef *heth, uint32_t Index, uint8_t *pBuffer1, uint8_t *pBuffer2) { ETHx_DMADescTypeDef *dmarxdesc = (ETHx_DMADescTypeDef *)g_RxDescList.RxDesc[Index]; if((pBuffer1 == NULL) || (Index >= (uint32_t)ETH_RX_DESC_CNT)) { /* Set Error Code */ heth->ErrorCode = HAL_ETH_ERROR_PARAM; /* Return Error */ return HAL_ERROR; } /* write buffer address to RDES0 */ WRITE_REG(dmarxdesc->DESC0, (uint32_t)pBuffer1); /* store buffer address */ WRITE_REG(dmarxdesc->BackupAddr0, (uint32_t)pBuffer1); /* set buffer address valid bit to RDES3 */ SET_BIT(dmarxdesc->DESC3, ETH_DMARXNDESCRF_BUF1V); if(pBuffer2 != NULL) { /* write buffer 2 address to RDES1 */ WRITE_REG(dmarxdesc->DESC2, (uint32_t)pBuffer2); /* store buffer 2 address */ WRITE_REG(dmarxdesc->BackupAddr1, (uint32_t)pBuffer2); /* set buffer 2 address valid bit to RDES3 */ SET_BIT(dmarxdesc->DESC3, ETH_DMARXNDESCRF_BUF2V); } /* set OWN bit to RDES3 */ SET_BIT(dmarxdesc->DESC3, ETH_DMARXNDESCRF_OWN); return HAL_OK; } /** * @brief Stop Ethernet MAC and DMA reception/transmission in Interrupt mode * @param heth: pointer to a ETH_HandleTypeDef structure that contains * the configuration information for ETHERNET module * @retval HAL status */ HAL_StatusTypeDef ETHx_Stop_IT(ETH_HandleTypeDef *heth) { ETHx_DMADescTypeDef *dmarxdesc; uint32_t descindex; HAL_ETH_Stop_IT(heth); /* Clear IOC bit to all Rx descriptors */ for (descindex = 0; descindex < (uint32_t)ETH_RX_DESC_CNT; descindex++) { dmarxdesc = g_RxDescList.RxDesc[descindex]; CLEAR_BIT(dmarxdesc->DESC3, ETH_DMARXNDESCRF_IOC); } g_RxDescList.ItMode = 0U; return HAL_OK; } /** * @brief Sends an Ethernet Packet in polling mode. * @param heth: pointer to a ETH_HandleTypeDef structure that contains * the configuration information for ETHERNET module * @param pTxConfig: Hold the configuration of packet to be transmitted * @param txbuffer : TX buffers chain to be transmitted * @param Timeout: timeout value * @retval HAL status */ HAL_StatusTypeDef ETHx_Transmit(ETH_HandleTypeDef *heth, ETH_TxPacketConfig *pTxConfig, ETH_BufferTypeDef *txbuffer, uint32_t Timeout) { uint32_t tickstart; const ETHx_DMADescTypeDef *dmatxdesc; if(pTxConfig == NULL || txbuffer == NULL) { heth->ErrorCode |= HAL_ETH_ERROR_PARAM; return HAL_ERROR; } if(heth->gState == HAL_ETH_STATE_READY) { /* Config DMA Tx descriptor by Tx Packet info */ /* Assume TX DMA is idle else race can occur! pa01 */ if (ETHx_Prepare_Tx_Descriptors(heth, pTxConfig, txbuffer, 0) != HAL_ETH_ERROR_NONE) { /* Set the ETH error code */ heth->ErrorCode |= HAL_ETH_ERROR_BUSY; return HAL_ERROR; } dmatxdesc = g_TxDescList.TxDesc[g_TxDescList.CurTxDesc]; /* Incr current tx desc index */ INCR_TX_DESC_INDEX(g_TxDescList.CurTxDesc, 1U); /* Start transmission */ /* issue a poll command to Tx DMA by writing address of next immediate free descriptor */ WRITE_REG(heth->Instance->DMACTDTPR, (uint32_t)(g_TxDescList.TxDesc[g_TxDescList.CurTxDesc])); tickstart = HAL_GetTick(); /* Wait for data to be transmitted or timeout occurred */ while((dmatxdesc->DESC3 & ETH_DMATXNDESCWBF_OWN) != (uint32_t)RESET) { if((heth->Instance->DMACSR & ETH_DMACSR_FBE) != (uint32_t)RESET) { heth->ErrorCode |= HAL_ETH_ERROR_DMA; heth->DMAErrorCode = heth->Instance->DMACSR; /* Set ETH HAL State to Ready */ heth->gState = HAL_ETH_STATE_ERROR; /* Return function status */ return HAL_ERROR; } /* Check for the Timeout */ if(Timeout != HAL_MAX_DELAY) { if(((HAL_GetTick() - tickstart ) > Timeout) || (Timeout == 0U)) { heth->ErrorCode |= HAL_ETH_ERROR_TIMEOUT; heth->gState = HAL_ETH_STATE_ERROR; return HAL_ERROR; } } } /* Return function status */ return HAL_OK; } else { return HAL_ERROR; } } /** * @brief Sends an Ethernet Packet in interrupt mode. * @param heth: pointer to a ETH_HandleTypeDef structure that contains * the configuration information for ETHERNET module * @param pTxConfig: Hold the configuration of packet to be transmitted * @retval HAL status */ HAL_StatusTypeDef ETHx_Transmit_IT(ETH_HandleTypeDef *heth, ETH_TxPacketConfig *pTxConfig, ETH_BufferTypeDef *txbuffer) { if(pTxConfig == NULL) { heth->ErrorCode |= HAL_ETH_ERROR_PARAM; return HAL_ERROR; } if(heth->gState == HAL_ETH_STATE_READY) { /* Config DMA Tx descriptor by Tx Packet info */ /* Assume TX DMA is idle else race can occur! pa01 */ if (ETHx_Prepare_Tx_Descriptors(heth, pTxConfig, txbuffer, 1) != HAL_ETH_ERROR_NONE) { heth->ErrorCode |= HAL_ETH_ERROR_BUSY; return HAL_ERROR; } /* Incr current tx desc index */ INCR_TX_DESC_INDEX(g_TxDescList.CurTxDesc, 1U); /* Start transmission */ /* issue a poll command to Tx DMA by writing address of next immediate free descriptor */ WRITE_REG(heth->Instance->DMACTDTPR, (uint32_t)(g_TxDescList.TxDesc[g_TxDescList.CurTxDesc])); return HAL_OK; } else { return HAL_ERROR; } } /** * @brief Checks for received Packets. * @param heth: pointer to a ETH_HandleTypeDef structure that contains * the configuration information for ETHERNET module * @retval 1: A Packet is received * 0: no Packet received */ uint8_t ETHx_IsRxDataAvailable(ETH_HandleTypeDef *heth) { ETH_RxDescListTypeDef *dmarxdesclist = &g_RxDescList; uint32_t descidx = dmarxdesclist->CurRxDesc; ETHx_DMADescTypeDef *dmarxdesc = dmarxdesclist->RxDesc[descidx]; uint32_t descscancnt = 0; uint32_t appdesccnt = 0, firstappdescidx = 0; if(dmarxdesclist->AppDescNbr != 0U) { /* data already received by not yet processed*/ return 0; } /* Check if descriptor is not owned by DMA */ while((READ_BIT(dmarxdesc->DESC3, ETH_DMARXNDESCWBF_OWN) == (uint32_t)RESET) && (descscancnt < (uint32_t)ETH_RX_DESC_CNT)) { descscancnt++; /* Check if last descriptor */ if(READ_BIT(dmarxdesc->DESC3, ETH_DMARXNDESCWBF_LD) != (uint32_t)RESET) { /* Increment the number of descriptors to be passed to the application */ appdesccnt += 1U; if(appdesccnt == 1U) { WRITE_REG(firstappdescidx, descidx); } /* Increment current rx descriptor index */ INCR_RX_DESC_INDEX(descidx, 1U); /* Check for Context descriptor */ /* Get current descriptor address */ dmarxdesc = dmarxdesclist->RxDesc[descidx]; if(READ_BIT(dmarxdesc->DESC3, ETH_DMARXNDESCWBF_OWN) == (uint32_t)RESET) { if(READ_BIT(dmarxdesc->DESC3, ETH_DMARXNDESCWBF_CTXT) != (uint32_t)RESET) { /* Increment the number of descriptors to be passed to the application */ dmarxdesclist->AppContextDesc = 1; /* Increment current rx descriptor index */ INCR_RX_DESC_INDEX(descidx, 1U); } } /* Fill information to Rx descriptors list */ dmarxdesclist->CurRxDesc = descidx; dmarxdesclist->FirstAppDesc = firstappdescidx; dmarxdesclist->AppDescNbr = appdesccnt; /* Return function status */ return 1; } /* Check if first descriptor */ else if(READ_BIT(dmarxdesc->DESC3, ETH_DMARXNDESCWBF_FD) != (uint32_t)RESET) { WRITE_REG(firstappdescidx, descidx); /* Increment the number of descriptors to be passed to the application */ appdesccnt = 1U; /* Increment current rx descriptor index */ INCR_RX_DESC_INDEX(descidx, 1U); /* Get current descriptor address */ dmarxdesc = dmarxdesclist->RxDesc[descidx]; } /* It should be an intermediate descriptor */ else { /* Increment the number of descriptors to be passed to the application */ appdesccnt += 1U; /* Increment current rx descriptor index */ INCR_RX_DESC_INDEX(descidx, 1U); /* Get current descriptor address */ dmarxdesc = dmarxdesclist->RxDesc[descidx]; } } /* Build Descriptors if an incomplete Packet is received */ if(appdesccnt > 0U) { dmarxdesclist->CurRxDesc = descidx; dmarxdesclist->FirstAppDesc = firstappdescidx; descidx = firstappdescidx; dmarxdesc = dmarxdesclist->RxDesc[descidx]; for(descscancnt = 0; descscancnt < appdesccnt; descscancnt++) { WRITE_REG(dmarxdesc->DESC0, dmarxdesc->BackupAddr0); WRITE_REG(dmarxdesc->DESC3, ETH_DMARXNDESCRF_BUF1V); if (READ_REG(dmarxdesc->BackupAddr1) != ((uint32_t)RESET)) { WRITE_REG(dmarxdesc->DESC2, dmarxdesc->BackupAddr1); SET_BIT(dmarxdesc->DESC3, ETH_DMARXNDESCRF_BUF2V); } SET_BIT(dmarxdesc->DESC3, ETH_DMARXNDESCRF_OWN); if(dmarxdesclist->ItMode != ((uint32_t)RESET)) { SET_BIT(dmarxdesc->DESC3, ETH_DMARXNDESCRF_IOC); } if(descscancnt < (appdesccnt - 1U)) { /* Increment rx descriptor index */ INCR_RX_DESC_INDEX(descidx, 1U); /* Get descriptor address */ dmarxdesc = dmarxdesclist->RxDesc[descidx]; } } /* Set the Tail pointer address to the last rx descriptor hold by the app */ WRITE_REG(heth->Instance->DMACRDTPR, (uint32_t)dmarxdesc); } /* Fill information to Rx descriptors list: No received Packet */ dmarxdesclist->AppDescNbr = 0U; return 0; } /** * @brief This function gets the buffer address of last received Packet. * @note Please insure to allocate the RxBuffer structure before calling this function * how to use example: * HAL_ETH_GetRxDataLength(heth, &Length); * BuffersNbr = (Length / heth->Init.RxBuffLen) + 1; * RxBuffer = (ETH_BufferTypeDef *)malloc(BuffersNbr * sizeof(ETH_BufferTypeDef)); * HAL_ETH_GetRxDataBuffer(heth, RxBuffer); * @param heth: pointer to a ETH_HandleTypeDef structure that contains * the configuration information for ETHERNET module * @param RxBuffer: Pointer to a ETH_BufferTypeDef structure * @retval HAL status */ HAL_StatusTypeDef ETHx_GetRxDataBuffer(ETH_HandleTypeDef *heth, ETH_BufferTypeDef *RxBuffer) { ETH_RxDescListTypeDef *dmarxdesclist = &g_RxDescList; uint32_t descidx = dmarxdesclist->FirstAppDesc; uint32_t index, accumulatedlen = 0, lastdesclen; __IO const ETHx_DMADescTypeDef *dmarxdesc = dmarxdesclist->RxDesc[descidx]; ETH_BufferTypeDef *rxbuff = RxBuffer; if(rxbuff == NULL) { heth->ErrorCode = HAL_ETH_ERROR_PARAM; return HAL_ERROR; } if(dmarxdesclist->AppDescNbr == 0U) { if(ETHx_IsRxDataAvailable(heth) == 0U) { /* No data to be transferred to the application */ return HAL_ERROR; } else { descidx = dmarxdesclist->FirstAppDesc; dmarxdesc = dmarxdesclist->RxDesc[descidx]; } } /* Get intermediate descriptors buffers: in case of the Packet is split into multi descriptors */ for(index = 0; index < (dmarxdesclist->AppDescNbr - 1U); index++) { /* Get Address and length of the first buffer address */ rxbuff->buffer = (uint8_t *) dmarxdesc->BackupAddr0; rxbuff->len = heth->Init.RxBuffLen; /* Check if the second buffer address of this descriptor is valid */ if(dmarxdesc->BackupAddr1 != 0U) { /* Point to next buffer */ rxbuff = rxbuff->next; /* Get Address and length of the second buffer address */ rxbuff->buffer = (uint8_t *) dmarxdesc->BackupAddr1; rxbuff->len = heth->Init.RxBuffLen; } else { /* Nothing to do here */ } /* get total length until this descriptor */ accumulatedlen = READ_BIT(dmarxdesc->DESC3, ETH_DMARXNDESCWBF_PL); /* Increment to next descriptor */ INCR_RX_DESC_INDEX(descidx, 1U); dmarxdesc = dmarxdesclist->RxDesc[descidx]; /* Point to next buffer */ rxbuff = rxbuff->next; } /* last descriptor data length */ lastdesclen = READ_BIT(dmarxdesc->DESC3, ETH_DMARXNDESCWBF_PL) - accumulatedlen; /* Get Address of the first buffer address */ rxbuff->buffer = (uint8_t *) dmarxdesc->BackupAddr0; /* data is in only one buffer */ if(lastdesclen <= heth->Init.RxBuffLen) { rxbuff->len = lastdesclen; } /* data is in two buffers */ else if(dmarxdesc->BackupAddr1 != 0U) { /* Get the Length of the first buffer address */ rxbuff->len = heth->Init.RxBuffLen; /* Point to next buffer */ rxbuff = rxbuff->next; /* Get the Address the Length of the second buffer address */ rxbuff->buffer = (uint8_t *) dmarxdesc->BackupAddr1; rxbuff->len = lastdesclen - (heth->Init.RxBuffLen); } else /* Buffer 2 not valid*/ { return HAL_ERROR; } return HAL_OK; } /** * @brief This function gets the length of last received Packet. * @param heth: pointer to a ETH_HandleTypeDef structure that contains * the configuration information for ETHERNET module * @param Length: parameter to hold Rx packet length * @retval HAL Status */ HAL_StatusTypeDef ETHx_GetRxDataLength(ETH_HandleTypeDef *heth, uint32_t *Length) { ETH_RxDescListTypeDef *dmarxdesclist = &g_RxDescList; uint32_t descidx = dmarxdesclist->FirstAppDesc; __IO const ETH_DMADescTypeDef *dmarxdesc; if(dmarxdesclist->AppDescNbr == 0U) { if(ETHx_IsRxDataAvailable(heth) == 0U) { /* No data to be transferred to the application */ return HAL_ERROR; } } /* Get index of last descriptor */ INCR_RX_DESC_INDEX(descidx, (dmarxdesclist->AppDescNbr - 1U)); /* Point to last descriptor */ dmarxdesc = (ETH_DMADescTypeDef *)dmarxdesclist->RxDesc[descidx]; *Length = READ_BIT(dmarxdesc->DESC3, ETH_DMARXNDESCWBF_PL); return HAL_OK; } /** * @brief Get the Rx data info (Packet type, VLAN tag, Filters status, ...) * @param heth: pointer to a ETH_HandleTypeDef structure that contains * the configuration information for ETHERNET module * @param RxPacketInfo: parameter to hold info of received buffer * @retval HAL status */ HAL_StatusTypeDef ETHx_GetRxDataInfo(ETH_HandleTypeDef *heth, ETH_RxPacketInfo *RxPacketInfo) { ETH_RxDescListTypeDef *dmarxdesclist = &g_RxDescList; uint32_t descidx = dmarxdesclist->FirstAppDesc; __IO const ETHx_DMADescTypeDef *dmarxdesc; if(dmarxdesclist->AppDescNbr == 0U) { if(ETHx_IsRxDataAvailable(heth) == 0U) { /* No data to be transferred to the application */ return HAL_ERROR; } } /* Get index of last descriptor */ INCR_RX_DESC_INDEX(descidx, ((dmarxdesclist->AppDescNbr) - 1U)); /* Point to last descriptor */ dmarxdesc = dmarxdesclist->RxDesc[descidx]; if((dmarxdesc->DESC3 & ETH_DMARXNDESCWBF_ES) != (uint32_t)RESET) { RxPacketInfo->ErrorCode = READ_BIT(dmarxdesc->DESC3, ETH_DMARXNDESCWBF_ERRORS_MASK); } else { if(READ_BIT(dmarxdesc->DESC3, ETH_DMARXNDESCWBF_RS0V) != 0U) { if(READ_BIT(dmarxdesc->DESC3, ETH_DMARXNDESCWBF_LT) == ETH_DMARXNDESCWBF_LT_DVLAN) { RxPacketInfo->VlanTag = READ_BIT(dmarxdesc->DESC0, ETH_DMARXNDESCWBF_OVT); RxPacketInfo->InnerVlanTag = READ_BIT(dmarxdesc->DESC0, ETH_DMARXNDESCWBF_IVT) >> 16; } else { RxPacketInfo->VlanTag = READ_BIT(dmarxdesc->DESC0, ETH_DMARXNDESCWBF_OVT); } } if(READ_BIT(dmarxdesc->DESC3, ETH_DMARXNDESCWBF_RS1V) != 0U) { /* Get Payload type */ RxPacketInfo->PayloadType =READ_BIT( dmarxdesc->DESC1, ETH_DMARXNDESCWBF_PT); /* Get Header type */ RxPacketInfo->HeaderType = READ_BIT(dmarxdesc->DESC1, (ETH_DMARXNDESCWBF_IPV4 | ETH_DMARXNDESCWBF_IPV6)); /* Get Checksum status */ RxPacketInfo->Checksum = READ_BIT(dmarxdesc->DESC1, (ETH_DMARXNDESCWBF_IPCE | ETH_DMARXNDESCWBF_IPCB | ETH_DMARXNDESCWBF_IPHE)); } if(READ_BIT(dmarxdesc->DESC3, ETH_DMARXNDESCWBF_RS2V) != 0U) { RxPacketInfo->MacFilterStatus = READ_BIT(dmarxdesc->DESC2, (ETH_DMARXNDESCWBF_HF | ETH_DMARXNDESCWBF_DAF | ETH_DMARXNDESCWBF_SAF | ETH_DMARXNDESCWBF_VF)); RxPacketInfo->L3FilterStatus = READ_BIT(dmarxdesc->DESC2, (ETH_DMARXNDESCWBF_L3FM | ETH_DMARXNDESCWBF_L3L4FM)); RxPacketInfo->L4FilterStatus = READ_BIT(dmarxdesc->DESC2, (ETH_DMARXNDESCWBF_L4FM | ETH_DMARXNDESCWBF_L3L4FM)); } } /* Get the segment count */ WRITE_REG(RxPacketInfo->SegmentCnt, dmarxdesclist->AppDescNbr); return HAL_OK; } /** * @brief This function gives back Rx Desc of the last received Packet * to the DMA, so ETH DMA will be able to use these descriptors * to receive next Packets. * It should be called after processing the received Packet. * @param heth: pointer to a ETH_HandleTypeDef structure that contains * the configuration information for ETHERNET module * @retval HAL status. */ HAL_StatusTypeDef ETHx_BuildRxDescriptors(ETH_HandleTypeDef *heth) { ETH_RxDescListTypeDef *dmarxdesclist = &g_RxDescList; uint32_t descindex = dmarxdesclist->FirstAppDesc; __IO ETHx_DMADescTypeDef *dmarxdesc = dmarxdesclist->RxDesc[descindex]; uint32_t totalappdescnbr = dmarxdesclist->AppDescNbr; uint32_t descscan; if(dmarxdesclist->AppDescNbr == 0U) { /* No Rx descriptors to build */ return HAL_ERROR; } if(dmarxdesclist->AppContextDesc != 0U) { /* A context descriptor is available */ totalappdescnbr += 1U; } for(descscan =0; descscan < totalappdescnbr; descscan++) { WRITE_REG(dmarxdesc->DESC0, dmarxdesc->BackupAddr0); WRITE_REG(dmarxdesc->DESC3, ETH_DMARXNDESCRF_BUF1V); if (READ_REG(dmarxdesc->BackupAddr1) != 0U) { WRITE_REG(dmarxdesc->DESC2, dmarxdesc->BackupAddr1); SET_BIT(dmarxdesc->DESC3, ETH_DMARXNDESCRF_BUF2V); } SET_BIT(dmarxdesc->DESC3, ETH_DMARXNDESCRF_OWN); if(dmarxdesclist->ItMode != 0U) { SET_BIT(dmarxdesc->DESC3, ETH_DMARXNDESCRF_IOC); } if(descscan < (totalappdescnbr - 1U)) { /* Increment rx descriptor index */ INCR_RX_DESC_INDEX(descindex, 1U); /* Get descriptor address */ dmarxdesc = dmarxdesclist->RxDesc[descindex]; } } /* Set the Tail pointer address to the last rx descriptor hold by the app */ WRITE_REG(heth->Instance->DMACRDTPR, (uint32_t)dmarxdesc); /* reset the Application desc number */ WRITE_REG(dmarxdesclist->AppDescNbr, 0); /* reset the application context descriptor */ WRITE_REG(g_RxDescList.AppContextDesc, 0); return HAL_OK; } /** * @brief Prepare Tx DMA descriptor before transmission. * called by HAL_ETH_Transmit_IT and HAL_ETH_Transmit_IT() API. * @param heth: pointer to a ETH_HandleTypeDef structure that contains * the configuration information for ETHERNET module * @param pTxConfig: Tx packet configuration * @param ItMode: Enable or disable Tx EOT interrupt * @retval Status * NOTE: assuming TX DMA is not running, else race! - pa01 * NOTE: the idea after conversion is that pTxConfig is immutable; all per-TX params passed separately - pa01 */ static uint32_t ETHx_Prepare_Tx_Descriptors(ETH_HandleTypeDef *heth, ETH_TxPacketConfig *pTxConfig, ETH_BufferTypeDef *txbuffer, uint32_t ItMode) { ETH_TxDescListTypeDef *dmatxdesclist = &g_TxDescList; uint32_t descidx = dmatxdesclist->CurTxDesc; uint32_t firstdescidx = dmatxdesclist->CurTxDesc; uint32_t descnbr = 0, idx; ETH_DMADescTypeDef *dmatxdesc = (ETH_DMADescTypeDef *)dmatxdesclist->TxDesc[descidx]; uint32_t bd_count = 0; uint32_t framelen = 0; // total frame len +pa01 /* Current Tx Descriptor Owned by DMA: cannot be used by the application */ if((READ_BIT(dmatxdesc->DESC3, ETH_DMATXNDESCWBF_OWN) == ETH_DMATXNDESCWBF_OWN) || (dmatxdesclist->PacketAddress[descidx] != NULL)) { return HAL_ETH_ERROR_BUSY; } /***************************************************************************/ /***************** Context descriptor configuration (Optional) **********/ /***************************************************************************/ /* If VLAN tag is enabled for this packet */ if(READ_BIT(pTxConfig->Attributes, ETH_TX_PACKETS_FEATURES_VLANTAG) != 0U) { /* Set vlan tag value */ MODIFY_REG(dmatxdesc->DESC3, ETH_DMATXCDESC_VT, pTxConfig->VlanTag); /* Set vlan tag valid bit */ SET_BIT(dmatxdesc->DESC3, ETH_DMATXCDESC_VLTV); /* Set the descriptor as the vlan input source */ SET_BIT(heth->Instance->MACVIR, ETH_MACVIR_VLTI); /* if inner VLAN is enabled */ if(READ_BIT(pTxConfig->Attributes, ETH_TX_PACKETS_FEATURES_INNERVLANTAG) != 0U) { /* Set inner vlan tag value */ MODIFY_REG(dmatxdesc->DESC2, ETH_DMATXCDESC_IVT, (pTxConfig->InnerVlanTag << 16)); /* Set inner vlan tag valid bit */ SET_BIT(dmatxdesc->DESC3, ETH_DMATXCDESC_IVLTV); /* Set Vlan Tag control */ MODIFY_REG(dmatxdesc->DESC3, ETH_DMATXCDESC_IVTIR, pTxConfig->InnerVlanCtrl); /* Set the descriptor as the inner vlan input source */ SET_BIT(heth->Instance->MACIVIR, ETH_MACIVIR_VLTI); /* Enable double VLAN processing */ SET_BIT(heth->Instance->MACVTR, ETH_MACVTR_EDVLP); } } /* if tcp segmentation is enabled for this packet */ if(READ_BIT(pTxConfig->Attributes, ETH_TX_PACKETS_FEATURES_TSO) != 0U) { /* Set MSS value */ MODIFY_REG(dmatxdesc->DESC2, ETH_DMATXCDESC_MSS, pTxConfig->MaxSegmentSize); /* Set MSS valid bit */ SET_BIT(dmatxdesc->DESC3, ETH_DMATXCDESC_TCMSSV); } if((READ_BIT(pTxConfig->Attributes, ETH_TX_PACKETS_FEATURES_VLANTAG) != 0U)|| (READ_BIT(pTxConfig->Attributes, ETH_TX_PACKETS_FEATURES_TSO) != 0U)) { /* Set as context descriptor */ SET_BIT(dmatxdesc->DESC3, ETH_DMATXCDESC_CTXT); /* Set own bit */ SET_BIT(dmatxdesc->DESC3, ETH_DMATXCDESC_OWN); /* Increment current tx descriptor index */ INCR_TX_DESC_INDEX(descidx, 1U); /* Get current descriptor address */ dmatxdesc = (ETH_DMADescTypeDef *)dmatxdesclist->TxDesc[descidx]; descnbr += 1U; /* Current Tx Descriptor Owned by DMA: cannot be used by the application */ if(READ_BIT(dmatxdesc->DESC3, ETH_DMATXNDESCWBF_OWN) == ETH_DMATXNDESCWBF_OWN) { dmatxdesc = (ETH_DMADescTypeDef *)dmatxdesclist->TxDesc[firstdescidx]; /* Clear own bit */ CLEAR_BIT(dmatxdesc->DESC3, ETH_DMATXCDESC_OWN); return HAL_ETH_ERROR_BUSY; } } /***************************************************************************/ /***************** Normal descriptors configuration *****************/ /***************************************************************************/ descnbr += 1U; /* Set header or buffer 1 address */ WRITE_REG(dmatxdesc->DESC0, (uint32_t)txbuffer->buffer); /* Set header or buffer 1 Length */ MODIFY_REG(dmatxdesc->DESC2, ETH_DMATXNDESCRF_B1L, txbuffer->len); framelen += txbuffer->len; if(txbuffer->next != NULL) { txbuffer = txbuffer->next; /* Set buffer 2 address */ WRITE_REG(dmatxdesc->DESC1, (uint32_t)txbuffer->buffer); /* Set buffer 2 Length */ MODIFY_REG(dmatxdesc->DESC2, ETH_DMATXNDESCRF_B2L, (txbuffer->len << 16)); framelen += txbuffer->len; if (txbuffer->next != NULL) { // More than 2 buffers not supported yet see below! -pa01 __BKPT(0x40); return HAL_ETH_ERROR_PARAM; } } else { WRITE_REG(dmatxdesc->DESC1, 0x0); /* Set buffer 2 Length */ MODIFY_REG(dmatxdesc->DESC2, ETH_DMATXNDESCRF_B2L, 0x0U); } if(READ_BIT(pTxConfig->Attributes, ETH_TX_PACKETS_FEATURES_TSO) != 0U) { /* Set TCP Header length */ MODIFY_REG(dmatxdesc->DESC3, ETH_DMATXNDESCRF_THL, (pTxConfig->TCPHeaderLen << 19)); /* Set TCP payload length */ MODIFY_REG(dmatxdesc->DESC3, ETH_DMATXNDESCRF_TPL, pTxConfig->PayloadLen); //pa01 ??PayloadLen /* Set TCP Segmentation Enabled bit */ SET_BIT(dmatxdesc->DESC3, ETH_DMATXNDESCRF_TSE); } else { MODIFY_REG(dmatxdesc->DESC3, ETH_DMATXNDESCRF_FL, framelen /*pTxConfig->Length*/); if(READ_BIT(pTxConfig->Attributes, ETH_TX_PACKETS_FEATURES_CSUM) != 0U) { MODIFY_REG(dmatxdesc->DESC3, ETH_DMATXNDESCRF_CIC, pTxConfig->ChecksumCtrl); } if(READ_BIT(pTxConfig->Attributes, ETH_TX_PACKETS_FEATURES_CRCPAD) != 0U) { MODIFY_REG(dmatxdesc->DESC3, ETH_DMATXNDESCRF_CPC, pTxConfig->CRCPadCtrl); } } if(READ_BIT(pTxConfig->Attributes, ETH_TX_PACKETS_FEATURES_VLANTAG) != 0U) { /* Set Vlan Tag control */ MODIFY_REG(dmatxdesc->DESC2, ETH_DMATXNDESCRF_VTIR, pTxConfig->VlanCtrl); } /* Mark it as First Descriptor */ SET_BIT(dmatxdesc->DESC3, ETH_DMATXNDESCRF_FD); /* Mark it as NORMAL descriptor */ CLEAR_BIT(dmatxdesc->DESC3, ETH_DMATXNDESCRF_CTXT); /* set OWN bit of FIRST descriptor */ SET_BIT(dmatxdesc->DESC3, ETH_DMATXNDESCRF_OWN); /* If source address insertion/replacement is enabled for this packet */ //$$$$ BUGBUG revise! OWN bit is already set here! pa01 if(READ_BIT(pTxConfig->Attributes, ETH_TX_PACKETS_FEATURES_SAIC) != 0U) { MODIFY_REG(dmatxdesc->DESC3, ETH_DMATXNDESCRF_SAIC, pTxConfig->SrcAddrCtrl); } /* only if the packet is split into more than one descriptors > 1 */ //$$$$ BUGBUG revise! OWN bit is already set here! pa01 while (txbuffer->next != NULL) { /* Clear the LD bit of previous descriptor */ CLEAR_BIT(dmatxdesc->DESC3, ETH_DMATXNDESCRF_LD); /* Increment current tx descriptor index */ INCR_TX_DESC_INDEX(descidx, 1U); /* Get current descriptor address */ dmatxdesc = (ETH_DMADescTypeDef *)dmatxdesclist->TxDesc[descidx]; /* Clear the FD bit of new Descriptor */ CLEAR_BIT(dmatxdesc->DESC3, ETH_DMATXNDESCRF_FD); /* Current Tx Descriptor Owned by DMA: cannot be used by the application */ if((READ_BIT(dmatxdesc->DESC3, ETH_DMATXNDESCRF_OWN) == ETH_DMATXNDESCRF_OWN) || (dmatxdesclist->PacketAddress[descidx] != NULL)) { descidx = firstdescidx; dmatxdesc = (ETH_DMADescTypeDef *)dmatxdesclist->TxDesc[descidx]; /* clear previous desc own bit */ for(idx = 0; idx < descnbr; idx ++) { CLEAR_BIT(dmatxdesc->DESC3, ETH_DMATXNDESCRF_OWN); /* Increment current tx descriptor index */ INCR_TX_DESC_INDEX(descidx, 1U); /* Get current descriptor address */ dmatxdesc = (ETH_DMADescTypeDef *)dmatxdesclist->TxDesc[descidx]; } return HAL_ETH_ERROR_BUSY; } descnbr += 1U; /* Get the next Tx buffer in the list */ txbuffer = txbuffer->next; /* Set header or buffer 1 address */ WRITE_REG(dmatxdesc->DESC0, (uint32_t)txbuffer->buffer); /* Set header or buffer 1 Length */ MODIFY_REG(dmatxdesc->DESC2, ETH_DMATXNDESCRF_B1L, txbuffer->len); framelen += txbuffer->len; if (txbuffer->next != NULL) { /* Get the next Tx buffer in the list */ txbuffer = txbuffer->next; /* Set buffer 2 address */ WRITE_REG(dmatxdesc->DESC1, (uint32_t)txbuffer->buffer); /* Set buffer 2 Length */ MODIFY_REG(dmatxdesc->DESC2, ETH_DMATXNDESCRF_B2L, (txbuffer->len << 16)); framelen += txbuffer->len; } else { WRITE_REG(dmatxdesc->DESC1, 0x0); /* Set buffer 2 Length */ MODIFY_REG(dmatxdesc->DESC2, ETH_DMATXNDESCRF_B2L, 0x0U); } if(READ_BIT(pTxConfig->Attributes, ETH_TX_PACKETS_FEATURES_TSO) != 0U) { /* Set TCP payload length */ MODIFY_REG(dmatxdesc->DESC3, ETH_DMATXNDESCRF_TPL, pTxConfig->PayloadLen); //pa01 ??PayloadLen /* Set TCP Segmentation Enabled bit */ SET_BIT(dmatxdesc->DESC3, ETH_DMATXNDESCRF_TSE); } else { /* Set the packet length */ MODIFY_REG(dmatxdesc->DESC3, ETH_DMATXNDESCRF_FL, framelen /*pTxConfig->Length*/); if(READ_BIT(pTxConfig->Attributes, ETH_TX_PACKETS_FEATURES_CSUM) != 0U) { /* Checksum Insertion Control */ MODIFY_REG(dmatxdesc->DESC3, ETH_DMATXNDESCRF_CIC, pTxConfig->ChecksumCtrl); } } bd_count += 1U; /* Set Own bit */ SET_BIT(dmatxdesc->DESC3, ETH_DMATXNDESCRF_OWN); /* Mark it as NORMAL descriptor */ CLEAR_BIT(dmatxdesc->DESC3, ETH_DMATXNDESCRF_CTXT); } if(ItMode != ((uint32_t)RESET)) { /* Set Interrupt on completion bit */ SET_BIT(dmatxdesc->DESC2, ETH_DMATXNDESCRF_IOC); } else { /* Clear Interrupt on completion bit */ CLEAR_BIT(dmatxdesc->DESC2, ETH_DMATXNDESCRF_IOC); } /* Mark it as LAST descriptor */ SET_BIT(dmatxdesc->DESC3, ETH_DMATXNDESCRF_LD); /* Save the current packet address to expose it to the application */ dmatxdesclist->PacketAddress[descidx] = dmatxdesclist->CurrentPacketAddress; dmatxdesclist->CurTxDesc = descidx; /* disable the interrupt */ __disable_irq(); dmatxdesclist->BuffersInUse += bd_count + 1U; /* Enable interrupts back */ __enable_irq(); /* Return function status */ return HAL_ETH_ERROR_NONE; } static void RxDescListInit_(ETH_DMADescTypeDef *a_dmarxdesc, unsigned cnt) { // Factored out from ETH_DMARxDescListInit - pa01 for (unsigned i = 0; i < cnt; i++) { ETHx_DMADescTypeDef *dmarxdesc = (ETHx_DMADescTypeDef*)&a_dmarxdesc[i]; memset(dmarxdesc, 0, sizeof(ETHx_DMADescTypeDef)); g_RxDescList.RxDesc[i] = dmarxdesc; } g_RxDescList.CurRxDesc = 0; g_RxDescList.FirstAppDesc = 0; g_RxDescList.AppDescNbr = 0; g_RxDescList.ItMode = 0; g_RxDescList.AppContextDesc = 0; } static void TxDescListInit_(ETH_DMADescTypeDef *a_dmatxdesc, unsigned cnt) { // Factored out from ETH_DMATxDescListInit - pa01 for (unsigned i = 0; i < cnt; i++) { ETHx_DMADescTypeDef *dmatxdesc = (ETHx_DMADescTypeDef*)&a_dmatxdesc[i]; memset(dmatxdesc, 0, sizeof(ETHx_DMADescTypeDef)); g_TxDescList.TxDesc[i] = dmatxdesc; } g_TxDescList.CurTxDesc = 0; } // pa03 Initialize "middleware" layer and call HAL_ETH_Init // Caller should fill other heth->Init fields! TODO revise HAL_StatusTypeDef ETHx_init(ETH_HandleTypeDef *heth) { heth->Init.RxDescCnt = ETH_RX_DESC_CNT; heth->Init.TxDescCnt = ETH_TX_DESC_CNT; heth->Init.RxBuffLen = ETH_RX_BUFFER_SIZE; // Init g_RxDescList, g_TxDescList TxDescListInit_(heth->Init.TxDesc, heth->Init.TxDescCnt); RxDescListInit_(heth->Init.RxDesc, heth->Init.RxDescCnt); /* Configure ethernet peripheral (GPIOs, clocks, MAC, DMA) */ return HAL_ETH_Init(heth); } <file_sep>/** Based on stm32h7xx_hal_eth.h from STM32H7 HAL lib v.1.10 (Cube H7 package v 1.9.0) ****************************************************************************** * @file stm32h7xx_eth_MW.h * @author * @brief Header file of ETH "middleware" layer on top of the ETH HAL driver ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2017 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under BSD 3-Clause license, * the "License"; You may not use this file except in compliance with the * License. You may obtain a copy of the License at: * opensource.org/licenses/BSD-3-Clause * ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef STM32H7xx_YYY_ETH_H #define STM32H7xx_YYY_ETH_H #ifdef __cplusplus extern "C" { #endif /* Includes ------------------------------------------------------------------*/ #include "stm32h7xx_eth.h" #ifndef ETH_TX_DESC_CNT #define ETH_TX_DESC_CNT 4U #endif #ifndef ETH_RX_DESC_CNT #define ETH_RX_DESC_CNT 4U #endif #define ETH_RX_BUFFER_SIZE ((ETH_MAX_PACKET_SIZE + 31U) & ~31U)//(1536UL) // RX buffer size = ETH_MAX_PACKET_SIZE rounded up to cacheline (Standard size, no jumbo) /** * @brief Extended ETH DMA Descriptor structure definition * NOTE: size of extension is same for RX and TX descriptors */ #if (ETH_DESC_EXTRA_SIZE != 8) #error This software needs 2 extra words in descriptors #endif typedef struct { uint32_t DESC0; uint32_t DESC1; uint32_t DESC2; uint32_t DESC3; uint32_t BackupAddr0; /* used to store rx buffer 1 address */ uint32_t BackupAddr1; /* used to store rx buffer 2 address */ } ETHx_DMADescTypeDef; /** * @brief ETH Buffers List structure definition */ typedef struct __ETH_BufferTypeDef { uint8_t *buffer; /*<! buffer address */ uint32_t len; /*<! buffer length */ struct __ETH_BufferTypeDef *next; /*<! Pointer to the next buffer in the list */ }ETH_BufferTypeDef; /** * @brief DMA Transmit Descriptors Wrapper structure definition */ typedef struct { ETHx_DMADescTypeDef * TxDesc[ETH_TX_DESC_CNT]; /*<! Tx DMA descriptors addresses */ uint32_t CurTxDesc; /*<! Current Tx descriptor index for packet transmission */ uint32_t* PacketAddress[ETH_TX_DESC_CNT]; /*<! Ethernet packet addresses array */ uint32_t* CurrentPacketAddress; /*<! Current transmit NX_PACKET addresses */ uint32_t BuffersInUse; /*<! Buffers in Use */ }ETH_TxDescListTypeDef; /** * @brief DMA Receive Descriptors Wrapper structure definition */ typedef struct { ETHx_DMADescTypeDef * RxDesc[ETH_RX_DESC_CNT]; /*<! Rx DMA descriptors addresses. */ uint32_t CurRxDesc; /*<! Current Rx descriptor, ready for next reception. */ uint32_t FirstAppDesc; /*<! First descriptor of last received packet. */ uint32_t AppDescNbr; /*<! Number of descriptors of last received packet. */ uint32_t AppContextDesc; /*<! If 1 a context descriptor is present in last received packet. If 0 no context descriptor is present in last received packet. */ uint32_t ItMode; /*<! If 1, DMA will generate the Rx complete interrupt. If 0, DMA will not generate the Rx complete interrupt. */ }ETH_RxDescListTypeDef; /* Exported functions --------------------------------------------------------*/ HAL_StatusTypeDef ETHx_DescAssignMemory(ETH_HandleTypeDef *heth, uint32_t Index, uint8_t *pBuffer1, uint8_t *pBuffer2); uint8_t ETHx_IsRxDataAvailable(ETH_HandleTypeDef *heth); HAL_StatusTypeDef ETHx_GetRxDataBuffer(ETH_HandleTypeDef *heth, ETH_BufferTypeDef *RxBuffer); HAL_StatusTypeDef ETHx_GetRxDataLength(ETH_HandleTypeDef *heth, uint32_t *Length); HAL_StatusTypeDef ETHx_GetRxDataInfo(ETH_HandleTypeDef *heth, ETH_RxPacketInfo *RxPacketInfo); HAL_StatusTypeDef ETHx_BuildRxDescriptors(ETH_HandleTypeDef *heth); HAL_StatusTypeDef ETHx_Transmit(ETH_HandleTypeDef *heth, ETH_TxPacketConfig *pTxConfig, ETH_BufferTypeDef *txbuffer, uint32_t Timeout); HAL_StatusTypeDef ETHx_Transmit_IT(ETH_HandleTypeDef *heth, ETH_TxPacketConfig *pTxConfig, ETH_BufferTypeDef *txbuffer); // Initialize "middleware layer" ++ pa03 HAL_StatusTypeDef ETHx_init(ETH_HandleTypeDef *heth); #ifdef __cplusplus } #endif #endif /* STM32H7xx_???_ETH_H */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ <file_sep>STM32H7 Ethernet driver split POC Example how the H7 ETH driver separation to "core" and "middleware" may look Based on ST Cube library examples with LwIP WIP ************* * stm32h7xx_eth_conf.h is a new config file that replaces ethernet section in stm32h7xx_hal_conf.h * stm32h7xx_hal_eth.c renamed to stm32h7xx_eth.c , all descriptor related code moved out * stm32h7xx_hal_eth.h renamed to stm32h7xx_eth.h, all descriptor related code moved out * stm32h7xx_eth_MW.c - "middleware" layer extracted from ^^ * stm32h7xx_eth_MW.h - "middleware" layer extracted from ^^ This #includes stm32h7xx_hal_eth.h and stm32h7xx_eth_conf.h The "middleware" layers should be different and specific for each network stack such as LwIP, FreeRTOS+ etc. Size of DMA descriptors (extra fields in the descritors) is defined by the "middleware" layer. This is defined as ETH_DESC_EXTRA_SIZE in stm32h7xx_eth_conf.h (fixed at compile time for simplicity; cannot move this definition to stm32h7xx_eth_MW.h as it is needed in stm32h7xx_hal_eth.c. This extra size could be made variable and defined in runtime, may consider for later.) Number of the DMA descriptors is variable, specified in runtime. (this is to ease configuration for our project where all boards have same "middleware" layer, but variable amount of descriptors) stm32h7xx_eth_MW.c uses the 'legacy' definitions ETH_TX_DESC_CNT, ETH_RX_DESC_CNT and passes them to stm32h7xx_hal_eth.c stm32h7xx_hal_eth.c no longer depends on these definitions. TODO For LwIP based examples: rework ethernetif.c to use stm32h7xx_eth_MW.c|h Factor out remaining few register-level deps from stm32h7xx_eth_MW.c to stm32h7xx_hal_eth.c (TX start...) ===== When using this driver, either do NOT define HAL_ETH_MODULE_ENABLED in stm32h7xx_hal_conf.h (but HAL_ETH_MspInit is still requred, bring your own) or remove/exclude the original stm32h7xx_hal_eth.c from build, and do not include original stm32h7xx_hal_eth.h. Original from STM32H7 HAL drivers v 10.0.0, included in Cube package H7_V1.9.0 To distinguish variants and patches, use following defines in stm32h7xx_eth.h (and/or stm32h7xx_eth_MW.h , and/or stm32h7xx_eth_conf.h) Nothing of following defined -- ST HAL driver with minimal changes only (renamed, hal_conf dependency decoupled...) #define STM32H7_ETH_PATCH_x 1 etc <file_sep>/** ****************************************************************************** * @file ethernetif.c * @brief This file implements Ethernet network interface for lwIP * * Variant for polling with no RTOS. Not using interrupts. * PHY: LAN8742 as on STM32 Nucleo and other eval boards * pa02 TODO: adapt to actual PHY * ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "stm32h7xx_hal.h" #include "stm32h7xx_eth_MW.h" //+pa03 #include "lwip/opt.h" #include "lwip/timeouts.h" #include "lwip/netif.h" #include "netif/etharp.h" #include "ethernetif.h" #include <string.h> #include "debug.h" #include "BSP_MPU_defs.h" #include "../Components/lan8742/lan8742.h" /* PHY on EVB! */ extern uint8_t BSP_alloc_MPU_region(char who); /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /* Network interface name */ #define IFNAME0 's' #define IFNAME1 't' #ifndef ETH_RX_BUFFER_SIZE #define ETH_RX_BUFFER_SIZE (1536UL) #endif #define ETH_DMA_TRANSMIT_TIMEOUT (20U) #if 0 uint8_t macaddress[6]= {ETH_MAC_ADDR0, ETH_MAC_ADDR1, ETH_MAC_ADDR2, ETH_MAC_ADDR3, ETH_MAC_ADDR4, ETH_MAC_ADDR5}; #endif extern uint8_t g_MAC_addr[6]; /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ unsigned g_RX_drop_cnt; // count of RX dropped packets, dbg /* @Note: This interface is implemented to operate in zero-copy mode only: - Rx buffers are allocated statically and passed directly to the LwIP stack they will return back to DMA after been processed by the stack. - Tx Buffers will be allocated from LwIP stack memory heap, then passed to ETH HAL driver. @Notes: 1.a. ETH DMA Rx descriptors must be contiguous, the default count is 4, to customize it please redefine ETH_RX_DESC_CNT in stm32xxxx_hal_conf.h 1.b. ETH DMA Tx descriptors must be contiguous, the default count is 4, to customize it please redefine ETH_TX_DESC_CNT in stm32xxxx_hal_conf.h 2.a. Rx Buffers number must be between ETH_RX_DESC_CNT and 2*ETH_RX_DESC_CNT 2.b. Rx Buffers must have the same size: ETH_RX_BUFFER_SIZE, this value must passed to ETH DMA in the init field (EthHandle.Init.RxBuffLen) */ #if defined ( __GNUC__ ) /* GNU Compiler */ ETH_DMADescTypeDef DMARxDscrTab[ETH_RX_DESC_CNT] __attribute__((section(".RxDecripSection"))); /* Ethernet Rx DMA Descriptors */ ETH_DMADescTypeDef DMATxDscrTab[ETH_TX_DESC_CNT] __attribute__((section(".TxDecripSection"))); /* Ethernet Tx DMA Descriptors */ uint8_t Rx_Buff[ETH_RX_DESC_CNT][ETH_RX_BUFFER_SIZE] __attribute__((section(".RxArraySection"))); /* Ethernet Receive Buffers */ #else #error "Revise for other compilers" #endif ETH_HandleTypeDef EthHandle; ETH_TxPacketConfig TxConfig; lan8742_Object_t LAN8742; // PHY on EVB *** /* Private function prototypes -----------------------------------------------*/ static void MPU_Config_for_ETH(void); u32_t sys_now(void); void pbuf_free_custom(struct pbuf *p); // PHY interface: int32_t ETH_PHY_IO_Init(void); int32_t ETH_PHY_IO_DeInit (void); int32_t ETH_PHY_IO_ReadReg(uint32_t DevAddr, uint32_t RegAddr, uint32_t *pRegVal); int32_t ETH_PHY_IO_WriteReg(uint32_t DevAddr, uint32_t RegAddr, uint32_t RegVal); int32_t ETH_PHY_IO_GetTick(void); lan8742_IOCtx_t LAN8742_IOCtx = {ETH_PHY_IO_Init, ETH_PHY_IO_DeInit, ETH_PHY_IO_WriteReg, ETH_PHY_IO_ReadReg, ETH_PHY_IO_GetTick}; LWIP_MEMPOOL_DECLARE(RX_POOL, 10, sizeof(struct pbuf_custom), "Zero-copy RX PBUF pool"); /* Private functions ---------------------------------------------------------*/ /******************************************************************************* Driver Interface ( LwIP stack --> ETH) *******************************************************************************/ /** * @brief In this function, the hardware should be initialized. * Called from ethernetif_init(). * * @param netif the already initialized lwip network interface structure * for this ethernetif */ static err_enum_t low_level_init(struct netif *netif, const uint8_t *macaddress) { #if defined(STM32H7_ETH_TREGO_PATCH) # if STM32H7_ETH_TREGO_PATCH == 1 dbgprintf("ETH: Trego patch 1\n"); # else # error "unsupported" # endif #else dbgprintf("ETH: ST driver unmodified\n"); #endif static bool init_done = false; if (init_done) { dbgprintf("Repeated init not supported yet, restart!\n"); return ERR_ALREADY; //TODO restart lwip? take the netif down/up? } init_done = true; uint32_t idx = 0; STATIC_ASSERT(6==ETH_HWADDR_LEN, "sanity..."); STATIC_ASSERT(0 == (ETH_RX_BUFFER_SIZE % 32), "buffers size must be multiple of cache line"); // Configure memory areas used by ETH DMA... MPU_Config_for_ETH(); EthHandle.Instance = ETH; EthHandle.Init.MACAddr = (void*)macaddress; EthHandle.Init.MediaInterface = HAL_ETH_RMII_MODE; EthHandle.Init.RxDesc = DMARxDscrTab; EthHandle.Init.TxDesc = DMATxDscrTab; EthHandle.Init.RxBuffLen = ETH_RX_BUFFER_SIZE; //pa03 Initialize "middleware" layer: HAL_StatusTypeDef st = ETHx_init(&EthHandle); if (st != HAL_OK) { dbgprintf("ETHx: Failed init!\n"); return ERR_IF; } /* set MAC hardware address */ STATIC_ASSERT(sizeof(netif->hwaddr) >= ETH_HWADDR_LEN, "sanity"); netif->hwaddr_len = ETH_HWADDR_LEN; printf("ETHERNET: MAC Address "); for (idx = 0; idx < ETH_HWADDR_LEN; idx++) { netif->hwaddr[idx] = macaddress[idx]; printf("%02x, ", macaddress[idx]); } printf("\n"); /* maximum transfer unit */ netif->mtu = ETH_MAX_PAYLOAD; // use standard eth packet size, no jumbo STATIC_ASSERT((ETH_MAX_PAYLOAD + 2*ETH_HWADDR_LEN + 4) <= ETH_RX_BUFFER_SIZE, "sanity"); /* NETIF_FLAG_ETHARP tells LwIP to use ARP */ netif->flags |= NETIF_FLAG_BROADCAST | NETIF_FLAG_ETHARP; /* Initialize RX buffers, descriptors */ for (idx = 0; idx < ETH_RX_DESC_CNT; idx++) { ETHx_DescAssignMemory(&EthHandle, idx, Rx_Buff[idx], NULL); } /* Initialize LwIP RX POOL */ LWIP_MEMPOOL_INIT(RX_POOL); /* Set Tx parameters */ /* Enable L2 CRC & padding offload. */ memset(&TxConfig, 0, sizeof(ETH_TxPacketConfig)); TxConfig.Attributes = ETH_TX_PACKETS_FEATURES_CSUM | ETH_TX_PACKETS_FEATURES_CRCPAD; TxConfig.CRCPadCtrl = ETH_CRC_PAD_INSERT; // L3 cksm offload - must correspond to LwIP config TxConfig.ChecksumCtrl = ETH_CHECKSUM_IPHDR_PAYLOAD_INSERT_PHDR_CALC; /* Set PHY IO functions */ LAN8742_RegisterBusIO(&LAN8742, &LAN8742_IOCtx); /* Initialize the LAN8742 ETH PHY */ int32_t phy_st = LAN8742_Init(&LAN8742); if (phy_st < 0) { dbgprintf("ETH: Failed PHY init! err=%"PRId32"\n", phy_st); return ERR_IF; } ethernet_link_check_state(netif); return ERR_OK; } /** * @brief Configure the MPU * @param None * @retval None * @note Physical addresses for regions below must be as defined in the link script! */ static void MPU_Config_for_ETH(void) { MPU_Region_InitTypeDef MPU_InitStruct; /* Disable the MPU before config*/ HAL_MPU_Disable(); dbgprintf("ETH: #TX desc=%u, total size=%u\n", ETH_TX_DESC_CNT, ETH_TX_DESC_CNT*sizeof(ETH_DMADescTypeDef)); dbgprintf("ETH: #RX desc=%u, total size=%u\n", ETH_RX_DESC_CNT, ETH_RX_DESC_CNT*sizeof(ETH_DMADescTypeDef)); //! TODO STATIC_ASSERT(0 == (sizeof(ETH_DMADescTypeDef) % 32), "size of descriptor must be multiple of cacheline size"); STATIC_ASSERT(0 == (ETH_RX_BUFFER_SIZE % 32), "size of RX buf must be multiple of cacheline size"); // TX buffers are owned by LwIP; also must be multiple of cacheline size! //NOTE: 2 MPU regions modified per this KB article: // https://community.st.com/s/article/How-to-create-project-for-STM32H7-with-Ethernet-and-LwIP-stack-working // Region N = 32KB at 0x30040000 (~16KB for RX, ~16 KB 0x30044000 for TX, LwIP pool ) // Region N+1 overlapping over N : 256 bytes for DMA descriptors MPU_InitStruct.Number = BSP_alloc_MPU_region('E'); MPU_InitStruct.BaseAddress = 0x30040000; // ORIGIN(SRAM_D2ETH) in link script MPU_InitStruct.Size = MPU_REGION_SIZE_32KB; //MPU_InitStruct.TypeExtField = MPU_TEX_LEVEL1; //MPU_InitStruct.IsBufferable = MPU_ACCESS_NOT_BUFFERABLE; //MPU_InitStruct.IsCacheable = MPU_ACCESS_NOT_CACHEABLE; //MPU_InitStruct.IsShareable = MPU_ACCESS_NOT_SHAREABLE; MPU_set_Normal_Noncached(&MPU_InitStruct); MPU_InitStruct.SubRegionDisable = 0x00; MPU_InitStruct.AccessPermission = MPU_REGION_FULL_ACCESS; MPU_InitStruct.DisableExec = MPU_INSTRUCTION_ACCESS_DISABLE; MPU_InitStruct.Enable = MPU_REGION_ENABLE; HAL_MPU_ConfigRegion(&MPU_InitStruct); /* Configure the MPU attributes as Device not cacheable for ETH DMA descriptors */ MPU_InitStruct.Number = BSP_alloc_MPU_region('e'); //$$$ verify that reg. number == previous+1 MPU_InitStruct.BaseAddress = 0x30040000; // overlaps previous, so has priority MPU_InitStruct.Size = MPU_REGION_SIZE_256B; STATIC_ASSERT(256 >= (ETH_TX_DESC_CNT+ETH_RX_DESC_CNT)*sizeof(ETH_DMADescTypeDef), "increase MPU region size for ETH descriptors"); //MPU_InitStruct.IsBufferable = MPU_ACCESS_BUFFERABLE; //MPU_InitStruct.IsCacheable = MPU_ACCESS_NOT_CACHEABLE; //MPU_InitStruct.IsShareable = MPU_ACCESS_SHAREABLE; //MPU_InitStruct.TypeExtField = MPU_TEX_LEVEL0; MPU_set_SharedDevice(&MPU_InitStruct); MPU_InitStruct.SubRegionDisable = 0x00; MPU_InitStruct.AccessPermission = MPU_REGION_FULL_ACCESS; MPU_InitStruct.DisableExec = MPU_INSTRUCTION_ACCESS_DISABLE; MPU_InitStruct.Enable = MPU_REGION_ENABLE; HAL_MPU_ConfigRegion(&MPU_InitStruct); /* Enable the MPU */ HAL_MPU_Enable(MPU_PRIVILEGED_DEFAULT); } /** * Flush data cache in specified range * @param p - address, may be not cache aligned * @param len - length in bytes * For TX: flush cache. For RX: invalidate cache */ static inline void flush_cache_(bool is_TX, void *ptr, unsigned len) { if (!ptr || (len == 0)) __BKPT(0); #if 0 //pa05 -- cache NOT enabled. SCB_invalidate causes fault! // Align the pointer down and size up. // Cache line size for M7 is 32, not defined in ST CMSIS header yet! uint8_t a = (uintptr_t)ptr & (32-1); if (a) { ptr = (void*)((uintptr_t)ptr - a); len += a; // CMSIS v.5 does this but v4 not! } if (is_TX) { // ptr, len may be not cache line aligned: see impl. of SCB_CleanDCache_by_Addr SCB_CleanDCache_by_Addr(ptr, len); } else { // ptr, len may be not cache line aligned: see impl. of SCB_InvalidateDCache_by_Addr SCB_InvalidateDCache_by_Addr(ptr, len); } #endif } /** * @brief This function should do the actual transmission of the packet. The packet is * contained in the pbuf that is passed to the function. This pbuf * might be chained. * * @param netif the lwip network interface structure for this ethernetif * @param p the MAC packet to send (e.g. IP packet including MAC addresses and type) * @return ERR_OK if the packet could be sent * an err_t value if the packet couldn't be sent * * @note Returning ERR_MEM here if a DMA queue of your MAC is full can lead to * strange results. You might consider waiting for space in the DMA queue * to become available since the stack doesn't retry to send a packet * dropped because of memory failure (except for the TCP timers). */ static err_t low_level_output(struct netif *netif, struct pbuf *p) { uint32_t i=0, framelen = 0; struct pbuf *q; err_t errval = ERR_OK; ETH_BufferTypeDef Txbuffer[ETH_TX_DESC_CNT]; memset(Txbuffer, 0 , ETH_TX_DESC_CNT*sizeof(ETH_BufferTypeDef)); for(q = p; q != NULL; q = q->next) { if (i >= ETH_TX_DESC_CNT) { return ERR_IF; } Txbuffer[i].buffer = q->payload; Txbuffer[i].len = q->len; framelen += q->len; if(i>0) { Txbuffer[i-1].next = &Txbuffer[i]; } if(q->next == NULL) { Txbuffer[i].next = NULL; } i++; } //- TxConfig.Length = framelen; //pa01 ETHx_Transmit calculates framelen itself! HAL_StatusTypeDef st = ETHx_Transmit(&EthHandle, &TxConfig, Txbuffer, ETH_DMA_TRANSMIT_TIMEOUT); if (st != HAL_OK) { dbgprintf("ETH: TX error!\n"); } return errval; } /** * @brief Should allocate a pbuf and transfer the bytes of the incoming * packet from the interface into the pbuf. * * @param netif the lwip network interface structure for this ethernetif * @return a pbuf filled with the received packet (including MAC header) * NULL on memory error */ static struct pbuf * low_level_input(struct netif *netif) { #if defined(STM32H7_ETH_TREGO_PATCH) # if STM32H7_ETH_TREGO_PATCH == 1 struct pbuf *p = NULL; ETH_BufferTypeDef RxBuff; uint32_t framelength = 0; struct pbuf_custom* custom_pbuf; HAL_StatusTypeDef st = HAL_ETH_GetRxDataBuffer(&EthHandle, &RxBuff); if (st != HAL_OK) { return NULL; } framelength = RxBuff.len; if (framelength == 0) { dbgprintf("ETH: RX len=0 ??\n"); return NULL; } /* Invalidate data cache for ETH Rx Buffers. Assume buffers are DCACHE_LINE_SIZE aligned */ flush_cache_(false, RxBuff.buffer, framelength); custom_pbuf = (struct pbuf_custom*)LWIP_MEMPOOL_ALLOC(RX_POOL); if (!custom_pbuf) { //__BKPT(1); ++g_RX_drop_cnt; dbgprintf("ETH RX drop %u, len %u\n", g_RX_drop_cnt, (unsigned)framelength); return NULL; } custom_pbuf->custom_free_function = pbuf_free_custom; p = pbuf_alloced_custom(PBUF_RAW, framelength, PBUF_REF, custom_pbuf, RxBuff.buffer, ETH_RX_BUFFER_SIZE); return p; # else # error # endif #else /* no patch */ struct pbuf *p = NULL; ETH_BufferTypeDef RxBuff; uint32_t framelength = 0; struct pbuf_custom* custom_pbuf; if (ETHx_IsRxDataAvailable(&EthHandle)) { ETHx_GetRxDataBuffer(&EthHandle, &RxBuff); ETHx_GetRxDataLength(&EthHandle, &framelength); /* Build Rx descriptor to be ready for next data reception */ ETHx_BuildRxDescriptors(&EthHandle); /* Invalidate data cache for ETH Rx Buffers */ flush_cache_(false, RxBuff.buffer, framelength); custom_pbuf = (struct pbuf_custom*)LWIP_MEMPOOL_ALLOC(RX_POOL); if (!custom_pbuf) { //Packet dropped because no memory //__BKPT(1); ++g_RX_drop_cnt; dbgprintf("ETH RX drop %u, len %u\n", g_RX_drop_cnt, (unsigned)framelength); return NULL; } custom_pbuf->custom_free_function = pbuf_free_custom; p = pbuf_alloced_custom(PBUF_RAW, framelength, PBUF_REF, custom_pbuf, RxBuff.buffer, ETH_RX_BUFFER_SIZE); return p; } return NULL; #endif } /** * @brief This function is the ethernetif_input task, it is processed when a packet * is ready to be read from the interface. It uses the function low_level_input() * that should handle the actual reception of bytes from the network * interface. Then the type of the received packet is determined and * the appropriate input function is called. * * @param netif the lwip network interface structure for this ethernetif */ void ethernetif_input(struct netif *netif) { err_t err; struct pbuf *p; /* Try to get received packet into a new pbuf */ p = low_level_input(netif); /* If no input packet is available return */ if (p == NULL) return; /* Pass it to the LwIP stack */ err = netif->input(p, netif); if (err != ERR_OK) { dbgprintf("ETH: IP input error %d\n", err); pbuf_free(p); p = NULL; } } /** * @brief Should be called at the beginning of the program to set up the * network interface. It calls the function low_level_init() to do the * actual setup of the hardware. * * This function should be passed as a parameter to netif_add(). * * @param netif the lwip network interface structure for this ethernetif * @return ERR_OK if the loopif is initialized * ERR_MEM if private data couldn't be allocated * any other err_t on error */ err_t ethernetif_init(struct netif *netif) { ASSERT(netif != NULL); #if LWIP_NETIF_HOSTNAME /* Initialize interface hostname */ netif->hostname = "lwip"; #endif /* LWIP_NETIF_HOSTNAME */ STATIC_ASSERT(sizeof(netif->name)/sizeof(netif->name[0]) == 2, "compat"); netif->name[0] = IFNAME0; netif->name[1] = IFNAME1; /* We directly use etharp_output() here to save a function call. * You can instead declare your own function and call etharp_output() * from it if you have to do some checks before sending */ netif->output = etharp_output; netif->linkoutput = low_level_output; /* initialize the hardware */ return low_level_init(netif, g_MAC_addr); } void ethernetif_shutdown(struct netif *netif) { HAL_ETH_Stop(&EthHandle); LAN8742_DeInit(&LAN8742); } /** * @brief Custom Rx pbuf free callback * @param pbuf: pbuf to be freed * @retval None */ void pbuf_free_custom(struct pbuf *p) { struct pbuf_custom* custom_pbuf = (struct pbuf_custom*)p; /* Invalidate data cache: lwIP and/or application may have written into buffer */ //SCB_InvalidateDCache_by_Addr((uint32_t *)p->payload, p->tot_len); flush_cache_(false, p->payload, p->tot_len); LWIP_MEMPOOL_FREE(RX_POOL, custom_pbuf); } /** * @brief Returns the current system time in milliseconds * when LWIP_TIMERS == 1 and NO_SYS == 1 * @param None * @retval Current Time value */ u32_t sys_now(void) { // Assume the HAL tick is 1 ms return HAL_GetTick(); } /******************************************************************************* Ethernet MSP Routines *******************************************************************************/ /** * @brief Initializes the ETH MSP. * @param heth: ETH handle * @retval None */ void HAL_ETH_MspInit(ETH_HandleTypeDef *heth) { /* Ethernet MSP init: RMII Mode */ GPIO_InitTypeDef GPIO_InitStructure; GPIO_InitStructure.Speed = GPIO_SPEED_FREQ_HIGH; GPIO_InitStructure.Mode = GPIO_MODE_AF_PP; GPIO_InitStructure.Pull = GPIO_NOPULL; GPIO_InitStructure.Alternate = GPIO_AF11_ETH; /* Enable GPIOs clocks */ __HAL_RCC_GPIOA_CLK_ENABLE(); __HAL_RCC_GPIOB_CLK_ENABLE(); __HAL_RCC_GPIOC_CLK_ENABLE(); __HAL_RCC_GPIOG_CLK_ENABLE(); #if defined(EVB_ST_EVAL2) && (EVB_ST_EVAL2) /* Ethernet RMII pins configuration for EVAL2 Rev. E; checked per UM2198 ******************* RMII_REF_CLK ----------------------> PA1 RMII_MDIO -------------------------> PA2 RMII_CRS_DV -----------------------> PA7 RMII_MDC --------------------------> PC1 RMII_RXD0 -------------------------> PC4 RMII_RXD1 -------------------------> PC5 RMII_TX_EN ------------------------> PG11 RMII_TXD1 -------------------------> PG12 RMII_TXD0 -------------------------> PG13 ETH_PPS_OUT - not connected; can be PB5|PG8 PA8 (MCO1 @ 25 Mhz) can be used as RMII_REF_CLK; selected by jumper (default: NO) */ /* Configure PA1, PA2 and PA7 */ GPIO_InitStructure.Pin = GPIO_PIN_1 | GPIO_PIN_2 | GPIO_PIN_7; HAL_GPIO_Init(GPIOA, &GPIO_InitStructure); /* Configure PG11, PG12 and PG13 */ GPIO_InitStructure.Pin = GPIO_PIN_11 | GPIO_PIN_12 | GPIO_PIN_13; HAL_GPIO_Init(GPIOG, &GPIO_InitStructure); /* Configure PC1, PC4 and PC5 */ GPIO_InitStructure.Pin = GPIO_PIN_1 | GPIO_PIN_4 | GPIO_PIN_5; HAL_GPIO_Init(GPIOC, &GPIO_InitStructure); #elif defined(EVB_NUCLEO743) && (EVB_NUCLEO743) /* Ethernet RMII pins configuration for NUCLEO-H7; checked per UM2407 ******************* RMII_REF_CLK ----------------------> PA1 RMII_MDIO -------------------------> PA2 RMII_CRS_DV -----------------------> PA7 RMII_TXD1 -------------------------> PB13 RMII_MDC --------------------------> PC1 RMII_RXD0 -------------------------> PC4 RMII_RXD1 -------------------------> PC5 RMII_TX_EN ------------------------> PG11 RMII_TXD0 -------------------------> PG13 ETH_PPS_OUT - not connected; can be PB5|PG8 */ /* Configure PA1, PA2 and PA7 */ GPIO_InitStructure.Pin = GPIO_PIN_1 | GPIO_PIN_2 | GPIO_PIN_7; HAL_GPIO_Init(GPIOA, &GPIO_InitStructure); /* Configure PB13 */ GPIO_InitStructure.Pin = GPIO_PIN_13; HAL_GPIO_Init(GPIOB, &GPIO_InitStructure); /* Configure PC1, PC4 and PC5 */ GPIO_InitStructure.Pin = GPIO_PIN_1 | GPIO_PIN_4 | GPIO_PIN_5; HAL_GPIO_Init(GPIOC, &GPIO_InitStructure); /* Configure PG11, PG13 ??? was also PG2, why ?? */ GPIO_InitStructure.Pin = GPIO_PIN_11 | GPIO_PIN_13; HAL_GPIO_Init(GPIOG, &GPIO_InitStructure); #else #error "ETH: undefined board" #endif /* Enable Ethernet clocks */ __HAL_RCC_ETH1MAC_CLK_ENABLE(); __HAL_RCC_ETH1TX_CLK_ENABLE(); __HAL_RCC_ETH1RX_CLK_ENABLE(); } /******************************************************************************* PHY IO Functions *******************************************************************************/ /** * @brief Initializes the MDIO interface GPIO and clocks. * @param None * @retval 0 if OK, -1 if ERROR */ int32_t ETH_PHY_IO_Init(void) { /* We assume that MDIO GPIO configuration is already done in the ETH_MspInit() else it should be done here */ /* Configure the MDIO Clock */ HAL_ETH_SetMDIOClockRange(&EthHandle); return 0; } /** * @brief De-Initializes the MDIO interface . * @param None * @retval 0 if OK, -1 if ERROR */ int32_t ETH_PHY_IO_DeInit (void) { return 0; } /** * @brief Read a PHY register through the MDIO interface. * @param DevAddr: PHY port address * @param RegAddr: PHY register address * @param pRegVal: pointer to hold the register value * @retval 0 if OK -1 if Error */ int32_t ETH_PHY_IO_ReadReg(uint32_t DevAddr, uint32_t RegAddr, uint32_t *pRegVal) { if(HAL_ETH_ReadPHYRegister(&EthHandle, DevAddr, RegAddr, pRegVal) != HAL_OK) { return -1; } return 0; } /** * @brief Write a value to a PHY register through the MDIO interface. * @param DevAddr: PHY port address * @param RegAddr: PHY register address * @param RegVal: Value to be written * @retval 0 if OK -1 if Error */ int32_t ETH_PHY_IO_WriteReg(uint32_t DevAddr, uint32_t RegAddr, uint32_t RegVal) { if(HAL_ETH_WritePHYRegister(&EthHandle, DevAddr, RegAddr, RegVal) != HAL_OK) { return -1; } return 0; } static inline int32_t PHY_GetLinkState(void) {return LAN8742_GetLinkState(&LAN8742); } // Map PHY link status to generic - pa02 // Negative values are errors #define ETH_PHY_STATUS_OK LAN8742_STATUS_OK _Static_assert(0 == ETH_PHY_STATUS_OK, "sanity"); #define ETH_PHY_STATUS_LINK_DOWN LAN8742_STATUS_LINK_DOWN #define ETH_PHY_STATUS_100MBITS_FULLDUPLEX LAN8742_STATUS_100MBITS_FULLDUPLEX #define ETH_PHY_STATUS_100MBITS_HALFDUPLEX LAN8742_STATUS_100MBITS_HALFDUPLEX #define ETH_PHY_STATUS_10MBITS_FULLDUPLEX LAN8742_STATUS_10MBITS_FULLDUPLEX #define ETH_PHY_STATUS_10MBITS_HALFDUPLEX LAN8742_STATUS_10MBITS_HALFDUPLEX #define ETH_PHY_STATUS_AUTONEGO_NOTDONE LAN8742_STATUS_AUTONEGO_NOTDONE /** * @brief Get the system time in milliseconds used for internal PHY driver process. * @retval Time value */ int32_t ETH_PHY_IO_GetTick(void) { // Assume the HAL tick is 1 ms return HAL_GetTick(); } /** * @brief Checks PHY link state, update netif logical state * @retval None */ void ethernet_link_check_state(struct netif *netif) { ETH_MACConfigTypeDef MACConf; uint32_t PHYLinkState; uint32_t linkchanged = 0, speed = 0, duplex =0; PHYLinkState = PHY_GetLinkState(); if (PHYLinkState < 0 && netif_is_link_up(netif)) { dbgprintf("ETH: PHY state error %"PRId32"\n", PHYLinkState); } if (netif_is_link_up(netif) && (PHYLinkState <= ETH_PHY_STATUS_LINK_DOWN)) { // Link goes DOWN dbgprintf("ETH: cable disconnect\n"); HAL_ETH_Stop(&EthHandle); netif_set_down(netif); netif_set_link_down(netif); } else if(!netif_is_link_up(netif) && (PHYLinkState > ETH_PHY_STATUS_LINK_DOWN)) { // Link goes UP dbgprintf("ETH: cable connected\n"); switch (PHYLinkState) { case ETH_PHY_STATUS_100MBITS_FULLDUPLEX: dbgprintf("ETH: link 100/FDX\n"); duplex = ETH_FULLDUPLEX_MODE; speed = ETH_SPEED_100M; linkchanged = 1; break; case ETH_PHY_STATUS_100MBITS_HALFDUPLEX: dbgprintf("ETH: link 100/HDX\n"); duplex = ETH_HALFDUPLEX_MODE; speed = ETH_SPEED_100M; linkchanged = 1; break; case ETH_PHY_STATUS_10MBITS_FULLDUPLEX: dbgprintf("ETH: link 10/FDX\n"); duplex = ETH_FULLDUPLEX_MODE; speed = ETH_SPEED_10M; linkchanged = 1; break; case ETH_PHY_STATUS_10MBITS_HALFDUPLEX: dbgprintf("ETH: link 10/HDX\n"); duplex = ETH_HALFDUPLEX_MODE; speed = ETH_SPEED_10M; linkchanged = 1; break; case ETH_PHY_STATUS_AUTONEGO_NOTDONE: dbgprintf("ETH: link not ready yet ...\n"); break; default: dbgprintf("ETH: link UNDEFINED??\n"); break; } if (linkchanged) { /* Update MAC Config and restart ETH */ HAL_ETH_GetMACConfig(&EthHandle, &MACConf); MACConf.DuplexMode = duplex; MACConf.Speed = speed; HAL_StatusTypeDef st = HAL_ETH_SetMACConfig(&EthHandle, &MACConf); if (st != HAL_OK) { dbgprintf("ETH: error SetMACConfig!\n"); } st = HAL_ETH_Start(&EthHandle); if (st != HAL_OK) { dbgprintf("ETH: error ETH_Start!\n"); } netif_set_up(netif); netif_set_link_up(netif); } } } /* ****************************************************************************** * @ file LwIP/LwIP_UDP_Echo_Server/Src/ethernetif.c * @ author MCD Application Team * @ brief This file implements Ethernet network interface drivers for lwIP * <h2><center>&copy; Copyright (c) 2017 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 ****************************************************************************** */ <file_sep>#pragma once /* Number of descriptors */ #ifdef ETH_TX_DESC_CNT #undef ETH_TX_DESC_CNT #endif #define ETH_TX_DESC_CNT 4U #ifdef ETH_RX_DESC_CNT #undef ETH_RX_DESC_CNT #endif #define ETH_RX_DESC_CNT 4U /* Size of extension of DMA descriptors; both RX and TX */ #define ETH_DESC_EXTRA_SIZE 8 /* 2 words */ /* MAC address */ #define ETH_MAC_ADDR0 0x02 #define ETH_MAC_ADDR1 0x00 #define ETH_MAC_ADDR2 0x00 #define ETH_MAC_ADDR3 0x00 #define ETH_MAC_ADDR4 0x00 #define ETH_MAC_ADDR5 0x00 /* Definitions for PHY - TODO ... */
a32816f716e62a4125f75705bcafdfa9838fc873
[ "C", "Text" ]
5
C
pavel-a/stm32h7_eth_rework
079e8cd8f9cb196b814336c964b3eb93cfc1ef04
00c8ae3cea459b3d2d01be17116052c717555b60
refs/heads/main
<repo_name>entrymissing/scripts<file_sep>/README.md # Scripts Script repository. <file_sep>/install_jekyll.sh #!/bin/bash sudo apt-get install -y ruby-full build-essential zlib1g-dev CONTAINS=$(grep "export GEM_HOME" ~/.bashrc | wc -l) if [ $CONTAINS -eq 0 ] then echo '# Install Ruby Gems to ~/gems' >> ~/.bashrc echo 'export GEM_HOME="$HOME/gems"' >> ~/.bashrc echo 'export PATH="$HOME/gems/bin:$PATH"' >> ~/.bashrc source ~/.bashrc fi gem install jekyll bundler
7c07ed9f76610d64a086187e2fb6113379ab7374
[ "Markdown", "Shell" ]
2
Markdown
entrymissing/scripts
9e14f284a608f93e5f644eaabd71f7b93dbcf15b
3204e1097d6e1c4c7e16ad6ff30213623ea39e3d
refs/heads/master
<file_sep><?php namespace Tokenly\ConsulHealthDaemon; use Exception; use GuzzleHttp\Client; use GuzzleHttp\Exception\ClientException; use Illuminate\Support\Facades\Log; /** * ConsulClient */ class ConsulClient { protected $consul_url = null; public function __construct($consul_url=null) { if ($consul_url === null) { $consul_url = \Illuminate\Support\Facades\Config::get('consul-health.consul_url'); } $this->consul_url = rtrim($consul_url, '/'); $this->guzzle_client = new Client(); } public function healthUp($container_name) { $this->setKeyValue("health/$container_name", 1); } public function healthDown($container_name) { $this->deleteKey("health/$container_name"); } public function checkPass($check_id) { try { $this->guzzle_client->get($this->consul_url.'/v1/agent/check/pass/'.urlencode($check_id)); return true; } catch (Exception $e) { if (class_exists(Log::class, true)) { Log::warning("failed to update check pass: ".$check_id); } return false; } } public function checkWarn($check_id, $note=null) { try { $this->guzzle_client->get($this->consul_url.'/v1/agent/check/warn/'.urlencode($check_id), ['query' => ['note' => $note]]); return true; } catch (Exception $e) { if (class_exists(Log::class, true)) { Log::warning("failed to update check warn: ".$check_id); } return false; } } public function checkFail($check_id, $note=null) { try { $this->guzzle_client->get($this->consul_url.'/v1/agent/check/fail/'.urlencode($check_id), ['query' => ['note' => $note]]); return true; } catch (Exception $e) { if (class_exists(Log::class, true)) { Log::warning("failed to update check failure: ".$check_id); } return false; } } public function setKeyValue($key, $value) { $this->guzzle_client->put($this->consul_url.'/v1/kv/'.urlencode($key), ['body' => (string)$value]); } public function deleteKey($key) { $this->guzzle_client->delete($this->consul_url.'/v1/kv/'.urlencode($key)); } public function getKeyValue($key) { try { $response = $this->guzzle_client->get($this->consul_url.'/v1/kv/'.urlencode($key)); } catch (ClientException $e) { $e_respone = $e->getResponse(); if ($e_respone->getStatusCode() == 404) { return null; } throw $e; } // decode this... $response_data = json_decode($response->getBody(), true); return base64_decode($response_data[0]['Value']); } } <file_sep><?php namespace Tokenly\ConsulHealthDaemon\HealthController; use Exception; use Illuminate\Http\Response; use Illuminate\Routing\Controller; use Illuminate\Support\Facades\Event; use Illuminate\Support\Facades\Log; /** * HealthController */ class HealthController extends Controller { public function __construct() { } public function healthcheck($checkType) { try { // fire a check event // for other handlers Event::fire('consul-health.http.check', $checkType); } catch (Exception $e) { Log::error('Health check failed: '.$e->getMessage()); return new Response('failed', 500); } return new Response('ok', 200); } } <file_sep><?php namespace Tokenly\ConsulHealthDaemon\ServiceProvider; use Exception; use Illuminate\Support\Facades\Config; use Illuminate\Support\ServiceProvider; /* * ConsulHealthDaemonServiceProvider */ class ConsulHealthDaemonServiceProvider extends ServiceProvider { public function boot() { } /** * Register the service provider. * * @return void */ public function register() { $this->bindConfig(); $this->app->bind('Tokenly\ConsulHealthDaemon\ConsulClient', function($app) { $client = new \Tokenly\ConsulHealthDaemon\ConsulClient(Config::get('consul-health.consul_url')); return $client; }); $this->app->bind('Tokenly\ConsulHealthDaemon\ServicesChecker', function($app) { $checker = new \Tokenly\ConsulHealthDaemon\ServicesChecker($app->make('Tokenly\ConsulHealthDaemon\ConsulClient')); $checker->setServicePrefix(Config::get('consul-health.service_id_prefix')); return $checker; }); // register artisan command $this->commands([ \Tokenly\ConsulHealthDaemon\Console\ConsulHealthMonitorCommand::class, ]); } protected function bindConfig() { $prefix = rtrim(env('CONSUL_HEALTH_SERVICE_ID_PREFIX', 'generic'), '_').'_'; $config = [ 'consul-health.consul_url' => env('CONSUL_URL', 'http://consul.service.consul:8500'), 'consul-health.health_service_id' => env('CONSUL_HEALTH_SERVICE_ID', $prefix.'monitor_health'), 'consul-health.loop_delay' => env('CONSUL_LOOP_DELAY', 15), 'consul-health.service_id_prefix' => $prefix, ]; // set the laravel config Config::set($config); } } <file_sep><?php namespace Tokenly\ConsulHealthDaemon\Console; use Exception; use Illuminate\Console\Command; use Illuminate\Support\Facades\Config; use Illuminate\Support\Facades\Event; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputOption; use Tokenly\ConsulHealthDaemon\ConsulClient; use Tokenly\LaravelEventLog\Facade\EventLog; class ConsulHealthMonitorCommand extends Command { /** * The console command name. * * @var string */ protected $name = 'consul:monitor'; /** * The console command description. * * @var string */ protected $description = 'Monitors Health'; /** * Get the console command options. * * @return array */ protected function getOptions() { return [ ['test', null, InputOption::VALUE_NONE, 'Test Mode'], ]; } /** * Execute the console command. * * @return mixed */ public function handle() { $this->info('begin'); $consul = app(ConsulClient::class); $my_service_id = Config::get('consul-health.health_service_id'); $sleep_delay = Config::get('consul-health.loop_delay'); while(true) { try { $consul->checkPass($my_service_id); } catch (Exception $e) { EventLog::logError('healthcheck.failed', $e); } try { // fire a check event // for other handlers Event::fire('consul-health.console.check'); } catch (Exception $e) { EventLog::logError('healthcheck.failed', $e); $consul->checkFail($my_service_id, $e->getMessage()); } sleep($sleep_delay); } $this->info('done'); } } <file_sep>A library to monitor services health and report to consul # Installation ### Add the Laravel package via composer ``` composer require tokenly/consul-health-daemon ``` ### Add the Service Provider Add the following to the `providers` array in your application config: ``` Tokenly\ConsulHealthDaemon\ServiceProvider\ConsulHealthDaemonServiceProvider::class ``` <file_sep><?php namespace Tokenly\ConsulHealthDaemon; use Carbon\Carbon; use Exception; use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Queue; use Tokenly\ConsulHealthDaemon\ConsulClient; /** * This is invoked when a new block is received */ class ServicesChecker { public function __construct(ConsulClient $consul_client) { $this->consul_client = $consul_client; } public function setServicePrefix($service_prefix) { $this->service_prefix = $service_prefix; } //////////////////////////////////////////////////////////////////////// // Checks public function checkMySQLConnection() { $service_id = $this->service_prefix."mysql"; try { $result = DB::selectOne('SELECT 1 AS n'); if ($result->n != 1) { throw new Exception("Unexpected Database Connection Result", 1); } $this->consul_client->checkPass($service_id); } catch (Exception $e) { $this->consul_client->checkFail($service_id, $e->getMessage()); Log::warning("Database Connection Failed: ".$e->getMessage()); } } public function checkQueueConnection($connection=null) { $service_id = $this->service_prefix."queue"; try { $pheanstalk = Queue::connection($connection)->getPheanstalk(); $stats = $pheanstalk->stats(); if ($stats['uptime'] < 1) { throw new Exception("Unexpected Queue Connection", 1); } $this->consul_client->checkPass($service_id); } catch (Exception $e) { $this->consul_client->checkFail($service_id, $e->getMessage()); Log::warning("Queue Connection Failed: ".$e->getMessage()); } } public function checkPusherConnection() { $service_id = $this->service_prefix."pusher"; try { $pusher_client = app('Tokenly\PusherClient\Client'); $pusher_client->send('/check', time()); $this->consul_client->checkPass($service_id); } catch (Exception $e) { $this->consul_client->checkFail($service_id, $e->getMessage()); Log::warning("Pusher Connection Failed: ".$e->getMessage()); } } public function checkXCPDConnection() { $service_id = $this->service_prefix."xcpd"; try { $xcpd_client = app('Tokenly\XCPDClient\Client'); $info = $xcpd_client->get_running_info(); if (!$info) { throw new Exception("Unexpected response from Counterparty Server", 1); } if (!$info['db_caught_up']) { throw new Exception("Counterparty Server is not caught up. On block ".$info['last_block']['block_index'], 1); } $this->consul_client->checkPass($service_id); } catch (Exception $e) { $this->consul_client->checkFail($service_id, $e->getMessage()); Log::warning("Counterparty Server Connection Failed: ".$e->getMessage()); } } public function checkBitcoindConnection() { $service_id = $this->service_prefix."bitcoind"; try { $bitcoind_client = app('Nbobtc\Bitcoind\Bitcoind'); $info = $bitcoind_client->getinfo(); $info = (array)$info; if (!$info) { throw new Exception("Unexpected response from Bitcoind Server", 1); } if (!isset($info['blocks']) OR !$info['blocks']) { throw new Exception("Unexpected response from Bitcoind Server (No Blocks)", 1); } if (!isset($info['errors']) AND strlen($info['errors'])) { throw new Exception($info['errors'], 1); } $this->consul_client->checkPass($service_id); } catch (Exception $e) { $this->consul_client->checkFail($service_id, $e->getMessage()); Log::warning("Bitcoind Server Connection Failed: ".$e->getMessage()); } } public function checkQueueSizes($queue_params, $connection=null) { foreach($queue_params as $queue_name => $max_size) { try { $service_id = $this->service_prefix."queue_".$queue_name; $queue_size = $this->getQueueSize($queue_name, $connection); try { if ($queue_size < $max_size) { $this->consul_client->checkPass($service_id); } else { $this->consul_client->checkFail($service_id, "Queue $queue_name was $queue_size"); } } catch (Exception $e) { Log::error($e->getMessage()); } } catch (Exception $e) { try { $this->consul_client->checkFail($service_id, $e->getMessage()); Log::error("checkQueueSizes ($queue_name) failed: ".$e->getMessage()); } catch (Exception $e) { Log::error($e->getMessage()); } } } return; } public function checkTotalQueueJobsVelocity($queue_velocity_params, $connection=null) { foreach($queue_velocity_params as $queue_name => $velocity_params) { // echo "checking queue $queue_name. Now is ".Carbon::now()."\n"; $service_id = $this->service_prefix."queue_velocity_".$queue_name; try { $minumum_velocity = $velocity_params[0]; $time_description = $velocity_params[1]; $now = Carbon::now(); $old_time = Carbon::parse('-'.$time_description); $seconds_to_check = $old_time->diffInSeconds($now); $total_size_now = $this->getTotalQueueJobs($queue_name, $connection); $total_size_past = $this->getTotalQueueJobsInThePast($queue_name, $old_time); // echo "$queue_name \$now={$now} \$old_time={$old_time} \$total_size_now=".json_encode($total_size_now, 192)." \$total_size_past=".json_encode($total_size_past, 192)."\n"; // cache $total_size_now $expires_at_time = $now->copy()->addSeconds($seconds_to_check)->addMinutes(10); $key = 'qTotalJobs_'.$queue_name.'_'.$now->format('Ymd_Hi'); // echo "PUT key={$key} value=".json_encode($total_size_now, 192)." Expires at ".$expires_at_time."\n"; Cache::add($key, $total_size_now, $expires_at_time); if ($total_size_past === null) { // not enough information - pass for now $this->consul_client->checkPass($service_id); return; } try { $actual_velocity = $total_size_now - $total_size_past; // echo "$queue_name \$actual_velocity=$actual_velocity\n"; if ($actual_velocity >= $minumum_velocity) { $this->consul_client->checkPass($service_id); } else { $this->consul_client->checkFail($service_id, "Queue $queue_name velocity was $actual_velocity in $time_description"); } } catch (Exception $e) { Log::error($e->getMessage()); } } catch (Exception $e) { try { $this->consul_client->checkFail($service_id, $e->getMessage()); Log::error($e->getMessage()); } catch (Exception $e) { Log::error($e->getMessage()); } } } return; } protected function getTotalQueueJobsInThePast($queue_name, $old_time) { $now = Carbon::now()->second(0); $working_time = $old_time->copy()->second(0); $max_minutes_to_check = 10; while($working_time->lte($now)) { $key = 'qTotalJobs_'.$queue_name.'_'.$working_time->format('Ymd_Hi'); $value = Cache::get($key); // echo "getTotalQueueJobsInThePast key={$key} value=".json_encode($value, 192)."\n"; if ($value !== null) { return $value; } $working_time->addMinutes(1); } return null; } public function getTotalQueueJobs($queue_name, $connection=null) { $pheanstalk = Queue::connection($connection)->getPheanstalk(); $stats = $pheanstalk->statsTube($queue_name); return $stats['total-jobs']; } public function getQueueSize($queue_name, $connection=null) { $pheanstalk = Queue::connection($connection)->getPheanstalk(); $stats = $pheanstalk->statsTube($queue_name); return $stats['current-jobs-urgent']; } }
f2b0ea0119107b76d9ac451214bdf6f1dfb85557
[ "Markdown", "PHP" ]
6
PHP
tokenly/consul-health-daemon
b487f17585c5b5ea36965365088c5faf6692372b
30fcc1ccdccc5562e181afa53360534dd8089217
refs/heads/master
<repo_name>mrahbar/my-bloody-jenkins<file_sep>/README.md # Cloud Jenkins - An opinionated Jenkins Docker Image ## Features * Configuration Coverage: * Security Realm (LDAP/AD/Simple Jenkins database) * Glabal Security Options * Authorization * Jenkins Clouds (Amazon ECS, Kubernetes, Docker) * Global Pipeline Libraries * Seed Jobs * Script approvals * Notifiers (Hipchat, Slack, Email, Email-Ext) * Credentials (aws, userpass, sshkeys, certs, kubernetes, gitlab, simple secrets) * Tools and installers (JDK, Ant, Maven, Gradle, SonarQube, Xvfb) * Misc. Plugins configuration such as Jira, SonarQube, Checkmarx * Misc. Configuration options such as Environment variables, Proxy * Support additional plugins installation during startup without the need to build your own image * Supports quiet startup period to enable docker restarts with a graceful time which Jenkins is in *Quiet Mode* * Automated Re-Configure based on configuration data change without restarts * Supports Dynamic Host IP configuration passed to clouds when Jenkins is running in a cluster ## Releases See [Changes](CHANGELOG.md) Docker Images are pushed to [Docker Hub](https://hub.docker.com/r/endianogino/cloud-jenkins/) Each release is a git tag v$LTS_VERSION-$INCREMENT where: * LTS_VERSION is the Jenkins LTS version * INCREMENT is a number representing that representing the release contents (i.e additional configuration options, bugs in configuration, plugins, etc...) For each git tag, there following tags will be created: * $LTS_VERSION-$INCREMENT - one to one releationship with git tag * $LTS_VERSION - latest release for that LTS version * lts - represents the latest release Each master commit, will be tagged as latest ```bash # get the latest release docker pull endianogino/cloud-jenkins:lts # get the latest 2.73.3 LTS docker pull endianogino/cloud-jenkins:2.73.3 # get a concrete 2.73.3 release docker pull endianogino/cloud-jenkins:2.73.3-6 # get the latest unstable image docker pull endianogino/cloud-jenkins ``` ## Some Usage Examples * [docker-plugin cloud](examples/docker/) cloud using Docker Plugin cloud with seed job. See [examples/docker](examples/docker/) * [kubernetes](examples/kubernetes/) cloud using Minikube with seed job. See [examples/kubernetes](examples/kubernetes/) ## Environment Variables The following Environment variables are supported * __JENKINS_ENV_ADMIN_USER__ - (***mandatory***) Represents the name of the admin user. If LDAP is your choice of authentication, then this should be a valid LDAP user id. If Using Jenkins Database, then you also need to pass the password of this user within the [configuration](#configuration-reference). * __JAVA_OPTS\_*__ - All JAVA_OPTS_ variables will be appended to the JAVA_OPTS during startup. Use them to control options (system properties) or memory/gc options. I am using few of them by default to tweak some known issues: * JAVA_OPTS_DISABLE_WIZARD - disables the Jenkins 2 startup wizard * JAVA_OPTS_CSP - Default content security policy for HTML Publisher/Gatling plugins - See [Configuring Content Security Policy](https://wiki.jenkins.io/display/JENKINS/Configuring+Content+Security+Policy) * JAVA_OPTS_LOAD_STATS_CLOCK - This one is sweet (: - Reducing the load stats clock enables ephemeral slaves to start immediately without waiting for suspended slaves to be reaped * __JENKINS_ENV_CONFIG_YAML__ - The [configuration](#configuration-reference) as yaml. When this variable is set, the contents of this variable can be fetched from Consul and also be watched so jenkins can update its configuration everytime this variable is being changed. Since the contents of this variable contains secrets, it is wise to store and pass it from Consul/S3 bucket. In any case, before Jenkins starts, this variable is being unset, so it won't appear in Jenkins 'System Information' page (As I said, blood...) * __JENKINS_ENV_CONFIG_YML_URL__ - A URL that will be used to fetch the configuration and updated jenkins everytime it changes. This is an alternative to __JENKINS_ENV_CONFIG_YAML__ setup. Supported URLs: * s3://\<s3path> - s3 path * file://\<filepath> - a file path (should be mapped as volume) * http[s]://\<path> - an http endpoint * __JENKINS_ENV_CONFIG_YML_URL_DISABLE_WATCH__ - If equals to 'true', then the configuration file will be fetched only at startup, but won't be watched. Default 'false' * __JENKINS_ENV_CONFIG_YML_URL_POLLING__ - polling interval in seconds to check if file changed in s3. Default (30) * __JENKINS_ENV_HOST_IP__ - When Jenkins is running behind an ELB or a reverse proxy, JNLP slaves must know about the real IP of Jenkins, so they can access the 50000 port. Usually they are using the Jenkins URL to try to get to it, so it is very important to let them know what is the original Jenkins IP Address. If the master has a static IP address, then this variable should be set with the static IP address of the host. * __JENKINS_ENV_HOST_IP_CMD__ - Same as ___JENKINS_ENV_HOST_IP___, but this time a shell command expression to fetch the IP Address. In AWS, it is useful to use the EC2 Magic IP: ```JENKINS_ENV_HOST_IP_CMD='curl http://169.254.169.254/latest/meta-data/local-ipv4'``` * __JENKINS_HTTP_PORT_FOR_SLAVES__ - (Default: 8080) Used together with JENKINS_ENV_HOST_IP to construct the real jenkinsUrl for jnlp slaves. * __JENKINS_ENV_JENKINS_URL__ - Define the Jenkins root URL in configuration. This can be useful when you cannot run the Jenkins master docker container with host network and you need it to be available to slaves * __JENKINS_ENV_ADMIN_ADDRESS__ - Define the Jenkins admin email address * __JENKINS_ENV_PLUGINS__ - Ability to define comma separated list of additional plugins to install before starting up. See [plugin-version-format](https://github.com/jenkinsci/docker#plugin-version-format). This is option is not recommended, but sometimes it is useful to run the container without creating an inherited image. * __JENKINS_ENV_QUIET_STARTUP_PERIOD__ - Time in seconds. If speficied, jenkins will start in quiet mode and disable all running jobs. Useful for major upgrade. ## Configuration Reference The configuration is divided into main configuration sections. Each section is responsible for a specific aspect of jenkins configuration. ### Environment Variables Section Responsible for adding global environment variables to jenkins config. Keys are environment variable names and values are their corresponding values. Note that variables names should be a valid environment variable name. ```yaml environment: ENV_KEY_NAME1: ENV_VALUE1 ENV_KEY_NAME2: ENV_VALUE1 ``` ### Security Section Responsible for: * Setting up security realm * jenkins_database - the adminPassword must be provided * ldap - LDAP Configuration must be provided * active_directory - Uses [active-directory plugin](https://wiki.jenkins.io/display/JENKINS/Active+Directory+plugin) * User/Group Permissions dict - Each key represent a user or a group and its value is a list of Jenkins [Permissions IDs](https://wiki.jenkins.io/display/JENKINS/Matrix-based+security) ```yaml # jenkins_database - adminPassword must be provided security: realm: jenkins_database adminPassword: <PASSWORD> ``` ```yaml # ldap - ldap configuration must be provided security: realm: ldap server: myldap.server.com:389 # mandatory rootDN: dc=mydomain,dc=com # mandatory managerDN: cn=search-user,ou=users,dc=mydomain,dc=com # mandatory managerPassword: <<PASSWORD>> # mandatory userSearchBase: ou=users userSearchFilter: uid={0} groupSearchBase: ou=groups groupSearchFilter: cn={0} ######################## # Only one is mandatory - depends on the group membership strategy # If a user record contains the groups, then we need to set the # groupMembershipAttribute. # If a group contains the users belong to it, then groupMembershipFilter # should be set. groupMembershipAttribute: group groupMembershipFilter: memberUid={1} ######################## disableMailAddressResolver: false # default = false connectTimeout: 5000 # default = 5000 readTimeout: 60000 # default = 60000 displayNameAttr: cn emailAttr: email ``` ```yaml # Permissions - each key represents a user/group and has list of Jenkins Permissions security: realm: ... permissions: authenticated: # Special group - hudson.model.Hudson.Read # Permission Id - see - hudson.model.Item.Read - hudson.model.Item.Discover - hudson.model.Item.Cancel junior-developers: - hudson.model.Item.Build ``` ```yaml # Misc security options security: securityOptions: preventCSRF: true # default true enableScriptSecurityForDSL: false # default false enableCLIOverRemoting: false # default false enableAgentMasterAccessControl: true # default true disableRememberMe: false # default false sshdEnabled: true # default false, if true, port 16022 is exposed jnlpProtocols: # by default only JNLP4 is enabled - JNLP - JNLP2 - JNLP3 - JNLP4 ``` ### Tools Section Responsible for: * Setting up tools locations and auto installers The following tools are currently supported: * JDK - (type: jdk) * Apache Ant (type: ant) * Apache Maven (type: maven) * Gradle (type: gradle) * Xvfb (type: xvfb) * SonarQube Runner (type: sonarQubeRunner) The following auto installers are currently supported: * Oracle JDK installers * Maven/Gradle/Ant/SonarQube version installers * Shell command installers (type: command) * Remote Zip/Tar files installers (type: zip) The tools section is a dict of tools. Each key represents a tool location/installer ID. Each tools should have either home property or a list of installers property. Note: For Oracle JDK Downloaders to work, the oracle download user/password should be provided as well. ```yaml tools: oracle_jdk_download: # The oracle download user/password should be provided username: xxx password: yyy installations: JDK8-u144: # The Tool ID type: jdk installers: - id: jdk-8u144-oth-JPR # The exact oracle version id JDK7-Latest: type: jdk home: /usr/java/jdk7/latest # The location of the jdk MAVEN-3.1.1: type: maven home: /usr/share/apache-maven-3.1.1 MAVEN-3.5.0: installers: - id: '3.5.0' # The exact maven version to be downloaded ANT-1.9.4: type: ant home: /usr/share/apache-ant-1.9.4 ANT-1.10.1: type: ant installers: - id: '1.10.1' # The exact ant version to be downloaded GRADLE-4.2.1: type: gradle ... # Same as the above - home/installers with id: <gradle version> SONAR-Default: type: sonarQubeRunner installers: - id: '3.0.3.778' ... # Same as the above - home/installers with id: <sonar runner version> # zip installer and shell command installers ANT-XYZ: type: ant installers: - type: zip label: centos7 # nodes labels that will use this installer url: http://mycompany.domain/ant/xyz/ant.tar.gz subdir: apache-ant-zyz # the sub directoy where the tool exists within the zip file - type: command label: centos6 # nodes labels that will use this installer command: /opt/install-ant-xyz toolHome: # the directoy on the node where the tool exists after running the command ``` ### Credentials Section Responsible for: * Setting up [credentials](https://wiki.jenkins.io/display/JENKINS/Credentials+Plugin) to be used later on by pipelines/tools * Each credential has an id, type, description and arbitary attributes according to its type * The following types are supported: * type: text - [simple secret](https://wiki.jenkins.io/display/JENKINS/Plain+Credentials+Plugin). Mandatory attributes: * text - the text to encrypt * type: aws - an [aws secret](https://wiki.jenkins.io/display/JENKINS/CloudBees+AWS+Credentials+Plugin). Mandatory attributes: * access_key - AWS access key * secret_access_key - AWS secret access key * type: userpass - a [user/password](https://github.com/jenkinsci/credentials-plugin/blob/master/src/main/java/com/cloudbees/plugins/credentials/impl/UsernamePasswordCredentialsImpl.java) pair. Mandatory attributes: * username * password * type: sshkey - an [ssh private key](https://wiki.jenkins.io/display/JENKINS/SSH+Credentials+Plugin) in PEM format. Mandatory attributes: * username * privatekey - PEM format text * base64 - PEM format text base64 encoded. Mandatory if privatekey is not provided * passphrase - not mandatory, but encouraged * type: cert - a [Certificate](https://wiki.jenkins.io/display/JENKINS/Credentials+Plugin). Mandatory attributes: * base64 - the PKCS12 certificate bytes base64 encoded * password - not mandatory, but encouraged * type: gitlab-api-token - a [Gitlab API token](https://wiki.jenkins.io/display/JENKINS/GitLab+Plugin) to be used with the gitlab plugin * text - the api token as text > `Note: Currently the configuration supports only the global credentials domain.` ```yaml # Each top level key represents the credential id credentials: slack: type: text description: The slace secret token text: slack-secret-token hipchat: type: text text: hipchat-token awscred: type: aws access_key: xxxx secret_access_key: yyyy gituserpass: type: userpass username: user password: <PASSWORD> my-gitlab-api-token: type: gitlab-api-token text: <api-token-of-gitlab> gitsshkey: type: sshkey description: git-ssh-key username: user passphrase: <PASSWORD> privatekey: | ## This is why I love yaml... So simple to handle text with newlines -----BEGIN RSA PRIVATE KEY----- Proc-Type: 4,ENCRYPTED DEK-Info: AES-128-CBC,B1615A0CA4F11333D058A5A9C4D0144E wxr6qxA/gcj+Bf1he0YRaqH2HbvHXIshrXTFq7oet5OeF1oaX4yyejotI9oPXvvM X9jzLpPwhdpriuFKJKr9jc+1rto/71QExTYEaAWwfYi1EVb1ERGmG4DMANqBKssO FTn01t4wew3d6DPcAIwFBT7gvlJfg0poCxae1fhsXGijMy2YryiU+BcV0BYsM6Lj VAfn9+djoxPKTv3wPFZPXVrzSkWG8IFUcLBIKE6hf3xxwV5FPHDSegAnwTBV9sVB BkVfAHDkzecEtK3iHqa9QUsW014TTLZ7Rbbzh6mskrGxgjgDXXjbdEYbJDtSES6E d2o1nXqJEsDdUrSWAoaViR052KyW8f8n//LEjI1a6aveOQWoWXgPwD9jnp5cPrGv mWGrZmhWLh0rx61qG+bBVEfbGmLmbi74jxq1/6vaAF4ChtfBks2mpOMMOKf+bKar w1laJKgwFRWO7iYql9dHzny2GXy4z6hjD5g3omEdFyWh3GSW8NNkX<KEY> kubernetes-cert: type: cert password: <PASSWORD> base64: > MIIM2QIBAzCCDJ8GCSqGSIb3DQEHAaCCDJAEggyMMIIMiDCCBz8GCSqGSIb3DQEHBq CCBzAwggcsAgEAMIIHJQYJKoZIhvcNAQcBMBwGCiqGSIb3DQEMAQYwDgQIPPHR3lAy ... ``` ### Notifiers Section Responsible for Configuration of the following notifiers: * Mail - [Default Mailer](https://wiki.jenkins.io/display/JENKINS/Mailer) and [Email-ext](https://wiki.jenkins.io/display/JENKINS/Email-ext+plugin) plugin * [Slack plugin](https://wiki.jenkins.io/display/JENKINS/Slack+Plugin) * [Hipchat plugin](https://wiki.jenkins.io/display/JENKINS/Hipchat+Plugin) ```yaml notifiers: mail: host: xxx.mydomain.com port: 25 authUser: test autPassword: <PASSWORD> replyToAddress: <EMAIL> defaultSuffix: '@mydomain.com' useSsl: true charset: UTF-8 hipchat: server: my.api.hipchat.com room: JenkinsNotificationRoom sendAs: TestSendAs v2Enabled: true credentialId: hipchat # should be defined in credentials section slack: teamDomain: teamDoamin botUser: true room: TestRoom baseUrl: http://localhost:8080/ sendAs: JenkinsSlack credentialId: slack # should be defined in credentials section ``` ### Pipeline Libraries Section Responsible for setting up [Global Pipeline Libraries](https://wiki.jenkins.io/display/JENKINS/Pipeline+Shared+Groovy+Libraries+Plugin) Configuration is composed of dicts where each top level key is the name of the library and its value contains the library configuration (source, default version) ```yaml pipeline_libraries: my-library: # the library name source: remote: git@github.com:odavid/jenkins-docker.git credentialsId: gitsshkey # should be defined in credentials section defaultVersion: master implicit: false # Default false - if true the library will be available within all pipeline jobs with declaring it with @Library allowVersionOverride: true # Default true, better to leave it as is includeInChangesets: true # see https://issues.jenkins-ci.org/browse/JENKINS-41497 my-other-lib: source: remote: ... ``` ### Script Approval Section Responsible for configuration list of white-listed methods to be used within your pipeline groovy scripts. See [Script Security](https://wiki.jenkins.io/display/JENKINS/Script+Security+Plugin) Contains list of method/field signatures that will be added to the [Script Approval Console](https://wiki.jenkins.io/display/JENKINS/Script+Security+Plugin) ```yaml script_approval: approvals: - field hudson.model.Queue$Item task - method groovy.lang.Binding getVariable java.lang.String - method groovy.lang.Binding getVariables - method groovy.lang.Binding hasVariable java.lang.String - method hudson.model.AbstractCIBase getQueue - staticMethod java.lang.Math max int int - staticMethod java.lang.Math max long long - staticMethod java.lang.Math min int int - staticMethod java.lang.Math min long long - staticMethod java.lang.Math pow double double - staticMethod java.lang.Math sqrt double ``` ### Clouds Section Responsible for configuration of the following docker cloud providers: * Docker - [type: docker](https://wiki.jenkins.io/display/JENKINS/Docker+Plugin) * Amazon ECS - [type: ecs](https://wiki.jenkins.io/display/JENKINS/Amazon+EC2+Container+Service+Plugin) * Kubernetes - [type: kubernetes](https://wiki.jenkins.io/display/JENKINS/Kubernetes+Plugin) You can define multiple clouds. Each cloud is configured as a dict. For top level key represents the cloud name. Each dict has a mandatory type attritube, and a section of templates representing slave docker templates that correspond to list of labels. #### Amazon ECS ```yaml clouds: # Top level key -> name of the cloud ecs-cloud: # type is mandatory type: ecs # If your jenkins master is running on EC2 and is using IAM Role, then you can # discard this credential, otherwise, you need to have an # aws credential declared in the credentials secion credentialsId: 'my-aws-key' # AWS region where your ECS Cluster reside region: eu-west-1 # ARN of the ECS Cluster cluster: 'arn:ssss' # Timeout (in second) for ECS task to be created, usefull if you use large docker # slave image, because the host will take more time to pull the docker image # If empty or <= 0, the 900 is the default. connectTimeout: 0 # List of templates templates: - name: ecsSlave # Only JNLP slaves are supported image: jenkinsci/jnlp-slave:latest # Labels are mandatory! # Your pipeline jobs will need to use node(label){} in order to use # this slave template labels: - ecs-slave # The directory within the container that is used as root filesystem remoteFs: /home/jenkins # JVM arguments to pass to the jnlp jar jvmArgs: -Xmx1g # ECS memory reservation memoryReservation: 2048 # ECS cpu reservation cpu: 1024 # Volume mappings # If your slave need to build docker images, then map the host docker socket # to the container docker socket. Also make sure the user within the container # has privileges to that socket within the entrypoint volumes: - '/var/run/docker.sock:/var/run/docker.sock' # Environment variables to pass to the slave container environment: XXX: xxx ``` #### Kubernetes ```yaml clouds: # Top level key -> name of the cloud kube-cloud: # type is mandatory type: kubernetes # Kubernetes URL serverUrl: http://mykubernetes # Default kubernetes namespace for slaves namespace: jenkins # Pod templates templates: - name: kubeslave # Only JNLP slaves are supported image: jenkinsci/jnlp-slave:latest # Labels are mandatory! # Your pipeline jobs will need to use node(label){} in order to use this slave template labels: - kubeslave # The directory within the container that is used as root filesystem remoteFs: /home/jenkins # JVM arguments to pass to the jnlp jar jvmArgs: -Xmx1g # Volume mappings # If your slave need to build docker images, then map the host docker socket # to the container docker socket. Also make sure the user within the container # has privileges to that socket within the entrypoint volumes: - '/var/run/docker.sock:/var/run/docker.sock' # Environment variables to pass to the slave container environment: XXX: xxx ``` #### Docker Cloud ```yaml clouds: # Top level key -> name of the cloud docker-cloud: # type is mandatory type: docker templates: - name: dockerslave ## How many containers can run at the same time instanceCap: 100 # Only JNLP slaves are supported image: jenkinsci/jnlp-slave:latest # Labels are mandatory! # Your pipeline jobs will need to use node(label){} in order to use this slave template labels: - dockerslave # The directory within the container that is used as root filesystem remoteFs: /home/jenkins # JVM arguments to pass to the jnlp jar jvmArgs: -Xmx1g # Volume mappings # If your slave need to build docker images, then map the host docker socket # to the container docker socket. Also make sure the user within the container # has privileges to that socket within the entrypoint volumes: - '/var/run/docker.sock:/var/run/docker.sock' # Environment variables to pass to the slave container environment: XXX: xxx ``` ### Seed Jobs Section Responsible for seed job creation and execution. Each seed job would be a pipeline script that can use [jobDsl pipeline step](https://github.com/jenkinsci/job-dsl-plugin/wiki/User-Power-Moves#use-job-dsl-in-pipeline-scripts) ```yaml seed_jobs: # Each top level key is the seed job name SeedJob: source: # git repo where of the seed job remote: <EMAIL>:endianogino/cloud-jenkins.git credentialsId: gitsshkey branch: 'master' triggers: # scm polling trigger pollScm: '* * * * *' # period trigger periodic: '* * * * *' # Location of the pipeline script within the repository pipeline: example/SeedJobPipeline.groovy # always - will be executed everytime the config loader will run # firstTimeOnly - will be executed only if the job was not exist # never - don't execute the job, let the triggers do their job executeWhen: always #firstTimeOnly always never # Define parameters with default values to the seed job parameters: a_boolean_param: # the name of the param type: boolean value: true a_string_param: type: string value: The String default value a_password_param: type: password value: <PASSWORD> a_choice_param: type: choice choices: - choice1 ## The first choice is the default one - choice2 - choice3 a_text_param: type: text value: | A text with new lines ``` ### Running Jenkins behind proxy When running Jenkins behind a proxy server, add the following to your config yaml file: ```yaml proxy: proxyHost: <proxy_address> port: <port> username: <proxy_auth> # leave empty if not required password: <proxy_auth> # leave empty if not required noProxyHost: <comma delimited> ```<file_sep>/tests/bats/tests.bats #!/usr/bin/env bats load tests_helpers @test "start container" { run_test_container_and_wait } @test "Sanity" { run_groovy_test } @test "CloudsConfig" { run_groovy_test } @test "CredsConfig" { run_groovy_test } @test "ToolsConfig" { run_groovy_test } @test "SecurityConfig" { run_groovy_test } @test "CheckmarxConfig" { run_groovy_test } @test "EnvironmentVarsConfig" { run_groovy_test } @test "GitlabConfig" { run_groovy_test } @test "JiraConfig" { run_groovy_test } @test "NotifiersConfig" { run_groovy_test } @test "PipelineLibrariesConfig" { run_groovy_test } @test "ScriptApprovalConfig" { run_groovy_test } @test "SeedJobsConfig" { run_groovy_test } @test "SonarQubeServersConfig" { run_groovy_test } @test "terminate container" { teardown_test_container } <file_sep>/tests/bats/tests_helpers.bash #!/bin/bash SCRIPT_DIR="$BATS_TEST_DIRNAME" TEST_CONTAINER_NAME="jenkins-test" TEST_IMAGE_NAME="odavid/my-bloody-jenkins" TEST_IMAGE_CONTEXT_DIR="$SCRIPT_DIR/.." function run_test_container_and_wait(){ docker rm -f -v "$TEST_CONTAINER_NAME" || true docker run --name $TEST_CONTAINER_NAME -d \ -e JAVA_OPTS_MEM='-Xmx1g' \ -e JENKINS_ENV_ADMIN_USER=admin \ -v $TEST_IMAGE_CONTEXT_DIR/groovy:/tests \ -v $TEST_IMAGE_CONTEXT_DIR/run-test.sh:/usr/bin/run-test.sh \ -e JENKINS_ENV_CONFIG_YAML=" security: realm: jenkins_database adminPassword: <PASSWORD> " \ $TEST_IMAGE_NAME JENKINS_IS_UP=1 echo "before waiting JENKINS_IS_UP: $JENKINS_IS_UP" while [ "$JENKINS_IS_UP" != "0" ]; do JENKINS_IS_UP=$(docker logs jenkins-test 2>&1 | grep "Jenkins is fully up and running" > /dev/null; echo $?) echo "Waiting for jenkins to be up... JENKINS_IS_UP=$JENKINS_IS_UP" sleep 2 done } function teardown_test_container(){ docker rm -f -v "$TEST_CONTAINER_NAME" || true } function run_groovy_test(){ local test_name=${1:-$BATS_TEST_DESCRIPTION} docker exec -t $TEST_CONTAINER_NAME run-test.sh /tests/${test_name}Test.groovy } <file_sep>/Makefile .PHONY: default default: test build: docker build --rm --force-rm -t odavid/my-bloody-jenkins . test: build bats tests/bats update-plugins: env python $(PWD)/get-latest-plugins.py release: $(eval NEW_INCREMENT := $(shell expr `git describe --tags --abbrev=0 | cut -d'-' -f2` + 1)) $(eval BASE_VERSION := $(shell grep FROM Dockerfile | cut -d':' -f 2 | cut -d '-' -f 1)) git tag v$(BASE_VERSION)-$(NEW_INCREMENT) git push origin v$(BASE_VERSION)-$(NEW_INCREMENT) <file_sep>/examples/docker/docker-compose.yml version: '2' services: jenkins-master: image: odavid/my-bloody-jenkins ports: - '8080:8080' - '50000:50000' volumes: - '${PWD}/config.yml:/config.yml' - '.data/jenkins_home:/var/jenkins_home' - '.data/jenkins-workspace-home:/jenkins-workspace-home' - '/var/run/docker.sock:/var/run/docker.sock' environment: JAVA_OPTS_MEM: '-Xmx1g' # JENKINS_ENV_JENKINS_URL: http://${MY_HOST_IP}:8080 JENKINS_ENV_ADMIN_USER: admin JENKINS_ENV_HOST_IP: ${MY_HOST_IP} JENKINS_ENV_CONFIG_YML_URL: file:///config.yml JENKINS_ENV_QUIET_STARTUP_PERIOD: 120 <file_sep>/Dockerfile FROM jenkins/jenkins:2.107-alpine MAINTAINER <NAME> <<EMAIL>> ARG JENKINS_TIMEZONE="Europe/Berlin" ENV JENKINS_WORKSPACE_HOME="/jenkins-workspace-home" ENV JENKINS_PERSISTANT_STATE="/jenkins-persistant-state" ARG GOSU_VERSION=1.10 # Using root to install and run entrypoint. # We will change the user to jenkins using gosu USER root # Ability to use usermod + install awscli in order to be able to watch s3 if needed # https://wiki.alpinelinux.org/wiki/Docker RUN echo "http://dl-cdn.alpinelinux.org/alpine/edge/community" > /etc/apk/repositories \ && echo "http://dl-cdn.alpinelinux.org/alpine/edge/main" >> /etc/apk/repositories \ && apk add --update --no-cache docker python python-dev procps ncurses shadow py-setuptools less outils-md5 \ && easy_install-2.7 pip \ && pip install awscli ## Use this to be able to watch s3 configuration file and update jenkins everytime it changes RUN curl -SsLo /usr/bin/watch-file.sh https://raw.githubusercontent.com/odavid/utility-scripts/master/scripts/watch-file.sh && \ chmod +x /usr/bin/watch-file.sh RUN curl -SsLo /usr/bin/gosu https://github.com/tianon/gosu/releases/download/${GOSU_VERSION}/gosu-amd64 && \ chmod +x /usr/bin/gosu COPY update-config.sh /usr/bin/ RUN chmod +x /usr/bin/update-config.sh # Separate between JENKINS_HOME and WORKSPACE dir. Best if we use NFS for JENKINS_HOME RUN mkdir -p ${JENKINS_WORKSPACE_HOME} && \ chown -R jenkins:jenkins ${JENKINS_WORKSPACE_HOME} RUN mkdir -p ${JENKINS_PERSISTANT_STATE} && \ chown -R jenkins:jenkins ${JENKINS_PERSISTANT_STATE} # Change the original entrypoint. We will later on run it using gosu RUN mv /usr/local/bin/jenkins.sh /usr/local/bin/jenkins-orig.sh COPY jenkins.sh /usr/local/bin/jenkins.sh RUN chmod +x /usr/local/bin/jenkins.sh # installing specific list of plugins. see: https://github.com/jenkinsci/docker/blob/master/README.md#preinstalling-plugins COPY plugins.txt /usr/share/jenkins/ref/ COPY install-plugins-with-retry.sh /usr/local/bin/install-plugins-with-retry.sh RUN chmod +x /usr/local/bin/install-plugins-with-retry.sh RUN /usr/local/bin/install-plugins-with-retry.sh < /usr/share/jenkins/ref/plugins.txt # Add all init groovy scripts to ref folder and change their ext to .override # so Jenkins will override them every time it starts COPY init-scripts/* /usr/share/jenkins/ref/init.groovy.d/ # Add configuration handlers groovy scripts COPY config-handlers /usr/share/jenkins/config-handlers ENV JOB_PIPELINE_LOCATION=/tmp/jobs COPY config/jobs ${JOB_PIPELINE_LOCATION} RUN cd /usr/share/jenkins/ref/init.groovy.d/ && \ for f in *.groovy; do mv "$f" "${f}.override"; done VOLUME /var/jenkins_home VOLUME ${JENKINS_WORKSPACE_HOME} VOLUME ${JENKINS_PERSISTANT_STATE} RUN mkdir -p /usr/share/jenkins/ref/secrets RUN echo "false" > /usr/share/jenkins/ref/secrets/slave-to-master-security-kill-switch # Revert to root USER root RUN mkdir -p /dev/shm ENV CONFIG_FILE_LOCATION=/dev/shm/jenkins-config.yml ENV TOKEN_FILE_LOCATION=/dev/shm/.api-token ENV CONFIG_CACHE_DIR=/dev/shm/.jenkins-config-cache ENV QUIET_STARTUP_FILE_LOCATION=/dev/shm/quiet-startup-mutex #################################################################################### # GENERAL Configuration variables #################################################################################### ENV JENKINS_OPTS --httpPort=8080 ENV JENKINS_ENV_EXECUTERS=4 # See https://jenkins.io/blog/2017/04/11/new-cli/ ENV JENKINS_ENV_CLI_REMOTING_ENABLED=false # See https://wiki.jenkins.io/display/JENKINS/CSRF+Protection ENV JENKINS_ENV_CSRF_PROTECTION_ENABLED=true # Agent JNLP Protocol ENV JENKINS_ENV_JNLP_KILL_SWITCH=true # If true, then workspaceDir will changed its defaults from ${JENKINS_HOME}/workspace # to /jenkins-workspace-home/workspace/${ITEM_FULLNAME} # This is useful in case your JENKINS_HOME is mapped to NFS mount, # slowing down the workspace ENV JENKINS_ENV_CHANGE_WORKSPACE_DIR=true # If true, every DSL script would have to be approved using the ScriptApproval console # See https://github.com/jenkinsci/job-dsl-plugin/wiki/Script-Security ENV JENKINS_ENV_USE_SCRIPT_SECURITY=false #################################################################################### # ADDITIONAL JAVA_OPTS #################################################################################### # Each JAVA_OPTS_* variable will be added to the JAVA_OPTS variable before startup # # Enable permissive script security ENV JAVA_OPTS_PERMISSIVE_SCRIPT_SECURITY="-Dpermissive-script-security.enabled=true" # Set Timezone ENV JAVA_OPTS_TIMEZONE="-Duser.timezone=${JENKINS_TIMEZONE}" # Don't run the setup wizard ENV JAVA_OPTS_DISABLE_WIZARD="-Djenkins.install.runSetupWizard=false" # See https://wiki.jenkins.io/display/JENKINS/Configuring+Content+Security+Policy ENV JAVA_OPTS_CSP="-Dhudson.model.DirectoryBrowserSupport.CSP=\"sandbox allow-same-origin allow-scripts; default-src 'self'; script-src * 'unsafe-eval'; img-src *; style-src * 'unsafe-inline'; font-src *\"" # See https://issues.jenkins-ci.org/browse/JENKINS-24752 ENV JAVA_OPTS_LOAD_STATS_CLOCK="-Dhudson.model.LoadStatistics.clock=1000" #################################################################################### #################################################################################### # JNLP Tunnel Variables #################################################################################### # Default port for http ENV JENKINS_HTTP_PORT_FOR_SLAVES=9090 # This is used by docker slaves to get the actual jenkins URL # in case jenkins is behind a load-balancer or a reverse proxy # # JENKINS_IP_FOR_SLAVES will be evaluated in the following order: # $JENKINS_ENV_HOST_IP || # $(eval $JENKINS_ENV_HOST_IP_CMD) || # '' #ENV JENKINS_ENV_HOST_IP=<REAL_IP> #ENV JENKINS_ENV_HOST_IP_CMD='<command to fetch ip>' # This variable will be evaluated and should retrun a valid IP address: # AWS: JENKINS_ENV_HOST_IP_CMD='curl http://169.254.169.254/latest/meta-data/local-ipv4' # General: JENKINS_ENV_HOST_IP_CMD='ip route | grep default | awk '"'"'{print $3}'"'"'' #################################################################################### # If sshd enabled, this will be the port EXPOSE 16022
b326ac1e4aa66b7e9644bb38f008c04578d8635e
[ "YAML", "Markdown", "Makefile", "Dockerfile", "Shell" ]
6
Markdown
mrahbar/my-bloody-jenkins
acdf5a14f8fd554997fc71bf63c3a5eda080c2df
e32af97d3393fb22fa49c236b583a673b412ac36
refs/heads/master
<file_sep>#!/usr/bin/env python3 # client.py import socket soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) soc.connect(("10.50.0.55", 12345)) clients_input = "beacon_data" soc.send(clients_input.encode()) # we must encode the string to bytes data = b'' # recv() does return bytes while True: try: chunk = soc.recv(4096) # some 2^n number if not chunk: # chunk == '' break data += chunk except socket.error: soc.close() break result_bytes = data # the number means how the response can be in bytes result_string = result_bytes.decode("utf8") # the return will be in bytes, so decode print (result_string) print ("----------") <file_sep><!doctype html> <html> <head> <meta charset="UTF-8"> <title>BLE-Presence PHP Client</title> </head> <body> <?php $password = htmlspecialchars($_POST["password"]); $address = htmlspecialchars($_POST["address"]); $port = htmlspecialchars($_POST["port"]); //$msg="beacon_data"; $msg = htmlspecialchars($_POST["msg"]); $order = htmlspecialchars($_POST["order"]); if ($password == "<PASSWORD>"){ $sock=socket_create(AF_INET,SOCK_STREAM,0) or die("Cannot create a socket"); socket_connect($sock,$address,$port) or die("Could not connect to the socket"); socket_write($sock,$msg); $data=''; $chunk=''; while(true){ $chunk = socket_read($sock,4096); if (!$chunk) { socket_close($sock); break; } $data .= $chunk; } //THIS IS COMMENTED OUT BECAUSE NOW WE HAVE A DIFFERENT APPROACH: //echo $data; } ?> <h1>BLE-Presence PHP Client</h1> <form action=<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?> method="post">&nbsp; <label for="password">Client Password:</label> <input name="password" type="text" id="password" <?php if ($password !== '' ) { echo 'value="'.$password.'"'; }?> > <label for="address">Server IP:</label> <input name="address" type="text" id="address" <?php if ($address !== '' ) { echo 'value="'.$address.'"'; }?> > <label for="port">Port:</label> <input name="port" type="text" id="port" <?php if ($port !== '' ) { echo 'value="'.$port.'"'; } else { echo 'value="12345"'; } ?> > <label for="msg">Message to send:</label> <input name="msg" type="text" id="msg" <?php if ($msg !== '' ) { echo 'value="'.$msg.'"'; } else { echo 'value="beacon_data"'; } ?> > <label for="order">Order:</label> <select name="order" id="order"> <option value="RAW"<?php if ($order == 'RAW' ) { echo ' selected="selected"'; }?>>Just raw data</option> <option value="UPDATE"<?php if ($order == 'UPDATE' ) { echo ' selected="selected"'; }?>>Last update (last heard first)</option> <option value="RSSI"<?php if ($order == 'RSSI' ) { echo ' selected="selected"'; }?>>RSSI signal (strongest first)</option> </select> <input type="submit" name="submit" id="submit" value="Invia/Aggiorna"> </form> <hr> <?php if ($order == "RAW" and $data !== ""){ echo $data; } if ($order == "UPDATE" and $data !== ""){ $result_string = substr($data, 1, -1); $result_string = str_replace("(","",$result_string); $items = explode("), ", $result_string); foreach ($items as $item) { $bucket = explode("', ['", $item); $BLE_MAC = str_replace("'","",$bucket[0]); $ble_data = explode("', '", $bucket[1]); $BLE_RSSI = $ble_data[0]; $BLE_TIME = str_replace("']","",$ble_data[1]); $BLE_TIME = str_replace(")","",$BLE_TIME); echo $BLE_MAC." RSSI: ".round(((100 - abs($BLE_RSSI))*100)/74)." TIMESTAMP: ".$BLE_TIME."<br>"; } } ?> </body> </html><file_sep>If this project help you reduce time to develop, you can give me a cup of coffee :) [![paypal](https://www.paypalobjects.com/en_US/i/btn/btn_donateCC_LG.gif)](https://paypal.me/marcobag) # BLE Presence - All in One version (Server + Client) BLE-Presence it's Client/Server software that allow to scan all the BLE beacons/request battery level using one or more servers (a small Raspberry Pi v1 is more than enought ) and read the results thru multiple clients. Due to the architecture the **Server part can be installed on Linux only** (tested Ubuntu & Raspian Stretch). The Client can be installed on any OS capable of interpret Python 3 (or other languages, depending on the client) > **Before going forward in the reading and consider installing it, please consider that this software is in a TRUE EARLY STAGE of development and it's not recommended the installation.** > Feel free to use it, but at your own risk. ## How does it work? ### Server: - Constantly scan the BLE devices - Is able to request batery level of the devices - Output all those informations thru a socket that can be opened by all the clients to read the required data ### Clients: - Open a soket to the specified server - Read informations about BLE DEVICES - Ask to the specified server about BLE DEVICES (ex: battery level) **Both Server and Client scripts can be installed in the same machine** # Installation process (Server Part): Due to the architecture the **Server part can be installed on Linux only** (tested Ubuntu & Raspian Stretch). Clone the repository on your machine: ```sh $ git clone https://github.com/mydomo/ble-presence.git $ cd ble-presence ``` Install the dependencies required: ```sh $ sudo apt-get install -y libbluetooth-dev bluez $ sudo apt-get install python-dev python3-dev python3-setuptools python3-pip $ sudo pip3 install pybluez ``` Create the service: ```sh $ sudo nano /etc/systemd/system/bleserver.service ``` Copy and paste the following, **but remember to EDIT IT in order to match your current home folder**. (ExecStart=/home/**pi**/ble-presence/server.py and WorkingDirectory=/home/**pi**/ble-presence) ```sh [Unit] Description=BLE Python Socket Server After=multi-user.target [Service] Type=simple ExecStart=/home/pi/ble-presence/server.py User=root WorkingDirectory=/home/pi/ble-presence Restart=on-failure [Install] WantedBy=multi-user.target ``` **CTRL + X** to save it. Enable the service: ```sh $ systemctl enable bleserver.service ``` Reboot the machine and you are done! ### To manually start/stop/remove the service: To manual start the service: ```sh $ systemctl start bleserver.service ``` To manual stop the service: ```sh $ systemctl stop bleserver.service ``` To remove the service: ```sh $ systemctl disable bleserver.service ``` ### References BLE-Presence uses a number of open source projects to work properly and many fonts of inspirations: * [RasPi-iBeacons] - Part of the cose used for the server part. * [Reddit Community] - Spiral6 post on how to create a service. And of course BLE-Presence itself is open source with a [public repository] on GitHub. # Clients BLE-Presence is currently extended with the following clients. | Client | Location | How to install | | ------ | ------ | ------ | | Domoticz | /clients/DOMOTICZ | [Install Domoticz] | | PHP | /clients/PHP | coming soon | | PYTHON | /clients/PYTHON | coming soon | ## Install Domoticz Plugin Copy and paste the following, **but remember to EDIT IT in order to match your current home folder and the installation path of Domoticz**. (in this case my home is "/home/pi", the installation path of Domoticz is "/home/pi/domoticz/") ```sh $ sudo ln -s /home/pi/ble-presence/clients/DOMOTICZ/ble-presence /home/pi/domoticz/plugins $ chmod +x /home/pi/ble-presence/clients/DOMOTICZ/ble-presenceplugin.py ``` Since you created a Symbolic Link you will not need to update the Domoticz Plugin folder for each release, it will follow the content on the main Git repository. ## Todos - Pythonize and clean the code - Sending Encrypted data thru socket and authentication. - Create different repository for server only/client only installs. License ---- coming soon **Free Software, Hell Yeah!** If this project help you reduce time to develop, you can give me a cup of coffee :) [![paypal](https://www.paypalobjects.com/en_US/i/btn/btn_donateCC_LG.gif)](https://paypal.me/marcobag) [//]: # (These are reference links used in the body of this note and get stripped out when the markdown processor does its job. There is no need to format nicely because it shouldn't be seen. Thanks SO - http://stackoverflow.com/questions/4823468/store-comments-in-markdown-syntax) [RasPi-iBeacons]: <https://github.com/flyinactor91/RasPi-iBeacons> [Reddit Community]: <https://www.reddit.com/r/raspberry_pi/comments/4vhofs/creating_a_systemd_daemon_so_you_can_run_a_python/> [public repository]: <https://github.com/mydomo/ble-presence> [Install Domoticz]: <#install-domoticz-plugin> <file_sep><?php $address="10.50.0.55"; $port="12345"; $msg="stop"; $sock=socket_create(AF_INET,SOCK_STREAM,0) or die("Cannot create a socket"); socket_connect($sock,$address,$port) or die("Could not connect to the socket"); socket_write($sock,$msg); $read=socket_read($sock,1024); echo $read; socket_close($sock); ?><file_sep><?php $address="10.50.0.55"; $port="12345"; $msg="battery_level: de:7f:fd:9a:df:78,fd:6c:9a:dc:e2:a8,c7:7e:de:7a:a0:10"; $sock=socket_create(AF_INET,SOCK_STREAM,0) or die("Cannot create a socket"); socket_connect($sock,$address,$port) or die("Could not connect to the socket"); socket_write($sock,$msg); $read=socket_read($sock,32768); echo $read; socket_close($sock); ?><file_sep>#!/usr/bin/python3 ################################################################################# # BLE PRESENCE FOR DOMOTICZ # # # # AUTHOR: <NAME> (ITALY) (https://github.com/mydomo) # # # ################################################################################# # PLEASE READ THE README FILE FOR COMPLETE # # INSTALLATION INSTRUCTIONS AND LICENSE # ################################################################################# ################################################################################# # INSTALL REQUIREMENTS ON UBUNTU SERVER 16.04: # # # # sudo apt-get install -y libbluetooth-dev bluez # # sudo apt-get install python-dev python3-dev python3-setuptools python3-pip # # sudo pip3 install pybluez # # # ################################################################################# import socket from lib import ble_scan from threading import Thread import sys import os import time import bluetooth._bluetooth as bluez import signal import subprocess from collections import OrderedDict ##########- CONFIGURE SCRIPT -########## socket_ip = '0.0.0.0' socket_port = 12345 min_inval_between_batt_level_readings = 3600 ##########- CONFIGURE TRANSLATIONS -########## lang_SCAN_STOPPED = 'Scanning stopped by other function' lang_READING_LOCK = 'Reading in progress...' lang_READING_START = 'Reading started' lang_SERVICE_STOP = 'Service stopping...' ##########- START VARIABLE INITIALIZATION -########## mode = '' beacons_detected = '' batt_lev_detected = '' scan_beacon_data = True ble_value = '' devices_to_analize = {} batt_lev_detected = {} read_value_lock = False ##########- END VARIABLE INITIALIZATION -########## ##########- START FUNCTION THAT HANDLE CLIENT INPUT -########## def socket_input_process(input_string): global mode global devices_to_analize global lang_SCAN_STOPPED global lang_READING_LOCK global lang_READING_START global lang_SERVICE_STOP ###- TRANSMIT BEACON DATA -### # check if client requested "beacon_data" if input_string == 'beacon_data': # if beacon scanning function has being stopped in order to process one other request (ex.: battery level) warn the client if scan_beacon_data == False: return str(lang_SCAN_STOPPED) # if beacon scanning function is active send the data to the client if scan_beacon_data == True: # set operative mode to beacon_data mode = 'beacon_data' # return beacons detected return str(beacons_detected) ###- TRANSMIT BATTERY LEVEL -### # check if the request start with battery_level: if input_string.startswith('battery_level:'): # trim "battery_level:" from the request string_devices_to_analize = input_string.replace("battery_level: ", "").strip() # split each MAC address in a list in order to be processed devices_to_analize = string_devices_to_analize.split(',') # set operative mode to battery_level mode = 'battery_level' # if the reading has already requested and there is no result ask to wait if not batt_lev_detected and read_value_lock == True: return str(lang_READING_LOCK) # if the reading is requested for the first time start say that will start elif not batt_lev_detected and read_value_lock == False: return str(lang_READING_START) # we have some battery data but we have to check if the MAC addresses are the same of the request / timestamp expired / data error. else: batt_need_update = False for device in devices_to_analize: battery_level_moderator = str(batt_lev_detected.get(device, "Never")) # cleaning the value stored cleaned_battery_level_moderator = str(battery_level_moderator.replace("[", "").replace("]", "").replace(" ", "").replace("'", "")) # assign the battery level and the timestamp to different variables if cleaned_battery_level_moderator == "Never": batt_need_update = True if cleaned_battery_level_moderator != "Never": # DEVICE HAS A PREVIOUS STORED BATTERY LEVEL stored_batterylevel, stored_timestamp = cleaned_battery_level_moderator.split(',') time_difference = int(time.time()) - int(stored_timestamp) if ( (int(time_difference) >= int(min_inval_between_batt_level_readings)) or (str(stored_batterylevel) == '255') ): batt_need_update = True if batt_need_update == True and read_value_lock == True: return str(lang_READING_LOCK) if batt_need_update == True and read_value_lock == False: return str(lang_READING_START) if batt_need_update == False: return str(batt_lev_detected) ###- STOP RUNNING SERVICES -### if input_string == 'stop': killer.kill_now = True return str(lang_SERVICE_STOP) ##########- END FUNCTION THAT HANDLE CLIENT INPUT -########## ##########- START FUNCTION THAT HANDLE SOCKET'S TRANSMISSION -########## def client_thread(conn, ip, port, MAX_BUFFER_SIZE = 4096): # the input is in bytes, so decode it input_from_client_bytes = conn.recv(MAX_BUFFER_SIZE) # MAX_BUFFER_SIZE is how big the message can be # this is test if it's too big siz = len(input_from_client_bytes) if siz >= MAX_BUFFER_SIZE: print("The length of input is probably too long: {}".format(siz)) # decode input and strip the end of line input_from_client = input_from_client_bytes.decode("utf8").rstrip() res = socket_input_process(input_from_client) #print("Result of processing {} is: {}".format(input_from_client, res)) vysl = res.encode("utf8") # encode the result string conn.sendall(vysl) # send it to client conn.close() # close connection ##########- END FUNCTION THAT HANDLE SOCKET'S TRANSMISSION -########## def usb_dongle_reset(): process0 = subprocess.Popen("sudo hciconfig hci0 down", stdout=subprocess.PIPE, shell=True) process0.communicate() process1 = subprocess.Popen("sudo hciconfig hci0 reset", stdout=subprocess.PIPE, shell=True) process1.communicate() process2 = subprocess.Popen("sudo /etc/init.d/bluetooth restart", stdout=subprocess.PIPE, shell=True) process2.communicate() process3 = subprocess.Popen("sudo hciconfig hci0 up", stdout=subprocess.PIPE, shell=True) process3.communicate() def ble_scanner(): global beacons_detected dev_id = 0 usb_dongle_reset() try: sock = bluez.hci_open_dev(dev_id) #print ("ble thread started") except: print ("error accessing bluetooth device... restart in progress!") usb_dongle_reset() ble_scan.hci_le_set_scan_parameters(sock) ble_scan.hci_enable_le_scan(sock) beacons_detected = {} beacons_detected_scanned = {} beacons_detected_scanned_trimmed = {} SCANNING_FINISHED = False while (scan_beacon_data == True) and (not killer.kill_now): try: if SCANNING_FINISHED == True: beacons_detected = beacons_detected_scanned_trimmed SCANNING_FINISHED = False elif SCANNING_FINISHED == False: returnedList = ble_scan.parse_events(sock, 25) for beacon in returnedList: MAC, RSSI, LASTSEEN = beacon.split(',') beacons_detected_scanned[MAC] = [RSSI,LASTSEEN] # return beacons_detected ordered by timestamp ASC (tnx to: JkShaw - http://stackoverflow.com/questions/43715921/python3-ordering-a-complex-dict) # return "just" the last 150 results to prevent the end of the socket buffer (each beacon data is about 45 bytes) beacons_detected_scanned_trimmed = str(sorted(beacons_detected_scanned.items(), key=lambda x: x[1][1], reverse=True)[:150]) SCANNING_FINISHED = True time.sleep(1) except: print ("failed restarting device... let's try again!") usb_dongle_reset() dev_id = 0 sock = bluez.hci_open_dev(dev_id) ble_scan.hci_le_set_scan_parameters(sock) ble_scan.hci_enable_le_scan(sock) SCANNING_FINISHED = False time.sleep(1) def read_battery_level(): global scan_beacon_data global mode global devices_to_analize global batt_lev_detected global read_value_lock global min_inval_between_batt_level_readings uuid_to_check = '0x2a19' time_difference = 0 while (not killer.kill_now): if mode == 'battery_level' and read_value_lock == False: read_value_lock = True #print ("Dispositivi da analizzare: " + str(devices_to_analize)) for device in devices_to_analize: device_to_connect = device #print ("Analizzo dispositivo: " + str(device)) # i'm reading the value stored battery_level_moderator = str(batt_lev_detected.get(device, "Never")) # cleaning the value stored cleaned_battery_level_moderator = str(battery_level_moderator.replace("[", "").replace("]", "").replace(" ", "").replace("'", "")) # assign the battery level and the timestamp to different variables if cleaned_battery_level_moderator != "Never": # DEVICE HAS A PREVIOUS STORED BATTERY LEVEL stored_batterylevel, stored_timestamp = cleaned_battery_level_moderator.split(',') time_difference = int(time.time()) - int(stored_timestamp) if ( (int(time_difference) >= int(min_inval_between_batt_level_readings)) or (str(stored_batterylevel) == '255') ): # THE TIME DIFFERENCE IT'S OVER OR THE BATTERY LEVEL HAS NOT PROPERLY READ scan_beacon_data = False usb_dongle_reset() # CODE TO READ THE BATTERY LEVEL try: handle_ble = os.popen("sudo hcitool lecc --random " + device_to_connect + " | awk '{print $3}'").read() handle_ble_connect = os.popen("sudo hcitool ledc " + handle_ble).read() #ble_value = int(os.popen("sudo gatttool -t random --char-read --uuid " + uuid_to_check + " -b " + device_to_connect + " | awk '{print $4}'").read() ,16) ble_value = os.popen("sudo gatttool -t random --char-read --uuid " + uuid_to_check + " -b " + device_to_connect + " | awk '{print $4}'").read() except: ble_value = 'nd' if (ble_value != '') and (ble_value != 'nd'): ble_value = int(ble_value ,16) elif (ble_value == '') or (ble_value == 'nd'): ble_value = '255' time_checked = str(int(time.time())) batt_lev_detected[device] = [ble_value,time_checked] read_value_lock = False elif cleaned_battery_level_moderator == "Never": # DEVICE DON'T HAVE A PREVIOUS STORED BATTERY LEVEL scan_beacon_data = False usb_dongle_reset() # CODE TO READ THE BATTERY LEVEL try: handle_ble = os.popen("sudo hcitool lecc --random " + device_to_connect + " | awk '{print $3}'").read() handle_ble_connect = os.popen("sudo hcitool ledc " + handle_ble).read() #ble_value = int(os.popen("sudo gatttool -t random --char-read --uuid " + uuid_to_check + " -b " + device_to_connect + " | awk '{print $4}'").read() ,16) ble_value = os.popen("sudo gatttool -t random --char-read --uuid " + uuid_to_check + " -b " + device_to_connect + " | awk '{print $4}'").read() except: ble_value = 'nd' if (ble_value != '') and (ble_value != 'nd'): ble_value = int(ble_value ,16) elif (ble_value == '') or (ble_value == 'nd'): ble_value = '255' time_checked = str(int(time.time())) batt_lev_detected[device] = [ble_value,time_checked] read_value_lock = False #AS SOON AS IT FINISH RESTART THE scan_beacon_data PROCESS scan_beacon_data = True mode = 'beacon_data' Thread(target=ble_scanner).start() time.sleep(1) def start_server(): global soc soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # this is for easy starting/killing the app soc.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) #print('Socket created') try: soc.bind((socket_ip, socket_port)) # print('Socket bind complete') except socket.error as msg: # print('Bind failed. Error : ' + str(sys.exc_info())) sys.exit() #Start listening on socket soc.listen(10) #print('Socket now listening') # for handling task in separate jobs we need threading #from threading import Thread # this will make an infinite loop needed for # not reseting server for every client while (not killer.kill_now): conn, addr = soc.accept() ip, port = str(addr[0]), str(addr[1]) #print('Accepting connection from ' + ip + ':' + port) try: Thread(target=client_thread, args=(conn, ip, port)).start() except: print("Terible error!") import traceback traceback.print_exc() soc.close() def kill_socket(): global soc global kill_now kill_socket_switch = False while (not kill_socket_switch): if killer.kill_now: print ("KILL_SOCKET PROVA A CHIUDERE IL SOCKET") time.sleep(1) soc.shutdown(socket.SHUT_RDWR) soc.close() kill_socket_switch = True time.sleep(1) ### MAIN PROGRAM ### class GracefulKiller: kill_now = False def __init__(self): signal.signal(signal.SIGINT, self.exit_gracefully) signal.signal(signal.SIGTERM, self.exit_gracefully) def exit_gracefully(self,signum, frame): global soc self.kill_now = True print ('Program stopping...') if __name__ == '__main__': killer = GracefulKiller() Thread(target=start_server).start() Thread(target=ble_scanner).start() Thread(target=read_battery_level).start() Thread(target=kill_socket).start() # print ("End of the program. I was killed gracefully") <file_sep>""" BLE-Presence python plugin for Domoticz Author: <NAME>, some parts of the components are fork of other open source projects. Read README for more informations. Version: 0.0.1: pre-alpha 0.0.2: pre-alpha added handling of timestamp 0.0.3: pre-alpha something is working 0.1.0: alpha, Domoticz Plugin working... must be fixed the server 0.2.1 alpha, battery scan now functioning. 0.2.2 alpha, battery scan removed to see if fix some issues 0.2.3 alpha: FIX a problem where if a BLE device is not found in the BLE and in Domoticz devices panel "Signal" or "Battery" has bein deleted by the user, the emergency Kill Switch may not disable the device. 0.2.4 alpha: Battery reading every 24h re-enebled, should be fixed now. 0.2.5 alpha: Started some code refactoring, moreover added a feature where the security switch act even if both the optional devices (signal and battery) are deleted by the user. 0.2.6 alpha: Battery request disabled due to a bug where the server is locked requesting the battery level. 99% the issue isn't in the plugin but in the server part, but i'm going to disable it here. """ """ <plugin key="ble-presence" name="BLE-Presence Client" author="<NAME>" version="0.2.6" wikilink="" externallink="https://github.com/mydomo"> <params> <param field="Address" label="BLE-Presence Server IP address" width="200px" required="true" default="127.0.0.1"/> <param field="Port" label="Port" width="40px" required="true" default="12345"/> <param field="Mode1" label="Timeout from the last beacon received to pull off the device (in seconds)" width="40px" required="true" default="300"/> <param field="Mode2" label="Mac addresses (coma ',' separated) for manual adding of BLE devices. (optional)" width="100px" required="true" default="XX:XX:XX:XX:XX:XX"/> <param field="Mode6" label="Mode" width="200px" required="true"> <options> <option label="Auto add discovered BLE devices." value="AUTO_ADD_DEVICE" default="true" /> <option label="Scan only manually added BLE devices" value="MANUAL_ADD_DEVICE" /> <option label="BLE scanner" value="BLE_SCAN" /> </options> </param> </params> </plugin> """ import Domoticz import socket import time import datetime SCAN_STOPPED = False UPDATE_BLE = False UPDATE_SIGNAL = False BATTERY_REQUEST = False BATTERY_DEVICE_REQUEST = "" class BasePlugin: def __init__(self): self.debug = False self.error = False self.mode = "" return def onStart(self): if Parameters["Mode6"] == 'AUTO_ADD_DEVICE': self.mode = 'AUTO_ADD_DEVICE' if Parameters["Mode6"] == 'BLE_SCAN': self.mode = 'BLE_SCAN' if Parameters["Mode6"] == 'MANUAL_ADD_DEVICE': self.mode = 'MANUAL_ADD_DEVICE' if 1 not in Devices: Domoticz.Device(Name="BLE PRESENCE", Unit=1, TypeName="Switch").Create() return def onStop(self): Domoticz.Debug("onStop called") return def onHeartbeat(self): self.error = False if self.mode == 'AUTO_ADD_DEVICE': self.AUTO_ADD_DEVICE_devices() if self.mode == 'BLE_SCAN': self.BLE_SCAN_devices() if self.mode == 'MANUAL_ADD_DEVICE': self.MANUAL_ADD_DEVICE_devices() return #BLE-PRESENCE SPECIFIC METHODS def BLE_SCAN_devices(self): global SCAN_STOPPED global UPDATE_BLE global UPDATE_SIGNAL global BATTERY_REQUEST global BATTERY_DEVICE_REQUEST if not self.error: # Connect to the socket, ask and get the informations result_string = socket_communication() if result_string == "ERROR": self.error = True else: # CHECK IF THE SCANNING HAS THE EXPECTED RESULTS, THAN # START THE INPUT CLEANING FOR BEACONING DATA # REMOVE '[', ']' AND '(' FROM THE RECEIVED STRING # WHEN START IN THIS WAY MEANS THAT DATA ARE NOT CORRUPTED. if result_string.startswith("[('") and result_string.endswith("'])]"): if SCAN_STOPPED == True: SCAN_STOPPED = False Domoticz.Log("BLE SCANNING reasumed correctly") result_string = result_string[1:-1].replace("(", "") # RECURSIVE SPLIT THE STRING TO GET THE DATA: items = result_string.split("), ") if len(items) == 0: while len(items) < 1: result_string = "'xx:xx:xx:xx:xx:xx', ['-90', '1513096870']), " + result_string items = result_string.split("), ") for x in Devices: DEVICE_FOUND = False #Domoticz.Log("Looking for: " + str(Devices[x].DeviceID) + " in BLE SCAN") for item in items: bucket = item.split("', ['") BLE_MAC = bucket[0].replace("'", "") ble_data = bucket[1].split("', '") BLE_RSSI = ble_data[0] BLE_TIME = ble_data[1].replace("']", "").replace(")", "") # VARABLES FOR DEVICE ADDING NAME_BLE = BLE_MAC DEV_ID_BLE = str(BLE_MAC.replace(":", "")) # SIGNAL VARIABLES NAME_S_DATA = "SIGNAL " + BLE_MAC DEV_ID_S_DATA = str("S-" + BLE_MAC.replace(":", "")) SIGNAL_LEVEL = round(((100 - abs(int(BLE_RSSI)))*100)/74) if SIGNAL_LEVEL > 100: SIGNAL_LEVEL = 100 if SIGNAL_LEVEL < 0: SIGNAL_LEVEL = 0 # BATTERY VARIABLES NAME_B_DATA = "BATTERY " + BLE_MAC DEV_ID_B_DATA = str("B-" + BLE_MAC.replace(":", "")) BATTERY_LEVEL = 0 # CALCULATE THE TIME DIFFERENCE BETWEEN THE SCAN AND NOW time_difference = (round(int(time.time())) - round(int(BLE_TIME))) if ( str(Devices[x].DeviceID) == DEV_ID_BLE ): DEVICE_FOUND = True #Domoticz.Log( str(Devices[x].DeviceID) + " has being found on the BLE Server output") if int(time_difference) <= int(Parameters["Mode1"]): #Domoticz.Log( str(Devices[x].DeviceID) + " will be updated, last seen: " + str(time_difference) + "seconds ago") UpdateDevice_by_DEV_ID(DEV_ID_BLE, 1, str("On")) else: #Domoticz.Log( str(Devices[x].DeviceID) + " will be turned OFF, last seen: " + str(time_difference) + "seconds ago") UpdateDevice_by_DEV_ID(DEV_ID_BLE, 0, str("Off")) elif ( str(Devices[x].DeviceID) == DEV_ID_S_DATA ): #Domoticz.Log( str(Devices[x].DeviceID) + " has being found on the BLE Server output") DEVICE_FOUND = True if int(time_difference) <= int(Parameters["Mode1"]): #Domoticz.Log( str(Devices[x].DeviceID) + " will be updated, last seen: " + str(time_difference) + "seconds ago") UpdateDevice_by_DEV_ID(DEV_ID_S_DATA, SIGNAL_LEVEL, str(SIGNAL_LEVEL)) else: #Domoticz.Log( str(Devices[x].DeviceID) + " will be turned OFF, last seen: " + str(time_difference) + "seconds ago") UpdateDevice_by_DEV_ID(DEV_ID_S_DATA, 0, str("0")) # BATTERY REQUEST. # elif ( str(Devices[x].DeviceID) == DEV_ID_B_DATA ): # #Domoticz.Log( str(Devices[x].DeviceID) + " has being found on the BLE Server output") # DEVICE_FOUND = True # # if int(time_difference) <= int(Parameters["Mode1"]): # #Domoticz.Log( str(Devices[x].DeviceID) + " will be updated, last seen: " + str(time_difference) + "seconds ago") # #Domoticz.Log(str(Devices[x].DeviceID) + " Devices[x].LastUpdate = " + str(Devices[x].LastUpdate)) # LASTUPDATE_BATT = time.mktime(datetime.datetime.strptime(Devices[x].LastUpdate, "%Y-%m-%d %H:%M:%S").timetuple()) # time_difference_BATT = (round(int(time.time())) - round(int(LASTUPDATE_BATT))) # #Domoticz.Log("Time difference = " + str(time_difference_BATT) + " s") # if (time_difference_BATT >= 86400): # Domoticz.Log("Battery level requested for device: " + str(Devices[x].DeviceID)) # # DELETE_PREFIX_DEVICE = str(Devices[x].DeviceID).replace("B-", "").replace("S-", "") # DEVICE_FOR_BATTERY = str(DELETE_PREFIX_DEVICE[0:2]) + ":" + str(DELETE_PREFIX_DEVICE[2:4]) + ":" + str(DELETE_PREFIX_DEVICE[4:6]) + ":" + str(DELETE_PREFIX_DEVICE[6:8]) + ":" + str(DELETE_PREFIX_DEVICE[8:10]) + ":" + str(DELETE_PREFIX_DEVICE[10:12]) # BATTERY_DEVICE_REQUEST = "battery_level: " + str(DEVICE_FOR_BATTERY) # # BATTERY_REQUEST = True if DEVICE_FOUND == False: # DEVICE WAS NOT FOUND, STARTING THE SECURITY MODE security_switch() # DATA FROM THE SOCKET IS NOT A REGULAR SCANNING PROCESS. # IS A BATTERY READ? elif result_string.startswith('{') and result_string.endswith('}'): Domoticz.Log("Socket is sending battery info:" + result_string) # THIS IS ADDED FOR SECURITY, IF TIMEOUT HAS BEING REACHED AND NO INFORMATION FROM THE SERVER TURN OFF THAT DEVICE. security_switch() battery_items = result_string.split("'], '") if len(battery_items) == 1: #Domoticz.Log("Recognized one device") # THERE IS JUST ONE DEVICE... SO SPLIT HIM battery_all_data = result_string.split(" [") #Domoticz.Log(str(battery_all_data[0])) MAC_BATT_READING = battery_all_data[0].replace("{", "").replace("':", "").replace("'", "") battery_percentage_timestamp = battery_all_data[1].split(", ") BATT_BATT_READING = battery_percentage_timestamp[0].replace("'", "") TIMESTAMP_BATT_READING = battery_percentage_timestamp[1].replace("'", "").replace("]}", "") DEV_ID_B_DATA_READ = str("B-" + MAC_BATT_READING.replace(":", "")) if int(BATT_BATT_READING) == 255: BATTERY_LEVEL_READ = 0 elif int(BATT_BATT_READING) < 0: BATTERY_LEVEL_READ = 0 else: BATTERY_LEVEL_READ = int(BATT_BATT_READING) UpdateDevice_by_DEV_ID_NOCHECK(DEV_ID_B_DATA_READ, BATTERY_LEVEL_READ, str(BATTERY_LEVEL_READ)) BATTERY_REQUEST = False else: for b_item in battery_items: battery_all_data = b_item.split(" [") MAC_BATT_READING = battery_all_data[0].replace("{", "").replace("':", "").replace("'", "") battery_percentage_timestamp = battery_all_data[1].split(", ") BATT_BATT_READING = battery_percentage_timestamp[0].replace("'", "") TIMESTAMP_BATT_READING = battery_percentage_timestamp[1].replace("'", "").replace("]}", "") DEV_ID_B_DATA_READ = str("B-" + MAC_BATT_READING.replace(":", "")) if int(BATT_BATT_READING) == 255: BATTERY_LEVEL_READ = 0 elif int(BATT_BATT_READING) < 0: BATTERY_LEVEL_READ = 0 else: BATTERY_LEVEL_READ = int(BATT_BATT_READING) UpdateDevice_by_DEV_ID_NOCHECK(DEV_ID_B_DATA_READ, BATTERY_LEVEL_READ, str(BATTERY_LEVEL_READ)) BATTERY_REQUEST = False # IS NOT A SCANNING AND IS NOT A BATTERY READ, HANDLE SERVER REPLY OUT OF "MAIN SCOPE" else: # Handle server reply out of our main scope handle_server_reply(result_string) # THIS IS ADDED FOR SECURITY, IF TIMEOUT HAS BEING REACHED AND NO INFORMATION FROM THE SERVER TURN OFF THAT DEVICE. security_switch() return def AUTO_ADD_DEVICE_devices(self): global SCAN_STOPPED global UPDATE_BLE global UPDATE_SIGNAL if not self.error: result_string = socket_communication() if result_string == "ERROR": self.error = True else: # CHECK IF THE SCANNING HAS THE EXPECTED RESULTS, THAN # START THE INPUT CLEANING FOR BEACONING DATA # REMOVE '[', ']' AND '(' FROM THE RECEIVED STRING if result_string.startswith("[('") and result_string.endswith("'])]"): if SCAN_STOPPED == True: SCAN_STOPPED = False Domoticz.Log("BLE SCANNING reasumed correctly") result_string = result_string[1:-1].replace("(", "") # RECURSIVE SPLIT THE STRING TO GET THE DATA: items = result_string.split("), ") for item in items: bucket = item.split("', ['") BLE_MAC = bucket[0].replace("'", "") ble_data = bucket[1].split("', '") BLE_RSSI = ble_data[0] BLE_TIME = ble_data[1].replace("']", "").replace(")", "") # VARABLES FOR DEVICE ADDING NAME_BLE = BLE_MAC DEV_ID_BLE = str(BLE_MAC.replace(":", "")) # SIGNAL VARIABLES NAME_S_DATA = "SIGNAL " + BLE_MAC DEV_ID_S_DATA = str("S-" + BLE_MAC.replace(":", "")) SIGNAL_LEVEL = round(((100 - abs(int(BLE_RSSI)))*100)/74) if SIGNAL_LEVEL > 100: SIGNAL_LEVEL = 100 if SIGNAL_LEVEL < 0: SIGNAL_LEVEL = 0 # BATTERY VARIABLES NAME_B_DATA = "BATTERY " + BLE_MAC DEV_ID_B_DATA = str("B-" + BLE_MAC.replace(":", "")) BATTERY_LEVEL = 0 # CALCULATE THE TIME DIFFERENCE BETWEEN THE SCAN AND NOW time_difference = (round(int(time.time())) - round(int(BLE_TIME))) if int(time_difference) <= int(Parameters["Mode1"]): # DEVICE HAS BEING SEEN RECENTLY, ADD OR UPDATE IT if (isDEVICEIDinDB(DEV_ID_BLE) == True): # DEVICE PRESENT, UPDATE IT UpdateDevice_by_DEV_ID(DEV_ID_BLE, 1, str("On")) if (isDEVICEIDinDB(DEV_ID_BLE) == False): # DEVICE NOT PRESENT, CREATE IT createSwitch(NAME_BLE, DEV_ID_BLE) if (isDEVICEIDinDB(DEV_ID_S_DATA) == True): # DEVICE PRESENT, UPDATE IT UpdateDevice_by_DEV_ID(DEV_ID_S_DATA, SIGNAL_LEVEL, str(SIGNAL_LEVEL)) if (isDEVICEIDinDB(DEV_ID_S_DATA) == False): # DEVICE NOT PRESENT, CREATE IT createCustomSwitch(NAME_S_DATA, DEV_ID_S_DATA) # BATTERY DEVICE CANNOT BE UPDATED FROM DISCOVERY MODE BUT JUST BY SCANNER MODE if (isDEVICEIDinDB(DEV_ID_B_DATA) == False): # DEVICE NOT PRESENT, CREATE IT createCustomSwitch(NAME_B_DATA, DEV_ID_B_DATA) else: # DEVICE HAS NOT BEING SEEN RECENTLY, UPDATE THE STATUS ACCORDINGLY. if (isDEVICEIDinDB(DEV_ID_BLE) == True): UpdateDevice_by_DEV_ID(DEV_ID_BLE, 0, str("Off")) if (isDEVICEIDinDB(DEV_ID_S_DATA) == True): UpdateDevice_by_DEV_ID(DEV_ID_S_DATA, 0, str("0")) # THE DATA FROM THE SOCKET ARE NOT A REGULAR SCANNING PROCESS, IDENTIFY IT AND ACT ACCORDINGLY else: # DATA FROM THE SOCKET IS NOT A REGULAR SCANNING PROCESS, IDENTIFY IT AND ACT ACCORDINGLY handle_server_reply(result_string) return def MANUAL_ADD_DEVICE_devices(self): global SCAN_STOPPED if not self.error: clean_manual_items = Parameters["Mode2"].replace(" ", "") manual_items = clean_manual_items.split(",") for manual_item in manual_items: BLE_MAC = manual_item NAME_BLE = BLE_MAC DEV_ID_BLE = str(BLE_MAC.replace(":", "")) # SIGNAL VARIABLES NAME_S_DATA = "SIGNAL " + BLE_MAC DEV_ID_S_DATA = str("S-" + BLE_MAC.replace(":", "")) # BATTERY VARIABLES NAME_B_DATA = "BATTERY " + BLE_MAC DEV_ID_B_DATA = str("B-" + BLE_MAC.replace(":", "")) BATTERY_LEVEL = 0 if (isDEVICEIDinDB(DEV_ID_BLE) == False): # DEVICE NOT PRESENT, CREATE IT createSwitch(NAME_BLE, DEV_ID_BLE) if (isDEVICEIDinDB(DEV_ID_S_DATA) == False): # DEVICE NOT PRESENT, CREATE IT createCustomSwitch(NAME_S_DATA, DEV_ID_S_DATA) # BATTERY DEVICE CANNOT BE UPDATED FROM DISCOVERY MODE BUT JUST BY SCANNER MODE if (isDEVICEIDinDB(DEV_ID_B_DATA) == False): # DEVICE NOT PRESENT, CREATE IT createCustomSwitch(NAME_B_DATA, DEV_ID_B_DATA) self.mode = 'BLE_SCAN' return global _plugin _plugin = BasePlugin() def onStart(): global _plugin _plugin.onStart() def onStop(): global _plugin _plugin.onStop() def onHeartbeat(): global _plugin _plugin.onHeartbeat() def UpdateDevice_by_UNIT(Unit, nValue, sValue): # Make sure that the Domoticz device still exists (they can be deleted) before updating it if (Unit in Devices): if (Devices[Unit].nValue != nValue) or (Devices[Unit].sValue != sValue): Devices[Unit].Update(nValue=nValue, sValue=str(sValue)) Domoticz.Log("Device: " + str(Devices[Unit].Name) + " updated. (" + str(sValue) + ")") return def UpdateDevice_by_UNIT_NOCHECK(Unit, nValue, sValue): # Make sure that the Domoticz device still exists (they can be deleted) before updating it if (Unit in Devices): Devices[Unit].Update(nValue=nValue, sValue=str(sValue)) Domoticz.Log("Device: " + str(Devices[Unit].Name) + " updated. (" + str(sValue) + ")") return def UpdateDevice_by_DEV_ID(DEV_ID, nValue, sValue): # Make sure that the Domoticz device still exists (they can be deleted) before updating it #Domoticz.Log("Requested to update "+ str(DEV_ID)) for y in Devices: if ( str(DEV_ID) == str(Devices[y].DeviceID) ): #Domoticz.Log("UPDATING "+ str(DEV_ID) + "with Unit: " + str(y)) Unit = y UpdateDevice_by_UNIT(Unit, nValue, sValue) return def UpdateDevice_by_DEV_ID_NOCHECK(DEV_ID, nValue, sValue): # Make sure that the Domoticz device still exists (they can be deleted) before updating it #Domoticz.Log("Requested to update "+ str(DEV_ID)) for y in Devices: if ( str(DEV_ID) == str(Devices[y].DeviceID) ): #Domoticz.Log("UPDATING "+ str(DEV_ID) + "with Unit: " + str(y)) Unit = y UpdateDevice_by_UNIT_NOCHECK(Unit, nValue, sValue) return def isDEVICEIDinDB(DEV_ID): # Check if a BLE device is already in the database for x in Devices: if ( str(DEV_ID) == str(Devices[x].DeviceID) ): #ALREADY EXIST FOUND = True break else: FOUND = False return FOUND def createSwitch(NAME, DEV_ID): # Check if a BLE device is already in the database UNIT_GENERATED = len(Devices) + 1 if not UNIT_GENERATED in Devices: Domoticz.Device(Name=NAME, Unit=UNIT_GENERATED, DeviceID=DEV_ID, TypeName="Switch").Create() Domoticz.Log("Device " + str(NAME)+ " CREATED") return def createCustomSwitch(NAME, DEV_ID): # Check if a BLE device is already in the database UNIT_GENERATED = len(Devices) + 1 if not UNIT_GENERATED in Devices: Domoticz.Device(Name=NAME, Unit=UNIT_GENERATED, DeviceID=DEV_ID, TypeName="Custom", Options={"Custom": "1;%"}).Create() Domoticz.Log("Device " + str(NAME)+ " CREATED") return def security_switch(): # THIS IS ADDED FOR SECURITY, IF TIMEOUT HAS BEING REACHED AND NO INFORMATION FROM THE SERVER TURN OFF THAT DEVICE. for x in Devices: # FOR EACH DEVICE CHECK LAST UPDATE. ORIGINAL_EXPIRED = False BATTERY_EXPIRED = False SIGNAL_EXPIRED = False ORIGINAL_FOUND = False BATTERY_FOUND = False SIGNAL_FOUND = False if x > 1: # Check that no one of the devices has being updated # Search the original Device ID (no derivated) if not ( str(Devices[x].DeviceID).startswith("S-") or str(Devices[x].DeviceID).startswith("B-")): #LAST UPDATED ORGINAL: ORIGINAL_FOUND = True ORIGINAL_LAST_UPDATE = time.mktime(datetime.datetime.strptime(Devices[x].LastUpdate, "%Y-%m-%d %H:%M:%S").timetuple()) ORIGINAL_TIME_DIFF = (round(int(time.time())) - round(int(ORIGINAL_LAST_UPDATE))) if (ORIGINAL_TIME_DIFF > int(Parameters["Mode1"])): ORIGINAL_EXPIRED = True # CHECK BATTERY for b in Devices: if ( str(Devices[b].DeviceID) == str("B-" + Devices[x].DeviceID)): BATTERY_FOUND = True BATTERY_LAST_UPDATE = time.mktime(datetime.datetime.strptime(Devices[b].LastUpdate, "%Y-%m-%d %H:%M:%S").timetuple()) BATTERY_TIME_DIFF = (round(int(time.time())) - round(int(BATTERY_LAST_UPDATE))) if (BATTERY_TIME_DIFF > int(Parameters["Mode1"])): BATTERY_EXPIRED = True else: BATTERY_EXPIRED = False # CHECK SIGNAL for s in Devices: if ( str(Devices[s].DeviceID) == str("S-" + Devices[x].DeviceID)): SIGNAL_FOUND = True SIGNAL_LAST_UPDATE = time.mktime(datetime.datetime.strptime(Devices[s].LastUpdate, "%Y-%m-%d %H:%M:%S").timetuple()) SIGNAL_TIME_DIFF = (round(int(time.time())) - round(int(SIGNAL_LAST_UPDATE))) if (SIGNAL_TIME_DIFF > int(Parameters["Mode1"])): SIGNAL_EXPIRED = True else: SIGNAL_EXPIRED = False else: ORIGINAL_EXPIRED = False if ORIGINAL_FOUND and (BATTERY_FOUND or SIGNAL_FOUND): if ( ORIGINAL_EXPIRED and (BATTERY_EXPIRED or not BATTERY_FOUND) and (SIGNAL_EXPIRED or not SIGNAL_FOUND) ): # the check of the status is formarly unnecessary but allow us to know if the Security Switch has being used. if Devices[x].nValue == 1: Domoticz.Log( "Security Switch: Device " + Devices[x].DeviceID + " cannot be found and reached the timeout, setting as off/no-signal") UpdateDevice_by_DEV_ID(Devices[x].DeviceID, 0, str("Off")) if SIGNAL_FOUND: UpdateDevice_by_DEV_ID(Devices[s].DeviceID, 0, str("0")) elif ( (ORIGINAL_FOUND and ORIGINAL_EXPIRED) and not (BATTERY_FOUND or SIGNAL_FOUND) ): # the check of the status is formarly unnecessary but allow us to know if the Security Switch has being used. if Devices[x].nValue == 1: Domoticz.Log( "Security Switch: Device " + Devices[x].DeviceID + " cannot be found and reached the timeout, setting as off/no-signal") UpdateDevice_by_DEV_ID(Devices[x].DeviceID, 0, str("Off")) return def handle_server_reply(result_string): global SCAN_STOPPED # Domoticz.Log(" ") > insert something in the log. # Domoticz.Error(" ") > insert something in the ERROR log. # SCAN_STOPPED = True > warn the plugin that the scan was not performed if str(result_string).strip() == '': # No results, i guess the server is starting. Domoticz.Log( "Server connected but no BLE devices has being found in the scan. Hang on...") elif str(result_string).strip() == 'Scanning stopped by other function': Domoticz.Log( "BLE Server is busy, scan will be reasumed soon.") SCAN_STOPPED = True # ADDED for security security_switch() elif str(result_string).strip() == 'Reading started': Domoticz.Log( "BLE Server started reading the battery level for the selected device.") SCAN_STOPPED = True # ADDED for security security_switch() elif str(result_string).strip() == 'Reading in progress...': Domoticz.Log( "BLE Server busy reading the battery level for the selected device.") SCAN_STOPPED = True # ADDED for security security_switch() elif str(result_string).strip() == 'Service stopping...': Domoticz.Log( "BLE Server turning off.") SCAN_STOPPED = True # ADDED for security security_switch() else: Domoticz.Error("BLE Server unexpected reply: " + str(result_string) ) return def socket_communication(): global BATTERY_REQUEST global BATTERY_DEVICE_REQUEST try: soc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) SERV_ADDR = str(Parameters["Address"]) SERV_PORT = int(Parameters["Port"]) soc.connect((SERV_ADDR, SERV_PORT)) if BATTERY_REQUEST == True: clients_input = str(BATTERY_DEVICE_REQUEST) else: clients_input = "beacon_data" soc.send(clients_input.encode()) # we must encode the string to bytes data = b'' # recv() does return bytes while True: try: chunk = soc.recv(4096) # some 2^n number if not chunk: # chunk == '' break data += chunk except socket.error: soc.close() break result_bytes = data # the number means how the response can be in bytes socket_read = result_bytes.decode("utf8") # the return will be in bytes, so decode except: Domoticz.Error("Error connecting to BLE-Server: " + Parameters["Address"] + " on port: " + Parameters["Port"]) security_switch() # ERROR during the connection return "ERROR" else: return socket_read
b4db25ea4987e4d2dd5d2357888c1e4193a96d30
[ "Markdown", "Python", "PHP" ]
7
Python
mydomo/ble-presence
300f5ed3934d99b4f11d9d757ac3cf053f85bc46
b19f45d3697e16a597412c3a38a59924b7e15fbf
refs/heads/master
<file_sep>const express = require('express'); const mysql = require('mysql2'); const cors = require('cors'); const db = mysql.createPool({ host: 'mysql_db', user: 'root', password: '<PASSWORD>', database: 'books' }) // init app const app = express(); app.use(express.json()) // app will listen const PORT = 4000; app.listen(PORT, () => { console.log(`App is listening on ${PORT}`); }) // setup cors app.use(express.urlencoded({extended: true})) app.use(cors()) // Homepage app.get('/', (req, res) => { res.send('Hi There') }); // CRUD app.get('/get', (req, res) => { const SelectQuery = " SELECT * FROM books_reviews"; db.query(SelectQuery, (err, result) => { res.send(result) }) }) app.post("/post", (req, res) => { const bookName = req.body.setBookName; const bookReview = req.body.setReview; const InsertQuery = "INSERT INTO books_reviews (book_name, book_review) VALUES (?, ?)"; db.query(InsertQuery, [bookName, bookReview], (err, result) => { console.log(result) }) }) app.delete("/delete/:bookId", (req, res) => { const bookId = req.params.bookId; const DeleteQuery = "DELETE FROM books_reviews WHERE id = ?"; db.query(DeleteQuery, bookId, (err, result) => { if (err) console.log(err); }) })
3505780c1f917ea4b53bd92fc9034357ecbdc3c2
[ "JavaScript" ]
1
JavaScript
mkomljenovic/dockerized-fullstack-app
4c5832b6117a424515a68256f9c5ea48a87c00cb
d479604f042c11c81abbcf5d07bd68a88d40f1e2
refs/heads/main
<file_sep>import React, { useState } from 'react'; import GaleryForm from './GaleryForm'; const GaleryHeader = () => { return ( <div style={{ backgroundImage: 'url("images/galleryBackground.gif")', backgroundSize: 'cover', backgroundRepeat: 'no-repeat', height: 'auto', width: '100vw', backgroundColor: 'black', paddingLeft: '15%', paddingRight: '15%', }}> <div style={{ height: '100px' }}></div> <h3 style={{ fontSize: 'calc(12px + 1.5vw)', color: '#fff' }}>GALERIA DE ENSAIOS</h3> <h1 style={{ fontWeight: "bold", fontSize: 'calc(12px + 4vw)', color: '#fff' }}>2Pixels Fotografia</h1> <br /> <GaleryForm /> </div> ); } export default GaleryHeader;<file_sep>import React, { useEffect, useState } from 'react'; import { Carousel, CarouselItem, CarouselControl, CarouselIndicators, CarouselCaption, UncontrolledCarousel } from 'reactstrap'; const Background = () => { const [activeIndex, setActiveIndex] = useState(0); const [animating, setAnimating] = useState(false); const [windownSize, setWindowSize] = useState(1920); React.useEffect(() => { let width = window.innerWidth; if(width){ setWindowSize(width); } },[]); const getItems = () => { if (windownSize <= 767) { return [ { src: 'images/bg1md.jpg', caption: '', altText: '' }, { src: 'images/bg2md.jpg', caption: '', altText: '' }, { src: 'images/bg3md.jpg', caption: '', altText: '' }, ]; } return [ { src: 'images/bg1small.jpg', caption: '', altText: '' }, { src: 'images/bg2small.jpg', caption: '', altText: '' }, ]; } const next = () => { if (animating) return; const nextIndex = activeIndex === getItems().length - 1 ? 0 : activeIndex + 1; setActiveIndex(nextIndex); } const previous = () => { if (animating) return; const nextIndex = activeIndex === 0 ? getItems().length - 1 : activeIndex - 1; setActiveIndex(nextIndex); } const goToIndex = (newIndex) => { if (animating) return; setActiveIndex(newIndex); } const slides = getItems().map((item) => { return ( <CarouselItem onExiting={() => setAnimating(true)} onExited={() => setAnimating(false)} key={item.src} > <img src={item.src} alt={item.altText} style={{ width: '100vw', height: '100vh', objectFit: 'cover', float: 'left' }} /> <CarouselCaption captionText={item.caption} captionHeader={item.caption} /> </CarouselItem> ); }); return ( <div style={{ width: '100vw', height: '100vh', position: 'relative', top: '0px', left: '0px' }}> <Carousel activeIndex={activeIndex} next={next} previous={previous} > <CarouselIndicators items={getItems()} activeIndex={activeIndex} onClickHandler={goToIndex} /> {slides} <CarouselControl direction="prev" directionText=" " onClickHandler={previous} /> <CarouselControl direction="next" directionText=" " onClickHandler={next} /> </Carousel> </div> ); } export default Background;<file_sep>import Head from 'next/head'; import 'bootstrap/dist/css/bootstrap.min.css'; import Header from '../components/Header/Header'; import Background from '../components/IndexComponents/Background/Background'; import Video from '../components/IndexComponents/Video/Video'; export default function Home() { return ( <div> <Head> <title>2Pixels Fotografia</title> <meta name='robots' content='index/follow' /> <meta name='description' content='Registrando momentos em Itaboraí e região' /> </Head> <Header /> <Background /> <Video /> </div> ); }<file_sep>import React, { useEffect, useState } from 'react'; import Gallery from 'react-grid-gallery'; import { getImages } from '../../lib/Api'; const IMAGES = [{ src: "https://c2.staticflickr.com/9/8817/28973449265_07e3aa5d2e_b.jpg", thumbnail: "https://c2.staticflickr.com/9/8817/28973449265_07e3aa5d2e_n.jpg", thumbnailWidth: 320, thumbnailHeight: 174, caption: "After Rain (<NAME> - designerspics.com)" }, { src: "https://c2.staticflickr.com/9/8356/28897120681_3b2c0f43e0_b.jpg", thumbnail: "https://c2.staticflickr.com/9/8356/28897120681_3b2c0f43e0_n.jpg", thumbnailWidth: 320, thumbnailHeight: 212, tags: [{ value: "Ocean", title: "Ocean" }, { value: "People", title: "People" }], caption: "Boats (<NAME> - designerspics.com)" }, { src: "https://c4.staticflickr.com/9/8887/28897124891_98c4fdd82b_b.jpg", thumbnail: "https://c4.staticflickr.com/9/8887/28897124891_98c4fdd82b_n.jpg", thumbnailWidth: 320, thumbnailHeight: 212 }, { src: "https://c4.staticflickr.com/9/8887/28897124891_98c4fdd82b_b.jpg", thumbnail: "https://c4.staticflickr.com/9/8887/28897124891_98c4fdd82b_n.jpg", thumbnailWidth: 320, thumbnailHeight: 212 }, { src: "https://c4.staticflickr.com/9/8887/28897124891_98c4fdd82b_b.jpg", thumbnail: "https://c4.staticflickr.com/9/8887/28897124891_98c4fdd82b_n.jpg", thumbnailWidth: 320, thumbnailHeight: 212 }, { src: "https://c4.staticflickr.com/9/8887/28897124891_98c4fdd82b_b.jpg", thumbnail: "https://c4.staticflickr.com/9/8887/28897124891_98c4fdd82b_n.jpg", thumbnailWidth: 320, thumbnailHeight: 212 }, { src: "https://c4.staticflickr.com/9/8887/28897124891_98c4fdd82b_b.jpg", thumbnail: "https://c4.staticflickr.com/9/8887/28897124891_98c4fdd82b_n.jpg", thumbnailWidth: 320, thumbnailHeight: 212 }, { src: "https://c4.staticflickr.com/9/8887/28897124891_98c4fdd82b_b.jpg", thumbnail: "https://c4.staticflickr.com/9/8887/28897124891_98c4fdd82b_n.jpg", thumbnailWidth: 320, thumbnailHeight: 212 } ] const Galery = () => { const [images, setImages] = useState([]); useEffect(async () => { const response = await getImages(); if (response) { setImages(response); } }, []); return ( <div> <div style={{backgroundColor: 'gray', paddingTop: '2%', paddingBottom: '2%', paddingLeft: '2%'}}> <h4 style={{ fontSize: 'calc(12px + 2vw)', color: '#fff' }}><NAME></h4> </div> <Gallery images={IMAGES} /> </div> ); } export default Galery;<file_sep>import Head from 'next/head'; import 'bootstrap/dist/css/bootstrap.min.css'; import Header from '../components/Header/Header'; import Galery from '../components/Galery/Galery'; import GaleryHeader from '../components/Galery/GaleryHeader/GaleryHeader'; export default function Home() { return ( <div> <Head> <title>2Pixels Fotografia</title> <meta name='robots' content='index/follow' /> <meta name='description' content='Registrando momentos em Itaboraí e região' /> </Head> <Header /> <div style={{backgroundColor: 'black', height: '100vh'}}> <GaleryHeader /> <Galery /> </div> </div> ); }<file_sep>import React, { useState } from 'react'; import ReactPlayer from 'react-player' const Video = () => { return ( <div style={{width:'100%', backgroundColor: 'black', display: 'flex', justifyContent: 'center'}}> {/* <iframe src='https://www.youtube.com/embed/x0eYvFNTCLU?autoplay=1&loop=1' frameBorder='0' allow='autoplay; encrypted-media' allowFullScreen title='video' width='100%' height='auto' /> */} <ReactPlayer url='https://www.youtube.com/watch?v=x0eYvFNTCLU' light /> </div> ); } export default Video;<file_sep>import React, { useState } from 'react'; import { Button, Form, FormGroup, Label, Input, FormText } from 'reactstrap'; const GaleryForm = () => { return ( <div style={{ display: 'inline-block', width: '100%' }}> <div style={{ display: 'inherit', width: '75%' }}> <Input style={{ width: '100%' }} type="text" name="modelName" id="modelId" placeholder="Digite o nome da(o) modelo" /> </div > <div style={{ display: 'inherit' , marginLeft: '1%', width: '20%'}} > <Button >Buscar</Button> </div> <br /> <br /> </div> ); } export default GaleryForm;<file_sep># 2PixelsFotografia Website da @2PixelsFotografia
163114da83b7376923acd1559c6a614c92a41c42
[ "JavaScript", "Markdown" ]
8
JavaScript
jsimonassi/2PixelsFotografia
c415f3bf77dbce0cca73442e1d586964ee6621a3
1bf0f0cbd2140563b1c12971afa41542e84b90f7
refs/heads/master
<repo_name>laurencio-galicia/Apachetest<file_sep>/Dockerfile FROM centos:7 MAINTAINER <NAME> <<EMAIL>> & INFRA-CTIN RUN yum -y install epel-release.noarch && yum -y update && yum install -y httpd http-tools supervisor COPY config.sh /tmp/config.sh RUN /bin/bash /tmp/config.sh EXPOSE 80 #USER nobody ENTRYPOINT /usr/bin/supervisord -c /tmp/supervisord.conf <file_sep>/config.sh #!/bin/bash # Elimiar Warning de Apache echo 'ServerName localhost' >> /etc/httpd/conf/httpd.conf # modificar sitio echo '<KEY>' | base64 -w0 -d > /usr/share/httpd/noindex/index.html # Creacion de Supervisor echo '<KEY> | base64 -w0 -d > /tmp/supervisord.conf
225c52a6f16cdfcbdbfa070b92a55c78fec95a57
[ "Dockerfile", "Shell" ]
2
Dockerfile
laurencio-galicia/Apachetest
586ba34ea13c880fe51c188cf813a781fcf9df59
28d30d7f16c593a0f3c41afc22d0497130316fb3
refs/heads/master
<file_sep># importing required modules import PyPDF2 pagenumber = [] wordlist = [] #to convert a text file to list with open("convert.txt") as file: listfile = [] for line in file: #checking is the line is empty or not if line.strip(): listfile.append(line.strip()) print(listfile) print(len(listfile)) pdfFileObj = open('north.pdf', 'rb') pdfReader = PyPDF2.PdfFileReader(pdfFileObj) #print(pdfReader.numPages) for i in range(0,456): pageObj = pdfReader.getPage(i) text=(pageObj.extractText()) sentences=text.split(",") #text #keywords are given for searching inside pdf #search_keywords=['119371000006986','119371900001251'] search_keywords = listfile for sentence in sentences: #print(sentence) #lst = [] for word in search_keywords: if word in sentence: print(word) wordlist.append(word) pagenumber.append(i+1) pagenumber.append(i+2) print("hurray",i) print(pagenumber) print(len(pagenumber)) #compare 2 list and find missing values set1 = set(listfile) set2 = set(wordlist) missing = list(sorted(set1 - set2)) added = list(sorted(set2 - set1)) print('missing:', missing) print('added:', added)<file_sep>""" ####################################################### script to search files in your directory(ver 1) ####################################################### """ import os import fnmatch import sys def find(search, path): result=[] for root, dirs, files in os.walk(path): for name in files: if fnmatch.fnmatch(name,search): result.append(os.path.join(root, name)) return result """ here i have used "*" in print statement ,it is a way of displaying list in python and to view in seperate lines i have used "sep="\n"" """ print(*find('*'+sys.argv[1],sys.argv[2]),sep="\n") <file_sep>import pandas as pd df1=pd.read_csv('cmplx_data/human_ch0.csv',header=None) df2=pd.read_csv('cmplx_data/human_ch1.csv',header=None) df3=pd.read_csv('cmplx_data/noobj_ch0.csv',header=None) df4=pd.read_csv('cmplx_data/noobj_ch1.csv',header=None) frames = [df1, df2, df3,df4] result = pd.concat(frames) result.to_csv('merged.csv',header=None,index=None) print("done") <file_sep>''' applymap() is a function in pandas here x corresponds to each element in the dataframe ''' import pandas as pd import numpy as np frame1=pd.read_csv("/home/vkchlt0300/Music/new.csv") def every(x): x=complex(x) return abs(x) frame1=frame1.applymap(every) print(frame1) #csv frame1.to_csv('/home/vkchlt0300/Desktop/final_siva.csv',index=False,header=False) print("all_done_bro") <file_sep>import random for i in range (0,5): randomlist = random.sample(range(1, 99), 50) print(randomlist) print(type(randomlist)) with open(str(i)+'.txt', 'w') as f: for item in randomlist: f.write("%s" % item) f.write(",") f.write("1") for i in range (5,10): randomlist = random.sample(range(1, 99), 50) print(randomlist) print(type(randomlist)) with open(str(i)+'.txt', 'w') as f: for item in randomlist: f.write("%s" % item) f.write(",") f.write("0") <file_sep>#!/usr/bin/env python __authors__ = "Adarsh_K_Sudarsan <NAME>" __license__ = "GPL-3" __version__ = "1.0.1" __maintainer__ = "Adarsh_K_Sudarsan" __email__ = "<EMAIL>" """ simple script to fill the gaps between numerical values in a given series by calculating the mean values between the numerals in the series. """ def writerfunc(string_list): index_list = [] val = 0 if string_list[0] == "_": string_list[0] = 0 for i, j in enumerate(string_list): if j != "_": index_list.append(i) for n in range(0, len(index_list)-1): if index_list[n+1] - index_list[n] > 1: value = (int(string_list[index_list[n+1]])+int(string_list[index_list[n]]))/((index_list[n+1]-index_list[n])+1) for k in range(index_list[n], (index_list[n+1])+1): string_list[k] = value else: continue if len(string_list) != index_list[-1]: value1 = int(string_list[index_list[-1]])/(len(string_list)-index_list[-1]) for k in range(index_list[-1], len(string_list)): string_list[k] = value1 return string_list if __name__ == "__main__": string = input("Space Separated Input: ") input_list = string.split(" ") output = writerfunc(input_list) print() for out in output: print(out, end=" ") print() <file_sep>import pandas as pd #reading df1=pd.read_csv('human_ch0_complex.csv',header=None) #reshaping to desired size df1=df1.iloc[0:3000,0:52] #to find amplitude def every(x): try: x=complex(x) return(int(abs(x))) except: print("fine") return(x) df1=df1.applymap(every) #testing_data test_data=df1.iloc[2901:3000,0:52] #training data df=df1.iloc[0:2900, 0:52] df[52]=0 #saving testing and training data csv df.to_csv('train.csv',header=None,index=None) test_data.to_csv('test.csv',header=None,index=None) print("done") <file_sep>''' Given the names and grades for each student in a class of students, store them in a nested list and print the name(s) of any student(s) having the second lowest grade. ''' marksheet = [] for _ in range(0,int(input())): marksheet.append([input(), float(input())]) print("marksheet",marksheet) second_highest = sorted(list(set([marks for name, marks in marksheet])))[-2] print(sorted(list(set([marks for name, marks in marksheet])))) print('\n'.join([a for a,b in sorted(marksheet) if b == second_highest]))<file_sep>import glob import pandas as pd read_files = glob.glob("0/*.txt") with open("resultfinal.txt", "a") as outfile: for f in read_files: print(f) with open(f, "r") as infile: for lne in infile: print (lne) outfile.write(lne +"\n") df = pd.read_table("resultfinal.txt",delimiter=",",header=None) df.to_hdf('DATA.h5', key='df', mode='w') print("**DONE**") <file_sep>#!/usr/bin/env python __author__ = "mis_takes" __license__ = "GPL-3" __version__ = "1.0.1" __maintainer__ = "mis_takes" __email__ = "<EMAIL>" """ simple script to find the correct word from jumbled order, just give the jumbled string it will show all the possible word list using itertools (inbuilt) & enchant(to find the dictonary words) """ import enchant from itertools import permutations s = input ("Enter the string :") perms = [''.join(p) for p in permutations(s)] print(len(perms)) perms = list(set(perms)) print(len(perms)) d = enchant.Dict("en_US") for i in perms: if(d.check(i)): print(i) <file_sep>''' script to merge multiple csv files to a single big one ''' import pandas as pd import glob #give the path of csv files(with object) path1 = r'/home/vvdn/ML/job_jishnu/test/dataset/object_amplitude' all_files1 = glob.glob(path1 + "/*.csv") for f1 in all_files1: frame1=pd.concat((pd.read_csv(f1,delimiter='\t') for f1 in all_files1)) frame1.drop(frame1.columns[len(frame1.columns)-2], axis=1, inplace=True) frame1.drop(frame1.columns[len(frame1.columns)-1], axis=1, inplace=True) frame1['head'] =1 #path to csv files(with no objects) path2 = r'/home/vvdn/ML/job_jishnu/test/dataset/No_object_amplitude/' all_files2 = glob.glob(path2 + "/*.csv") for f2 in all_files2: frame2=pd.concat((pd.read_csv(f2,delimiter='\t') for f2 in all_files2)) frame2.drop(frame2.columns[len(frame2.columns)-2], axis=1, inplace=True) frame2.drop(frame2.columns[len(frame2.columns)-1], axis=1, inplace=True) frame2['head'] =0 #csv merging bigdata = frame1.append(frame2, ignore_index=True) # give path for final output bigdata.to_csv('/home/vvdn/Desktop/final.csv',index=False,header=False) print("sucessfully Merged your csv files ") <file_sep> # coding: utf-8 # In[ ]: import os import math #give path size_bytes= os.path.getsize('/home/vvdn/Desktop/final2.csv') print(size_bytes) def convert_size(size_bytes): if size_bytes == 0: return "0B" size_name = ("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB") i = int(math.floor(math.log(size_bytes, 1000))) power = math.pow(1000, i) size = round(size_bytes / power, 2) return "{} {}".format(size, size_name[i]) print(convert_size(size_bytes)) <file_sep>#image resize script from PIL import Image import os import sys directory = '/home/vvdn/Desktop/image_manipulations/images' a,b=input('Enter required width * height seperated by "*"').split("*") if not os.path.exists(output_directory): os.makedirs(output_directory) for file_name in os.listdir(directory): image = Image.open(os.path.join(directory, file_name)) x,y = image.size new_dimensions = (int(a),int(b)) #dimension set here output = image.resize(new_dimensions, Image.ANTIALIAS) output_file_name = os.path.join(directory, "small_" + file_name) output.save(output_file_name, "JPEG", quality = 95) print("All done")
29f3d0cb8a369c988ffc2969f53d5dec86ac4a15
[ "Python" ]
13
Python
adarshksudarsan/python_scripts
d5a7060a4623de1c3c69c7e556ecb57e81e1c09e
c4e4761df7e289348bfbef49979fd607afe8b6e3
refs/heads/main
<repo_name>EnricoSandri/AR-NavMesh<file_sep>/Assets/Nav/scripts/Spawner.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class Spawner : MonoBehaviour { public GameObject agent; public GameObject startPoint; // Start is called before the first frame update void Start() { SpawnAgentAtStartPoint(); } private void SpawnAgentAtStartPoint() { startPoint = GameObject.FindGameObjectWithTag("StartPoint"); if (startPoint != null) { Instantiate(agent, startPoint.transform.position, startPoint.transform.rotation); } } } <file_sep>/Assets/Nav/scripts/Manager.cs using System.Collections; using System.Collections.Generic; using UnityEngine; public class Manager : MonoBehaviour { public static GameObject[] agentClones; // Update is called once per frame void Update() { agentClones = GameObject.FindGameObjectsWithTag("Player"); } public static void AgentDestroyer() { foreach (GameObject agent in agentClones) { Destroy(agent.gameObject); } } } <file_sep>/Assets/Nav/scripts/NavMeshBuilder.cs using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.AI; public class NavMeshBuilder : MonoBehaviour { public NavMeshSurface surface; private void Awake() { surface.BuildNavMesh(); } }<file_sep>/Assets/Nav/scripts/MoveTo.cs using UnityEngine; using UnityEngine.AI; public class MoveTo : MonoBehaviour { public GameObject goal; NavMeshAgent agent; void Start() { AgentDestinationSetter(); } private void Update() { AgentGoalVerifier(); } private void AgentDestinationSetter() { if (goal != null) {return;} goal = GameObject.FindGameObjectWithTag("Goal"); agent = GetComponent<NavMeshAgent>(); agent.destination = goal.transform.position; } private void AgentGoalVerifier() { if (goal != null){return;} Manager.AgentDestroyer(); } }
2eb7c9c43bb18bf6e8ac764bfecdb1d9006c3345
[ "C#" ]
4
C#
EnricoSandri/AR-NavMesh
83bfd9031315ead18fb6a28eaf9774ced51382e0
eb7d1bb4416dc6d44129fe43216a27b579599fc9
refs/heads/master
<file_sep># SAAM Security System (Sniff All Around Me) based on airodump-ng data parsing # Introduction SAAM is a simple smart security system write in nodeJS, created for radio-control of the wireless device in the area. SAAM use your wireless device as a radio-wireless scanner, with airmon-ng in monitor mode can discover and recognize MAC address of the device inside the coverage area. If the discovered MAC address not match in the known address database the system notify the inclusion with a mail. The remote client app can control and setup the SAAM, for add new mac address to the known database and manage access level of associated people. # Related Project Airmon-ng https://www.aircrack-ng.org/doku.php?id=airmon-ng Airodump-ng https://www.aircrack-ng.org/doku.php?id=airodump-ng # Status At the moment i work at SAAM in free time, and i've just started because is a new project, if you want help me or are intrested to this project please contact me. <file_sep>////######################################################################################## // Dependancies //######################################################################################## const mysql = require('mysql') const utils = require('../utils.js') //######################################################################################## // Configuration //######################################################################################## let connection = null const events = utils.emitter const log = utils.log const db_config = { host : 'localhost', user : 'root', password : '<PASSWORD>', database : 'saam' } //######################################################################################## // Function //######################################################################################## function handleDisconnect() { connection = mysql.createConnection(db_config); // Recreate the connection, since // the old one cannot be reused. connection.connect(function(err) { // The server is either down if(err) { // or restarting (takes a while sometimes). console.log('error when connecting to db:', err); setTimeout(handleDisconnect, 2000); // We introduce a delay before attempting to reconnect, } // to avoid a hot loop, and to allow our node script to }); // process asynchronous requests in the meantime. // If you're also serving http, display a 503 error. connection.on('error', function(err) { console.log('db error', err); if(err.code === 'PROTOCOL_CONNECTION_LOST') { // Connection to the MySQL server is usually handleDisconnect(); // lost due to either server restart, or a } else { // connnection idle timeout (the wait_timeout throw err; // server variable configures this) } }); } function initDb(){ log.debug('Initializing database connection') handleDisconnect() // create a new connection with error handler log.info('database connected!') } function closeDb(){ log.debug('Closing database connection') connection.end() // close database connection log.info('Database connection succesfully closed') } //######################################################################################## // Main //######################################################################################## function start(){ log.info('initializing db') initDb() log.info('starting database module listener') events.on('insertLog', insertLog) } //######################################################################################## // Exports //######################################################################################## exports.start = start exports.initDb = initDb exports.closeDb = closeDb exports.searchLogs = searchLogs exports.getPort = getPort exports.searchLogsByName = searchLogsByName exports.downloadLog = downloadLog
71254d87c846907411c2947b02059368d547571b
[ "Markdown", "JavaScript" ]
2
Markdown
francescoagostini93/SAAM
e7aec7593ed095055bff4206d776e4a30aac9f6b
42b196de162e77142b347931e8f133be0e4948c7
refs/heads/master
<repo_name>KevinStock/bcsics<file_sep>/requirements.txt ###### Requirements without Version Specifiers ###### Flask requests python-dotenv sentry-sdk[flask] ###### Requirements with Version Specifiers ###### ics == 0.7<file_sep>/main.py from flask import Flask, render_template, redirect, url_for, session, request, send_file import apiFunctions from datetime import datetime, timedelta from ics import Calendar, Event import sentry_sdk from sentry_sdk.integrations.flask import FlaskIntegration from dotenv import load_dotenv import os load_dotenv() sentry_sdk.init( dsn=os.getenv("SENTRY_DSN"), integrations=[FlaskIntegration()], traces_sample_rate=1.0 ) app = Flask(__name__) app.config.from_pyfile('config.py') # home page @app.route('/') def welcome(): return render_template('index.html') # login page @app.route('/login', methods=['GET', 'POST']) def login(): # GET request if request.method == 'GET': # check if we already have a token if is_logged_in(): return redirect(url_for('calendar')) return render_template('login.html') # POST request else: user_detail = apiFunctions.get_token(request.form['Email'], request.form['Password']) if user_detail['errorCode'] is None: session['token'] = user_detail['authenticationInfo']['authToken'] session['user_id'] = user_detail['authenticationInfo']['userId'] return redirect(url_for('calendar')) else: return render_template('login.html', error='Authentication Issue. Please check your credentials and try again.', email=request.form['Email']) # calendar page @app.route('/calendar', methods=['GET', 'POST']) def calendar(): # GET request if request.method == 'GET': # check if user is logged in if is_logged_in(): enrollments = apiFunctions.get_enrollments(session['token']) if not enrollments: return render_template('calendar.html', enrollments=enrollments, error="You do not belong to any courses.") else: return render_template('calendar.html', enrollments=enrollments) else: return redirect(url_for('login')) # POST request else: enrollment_id = request.form['Course'] options = {} options['academicCal'] = True if (request.form.get('academicCheck')) else False options['officeHours'] = True if (request.form.get('officeHoursCheck')) else False options['academicIsTrans'] = True if (int(request.form.get('academicIsTrans'))) else False options['careerCal'] = True if (request.form.get('careerCheck')) else False options['careerIsTrans'] = True if (int(request.form.get('careerIsTrans'))) else False options['assignmentCal'] = True if (request.form.get('assignmentsCheck')) else False options['assignmentsIsTrans'] = True if (int(request.form.get('assignmentsIsTrans'))) else False calendar_files = apiFunctions.create_calendar(session['token'], enrollment_id, options) return render_template('calendar.html', fileList=calendar_files) @app.route('/files/<filename>') def files(filename): file = os.path.join(app.root_path, 'files', filename) return send_file(file, as_attachment=True) @app.route('/logout') def logout(): session.pop('token', None) session.pop('user_id', None) return redirect(url_for('welcome')) def is_logged_in(): if 'token' in session: return True return False @app.route('/debug-sentry') def trigger_error(): division_by_zero = 1 / 0 if __name__ == '__name__': app.run(port=3000) <file_sep>/apiFunctions.py import requests import json from datetime import datetime, timedelta from ics import Calendar, Event # Login # POST https://bootcampspot.com/api/instructor/v1/login def get_token(email, password): try: response = requests.post( url="https://bootcampspot.com/api/instructor/v1/login", headers={ "Content-Type": "text/plain; charset=utf-8", }, data=json.dumps({ "email": email, "password": <PASSWORD> }) ) return response.json() except requests.exceptions.RequestException: print('HTTP Request failed') # Me # POST https://bootcampspot.com/api/instructor/v1/me def get_user_detail(token): try: response = requests.post( url="https://bootcampspot.com/api/instructor/v1/me", headers={ "Content-Type": "application/json", "authToken": token, }, ) return response.json() except requests.exceptions.RequestException: print('HTTP Request failed') # Sessions # POST https://bootcampspot.com/api/instructor/v1/sessions def get_sessions(token, enrollment_id): try: response = requests.post( url="https://bootcampspot.com/api/instructor/v1/sessions", headers={ "Content-Type": "application/json", "authToken": token, }, data=json.dumps({ "enrollmentId": int(enrollment_id) }) ) return response.json() except requests.exceptions.RequestException: print('HTTP Request failed') # Assignments # POST https://bootcampspot.com/api/instructor/v1/assignments def get_assignments(token, enrollment_id): try: response = requests.post( url="https://bootcampspot.com/api/instructor/v1/assignments", headers={ "Content-Type": "application/json", "authToken": token, }, data=json.dumps({ "enrollmentId": int(enrollment_id) }) ) return response.json() except requests.exceptions.RequestException: print('HTTP Request failed') def get_enrollments(token): # get session enrollments user_enrollments = [] for enrollment in get_user_detail(token)['Enrollments']: if enrollment['active']: user_enrollments.append({'id': enrollment['id'], 'name': enrollment['course']['name'], 'startDate': datetime.strptime(enrollment['course']['startDate'], '%Y-%m-%dT%H:%M:%SZ').strftime("%B %d, %Y")}) return user_enrollments def create_calendar(token, enrollment_id, options): file_list = [] if options['academicCal'] or options['careerCal']: academic_calendar = Calendar() career_calendar = Calendar() for sess in get_sessions(token, enrollment_id)['calendarSessions']: e = Event() if (sess['context']['id'] == 1) and options['academicCal']: start_time = datetime.strptime(sess['session']['startTime'], '%Y-%m-%dT%H:%M:%SZ') end_time = datetime.strptime(sess['session']['endTime'], '%Y-%m-%dT%H:%M:%SZ') e.name = str(sess['session']['chapter']) + ': ' + sess['session']['name'] e.transparent = True if options['academicIsTrans'] else False if options['officeHours']: e.begin = start_time - timedelta(minutes=45) e.end = end_time + timedelta(minutes=30) else: e.begin = start_time e.end = end_time academic_calendar.events.add(e) elif (sess['context']['id'] == 2) and options['careerCal']: e.name = sess['session']['name'] e.begin = sess['session']['startTime'] e.end = sess['session']['endTime'] e.transparent = True if options['careerIsTrans'] else False career_calendar.events.add(e) if len(academic_calendar.events) > 0: academic_file_name = str(enrollment_id) + '-academic-calendar' academic_file_name = academic_file_name + '-oh.ics' if options['officeHours'] else academic_file_name + '.ics' file_list.append(academic_file_name) with open('files/' + academic_file_name, 'w') as f: f.writelines(academic_calendar) if len(career_calendar.events) > 0: career_file_name = str(enrollment_id) + '-career-calendar.ics' file_list.append(career_file_name) with open('files/' + career_file_name, 'w') as f: f.writelines(career_calendar) if options['assignmentCal']: assignment_calendar = Calendar() for assignment in get_assignments(token, enrollment_id)['calendarAssignments']: e = Event() if assignment['context']['id'] == 1: e.name = assignment['title'] e.begin = datetime.strptime(assignment['effectiveDueDate'], '%Y-%m-%dT%H:%M:%SZ') - timedelta(days=1) e.end = datetime.strptime(assignment['effectiveDueDate'], '%Y-%m-%dT%H:%M:%SZ') - timedelta(days=1) e.make_all_day() e.transparent = True if options['assignmentsIsTrans'] else False assignment_calendar.events.add(e) assignment_file_name = str(enrollment_id) + '-assignment-calendar.ics' file_list.append(assignment_file_name) with open('files/' + assignment_file_name, 'w') as f: f.writelines(assignment_calendar) return file_list <file_sep>/README.md # BootcampSpot ICS Generator ## Introduction **3rd Place Winning Submission** for Trilogy BCS API Hack-a-thon using the new Bootcamp Spot API. This application is designed to allow a user to login with their BCS credentials, select a course cohort which they are active in, and generate an ICS file for all Academic, Career, and Assignment calendars. Optionally, a user can enable office hours on the Academic Calendar. ## Getting Started ### Run local 1. Install dependencies with `pip install -r requirements.txt` 2. Set SECRET_KEY `echo "SECRET_KEY='SuperSecretKey'" >> .env` 3. Set Sentry DSN `echo "SENTRY_DSN='YourSentryDSN" >> .env` 3. Execute `FLASK_APP=main.py flask run` 4. Open browser to http://127.0.0.1:5000/ 5. Login with BootcampSpot credentials (user must have an active enrollment to create a calendar file) ## Dependencies Python3, Flask, requests, ics, python-dotenv, sentry-sdk[flask] ## Built With [ics](https://github.com/C4ptainCrunch/ics.py) - Python module to create ics files. ## Notes This application still needs quite a bit of error handling. While authentication errors are being handled on login, no checks are made to ensure that the API returns appropriate data at this time. Assignment due dates are being manually adjusted due to the time returned by the API is GMT and there is no decent way to identify a cohort's time zone for appropriate conversion. ## Future Enhancements * Add ability to set alarms * Add Location (relies on BCS data to be clean)
a34714dfb8408cf0d036e3995fab63b942e1bda1
[ "Markdown", "Python", "Text" ]
4
Text
KevinStock/bcsics
3dd96846ef12c5525dad59eb1d576a26cfd68d82
713cab6a12e73791577f0538a51a1cae62a990b6
refs/heads/master
<file_sep>#define PDC_DLL_BUILD 1 #include "MyHeader.h" int main(void) { /* WINDOWS */ WINDOW* main_window = nullptr; int num_cols = 0; int num_rows = 0; //initialize window main_window = initscr(); /* SETUP */ //RESIZE WINDOW //resize_term(5000, 5000); getmaxyx(main_window, num_rows, num_cols); resize_term(num_rows - 1, num_cols - 1); //TURN KEYBOARD ECHO OFF noecho(); //TURN KEYPAD ON keypad(main_window, TRUE); //HIDE CURSOS curs_set(TRUE); //SET BORDER COLOR //attron(COLOR_PAIR(2)); //start_color(); //init_pair(2, COLOR_YELLOW, COLOR_YELLOW); //attroff(COLOR_PAIR(2)); //color_set(1, main_window); //wcolor_set(main_window, COLOR_GREEN, main_window); /* MAIN PROGRAM LOGIC */ //ROWS MANIPULATION for (int i = 0; i < num_cols; i++) { //top row start_color(); init_pair(1, COLOR_YELLOW, COLOR_YELLOW); attron(COLOR_PAIR(1)); mvaddch(0, i, ACS_BLOCK); attroff(COLOR_PAIR(1)); //bottom row mvaddch(num_rows - 1, i, ACS_BLOCK); } // TEXT EDITOR NAME, VERSION, and FILE NAME char txtName[20] = "My Micro 1"; char fileName[20] = "File: "; start_color(); init_pair(2, COLOR_BLACK, COLOR_WHITE); attron(COLOR_PAIR(2)); mvprintw(0, 5, txtName); mvprintw(0, 50, fileName); attroff(COLOR_PAIR(2)); //COLUMNS MANIPULATION for (int i = 0; i < num_rows; i++) { //left column mvaddch(i, 0, ACS_BLOCK); //right column mvaddch(i, num_cols - 1, ACS_BLOCK); } /* GUI FILE TEXT here */ attron(COLOR_PAIR(2)); //mvprintw(27, 1, "^G Get Help ^O WriteOut ^R Read File ^Y Prev Page ^K Cut Text ^C Cur Pos"); //mvprintw(28, 1, "^X Exit ^J Justify ^W Where is ^V Next Page ^U UnCut Text ^T To Spell"); mvprintw(29, 1, "^F: FILE ^E: EDIT ^V: VIEW ^H: HELP"); attroff(COLOR_PAIR(2)); /* INPUT CODE HERE */ //creating a NEW WINDOW for input //WINDOW* inputwin = newwin(3, 12, 5, 5); //box(inputwin, 0, 0); //refresh(); //wrefresh(inputwin); //keypad(inputwin, true); //HOW TO CREATE NEW, etc int inChar = wgetch(main_window); //switch for input switch (inChar) { case KEY_UP: mvwprintw(main_window, 1, 1, "You pressed up!"), wrefresh(main_window); break; case KEY_DOWN: mvwprintw(main_window, 1, 1, "You pressed down!"), wrefresh(main_window); break; case KEY_RIGHT: mvwprintw(main_window, 1, 1, "You pressed right!"), wrefresh(main_window); break; case KEY_LEFT: mvwprintw(main_window, 1, 1, "You pressed left!"), wrefresh(main_window); break; }; for (int i = 0; i < num_cols; i++) { mvwprintw(main_window, 1, 1, "<Enter exit to exit>"); getch(); if (inChar == 'a' && inChar != 'e') { mvaddch( i + 2, 2, 'a'); getch(); } } getch(); //INPUT CODE HERE //get user input //pause for input //char input = getch(); //char userStr[100]; //getstr(userStr); //mvprintw(2, 2, userStr); //int input = getch(); //START NEW TEXT FILE //ifstream fin; //fin.open("myFile.txt"); //wifstream fin; ifstream fin; fin.open("C:\Users\<NAME>\2019-fall-cs211\projects\TextEditor\TextEditorProject1"); fin.open("myInFile.txt"); //use file here char tryOne[90]; fin >> tryOne; mvprintw(4, 4, tryOne); wrefresh(main_window); //try a nested statement to USE FILE fin.close(); //OUTPUT FILE //wofstream fout; //ofstream fout; //fout.open("myOutFile.txt"); //use output file //fout.close(); /* END CURSES MODE */ endwin(); return 0; }<file_sep>#define PDC_DLL_BUILD 1 #include "curses.h" #include <string> using namespace std; int main(void) { WINDOW* main_window = nullptr; int num_rows = 0; int num_cols = 0; //intialize screen, being curses mode main_window = initscr(); //take up most of the screen getmaxyx(main_window, num_rows, num_cols); resize_term(num_rows - 1, num_cols - 1); getmaxyx(main_window, num_rows, num_cols); //turn off key echo noecho(); //nodelay(main_window, TRUE); keypad(main_window, TRUE); curs_set(0); //FUN STUFF HAPPENS HERE for (int i = 0; i < num_cols; i++) { //top border mvaddch(0, i, ACS_CKBOARD); //bottom border mvaddch(num_rows - 1, i, ACS_CKBOARD); } for (int i = 0; i < num_rows; i++) { //left column mvaddch(i, 0, ACS_CKBOARD); //right column mvaddch(i, num_cols - 1, ACS_CKBOARD); } //tells curses to draw refresh(); //revert back to normal console mode nodelay(main_window, TRUE); keypad(main_window, TRUE); mvaddstr(0, 0, "Press any key to continue..."); char result = getch(); endwin(); }<file_sep>#ifndef MYHEADER_H_ #define MYHEADER_H_ #include <cstdlib> #include <ctime> #include <iostream> #include <fstream> #include <string> #include <iomanip> #include <vector> #include "curses.h" #include "curspriv.h" #include "panel.h" using namespace std; #endif /* MAINHEADER_H_ */ <file_sep># Design Diary Use this space to talk about your process. For inspiration, see [my prompts](../../../docs/sample_reflection.md) 1) The greatest struggle I was able to overcome this milestone was allowing a user to be able to interact with the console by entering any single character. I was able to include the right combination of commands that would allow the user to enter a character, which could then be used to output anything I dictated in my code to the screen. For example, if the user was to enter any of the arrows, such as the up arrow, I could output that the user hit the up arrow key to the screen. Alternatively, I designed it so that by hitting any of the arrow keys the cursor would be moved one line or space in that direction. I accomplished this by creating a switch statement that would convert user input into a command of my choice. 2) I am still struggling on integrating a vector to read in and read out an input file and output file, respectively. Furthermore, my unfamiliarity with Visual Studios is causing me issues being able to read a text input file in visual studios, an issue I haven't had with other IDE's. 3) I would advise future students to strongly familiarize themselves with the use of vectors, because it would make implementing one for integrating the files much easier. 4) After completing the first milestone minimum requirements, I was able to do some experimenting with more of pdcurses functions. I was able to mess around with the colors and box functions, which gave me some ideas for how I will approach future milestones. 5) The most difficult part of this milestone thus far is figuring how to allow a user to access a input and output file. I still am very unfamilar with how to utilize command line to to read input parameters. 6) I am still having some issues grasping the logic of how curses mode operates vs. just interacting with the editor, and how this ties into files. Understanding vectors will become much easier once I am able to fully use and integrate one within my program. 7) A small overview or resource to access on how to interact with input commands within the command line I belive would go a long way with many students.<file_sep># Design Diary Use this space to talk about your process. For inspiration, see [my prompts](../../../docs/sample_reflection.md) 1) One oustanding issue I came across was how to get my text to not overwrite the border I had created. I overcame this by watching some tutorials online on how to keep the text within the foreground. 2) I was unable to get to change the color of my border and text produced. With additional time I may be able to resolve this. I also need to dedicate more time to having the menu adjust as a user scrolls in any given direction. 3) I recommend taking the time to read through the user guides on what pdcurses is and how the different functions, variables, etc. relate. Also, definitely checkout some tutorials online on how to draw and utilize pdcurses. 5) I really enjoyed the opportunity to just play around and experiment with the different functions, and see what I could pull off. 6) As we're just getting exposed to the project, it took a bit of extra time in the early stages to setup the project and get familiar with pdcurses and how to draw with it. 7) I set a bit of time aside to get a better understanding of github, git files, and what version control is and how it is used. PDcurses is still confusing to me in certain aspects. Understanding how windows are used inside PDcurses, and being able to switch between multiple windows and pdcurses mode vs just interacting directly with the Virtual Studios console. 8) My next focus at the moment is to get the border and menu to move with the user as they scroll in any direction. I also wish to improve the location of the menu, and add color to my GUI. This project also exposed me to the functionality of Visual Studios and the range of its potential uses, as before this project I had no exposure to Visual Studios. <file_sep>#ifndef VECTOR_H_ #define VECTOR_H_ #include "myheader.h" class Vector { public: Vector(); ~Vector(); private: vector<int> numbers; }; #endif /* VECTOR_H_ */<file_sep>#include "vector.h" Vector::Vector() { //private attributes here numbers = {}; } Vector::~Vector() {}
82829b757ca1da7016dbe29f5be9152ed05b5d63
[ "Markdown", "C++" ]
7
C++
jmp192/2019-fall-cs211
6e664cfa0d254bf2e1e83b585bfefb62c5f55e67
abf1ddbde07bc90aff2a523a889a9fdaedc69b89
refs/heads/master
<file_sep><?php session_start(); ?> <!doctype html> <html lang='es'> <?php include 'head.php'; ?> <body role="document"> <?php include 'cabecera.php'; ?> <div class="container-fluid col-md-6 col-md-offset-3"> <div class="panel panel-default"> <div class="panel-heading"> <center> <h3 class="panel-title"><strong>GENERAL INFORMATION</strong></h3> </div> <div class="panel-body"> <p>The theater has a capacity for 1500 people, it can be used for events such as graduations, representation of theatrical plays, among others.</p><br> <strong><center>Restrictions</center></strong><br> <ul> <li> Do not enter food to the theater.</li> <li> Keep Silence During the Event.</li> <li> Do not enter pets.</li> <li> Do not smoke or drink alcoholic beverages./li> <li> Do not damage the area</li> <li> Keep the cell phone in silence during the development of the event.</li> </ul><br> <center><strong>Photo Gallery</strong></center> <div class="thumbnail"> <img src="img/Teatro1.jpg" heigth='300' class="img-rounded" alt="Teatro"><br> <img src="img/Teatro2.jpg" heigth='300' class="img-rounded" alt="Teatro"><br> <img src="img/Teatro3.jpg" heigth='300' class="img-rounded" alt="Teatro"><br> <img src="img/Teatro4.jpg" heigth='300' class="img-rounded" alt="Teatro"><br> <img src="img/Teatro5.jpg" heigth='300' class="img-rounded" alt="Teatro"> </div> </div> </div> <footer> </footer> </body> </html><file_sep><?php session_start(); ?> <!doctype html> <html lang='es'> <?php include 'head.php'; ?> <body role="document"> <?php include 'cabecera.php'; ?> <div class="container-fluid col-md-6 col-md-offset-3"> <div class="panel panel-default"> <div class="panel-heading"> <center> <h3 class="panel-title"><strong>INFORMACIÓN GENERAL</strong></h3> </div> <div class="panel-body"> <p>El teatro tiene una capacidad para 1500 personas sentadas, puede ser usado para eventos como graduaciones, representación de obras teatrales, entre otras cosas. </p><br> <strong><center>Restricciones</center></strong><br> <ul> <li> No se permite ingresar comida al teatro.</li> <li> Guardar silencio durante el evento activo.</li> <li> No ingresar mascotas.</li> <li> No fumar ni ingresar bebidas alcohólicas.</li> <li> No dañar las instalaciones</li> <li> Mantener el celular en silencio durante el desarrollo del evento</li> </ul><br> <center><strong>Galería de Imágenes</strong></center> <div class="thumbnail"> <img src="img/Teatro1.jpg" heigth='300' class="img-rounded" alt="Teatro"><br> <img src="img/Teatro2.jpg" heigth='300' class="img-rounded" alt="Teatro"><br> <img src="img/Teatro3.jpg" heigth='300' class="img-rounded" alt="Teatro"><br> <img src="img/Teatro4.jpg" heigth='300' class="img-rounded" alt="Teatro"><br> <img src="img/Teatro5.jpg" heigth='300' class="img-rounded" alt="Teatro"> </div> </div> </div> <footer> </footer> </body> </html><file_sep><?php session_start(); ?> <!doctype html> <html lang='es'> <?php include 'head.php'; ?> <body role="document"> <?php include 'cabecera.php'; ?> <div class="container-fluid col-md-6 col-md-offset-3"> <div class="panel panel-default"> <div class="panel-heading"> <center> <h3 class="panel-title"><strong>GENERAL INFORMATION</strong></h3> </div> <div class="panel-body"> <p>The swimming pool is semi-Olympic of 25 mts X 10 mts. and its depth ranges from 1.25 a 2 meters and can be used for competitions, recreation, among others</p><br> <strong><center>Restrictions</center></strong><br> <ul> <li> Do not enter food to the pool.</li> <li> Do not enter pets.</li> <li> You must have the proper equipment.</li> <li> Shower before enter to the pool.</li> <li> Respect the schedule.</li> </ul><br> <center><strong>Photo Gallery</strong></center> <div class="thumbnail"> <img src="img/Piscina1.jpg" heigth='300' class="img-rounded" alt="Piscina"><br> <img src="img/Piscina2.jpg" heigth='300' class="img-rounded" alt="Piscina"><br> <img src="img/Piscina3.jpg" heigth='300' class="img-rounded" alt="Piscina"> </div> </div> </div> <footer> </footer> </body> </html><file_sep><?php session_start(); if (isset($_SESSION['tipo'])){ if ($_SESSION['tipo']!=1){ header('Location: index.php'); } }else{ header('Location: index.php'); } include_once 'conn.php'; require_once('/PasswordHash.php'); $co=true; // coincide contraseña $exito=false; //si da error la base $nada=true; //nada no entra a if if (isset($_POST['contrasena1'])) { if(strcmp ($_POST['contrasena1'], $_POST['contrasena2'])==0){ $exito=agregar(); $nada=false; }else { $co=false; $nada=false; } } ?> <!doctype html> <html lang='es'> <?php include 'head.php'; ?> <body role="document"> <?php include 'cabecera.php'; ?> <div class="container-fluid"> <div class="row"> <div class=" col-md-6 col-md-offset-3 "> <?php if ($co && $exito ) {?> <div class="alert alert-success"> <strong>Success!</strong> User Created </div> <?php }elseif (!$co) { ?> <div class="alert alert-danger"> <strong>Alert!</strong> Try again </div> <?php } elseif ($co && !$exito && !$nada) { ?> <div class="alert alert-danger"> <strong>¡Alert!</strong> Try again </div> <?php } ?> <div class="panel panel-default "> <div class="panel-heading"> <h3 class="panel-title"><b>Create New User</b></h3> </div> <div class="panel-body"> <form role="form" style="padding: 20px;" method="post" action="nuevoUsuario.php"> <div class="form-group"> <label for="tipo" class=" control-label">User Type</label> <select class="form-control" id="tipo" name="tipo" required> <option value="1">Administrator</option> <option value="2">Client</option> </select> </div> <div class="form-group has-feedback"> <label for="usuario" class=" control-label">User</label> <input type="text" class="form-control " id="usuario" name="usuario" placeholder="User" required > <div id="resusu"></div> </div> <div class="form-group has-feedback"> <label for="Password1" class=" control-label">Password</label> <input type="<PASSWORD>" class="form-control" id="Password1" name= "contrasena1" placeholder="<PASSWORD>" required> <input type="Password" class="form-control" id="Password2" name= "contrasena2" placeholder="Repeat Password" required> <span id="contval" class="glyphicon control-label"></span> </div> <div class="form-group has-feedback"> <label for="email" class=" control-label">E-Mail</label> <input type="email" class="form-control " id="email" name="email" placeholder="E-Mail" required > </div> <div class="client" hidden="true"> <div class="form-group has-feedback"> <label for="usuario" class=" control-label">Name</label> <input type="text" class="form-control " id="nombre" name="nombre" placeholder="Name" > </div> <div class="form-group has-feedback"> <label for="usuario" class=" control-label">Lastname</label> <input type="text" class="form-control " id="apellido" name="apellido" placeholder="Lastname" > </div> <div class="form-group has-feedback"> <label for="usuario" class=" control-label">DUI</label> <input type="text" class="form-control " id="dui" name="DUI" placeholder="DUI" maxlength="10"> </div> <div class="form-group has-feedback"> <label for="usuario" class=" control-label">Telephone</label> <input type="text" class="form-control " id="tel" name="telefono" placeholder="Telephone" maxlength="9"> </div> <div class="form-group has-feedback"> <label for="usuario" class=" control-label">Address</label> <input type="text" class="form-control " id="adress" name="direccion" placeholder="Address" > </div> <div class="form-group has-feedback"> <label for="usuario" class=" control-label">Date of Birth</label> <input type="text" class="form-control " id="fechanac" name="fecha_nac" placeholder="Date of Birth" > </div> <div class="form-group has-feedback"> <label for="usuario" class=" control-label">NIT</label> <input type="text" class="form-control " id="nit" name="NIT" placeholder="NIT" maxlength="17"> </div> <div class="form-group has-feedback"> <label for="usuario" class=" control-label">Date of Credential</label> <input type="text" class="form-control " id="fechamem" name="fecha_mem" placeholder="Date of Credential" > </div> </div> <button type="submit" class="btn btn-default">Create</button> </form> </div> </div> </div> </div> </div> <footer> </footer> </body> <?php function agregar() { $pass=$_POST['contrasena1']; $pass=create_hash($pass); //echo $password; try { $dbh =conectarbase(); // new PDO("mysql:host=" . $hostname . ";dbname=cssreservation", $username, $password); /*** echo a message saying we have connected ***/ //echo 'Connected to database'; $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); /*** prepare the SQL statement ***/ $stmt = $dbh->prepare("INSERT into usuario (usuario,contrasena,correo,tipo) values (:usuario,:contrasena,:correo,:tipo) "); $stmt->bindParam(':usuario', $_POST['usuario'], PDO::PARAM_STR, 10); $stmt->bindParam(':contrasena', $pass, PDO::PARAM_STR, 32); $stmt->bindParam(':correo', $_POST['email'], PDO::PARAM_STR, 32); $stmt->bindParam(':tipo', $_POST['tipo'], PDO::PARAM_INT); /*** execute the prepared statement ***/ $stmt->execute(); if (isset($_POST['DUI'])) { if ($_POST['DUI']!="") { $fecha=date("Y-m-d"); $stmt = $dbh->prepare("INSERT into cliente (nombre, apellido, DUI, telefono, direccion, fecha_nac, NIT, fecha_mem,usuario_idusuario, saldo, total) values (:nombre, :apellido, :dui, :tel, :adress, :fechanac, :nit, :fechamem,(select idusuario from usuario where usuario=:usuario), 100, 100) "); $stmt->bindParam(':nombre', $_POST['nombre'], PDO::PARAM_STR, 50); $stmt->bindParam(':apellido', $_POST['apellido'], PDO::PARAM_STR, 50); $stmt->bindParam(':dui', $_POST['DUI'], PDO::PARAM_STR, 10); $stmt->bindParam(':tel', $_POST['telefono'], PDO::PARAM_STR, 9); $stmt->bindParam(':adress', $_POST['direccion'], PDO::PARAM_STR, 100); $stmt->bindParam(':fechanac', $_POST['fecha_nac'], PDO::PARAM_STR, 10); $stmt->bindParam(':nit', $_POST['NIT'], PDO::PARAM_STR, 17); $stmt->bindParam(':fechamem', $fecha, PDO::PARAM_STR, 15); $stmt->bindParam(':usuario', $_POST['usuario'], PDO::PARAM_STR, 15); $stmt->execute(); } } $exito=true; /*** close the database connection ***/ $dbh = null; } catch(PDOException $e) { echo $e->getMessage(); $exito=false; } return $exito; } ?> <script> $(document).ready(function(){ $("#Password2,#Password1").keyup(function (){ //alert( "Handler for .keyup() called." ); var Password1=$("#<PASSWORD>").val(); var Password2=$("#Password2").val(); if (Password1 != Password2) { $("#contval").parent().addClass("has-error"); $("#contval").parent().removeClass("has-success"); $("#contval").addClass("glyphicon-remove-circle"); $("#contval").text("Passwords don't match"); $("#contval").removeClass(" glyphicon-ok-circle"); }else if(Password1 == "" || Password2== ""){ $("#contval").parent().removeClass("has-success has-error"); $("#contval").removeClass(" glyphicon-ok-circle glyphicon-remove-circle"); $("#contval").text(""); }else{ $("#contval").parent().addClass("has-success "); $("#contval").parent().removeClass("has-error"); $("#contval").text("Passwords match"); $("#contval").removeClass(" glyphicon-remove-circle"); $("#contval").addClass(" glyphicon-ok-circle"); } }); $("#usuario").change(function (){ if ($("#usuario").val()!="") { var parametros = {"usuario" : $("#usuario").val() }; $.ajax({ data: parametros, url: 'serv_usuario.php', type: 'post', beforeSend: function () { $("#resusu").html("Processing, wait please..."); }, success: function (response) { if (response=="si") { $("#resusu").parent().addClass("has-error"); $("#resusu").parent().removeClass("has-success"); $("#resusu").html("<span class='glyphicon glyphicon-remove form-control-feedback'></span>"); }else{ $("#resusu").parent().addClass("has-success"); $("#resusu").parent().removeClass("has-error"); $("#resusu").html("<span class='glyphicon glyphicon-ok form-control-feedback'></span>"); } } }); }else{ $("#resusu").parent().removeClass("has-error has-success"); $("#resusu").html(""); } }); }); </script> <script> $( "select" ).change(function () { var str = ""; $( "select option:selected" ).each(function() { str += $( this ).text(); }); if (str=="Client") { $( ".client" ).show(); $(".cliente div input").attr('required', ''); }else{ $( ".client" ).hide(); $(".cliente div input").removeAttr('required'); $(".cliente div input").val(""); } }); </script> <link rel="stylesheet" type="text/css" href="js/datetimepicker.css"/ > <script type="text/javascript" src="js/datetimepicker.js"></script> <script type="text/javascript"> //$(document).ready(function() { //$('#hinicio').clockpicker(); $('#fechanac').datetimepicker({value:'12-31-1996' ,lang:'en',maxDate:'1996/12/31',format:'m-d-Y',timepicker:false, mask:true}); $('#fechamem').datetimepicker({value: hoy() , minDate:0,lang:'en',format:'m-d-Y',timepicker:false, mask:true}); function hoy(){ var today = new Date(); var dd = today.getDate(); var mm = today.getMonth()+1; //January is 0! var yyyy = today.getFullYear(); if(dd<10) { dd='0'+dd } if(mm<10) { mm='0'+mm } today = yyyy+'-'+mm+'-'+dd; return today; } </script> </html><file_sep><?php session_start(); ?> <!doctype html> <html lang='es'> <?php include 'head.php'; ?> <body role="document"> <?php include 'cabecera.php'; ?> <div class="container-fluid col-md-6 col-md-offset-3"> <div class="panel panel-default"> <div class="panel-heading"> <center> <h3 class="panel-title"><strong>INFORMACIÓN GENERAL</strong></h3> </div> <div class="panel-body"> <p>Cada una de las canchas tiene un área de 15 metros de ancho X 25 metros de largo. </p><br> <strong><center>Restricciones</center></strong><br> <ul> <li> Sólo se admiten 5 jugadores por equipo.</li> <li> No se permite ingresar a la cancha con tacos.</li> <li> No ingresar comida a la cancha.</li> <li> Sólo se permiten utilizar tennis deportivos.</li> <li> Respetar el horario establecido</li> </ul><br> <center><strong>Galería de Imágenes</strong></center> <div class="thumbnail"> <img src="img/Canchas1.jpg" heigth='300' class="img-rounded" alt="Cancha Sintética"><br> <img src="img/Canchas2.jpg" heigth='300' class="img-rounded" alt="Cancha Sintética"> </div> </div> </div> <footer> </footer> </body> </html><file_sep> <?php include_once 'conn.php'; session_start(); $tr=""; try { $dbh = conectarbase(); /*** echo a message saying we have connected ***/ //echo 'Connected to database'; $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $sql="SELECT cliente.nombre as nombre, horario.fecha as fecha, inicio, fin, espacio.nombre as espacio FROM usuario join cliente on(idusuario=usuario_idusuario) join factura on(idcliente=cliente_idcliente) join reserva on(idfactura=factura_idfactura) join horario on(idhorario=horario_idhorario) join espacio on(idespacio=espacio_idespacio) WHERE usuario=:usuario" ; /*** prepare the SQL statement ***/ $usu=trim($_SESSION['usuario']); $stmt = $dbh->prepare($sql); $stmt->bindParam(':usuario', $usu, PDO::PARAM_STR, 30); /*** execute the prepared statement ***/ $stmt->execute(); $result = $stmt->fetchAll(); /*** close the database connection ***/ $dbh = null; foreach ($result as $row) { $hinicio = strtotime($row['inicio']); $hinicio = date("h:i:00 a", $hinicio); $hfin = strtotime($row['fin']); $hfin = date("h:i:00 a", $hfin); $tr.="<tr><td>".$row['nombre']."</td><td>".$row['fecha']."</td><td>".$hinicio."</td><td>".$hfin."</td><td>".$row['espacio']."</td></tr>"; } } catch(PDOException $e) { echo $e->getMessage(); $exito=false; } ?> <!doctype html> <html lang='es'> <?php include 'head.php'; ?> <body role="document"> <?php include 'cabecera.php'; ?> <div class="container-fluid"> <div class="panel panel-default" id="reporte"> <div class="panel-heading"> <h3 class="panel-title">REPORTS</h3> </div> <div class="panel-body"> <div class="page"> <div class="table-responsive"> <table class="table table-hover"> <thead> <tr> <th>Name</th> <th>Date</th> <th>Start Hour</th> <th>End Hour</th> <th>Area</th> </tr> </thead> <tbody> <?= $tr?> </tbody> </table> </div> <a href="javascript:window.print()" id="ocultar" onclick="hide();return false;">Print Report</a> </div> </div> </div> </div> <footer> <script type="text/javascript"> function hide(){ document.getElementById('ocultar').style.display = 'none'; javascript:window.print(); document.getElementById('ocultar').style.display = 'block'; } </script> </footer> </body> </html> <file_sep><?php session_start(); if (isset($_SESSION['tipo'])){ if ($_SESSION['tipo']!=1){ header('Location: index.php'); } }else{ header('Location: index.php'); } if (isset($_REQUEST['usuario'])) { /*** mysql hostname ***/ $hostname = 'localhost'; /*** mysql username ***/ $username = 'root'; /*** mysql password ***/ $password = ''; try { $dbh = new PDO("mysql:host=" . $hostname . ";dbname=cssreservation", $username, $password); /*** echo a message saying we have connected ***/ //echo 'Connected to database'; $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); /*** prepare the SQL statement ***/ $stmt = $dbh->prepare("DELETE FROM cliente WHERE usuario_idusuario=(SELECT idusuario FROM USUARIO WHERE usuario=:usuario);DELETE FROM usuario WHERE usuario=:usuario"); $stmt->bindParam(':usuario', $_REQUEST['usuario'], PDO::PARAM_STR, 10); /*** execute the prepared statement ***/ $stmt->execute(); /*** close the database connection ***/ $dbh = null; } catch(PDOException $e) { echo $e->getMessage(); } } ?> <!doctype html> <html lang='es'> <?php include 'head.php'; ?> <body role="document"> <?php include 'cabecera.php'; ?> <div class="container-fluid col-md-6 col-md-offset-3"> <div class="panel panel-default"> <div class="panel-heading"> <h3 class="panel-title"><b><i class="fa fa-users"></i> Mostrar Usuarios</b></h3> </div> <div class="panel-body"> <table class="table table-striped table-hover "> <thead> <tr> <th><i class="fa fa-user"></i> Usuario</th> <th><i class="fa fa-user-md"></i> Tipo</th> <th><i class="fa fa-at"></i> Correo</th> <th><i class="fa fa-pencil"></i> Modificar</th> <th><i class="fa fa-user-times"></i> Eliminar</th> <th><i class="fa fa-credit-card"></i> Saldo</th> </tr> </thead> <tbody> <?php //echo '<br /> <br /> <h1> ' . $_POST['usuario'] . '</h1>'; /*** mysql hostname ***/ $hostname = 'localhost'; /*** mysql username ***/ $username = 'root'; /*** mysql password ***/ $password = ''; try { $dbh = new PDO("mysql:host=" . $hostname . ";dbname=cssreservation", $username, $password); /*** echo a message saying we have connected ***/ //echo 'Connected to database'; $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); /*** prepare the SQL statement ***/ $stmt = $dbh->prepare("SELECT usuario,tipo,correo FROM usuario WHERE tipo!=1 "); /*** execute the prepared statement ***/ $stmt->execute(); /*** fetch the results ***/ $result = $stmt->fetchAll(); /*** loop of the results ***/ foreach ($result as $row) { ?> <tr> <td><?=$row ["usuario"]?></td><td><?=$row ["tipo"]==1?"Administrador":"Cliente"?></td> <td><?=$row ["correo"]?></td> <td><a class="btn btn-info" <?="href='modificarUsuario.php?usuario=".$row ["usuario"]."'"?>><i class="fa fa-pencil"></i></a></td> <td><a class="btn btn-danger" <?="href='mostrarUsuario.php?usuario=".$row ["usuario"]."'"?> onclick="return confirm('¿Está seguro?');"><i class="fa fa-user-times"></i></a></td> <td><a class="btn btn-success" <?="href='agregarsaldo.php?usuario=".$row ["usuario"]."'"?>><i class="fa fa-credit-card"></i></a></td> </tr> <?php } /*** close the database connection ***/ $dbh = null; } catch(PDOException $e) { echo $e->getMessage(); } ?> </tbody> </table> </div> </div> <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> <h4 class="modal-title" id="myModalLabel">Eliminar Usuario</h4> </div> <div class="modal-body"> ¿Está seguro de eliminar el usuario seleccionado? </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Cancelar</button> <button type="button" class="btn btn-danger">Eliminar</button> </div> </div> </div> </div> </div> <footer> </footer> </body> </html><file_sep><?php session_start(); require_once('/PasswordHash.php'); include_once 'conn.php'; if (isset($_SESSION['tipo'])){ if ($_SESSION['tipo']!=1){ header('Location: index.php'); } }else{ header('Location: index.php'); } $co=true; // coincide contraseña $exito=false; //si da error la base $nada=true; //nada no entra a if $R=false; if (isset($_REQUEST['contrasena1'])) { $R=modif(); } ?> <!doctype html> <html lang='es'> <?php include 'head.php'; ?> <body role="document"> <?php include 'cabecera.php'; ?> <div class="container-fluid"> <div class="row"> <div class=" col-md-6 col-md-offset-3 "> <?php if ($R) {?> <div class="alert alert-success"> <strong>¡Éxito!</strong> Contraseña modificada Exitosamente </div> <?php }elseif (!$co) { ?> <div class="alert alert-danger"> <strong>¡Alerta!</strong> Contraseñas no coinciden, vuelva a intentarlo </div> <?php } elseif ($co && !$exito && !$nada) { ?> <div class="alert alert-danger"> <strong>¡Alerta!</strong> No se ha podido crear usuario, intente con otro nombre </div> <?php } ?> <div class="panel panel-default "> <div class="panel-heading"><b>Cambiar Contraseña</b></div> <div class="panel-body"> <form role="form" style="padding: 20px;" method="post" action="modificarUsuario.php"> <div class="form-group has-feedback"> <label for="usuario" class=" control-label">Usuario: <?=$_REQUEST['usuario']?></label> <input type="hidden" class="form-control " id="usuario" name="usuario" value=<?="'".$_REQUEST['usuario']."'" ?> > <div id="resusu"></div> </div> <div class="form-group has-feedback"> <label for="Password1" class=" control-label">Nueva Contraseña</label> <input type="Password" class="form-control" id="Password1" name= "contrasena1" placeholder="<PASSWORD>" required> <input type="Password" class="form-control" id="Password2" name= "contrasena2" placeholder="<PASSWORD>ir <PASSWORD>" required> <span id="contval" class="glyphicon control-label"></span> </div> <input type="submit" id="enviar" class="btn btn-default" value='Cambiar' disabled></input> </form> </div> </div> </div> </div> </div> <footer> </footer> </body> <?php function modif() { $pass=$_POST['<PASSWORD>']; $pass=create_hash($pass); try { $dbh =conectarbase(); /*** echo a message saying we have connected ***/ //echo 'Connected to database'; $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); /*** prepare the SQL statement ***/ $stmt = $dbh->prepare("UPDATE usuario set contrasena= :pass where usuario= :usuario "); $stmt->bindParam(':usuario', $_REQUEST['usuario'], PDO::PARAM_STR, 10); $stmt->bindParam(':pass', $pass, PDO::PARAM_STR, 32); /*** execute the prepared statement ***/ $stmt->execute(); $exito=true; /*** close the database connection ***/ $dbh = null; } catch(PDOException $e) { //echo $e->getMessage(); $exito=false; } return $exito; } function buscar($usuario,$contra) { try { $dbh = conectarbase(); /*** echo a message saying we have connected ***/ //echo 'Connected to database'; $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); /*** prepare the SQL statement ***/ $stmt = $dbh->prepare("SELECT * from usuario where usuario=:usuario"); $stmt->bindParam(':usuario', $usuario, PDO::PARAM_STR, 10); /*** execute the prepared statement ***/ $stmt->execute(); $result = $stmt->fetchAll(); $existe=false; /*** loop of the results ***/ foreach ($result as $row) { if(strcmp($row['usuario'], $usuario)==0){ if (validate_password($contra, $row['contrasena'])) { $existe=true; $resultado=$existe; break; } } } /*** close the database connection ***/ $dbh = null; } catch(PDOException $e) { //echo $e->getMessage(); $exito=false; } return $resultado; }?> <script> $(document).ready(function(){ $("#Password2,#Password1").keyup(function (){ //alert( "Handler for .keyup() called." ); var Password1=$("#Password1").val(); var Password2=$("#Password2").val(); if (Password1 != Password2) { $("#contval").parent().addClass("has-error"); $("#contval").parent().removeClass("has-success"); $("#contval").addClass("glyphicon-remove-circle"); $("#contval").text("contraseñas no coinciden"); $("#contval").removeClass(" glyphicon-ok-circle"); $("#enviar").attr('disabled','disabled'); }else if(Password1 == "" || Password2== ""){ $("#contval").parent().removeClass("has-success has-error"); $("#contval").removeClass(" glyphicon-ok-circle glyphicon-remove-circle"); $("#contval").text(""); $("#enviar").attr('disabled','disabled'); }else{ $("#contval").parent().addClass("has-success "); $("#contval").parent().removeClass("has-error"); $("#contval").text("contraseñas coinciden"); $("#contval").removeClass(" glyphicon-remove-circle"); $("#contval").addClass(" glyphicon-ok-circle"); $("#enviar").removeAttr('disabled'); } }); }); </script> </html><file_sep><?php session_start(); ?> <!doctype html> <html lang='es'> <?php include 'head.php'; ?> <body role="document"> <?php include 'cabecera.php'; ?> <div class="container-fluid col-md-6 col-md-offset-3"> <div class="panel panel-default"> <div class="panel-heading"> <center> <h3 class="panel-title"><strong>GENERAL INFORMATION</strong></h3> </div> <div class="panel-body"> <p>Each of the fields has an area of 49.21 feet wide X 82.02 feet long.</p><br> <strong><center>Restrictions</center></strong><br> <ul> <li> Only 5 players are allowed per team.</li> <li> Not allowed to enter the field with cleats.</li> <li> Do not enter food to the field.</li> <li> Respect the schedule</li> </ul><br> <center><strong>Photo Gallery</strong></center> <div class="thumbnail"> <img src="img/Canchas1.jpg" heigth='300' class="img-rounded" alt="Cancha Sintética"><br> <img src="img/Canchas2.jpg" heigth='300' class="img-rounded" alt="Cancha Sintética"> </div> </div> </div> <footer> </footer> </body> </html><file_sep>-- phpMyAdmin SQL Dump -- version 4.0.4 -- http://www.phpmyadmin.net -- -- Servidor: localhost -- Tiempo de generación: 13-08-2014 a las 19:38:35 -- Versión del servidor: 5.6.12-log -- Versión de PHP: 5.4.12 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8 */; -- -- Base de datos: `cssreservation` -- CREATE DATABASE IF NOT EXISTS `cssreservation` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci; USE `cssreservation`; DELIMITER $$ -- -- Procedimientos -- CREATE DEFINER=`root`@`localhost` PROCEDURE `simpleproc`(OUT param1 INT) BEGIN SELECT COUNT(*) INTO param1 FROM t; END$$ DELIMITER ; -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `cliente` -- CREATE TABLE IF NOT EXISTS `cliente` ( `idcliente` int(11) NOT NULL AUTO_INCREMENT, `nombre` varchar(50) NOT NULL, `apellido` varchar(50) NOT NULL, `DUI` varchar(10) NOT NULL, `telefono` varchar(9) NOT NULL, `direccion` varchar(100) NOT NULL, `fecha_nac` date NOT NULL, `NIT` varchar(17) NOT NULL, `miembro` tinyint(1) DEFAULT '0', `saldo` float DEFAULT '0', `fecha_mem` date DEFAULT NULL, `usuario_idusuario` int(11) NOT NULL DEFAULT '0', `total` float DEFAULT '0', PRIMARY KEY (`idcliente`), UNIQUE KEY `DUI_UNIQUE` (`DUI`), UNIQUE KEY `NIT_UNIQUE` (`NIT`), KEY `fk_cliente_usuario1_idx` (`usuario_idusuario`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ; -- -- Volcado de datos para la tabla `cliente` -- INSERT INTO `cliente` (`idcliente`, `nombre`, `apellido`, `DUI`, `telefono`, `direccion`, `fecha_nac`, `NIT`, `miembro`, `saldo`, `fecha_mem`, `usuario_idusuario`, `total`) VALUES (1, 'asd', 'asd', 'asd', 'asd', 'asd', '2014-07-01', 'asd', 1, 200, '2014-07-01', 1, 200), (2, 'mario', 'ponce', '1', '123', 'sad', '2014-07-01', '1', 1, 300, '2014-07-01', 8, 300), (4, 'Carlos', 'Minero', '454544544', '2259-8989', 'ghfgh', '0000-00-00', '154545454', 0, 35, '2014-07-20', 9, 100), (5, 'Carlos', 'Minero', '22233456-8', '2345-6578', 'Los Alpes', '0000-00-00', '22222234566-666-6', 0, 70, '2014-07-22', 10, 100); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `espacio` -- CREATE TABLE IF NOT EXISTS `espacio` ( `idespacio` int(11) NOT NULL AUTO_INCREMENT, `nombre` varchar(45) NOT NULL, `costo` float NOT NULL DEFAULT '0', `imagen` varchar(45) DEFAULT NULL, `descripcion` varchar(45) DEFAULT NULL, PRIMARY KEY (`idespacio`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ; -- -- Volcado de datos para la tabla `espacio` -- INSERT INTO `espacio` (`idespacio`, `nombre`, `costo`, `imagen`, `descripcion`) VALUES (1, 'Soccer Fields', 15, NULL, NULL), (2, 'Theater', 50, NULL, NULL), (3, 'Swimming Pool', 15, NULL, NULL), (4, 'Church', 75, NULL, NULL); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `factura` -- CREATE TABLE IF NOT EXISTS `factura` ( `idfactura` int(11) NOT NULL AUTO_INCREMENT, `fecha` datetime NOT NULL, `total` float NOT NULL DEFAULT '0', `cliente_idcliente` int(11) NOT NULL, PRIMARY KEY (`idfactura`), KEY `fk_factura_cliente1_idx` (`cliente_idcliente`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=16 ; -- -- Volcado de datos para la tabla `factura` -- INSERT INTO `factura` (`idfactura`, `fecha`, `total`, `cliente_idcliente`) VALUES (10, '2014-07-20 23:31:08', 65, 4), (14, '2014-07-22 04:14:56', 15, 5), (15, '2014-07-22 04:15:10', 15, 5); -- -- Disparadores `factura` -- DROP TRIGGER IF EXISTS `factura_ADEL`; DELIMITER // CREATE TRIGGER `factura_ADEL` AFTER DELETE ON `factura` FOR EACH ROW begin update cliente set cliente.saldo=cliente.total-(select COALESCE(sum(factura.total), 0) from factura where factura.cliente_idcliente= old.cliente_idcliente) where cliente.idcliente= old.cliente_idcliente ; END // DELIMITER ; DROP TRIGGER IF EXISTS `factura_AUPD`; DELIMITER // CREATE TRIGGER `factura_AUPD` AFTER UPDATE ON `factura` FOR EACH ROW begin if new.total<>old.total then update cliente set cliente.saldo=cliente.total-(select COALESCE(sum(factura.total), 0) from factura where factura.cliente_idcliente= new.cliente_idcliente) where cliente.idcliente= new.cliente_idcliente ; END IF; END // DELIMITER ; -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `horario` -- CREATE TABLE IF NOT EXISTS `horario` ( `idhorario` int(11) NOT NULL AUTO_INCREMENT, `inicio` time NOT NULL, `fin` time NOT NULL, `espacio_idespacio` int(11) NOT NULL, `reservado` tinyint(1) NOT NULL DEFAULT '0', `fecha` date DEFAULT NULL, PRIMARY KEY (`idhorario`), KEY `fk_horario_espacio1_idx` (`espacio_idespacio`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=15 ; -- -- Volcado de datos para la tabla `horario` -- INSERT INTO `horario` (`idhorario`, `inicio`, `fin`, `espacio_idespacio`, `reservado`, `fecha`) VALUES (1, '07:00:00', '08:00:00', 1, 0, '2014-07-05'), (2, '11:00:00', '12:00:00', 2, 0, '2014-07-05'), (3, '08:00:00', '09:00:00', 1, 0, '2014-07-08'), (4, '08:00:00', '09:00:00', 1, 0, '2014-07-08'), (7, '09:00:00', '10:00:00', 2, 0, '2014-07-08'), (8, '10:00:00', '11:00:00', 1, 0, '2014-07-08'), (9, '17:35:00', '17:40:00', 2, 1, '2014-07-20'), (10, '17:40:00', '18:10:00', 2, 0, '2014-07-20'), (11, '17:30:00', '18:15:00', 1, 1, '2014-07-20'), (13, '21:55:00', '22:30:00', 1, 1, '2014-07-21'), (14, '21:55:00', '22:30:00', 1, 1, '2014-07-21'); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `reserva` -- CREATE TABLE IF NOT EXISTS `reserva` ( `idreserva` int(11) NOT NULL AUTO_INCREMENT, `factura_idfactura` int(11) NOT NULL, `horario_idhorario` int(11) NOT NULL, PRIMARY KEY (`idreserva`), KEY `fk_reserva_factura1_idx` (`factura_idfactura`), KEY `fk_reserva_horario1_idx` (`horario_idhorario`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=17 ; -- -- Volcado de datos para la tabla `reserva` -- INSERT INTO `reserva` (`idreserva`, `factura_idfactura`, `horario_idhorario`) VALUES (13, 10, 11), (14, 10, 9), (15, 14, 13), (16, 15, 14); -- -- Disparadores `reserva` -- DROP TRIGGER IF EXISTS `reserva_ADEL`; DELIMITER // CREATE TRIGGER `reserva_ADEL` AFTER DELETE ON `reserva` FOR EACH ROW begin update factura set total=(select COALESCE(sum(espacio.costo), 0) from reserva join horario on (horario.idhorario=reserva.horario_idhorario) join espacio on(espacio.idespacio=horario.espacio_idespacio) where reserva.factura_idfactura= OLD.factura_idfactura) where idfactura= OLD.factura_idfactura; update horario set reservado=false where horario.idhorario=old.horario_idhorario; end // DELIMITER ; DROP TRIGGER IF EXISTS `reserva_AINS`; DELIMITER // CREATE TRIGGER `reserva_AINS` AFTER INSERT ON `reserva` FOR EACH ROW begin update factura set total=(select COALESCE(sum(espacio.costo), 0)from reserva join horario on (horario.idhorario=reserva.horario_idhorario) join espacio on(espacio.idespacio=horario.espacio_idespacio) where reserva.factura_idfactura=new.factura_idfactura) where idfactura= new.factura_idfactura; update horario set reservado=true where horario.idhorario=new.horario_idhorario; end // DELIMITER ; -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `usuario` -- CREATE TABLE IF NOT EXISTS `usuario` ( `idusuario` int(11) NOT NULL AUTO_INCREMENT, `usuario` varchar(45) NOT NULL, `contrasena` varchar(102) NOT NULL, `correo` varchar(50) NOT NULL, `tipo` int(11) NOT NULL, PRIMARY KEY (`idusuario`), UNIQUE KEY `usuario_UNIQUE` (`usuario`), UNIQUE KEY `correo_UNIQUE` (`correo`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=11 ; -- -- Volcado de datos para la tabla `usuario` -- INSERT INTO `usuario` (`idusuario`, `usuario`, `contrasena`, `correo`, `tipo`) VALUES (1, 'asd', 'asd', 'asd', 1), (3, 'a', 'sha256:1000:Ad2MpXsFxda1DbwmfTY2iYDlZd3q9/F/:PGuFGBm56lsxZcKFsvC3EQhHm7KPn5LM', 'a@a', 1), (4, 'admin', 'sha256:1000:hJrtQfmHeI+Ss64Jih4cL3rjJCnJKueH:EKcjtJHgjuWDyEkV21v1x5jfhP92sJFM', '<EMAIL>', 1), (8, 'cliente', 'sha256:1000:3sw5y3soSV+nFFVY9LJEg29sw6GZyQbF:AJbrAQ2fRY4xfS6/2AMm9c7Mt6pzWOws', 'cliente@cliente', 2), (9, 'Charles', 'sha256:1000:3bJkYjbwkQmV2F90Mc4HBzsJR/iJ4AZc:Lnxc7Ch3clKghyuECx/f0pPJfIOIib+q', '<EMAIL>', 2), (10, 'Minero', 'sha256:1000:tga9QapoIy2sd73nsr2WDV1jircMWy5Q:TgpgDVCqy2STV3mQ+c75nWL/h7m5pqFe', '<EMAIL>', 2); -- -- Restricciones para tablas volcadas -- -- -- Filtros para la tabla `cliente` -- ALTER TABLE `cliente` ADD CONSTRAINT `fk_cliente_usuario1` FOREIGN KEY (`usuario_idusuario`) REFERENCES `usuario` (`idusuario`) ON DELETE NO ACTION ON UPDATE NO ACTION; -- -- Filtros para la tabla `factura` -- ALTER TABLE `factura` ADD CONSTRAINT `fk_factura_cliente1` FOREIGN KEY (`cliente_idcliente`) REFERENCES `cliente` (`idcliente`) ON DELETE NO ACTION ON UPDATE NO ACTION; -- -- Filtros para la tabla `horario` -- ALTER TABLE `horario` ADD CONSTRAINT `fk_horario_espacio1` FOREIGN KEY (`espacio_idespacio`) REFERENCES `espacio` (`idespacio`) ON DELETE NO ACTION ON UPDATE NO ACTION; -- -- Filtros para la tabla `reserva` -- ALTER TABLE `reserva` ADD CONSTRAINT `fk_reserva_factura1` FOREIGN KEY (`factura_idfactura`) REFERENCES `factura` (`idfactura`) ON DELETE NO ACTION ON UPDATE NO ACTION, ADD CONSTRAINT `fk_reserva_horario1` FOREIGN KEY (`horario_idhorario`) REFERENCES `horario` (`idhorario`) ON DELETE NO ACTION ON UPDATE NO ACTION; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; <file_sep><html> <head> <title>has</title> </head> <body> <?php echo "'".trim(" auwewe ")."'<br>"; echo "'".rtrim(" auwewe ")."'<br>"; echo "'".ltrim(" auwewe ")."'<br>"; $dato=$_REQUEST["dato"]; echo "dato enviado: ".$dato."<br>"; if( $dato==1) { echo "El valor enviado fue 1 "; }elseif ($dato==2) { ?> <ul><li>vlor1</li> <li>valor2</li> </ul> <?php }else{ echo "valor no coincide"; } $v[0]=0; echo "<br>"; for ($i=0; $i < $dato ; $i++) { echo "iteracion: ".$i."<BR>"; $v[$i]=$i+$i; } for ($j=0; $j < $i ; $j++) { echo " v[".$j."]=".$v[$j]."<br>"; } $p["nombre"]="minero"; echo "nombre: ".$p["nombre"]; ?> </body> </html> <file_sep><?php include_once 'conn.php'; class Reserva{ private $idhorario; private $costo=0; private $inicio; private $fin; private $fecha; private $lugar; public function __construct($id){ $this->idhorario=$id; $r=horario(); $this->inicio=$r['inicio']; $this->fin=$r['fin']; $this->fecha=$r['fecha']; $this->costo=$r['costo']; $this->lugar=$r['nombre']; } public function horario(){ $respuesta; try { $dbh = conectarbase(); /*** echo a message saying we have connected ***/ //echo 'Connected to database'; $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $sql="SELECT inicio,fin,fecha,costo,nombre FROM horario,espacio WHERE idespacio=espacio_idespacio and idhorario='".$this->idhorario."'"; /*** prepare the SQL statement ***/ $stmt = $dbh->prepare(sql); /*** execute the prepared statement ***/ $stmt->execute(); $result = $stmt->fetch(PDO::FETCH_ASSOC); /*** close the database connection ***/ $dbh = null; return $result; } catch(PDOException $e) { //echo $e->getMessage(); $exito=false; } return NULL; } }<file_sep><!doctype html> <html lang="es"> <head> <meta charset="UTF-8"> <title>Document</title> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="css/bootstrap.css"> <link href="css/bootstrap-theme.css" rel="stylesheet"> </head> <body role="document"> <?php include 'cabecera.php' ; ?> <div class="jumbotron"> <h1>Bienvenido</h1> <p>...</p> <p><a class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal" role="button">Reserva CSSC</a></p> <button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal"> Launch demo modal </button> <!-- Modal --> <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> <h4 class="modal-title" id="myModalLabel">Modal PRUEBA</h4> </div> <div class="modal-body"> Lorem ipsum dolor sit amet, consectetur adipisicing elit. Itaque, eligendi, nam consectetur repellat odit asperiores accusamus beatae reiciendis dolor quas eveniet excepturi sit aliquid mollitia autem animi fugit ut harum. </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Save changes</button> </div> </div> </div> </div> </div> <div class="container-fluid"> <div class="row-fluid"> <div class="col-md-4">...asas</div> <div class="col-md-8">...asdr3</div> </div> </div> <div class="panel panel-default " style="margin: 20px;"> <div class="panel-heading">Datos de Usuario</div> <div class="panel-body "> <form action="#" type="post" role="form"> <div class="input-group"> <span class="input-group-addon">Nombre</span> <input type="text" class="form-control" placeholder="Nombre"> <span class="input-group-addon">$</span> <span class="input-group-addon">Nombre</span> </div> <input type="text" class="form-control"> <input type="submit" class="btn btn-primary" value="enviar"> <br><br><br><br><br><br><br><br> <div class="row-fluid"> <div class="col-xs-12 col-sm-6 col-md-3" ><p><h1>prueba</h1> ipsum dolor sit amet, consectetur adipisicing elit. Tenetur, ab, magni, totam officia dolor possimus repellendus vero ducimus explicabo obcaecati unde soluta reprehenderit vel similique quibusdam deleniti eaque ipsa commodi.</p></div> <div class="col-xs-12 col-sm-6 col-md-3"><p><h1>prueba</h1> ipsum dolor sit amet, consectetur adipisicing elit. Tenetur, ab, magni, totam officia dolor possimus repellendus vero ducimus explicabo obcaecati unde soluta reprehenderit vel similique quibusdam deleniti eaque ipsa commodi.</p></div> <div class="col-xs-12 col-sm-6 col-md-3"><p><h1>prueba</h1> ipsum dolor sit amet, consectetur adipisicing elit. Tenetur, ab, magni, totam officia dolor possimus repellendus vero ducimus explicabo obcaecati unde soluta reprehenderit vel similique quibusdam deleniti eaque ipsa commodi.</p></div> <div class="col-xs-12 col-sm-6 col-md-3"><p><h1>prueba</h1> ipsum dolor sit amet, consectetur adipisicing elit. Tenetur, ab, magni, totam officia dolor possimus repellendus vero ducimus explicabo obcaecati unde soluta reprehenderit vel similique quibusdam deleniti eaque ipsa commodi.</p></div> </div> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tenetur, ab, magni, totam officia dolor possimus repellendus vero ducimus explicabo obcaecati unde soluta reprehenderit vel similique quibusdam deleniti eaque ipsa commodi.</p> </form> </div> </div> <script src="js/jquery-1.11.0.js"></script> <script src="js/bootstrap.js"></script> </body> </html><file_sep><?php require_once('../common/connector/scheduler_connector.php'); include ('../common/config.php'); $scheduler = new schedulerConnector($res, $dbtype); $scheduler->render_table("horario","idhorario","inicio,fin,espacio_idespacio"); ?><file_sep><?php // "<NAME>" ; session_start(); require_once('/PasswordHash.php'); include 'conn.php'; $saldo=0; $noexiste=false; if (isset($_POST['usuario'])) { $usuario= trim($_POST['usuario']); $pass= $_POST['contrasena']; try { $dbh = conectarbase(); /*** echo a message saying we have connected ***/ //echo 'Connected to database'; $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); /*** prepare the SQL statement ***/ $stmt = $dbh->prepare("SELECT usuario,contrasena,tipo,idcliente FROM usuario left join cliente on idusuario=usuario_idusuario WHERE usuario = :usuario"); $stmt->bindParam(':usuario', $usuario, PDO::PARAM_STR, 10); /*** execute the prepared statement ***/ $stmt->execute(); /*** fetch the results ***/ $result = $stmt->fetchAll(); $noexiste=true; /*** loop of the results ***/ foreach ($result as $row) { if(strcmp($row['usuario'], $usuario)==0){ if (validate_password($pass, $row['contrasena'])) { $_SESSION['usuario'] = $row['usuario']; $_SESSION['tipo'] = $row['tipo']; if (isset($row['idcliente'])) { $_SESSION['idcliente'] = $row['idcliente']; } $noexiste=false; break; } } } /*** close the database connection ***/ $dbh = null; } catch(PDOException $e) { echo $e->getMessage(); } } ?> <!doctype html> <html lang='es'> <?php include 'head.php'; ?> <body role="document"> <?php include 'cabecera.php'; ?> <div class="container-fluid"> <?php if (isset($_SESSION['idcliente'])) { $cliente=null; try { $dbh = conectarbase(); /*** echo a message saying we have connected ***/ //echo 'Connected to database'; $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); /*** prepare the SQL statement ***/ $id=trim($_SESSION['idcliente']); $stmt = $dbh->prepare("SELECT * FROM cliente WHERE idcliente ='$id'"); /*** execute the prepared statement ***/ $stmt->execute(); /*** fetch the results ***/ $cliente = $stmt->fetch(); $noexiste=true; /*** close the database connection ***/ $dbh = null; } catch(PDOException $e) { echo $e->getMessage(); } echo "<center><FONT SIZE=5 COLOR=yellow><h2>¡BIENVENIDO/A! SESIÓN <br> INICIADA CON ÉXITO: </h2><h3>".$_SESSION['usuario']."</h3> <br> SU SALDO DISPONIBLE ES: $ ".$cliente['saldo']."</FONT></center>"; ?> <center><img src="img/crs.png" width='300' alt=""></center> <?php } else if(isset($_SESSION['usuario'])){ echo "<FONT ALIGN=center SIZE=5 COLOR=yellow><h2>¡BIENVENIDO/A! SESIÓN <br> INICIADA CON ÉXITO: </h2><h3>".$_SESSION['usuario']."</h3> <br></FONT>"; ?> <center><img src="img/crs.png" width='300' alt=""></center> <?php }else { // echo "Acceso Restringido"; ?> <div class="row"> <div class="col-md-6 col-md-offset-3"> <?php if ($noexiste) { ?> <div class="alert alert-dismissible alert-danger"> <button type="button" class="close" data-dismiss="alert">×</button> <strong>¡Alerta!</strong> El usuario o contraseña están incorrectas. </div> <?php } ?> <div class="panel panel-default "> <div class="panel-heading"><b>Iniciar Sesión</b></div> <div class="panel-body"> <form role="form" style="padding: 20px;" method="post" action="home.php"> <div class="form-group"> <label for="usuario" class=" control-label">Usuario</label> <input type="text" class="form-control " id="usuario" name="usuario" placeholder="Usuario" required > </div> <div class="form-group"> <label for="Password" class=" control-label">Contraseña</label> <input type="Password" class="form-control" id="Password" name= "contrasena" placeholder="Contraseña" required> </div> <button type="submit" class="btn btn-default">Ingresar</button> </form> </div> </div> </div> </div> <?php } ?> </div> <footer> </footer> </body> </html><file_sep><?php function conectarbase(){ /*** mysql hostname ***/ $hostname = 'localhost'; $port=3036; /*** mysql username ***/ $username = 'root'; $port= /*** mysql password ***/ $password = ''; $base='cssreservation'; try { $dbh = new PDO("mysql:host=$hostname;port=$port;dbname=$base", $username, $password); } catch(PDOException $e) { echo $e->getMessage(); $dbh=null; } return $dbh; } ?> <file_sep><?php // "hola mundo" ; session_start(); ?> <!doctype html> <html lang='es'> <head> <meta charset='utf-8'> <title>CSSC RESERVATION</title> <link rel="stylesheet" type="text/css" href="estilo.css"> </head> <body> <header> <div class="cabecera"> <h1>CSSC RESERVATION</h1> </div> </header> <nav> <ul> <li> <a href="index.php">INICIO</a></li> <li> <a href="prueba.php?dato=hola+adads">ESPACIOS Y HORARIOS</a></li> <li>¿CÓMO OBTENER TU MEMBRESÍA?</li> <?php if(isset($_SESSION['usuario'])){ ?> <li><a href="loggin.php">Cerrar SESIÓN</a> </li> </ul> </nav> <p>Has iniciado sesion: <?= $_SESSION['usuario']?> </p> <p><a href='cerrar.php'>Cerrar Sesion</a></p> <?php }else { ?> <img src="images.jpg" > <form method = "post" action="INDEX.php"> usuario <input type = "text" placeholder="Ingrese su usuario" name = "usuario" required> <br> contraseña <input type = "password" placeholder="Ingrese su contraseña" name = "contrasena" required> <br> <input type = "submit"> </form> <?php } ?> <footer> </footer> </body> </html><file_sep><?php session_start(); ?> <!doctype html> <html lang='es'> <?php include 'head.php'; ?> <body role="document"> <?php include 'cabecera.php'; ?> <div class="container-fluid col-md-6 col-md-offset-3"> <div class="panel panel-default"> <div class="panel-heading"> <center> <h3 class="panel-title"><strong>GENERAL INFORMATION</strong></h3> </div> <div class="panel-body"> <p> The Church has a capacity of 1000 persons, can be used for: first communion, matrimony, among others.</p><br> <strong><center>Restrictions</center></strong><br> <ul> <li> Do not enter food to the church</li> <li> Maintain the respect.</li> <li> Do not enter pets.</li> <li> Do not smoke or drink alcoholic beverages.</li> <li> Do not damage the area.</li> <li> Keep the cell phone in silence during the mass.</li> </ul><br> <center><strong>Photo Gallery</strong></center> <div class="thumbnail"> <img src="img/Iglesia1.jpg" heigth='300' class="img-rounded" alt="Iglesia"><br> <img src="img/Iglesia2.jpg" heigth='300' class="img-rounded" alt="Iglesia"><br> <img src="img/Iglesia3.jpg" heigth='300' class="img-rounded" alt="Iglesia"> </div> </div> </div> <footer> </footer> </body> </html><file_sep><?php session_start(); if (isset($_SESSION['tipo'])){ if ($_SESSION['tipo']!=1){ header('Location: index.php'); } }else{ header('Location: index.php'); } include_once 'conn.php'; require_once('/PasswordHash.php'); $co=true; // coincide contraseña $exito=false; //si da error la base $nada=true; //nada no entra a if if (isset($_POST['contrasena1'])) { if(strcmp ($_POST['contrasena1'], $_POST['contrasena2'])==0){ $exito=agregar(); $nada=false; }else { $co=false; $nada=false; } } ?> <!doctype html> <html lang='es'> <?php include 'head.php'; ?> <body role="document"> <?php include 'cabecera.php'; ?> <div class="container-fluid"> <div class="row"> <div class=" col-md-6 col-md-offset-3 "> <?php if ($co && $exito ) {?> <div class="alert alert-success"> <strong>¡Éxito!</strong> Usuario Creado Satisfactoriamente </div> <?php }elseif (!$co) { ?> <div class="alert alert-danger"> <strong>¡Alerta!</strong> Contraseñas no coinciden, vuelva a intentarlo </div> <?php } elseif ($co && !$exito && !$nada) { ?> <div class="alert alert-danger"> <strong>¡Alerta!</strong> No se ha podido crear usuario, intente con otro nombre </div> <?php } ?> <div class="panel panel-default "> <div class="panel-heading"> <h3 class="panel-title"><b>Crear Nuevo Usuario</b></h3> </div> <div class="panel-body"> <form role="form" style="padding: 20px;" method="post" action="nuevoUsuario.php"> <div class="form-group"> <label for="tipo" class=" control-label">Tipo de Usuario</label> <select class="form-control" id="tipo" name="tipo" required> <option value="1">Administrador</option> <option value="2">Cliente</option> </select> </div> <div class="form-group has-feedback"> <label for="usuario" class=" control-label">Usuario</label> <input type="text" class="form-control " id="usuario" name="usuario" placeholder="Usuario" required > <div id="resusu"></div> </div> <div class="form-group has-feedback"> <label for="Password1" class=" control-label">Contraseña</label> <input type="<PASSWORD>" class="form-control" id="Password1" name= "contrasena1" placeholder="<PASSWORD>" required> <input type="<PASSWORD>" class="form-control" id="Password2" name= "contrasena2" placeholder="<PASSWORD>" required> <span id="contval" class="glyphicon control-label"></span> </div> <div class="form-group has-feedback"> <label for="email" class=" control-label">Correo Electrónico</label> <input type="email" class="form-control " id="email" name="email" placeholder="Correo Electrónico" required > </div> <div class="cliente" hidden="true"> <div class="form-group has-feedback"> <label for="usuario" class=" control-label">Nombre</label> <input type="text" class="form-control " id="nombre" name="nombre" placeholder="Nombre" > </div> <div class="form-group has-feedback"> <label for="usuario" class=" control-label">Apellido</label> <input type="text" class="form-control " id="apellido" name="apellido" placeholder="Apellido" > </div> <div class="form-group has-feedback"> <label for="usuario" class=" control-label">DUI</label> <input type="text" class="form-control " id="dui" name="DUI" placeholder="DUI" maxlength="10"> </div> <div class="form-group has-feedback"> <label for="usuario" class=" control-label">Teléfono</label> <input type="text" class="form-control " id="tel" name="telefono" placeholder="Teléfono" maxlength="9"> </div> <div class="form-group has-feedback"> <label for="usuario" class=" control-label">Dirección</label> <input type="text" class="form-control " id="adress" name="direccion" placeholder="Dirección" > </div> <div class="form-group has-feedback"> <label for="usuario" class=" control-label">Fecha de Nacimiento</label> <input type="text" class="form-control " readonly="readonly" id="fechanac" name="fecha_nac" placeholder="Fecha de Nacimiento" > </div> <div class="form-group has-feedback"> <label for="usuario" class=" control-label">NIT</label> <input type="text" class="form-control " id="nit" name="NIT" placeholder="NIT" maxlength="17"> </div> <div class="form-group has-feedback"> <label for="usuario" class=" control-label">Fecha de Membresía</label> <input type="text" class="form-control" disabled="" id="fechamem" name="fecha_mem" placeholder="Fecha de Membresía" > </div> </div> <input type="submit" id="enviar" class="btn btn-default" value='Crear'> </form> </div> </div> </div> </div> </div> <footer> </footer> </body> <?php function agregar() { $pass=$_POST['contrasena1']; $pass=create_hash($pass); //echo $password; try { $dbh =conectarbase(); // new PDO("mysql:host=" . $hostname . ";dbname=cssreservation", $username, $password); /*** echo a message saying we have connected ***/ //echo 'Connected to database'; $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); /*** prepare the SQL statement ***/ $stmt = $dbh->prepare("INSERT into usuario (usuario,contrasena,correo,tipo) values (:usuario,:contrasena,:correo,:tipo) "); $stmt->bindParam(':usuario', $_POST['usuario'], PDO::PARAM_STR, 10); $stmt->bindParam(':contrasena', $pass, PDO::PARAM_STR, 32); $stmt->bindParam(':correo', $_POST['email'], PDO::PARAM_STR, 32); $stmt->bindParam(':tipo', $_POST['tipo'], PDO::PARAM_INT); /*** execute the prepared statement ***/ $stmt->execute(); if (isset($_POST['DUI'])) { if ($_POST['DUI']!="") { $fecha=date("Y-m-d"); $stmt = $dbh->prepare("INSERT into cliente (nombre, apellido, DUI, telefono, direccion, fecha_nac, NIT, fecha_mem,usuario_idusuario, saldo, total) values (:nombre, :apellido, :dui, :tel, :adress, :fechanac, :nit, :fechamem,(select idusuario from usuario where usuario=:usuario), 100, 100) "); $stmt->bindParam(':nombre', $_POST['nombre'], PDO::PARAM_STR, 50); $stmt->bindParam(':apellido', $_POST['apellido'], PDO::PARAM_STR, 50); $stmt->bindParam(':dui', $_POST['DUI'], PDO::PARAM_STR, 10); $stmt->bindParam(':tel', $_POST['telefono'], PDO::PARAM_STR, 9); $stmt->bindParam(':adress', $_POST['direccion'], PDO::PARAM_STR, 100); $stmt->bindParam(':fechanac', $_POST['fecha_nac'], PDO::PARAM_STR, 10); $stmt->bindParam(':nit', $_POST['NIT'], PDO::PARAM_STR, 17); $stmt->bindParam(':fechamem', $fecha, PDO::PARAM_STR, 15); $stmt->bindParam(':usuario', $_POST['usuario'], PDO::PARAM_STR, 15); $stmt->execute(); } } $exito=true; /*** close the database connection ***/ $dbh = null; } catch(PDOException $e) { echo $e->getMessage(); $exito=false; } return $exito; } ?> <script> $(document).ready(function(){ $("#Password2,#Password1").keyup(function (){ //alert( "Handler for .keyup() called." ); var Password1=$("#Password1").val(); var Password2=$("#Password2").val(); if (Password1 != Password2) { $("#contval").parent().addClass("has-error"); $("#contval").parent().removeClass("has-success"); $("#contval").addClass("glyphicon-remove-circle"); $("#contval").text("Contraseñas no Coinciden"); $("#contval").removeClass(" glyphicon-ok-circle"); boton(); }else if(Password1 == "" || Password2== ""){ $("#contval").parent().removeClass("has-success has-error"); $("#contval").removeClass(" glyphicon-ok-circle glyphicon-remove-circle"); $("#contval").text(""); }else{ $("#contval").parent().addClass("has-success "); $("#contval").parent().removeClass("has-error"); $("#contval").text("Contraseñas coinciden"); $("#contval").removeClass(" glyphicon-remove-circle"); $("#contval").addClass(" glyphicon-ok-circle"); boton(); } }); $("#usuario").change(function (){ if ($("#usuario").val()!="") { var parametros = {"usuario" : $("#usuario").val() }; $.ajax({ data: parametros, url: 'serv_usuario.php', type: 'post', beforeSend: function () { $("#resusu").html("Procesando, espere por favor..."); }, success: function (response) { if (response=="si") { $("#resusu").parent().addClass("has-error"); $("#resusu").parent().removeClass("has-success"); $("#resusu").html("El usuario existe. Elija otro"); boton(); }else{ $("#resusu").parent().addClass("has-success"); $("#resusu").parent().removeClass("has-error"); $("#resusu").html("El usuario no existe."); boton(); } } }); }else{ $("#resusu").parent().removeClass("has-error has-success"); $("#resusu").html(""); } }); function boton() { activo=true; if ($("#resusu").parent().hasClass("has-error")) { activo=false; } if ($("#contval").parent().hasClass("has-error")) { activo=false; } if (activo) { $("#enviar").removeAttr('disabled'); }else{ $("#enviar").attr('disabled','disabled'); } } }); </script> <script> $( "select" ).change(function () { var str = ""; $( "select option:selected" ).each(function() { str += $( this ).text(); }); if (str=="Cliente") { $( ".cliente" ).show(); $(".cliente div input").attr('required', ''); }else{ $( ".cliente" ).hide(); $(".cliente div input").removeAttr('required'); $(".cliente div input").val(""); } }); </script> <link rel="stylesheet" type="text/css" href="js/datetimepicker.css"/ > <script type="text/javascript" src="js/jquery.maskedinput.js"></script> <script type="text/javascript" src="js/datetimepicker.js"></script> <script type="text/javascript"> //$(document).ready(function() { //$('#hinicio').clockpicker(); $('#fechanac').datetimepicker({value:'1996-12-31' ,lang:'es',maxDate:'1996/12/31',format:'Y-m-d',timepicker:false, mask:true}); $('#fechamem').datetimepicker({value: hoy(), minDate:0,lang:'es',format:'Y-m-d',timepicker:false, mask:true}); $("#dui").mask("99999999-9"); $("#tel").mask("9999-9999"); $("#nit").mask("9999-999999-999-9"); function hoy(){ var today = new Date(); var dd = today.getDate(); var mm = today.getMonth()+1; //January is 0! var yyyy = today.getFullYear(); if(dd<10) { dd='0'+dd } if(mm<10) { mm='0'+mm } today = yyyy+'-'+mm+'-'+dd; return today; } </script> </html><file_sep><?php session_start(); ?> <!doctype html> <html lang='es'> <?php include 'head.php'; ?> <body role="document"> <?php include 'cabecera.php'; ?> <div class="container-fluid"> <div class="panel panel-default"> <div class="panel-body"> <div class="col-sm-12 col-md-3 "> <div class="thumbnail"> <img src="img/Canchas2.jpg" heigth='300' class="img-rounded" alt="canchas"> <div class="caption"> <h3>Soccer Fields</h3> <p align="justify"> Soccer Fields for 5 people, for tournaments and friendly matches.<br><br><b>Cost:</b> $15 per 45 minutes. </p> <br/> <p> <a href="agregarCarrito.php?espacio=1" class="btn btn-warning">Schedule</a> <a href="infcanchas.php" class="btn btn-default">Description</a> </p> </div> </div> </div> <div class="col-sm-12 col-md-3"> <div class="thumbnail"> <img src="img/Teatro1.jpg" heigth='300' class="img-rounded" alt="Teatro"> <div class="caption"> <h3>Theater</h3> <p align="justify"> Theater for events such as graduations, celebrations, plays, cultural events, among others.<br><br><b>Cost:</b> $50 per hour. </p> <p> <a href="agregarCarrito.php?espacio=2" class="btn btn-warning">Schedule</a> <a href="infteatro.php" class="btn btn-default">Description</a> </p> </div> </div> </div> <div class="col-sm-12 col-md-3"> <div class="thumbnail"> <img src="img/Piscina3.jpg" heigth='300' class="img-rounded" alt="Piscina"> <div class="caption"> <h3>Swimming Pool</h3> <p align="justify"> Semi-Olympic pool for competitions, fun and others.<br><br><b>Cost:</b> $15 per hour. </p> <br/> <p> <a href="agregarCarrito.php?espacio=3" class="btn btn-warning">Schedule</a> <a href="infpiscina.php" class="btn btn-default">Description</a> </p> </div> </div> </div> <div class="col-sm-12 col-md-3"> <div class="thumbnail"> <img src="img/Iglesia3.jpg" heigth='300' class="img-rounded" alt="Iglesia"> <div class="caption"> <h3>Church</h3> <p align="justify"> Church for baptism, matrimony, confirmation, among others.<br><br><b>Cost:</b> $75 per hour. </p> <br/> <p> <a href="agregarCarrito.php?espacio=4" class="btn btn-warning">Schedule</a> <a href="infiglesia.php" class="btn btn-default">Description</a> </p> </div> </div> </div> </div> </div> </div> </div> <footer> </footer> </body> </html><file_sep><?php session_start(); ?> <!doctype html> <html lang='es'> <?php include 'head.php'; ?> <body role="document"> <?php include 'cabecera.php'; ?> <div class="container-fluid"> </div> <footer> </footer> </body> </html><file_sep> <?php include_once 'conn.php'; include_once 'carrito.php'; session_start(); if (!isset($_SESSION['carrito'])) { $_SESSION['carrito']=serialize(new Carrito()); } $carrito=unserialize($_SESSION['carrito']); if (isset($_REQUEST['id'])) { $carrito->add($_REQUEST['id']); $_SESSION['carrito']=serialize($carrito); } if (isset($_REQUEST['quitar'])) { $carrito->delete($_REQUEST['quitar']); $_SESSION['carrito']=serialize($carrito); } function saldo(){ $respuesta; try { $dbh = conectarbase(); /*** echo a message saying we have connected ***/ //echo 'Connected to database'; $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $sql="SELECT saldo FROM cliente join usuario on(idusuario=usuario_idusuario) WHERE usuario='".$_SESSION['usuario']."'"; /*** prepare the SQL statement ***/ $stmt = $dbh->prepare($sql); /*** execute the prepared statement ***/ $stmt->execute(); $result = $stmt->fetch(PDO::FETCH_ASSOC); /*** close the database connection ***/ $dbh = null; return $result['saldo']; } catch(PDOException $e) { //echo $e->getMessage(); $exito=false; } return NULL; } $saldo=saldo(); $total=$carrito->total; $restante= $saldo-$total; $desactivado= $restante <0?"disabled":""; ?> <!doctype html> <html lang='es'> <?php include 'head.php'; ?> <body role="document"> <?php include 'cabecera.php'; ?> <div class="container-fluid col-md-6 col-md-offset-3"> <div class="panel panel-default"> <div class="panel-heading"> <h3> <center>Reservar</center></h3> </div> <div class="panel-body"> <div class='col-md-6'> <?php echo "Saldo Anterior: $saldo<BR/>Total: $total <BR/>Saldo Restante:$restante<BR/> <form action='reservar.php' method='post'> <input type='hidden' name='reservar' value='true' /> <input class='btn btn-info' type='submit' $desactivado /> </form>"; $tabla=$carrito->tabla(); echo $tabla; ?> <a href="areas.php" class="btn btn-warning" >Volver</a><BR/> </div></div></div></div> <footer> <link rel="stylesheet" type="text/css" href="js/datetimepicker.css"/ > <script type="text/javascript" src="js/datetimepicker.js"></script> <script type="text/javascript"> $(document).ready(function() { $("a.quitar").click(function() { if (confirm("¿Está seguro de quitar la reserva?") == true) { } else { return false; } }); }); </script> </footer> </body> </html> <?php function sumardia($fe){ $fe=strtotime('+1 day', strtotime($fe)); $fe=date("Y-m-d",$fe); return $fe; } ?> <file_sep><?php session_start(); ?> <!doctype html> <html lang='es'> <?php include 'head.php'; ?> <body role="document"> <?php include 'cabecera.php'; ?> <div class="container-fluid"> <div class="panel panel-default"> <div class="panel-body"> <div class="col-sm-12 col-md-3 "> <div class="thumbnail"> <img src="img/Canchas2.jpg" heigth='300' class="img-rounded" alt="canchas"> <div class="caption"> <h3>Canchas</h3> <p align="justify"> Canchas sintéticas de fútbol 5 para encuentros deportivos, torneos y amistosos.<br><br><b>Costo:</b> $15 por 45 minutos. </p> <p> <a href="agregarCarrito.php?espacio=1" class="btn btn-warning">Ver Horarios</a> </p> <p> <a href="infcanchas.php" class="btn btn-default">Descripción</a> </p> </div> </div> </div> <div class="col-sm-12 col-md-3"> <div class="thumbnail"> <img src="img/Teatro1.jpg" heigth='300' class="img-rounded" alt="Teatro"> <div class="caption"> <h3>Teatro</h3> <p align="justify"> Teatro para eventos como graduaciones, celebraciones, obras teatrales, eventos culturales, entre otros.<br><br><b>Costo:</b> $50 por 1 hora. </p> <p> <a href="agregarCarrito.php?espacio=2" class="btn btn-warning">Ver Horarios</a> </p> <p> <a href="infteatro.php" class="btn btn-default">Descripción</a> </p> </div> </div> </div> <div class="col-sm-12 col-md-3"> <div class="thumbnail"> <img src="img/Piscina3.jpg" heigth='300' class="img-rounded" alt="Piscina"> <div class="caption"> <h3>Piscina</h3> <p align="justify"> Piscina semi-olímpica para competencias, diversión, entre otros. <br><br><b>Costo:</b> $15 por 1 hora. </p> <br/> <p> <a href="agregarCarrito.php?espacio=3" class="btn btn-warning">Ver Horarios</a> </p> <a href="infpiscina.php" class="btn btn-default">Descripción</a> </p> </div> </div> </div> <div class="col-sm-12 col-md-3"> <div class="thumbnail"> <img src="img/Iglesia3.jpg" heigth='300' class="img-rounded" alt="Iglesia"> <div class="caption"> <h3>Iglesia</h3> <p align="justify"> Iglesia para bautismo, matrimonio, confirmación, novenas, entre otros. <br><br><b>Costo:</b> $75 por 1 hora. </p> <br/> <p> <a href="agregarCarrito.php?espacio=4" class="btn btn-warning">Ver Horarios</a> <p> </p> <a href="infiglesia.php" class="btn btn-default">Descripción</a> </p> </div> </div> </div> </div> </div> </div> </div> <footer> </footer> </body> </html><file_sep><?php session_start(); ?> <!doctype html> <html lang='es'> <?php include 'head.php'; ?> <body role="document"> <?php include 'cabecera.php'; ?> <div class="container-fluid"> <div class="panel panel-default"> <div class="panel-heading"> <h3 class="panel-title"><b><center>VER REPORTES</center></b></h3> </div> <div class="panel-body"> <div class="col-sm-12 col-md-3 "> <div class="thumbnail"> <div class="caption"> <h3><center>Usuario</center></h3><br> <p> <center><a href="reportes.php?modo=repusuarioes" class="btn btn-warning">Usuario</a></center><br> </p> </div> </div> </div> <div class="col-sm-12 col-md-3"> <div class="thumbnail"> <div class="caption"> <h3><center>Cliente</center></h3><br> <p> <center><a href="reportes.php?modo=repclientees" class="btn btn-warning">Cliente</a></center><br> </p> </div> </div> </div> <div class="col-sm-12 col-md-3"> <div class="thumbnail"> <div class="caption"> <h3><center>Reservas</center></h3><br> <p> <center><a href="reportes.php?modo=represerves" class="btn btn-warning">Reservas</a></center><br> </p> </div> </div> </div> <div class="col-sm-12 col-md-3"> <div class="thumbnail"> <div class="caption"> <h3><center>Áreas</center></h3> <p> <center><a href="reportes.php?modo=repcanchaes" class="btn btn-warning">Canchas</a> <a href="reportes.php?modo=repteatroes" class="btn btn-warning">Teatro</a></center><br> <center><a href="reportes.php?modo=reppiscinaes" class="btn btn-warning">Piscina</a> <a href="reportes.php?modo=repiglesiaes" class="btn btn-warning">Iglesia</a></center> </p> </div> </div> </div> </div> </div> </div> </div> <footer> </footer> </body> </html><file_sep><?php session_start(); if (isset($_SESSION['tipo'])){ if ($_SESSION['tipo']!=1){ header('Location: index.php'); } }else{ header('Location: index.php'); } include_once 'conn.php'; if (isset($_POST['monto'])) { try { $dbh = conectarbase(); /*** echo a message saying we have connected ***/ //echo 'Connected to database'; $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); /*** prepare the SQL statement ***/ $stmt = $dbh->prepare("UPDATE cliente set total= total+ :monto,saldo= saldo+ :monto where usuario_idusuario= (select idusuario from usuario where usuario=:usuario) "); $stmt->bindParam(':monto', $_POST['monto'], PDO::PARAM_STR, 10); $stmt->bindParam(':usuario', $_POST['usuario'], PDO::PARAM_STR, 10); /*** execute the prepared statement ***/ $stmt->execute(); $exito=true; /*** close the database connection ***/ $dbh = null; } catch(PDOException $e) { echo $e->getMessage(); $exito=false; } } ?> <!doctype html> <html lang='es'> <?php include 'head.php'; ?> <body role="document"> <?php include 'cabecera.php'; ?> <div class="row"> <div class=" col-md-5 col-md-offset-3 "> <div class="panel panel-default "> <div class="panel-heading"><b>Add Balance</b></div> <div class="panel-body"> <form action='agregarsaldo.php' method="post"> Amount: <div class="input-group col-lg-6 " > <span class="input-group-addon">$</span> <input type="number" min="1" max="90000000" value="1" name='monto' class="form-control"> <span class="input-group-addon">.00</span> </div> <br> <input type="text" name='usuario' value=<?="'".$_REQUEST['usuario']."'" ?> hidden> <input id="toptop" type="submit" class="btn btn-default"> </form> </div> </div> </div> </div> <footer> </footer> </body> </html><file_sep><!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <?php /*** mysql hostname ***/ $hostname = 'localhost'; /*** mysql username ***/ $username = 'root'; /*** mysql password ***/ $password = ''; try { $dbh = new PDO("mysql:host=".$hostname.";dbname=cssreservation", $username, $password); /*** echo a message saying we have connected ***/ echo 'Connected to database'; /*** The SQL SELECT statement ***/ /*** set the error reporting attribute ***/ $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); /*** some variables ***/ /* $animal_id = 6; $animal_name = 'bruce';*/ $id = 2; /*** prepare the SQL statement ***/ $stmt = $dbh->prepare("SELECT * FROM usuario "); //$stmt = $dbh->prepare("SELECT * FROM usuario WHERE idusuario = :id "); /*** bind the paramaters ***/ //$stmt->bindParam(':id', $id, PDO::PARAM_INT); // $stmt->bindParam(':animal_name', $animal_name, PDO::PARAM_STR, 5); /*** execute the prepared statement ***/ $stmt->execute(); /*** fetch the results ***/ $result = $stmt->fetchAll(); /*** loop of the results ***/ foreach ($result as $row) { echo $row['idusuario'] . '<br />'; echo $row['usuario'] . '<br />'; echo $row['contrasena'] . '<br />'; echo $row['correo']; } /*** close the database connection ***/ $dbh = null; } catch(PDOException $e) { echo $e->getMessage(); } ?> </body> </html> <file_sep><?php require "connsql.php"; require "fpdf17/fpdf.php"; if(isset($_GET['modo'])){ $modo = $_GET['modo']; function repclientees(){ class PDF extends FPDF{} $pdf=new PDF ('P', 'mm', 'Letter'); $pdf->SetMargins(8, 10); $pdf->AliasNbPages(); $pdf->AddPage(); $query = mysql_query("SELECT * FROM cliente"); $pdf->Image("img/letras.png"); $pdf->SetFont("Arial", "b", 12); $pdf->Cell(0, 19, utf8_decode("REPORTES CLIENTES"), 0, 1,'C'); $x =$pdf->GetX(); $y =$pdf->GetY(); $pdf-> SetTextColor(255, 255, 255); $pdf->SetFont("Arial", "b", 10); $pdf->MultiCell(10, 5, utf8_decode("ID"), 0, 1, 'L',0); $pdf->SetXY($x + 10, $y); $pdf->MultiCell(35, 5, utf8_decode("NOMBRE"), 0, 1, 'L',0); $pdf->SetXY($x + 45, $y); $pdf->MultiCell(35, 5, utf8_decode("APELLIDO"), 0, 1, 'L',0); $pdf->SetXY($x + 80, $y); $pdf->MultiCell(30, 5, utf8_decode("DUI"), 0, 1, 'L',0); $pdf->SetXY($x + 110, $y); $pdf->MultiCell(35, 5, utf8_decode("TELEFONO"), 0, 1, 'L',0); $pdf->SetXY($x + 145, $y); $pdf->MultiCell(40, 5, utf8_decode("NIT"), 0, 1, 'L',0); $pdf->SetXY($x + 185, $y); $pdf->MultiCell(20, 5, utf8_decode("SALDO"), 0, 1, 'L',0); $pdf->SetXY($x + 205, $y); $pdf->Ln(); while($row = mysql_fetch_row($query)){ $id = $row['0']; $nombre= $row['1']; $apellido = $row['2']; $dui = $row['3']; $telefono = $row['4']; $nit = $row['7']; $saldo = "$ ".$row['9']; $x =$pdf->GetX(); $y =$pdf->GetY(); $pdf-> SetFillColor(255, 255, 255); $pdf-> SetTextColor(0, 0, 0); $pdf->SetFont("Arial", "b", 9); $pdf->MultiCell(10, 5, utf8_decode($id), 1, 1, 'L',0); $pdf->SetXY($x + 10, $y); $pdf->MultiCell(35, 5, utf8_decode($nombre), 1, 1, 'L',0); $pdf->SetXY($x + 45, $y); $pdf->MultiCell(35, 5, utf8_decode($apellido), 1, 1, 'L',0); $pdf->SetXY($x + 80, $y); $pdf->MultiCell(30, 5, utf8_decode($dui), 1, 1, 'L',0); $pdf->SetXY($x + 110, $y); $pdf->MultiCell(35, 5, utf8_decode($telefono), 1, 1, 'L',0); $pdf->SetXY($x + 145, $y); $pdf->MultiCell(40, 5, utf8_decode($nit), 1, 1, 'L',0); $pdf->SetXY($x + 185, $y); $pdf->MultiCell(20, 5, utf8_decode($saldo), 1, 1, 'L',0); $pdf->SetXY($x + 205, $y); $pdf->Ln(); } $pdf->Output(); } function repclientein(){ class PDF extends FPDF{} $pdf=new PDF ('P', 'mm', 'Letter'); $pdf->SetMargins(8, 10); $pdf->AliasNbPages(); $pdf->AddPage(); $query = mysql_query("SELECT * FROM cliente"); $pdf->Image("img/letras.png"); $pdf->SetFont("Arial", "b", 12); $pdf->Cell(0, 19, utf8_decode("CLIENT REPORTS"), 0, 1,'C'); $x =$pdf->GetX(); $y =$pdf->GetY(); $pdf-> SetTextColor(255, 255, 255); $pdf->SetFont("Arial", "b", 10); $pdf->MultiCell(10, 5, utf8_decode("ID"), 0, 1, 'L',0); $pdf->SetXY($x + 10, $y); $pdf->MultiCell(35, 5, utf8_decode("NAME"), 0, 1, 'L',0); $pdf->SetXY($x + 45, $y); $pdf->MultiCell(35, 5, utf8_decode("LASTNAME"), 0, 1, 'L',0); $pdf->SetXY($x + 80, $y); $pdf->MultiCell(30, 5, utf8_decode("DUI"), 0, 1, 'L',0); $pdf->SetXY($x + 110, $y); $pdf->MultiCell(35, 5, utf8_decode("TELEPHONE"), 0, 1, 'L',0); $pdf->SetXY($x + 145, $y); $pdf->MultiCell(40, 5, utf8_decode("NIT"), 0, 1, 'L',0); $pdf->SetXY($x + 185, $y); $pdf->MultiCell(20, 5, utf8_decode("BALANCE"), 0, 1, 'L',0); $pdf->SetXY($x + 205, $y); $pdf->Ln(); while($row = mysql_fetch_row($query)){ $id = $row['0']; $nombre= $row['1']; $apellido = $row['2']; $dui = $row['3']; $telefono = $row['4']; $nit = $row['7']; $saldo = "$ ".$row['9']; $x =$pdf->GetX(); $y =$pdf->GetY(); $pdf-> SetFillColor(255, 255, 255); $pdf-> SetTextColor(0, 0, 0); $pdf->SetFont("Arial", "b", 9); $pdf->MultiCell(10, 5, utf8_decode($id), 1, 1, 'L',0); $pdf->SetXY($x + 10, $y); $pdf->MultiCell(35, 5, utf8_decode($nombre), 1, 1, 'L',0); $pdf->SetXY($x + 45, $y); $pdf->MultiCell(35, 5, utf8_decode($apellido), 1, 1, 'L',0); $pdf->SetXY($x + 80, $y); $pdf->MultiCell(30, 5, utf8_decode($dui), 1, 1, 'L',0); $pdf->SetXY($x + 110, $y); $pdf->MultiCell(35, 5, utf8_decode($telefono), 1, 1, 'L',0); $pdf->SetXY($x + 145, $y); $pdf->MultiCell(40, 5, utf8_decode($nit), 1, 1, 'L',0); $pdf->SetXY($x + 185, $y); $pdf->MultiCell(20, 5, utf8_decode($saldo), 1, 1, 'L',0); $pdf->SetXY($x + 205, $y); $pdf->Ln(); } $pdf->Output(); } function repusuarioes(){ class PDF extends FPDF{} $pdf=new PDF ('P', 'mm', 'Letter'); $pdf->SetMargins(8, 10); $pdf->AliasNbPages(); $pdf->AddPage(); $query = mysql_query("SELECT usuario.idusuario, usuario.usuario, usuario.correo, usuario.tipo, cliente.nombre, cliente.apellido, cliente.saldo FROM usuario INNER JOIN cliente ON usuario.idusuario = cliente.usuario_idusuario"); $pdf->Image("img/letras.png"); $pdf->SetFont("Arial", "b", 12); $pdf->Cell(0, 19, utf8_decode("REPORTES USUARIO"), 0, 1,'C'); $x =$pdf->GetX(); $y =$pdf->GetY(); $pdf-> SetTextColor(255, 255, 255); $pdf->SetFont("Arial", "b", 10); $pdf->MultiCell(10, 5, utf8_decode("ID"), 0, 1, 'L',0); $pdf->SetXY($x + 10, $y); $pdf->MultiCell(35, 5, utf8_decode("USUARIO"), 0, 1, 'L',0); $pdf->SetXY($x + 45, $y); $pdf->MultiCell(45, 5, utf8_decode("CORREO"), 0, 1, 'L',0); $pdf->SetXY($x + 90, $y); $pdf->MultiCell(15, 5, utf8_decode("TIPO"), 0, 1, 'L',0); $pdf->SetXY($x + 105, $y); $pdf->MultiCell(35, 5, utf8_decode("NOMBRE"), 0, 1, 'L',0); $pdf->SetXY($x + 140, $y); $pdf->MultiCell(35, 5, utf8_decode("APELLIDO"), 0, 1, 'L',0); $pdf->SetXY($x + 175, $y); $pdf->MultiCell(15, 5, utf8_decode("Saldo"), 0, 1, 'L',0); $pdf->SetXY($x + 190, $y); $pdf->Ln(); while($row = mysql_fetch_row($query)){ $id = $row['0']; $usuario= $row['1']; $correo = $row['2']; $tipo = $row['3']; $nombre = $row['4']; $apellido = $row['5']; $saldo= "$ " .$row['6']; $x =$pdf->GetX(); $y =$pdf->GetY(); $pdf-> SetFillColor(255, 255, 255); $pdf-> SetTextColor(0, 0, 0); $pdf->SetFont("Arial", "b", 9); $pdf->MultiCell(10, 5, utf8_decode($id), 1, 1, 'L',0); $pdf->SetXY($x + 10, $y); $pdf->MultiCell(35, 5, utf8_decode($usuario), 1, 1, 'L',0); $pdf->SetXY($x + 45, $y); $pdf->MultiCell(45, 5, utf8_decode($correo), 1, 1, 'L',0); $pdf->SetXY($x + 90, $y); $pdf->MultiCell(15, 5, utf8_decode($tipo), 1, 1, 'L',0); $pdf->SetXY($x + 105, $y); $pdf->MultiCell(35, 5, utf8_decode($nombre), 1, 1, 'L',0); $pdf->SetXY($x + 140, $y); $pdf->MultiCell(35, 5, utf8_decode($apellido), 1, 1, 'L',0); $pdf->SetXY($x + 175, $y); $pdf->MultiCell(15, 5, utf8_decode($saldo), 1, 1, 'L',0); $pdf->SetXY($x + 190, $y); $pdf->Ln(); } $pdf->Output(); } function repusuarioin(){ class PDF extends FPDF{} $pdf=new PDF ('P', 'mm', 'Letter'); $pdf->SetMargins(8, 10); $pdf->AliasNbPages(); $pdf->AddPage(); $query = mysql_query("SELECT usuario.idusuario, usuario.usuario, usuario.correo, usuario.tipo, cliente.nombre, cliente.apellido, cliente.saldo FROM usuario INNER JOIN cliente ON usuario.idusuario = cliente.usuario_idusuario"); $pdf->Image("img/letras.png"); $pdf->SetFont("Arial", "b", 12); $pdf->Cell(0, 19, utf8_decode("USER REPORTS"), 0, 1,'C'); $x =$pdf->GetX(); $y =$pdf->GetY(); $pdf-> SetTextColor(255, 255, 255); $pdf->SetFont("Arial", "b", 10); $pdf->MultiCell(10, 5, utf8_decode("ID"), 0, 1, 'L',0); $pdf->SetXY($x + 10, $y); $pdf->MultiCell(35, 5, utf8_decode("USER"), 0, 1, 'L',0); $pdf->SetXY($x + 45, $y); $pdf->MultiCell(45, 5, utf8_decode("E-MAIL"), 0, 1, 'L',0); $pdf->SetXY($x + 90, $y); $pdf->MultiCell(15, 5, utf8_decode("TYPE"), 0, 1, 'L',0); $pdf->SetXY($x + 105, $y); $pdf->MultiCell(35, 5, utf8_decode("NAME"), 0, 1, 'L',0); $pdf->SetXY($x + 140, $y); $pdf->MultiCell(35, 5, utf8_decode("LASTNAME"), 0, 1, 'L',0); $pdf->SetXY($x + 175, $y); $pdf->MultiCell(20, 5, utf8_decode("BALANCE"), 0, 1, 'L',0); $pdf->SetXY($x + 200, $y); $pdf->Ln(); while($row = mysql_fetch_row($query)){ $id = $row['0']; $usuario= $row['1']; $correo = $row['2']; $tipo = $row['3']; $nombre = $row['4']; $apellido = $row['5']; $saldo= "$ " .$row['6']; $x =$pdf->GetX(); $y =$pdf->GetY(); $pdf-> SetFillColor(255, 255, 255); $pdf-> SetTextColor(0, 0, 0); $pdf->SetFont("Arial", "b", 9); $pdf->MultiCell(10, 5, utf8_decode($id), 1, 1, 'L',0); $pdf->SetXY($x + 10, $y); $pdf->MultiCell(35, 5, utf8_decode($usuario), 1, 1, 'L',0); $pdf->SetXY($x + 45, $y); $pdf->MultiCell(45, 5, utf8_decode($correo), 1, 1, 'L',0); $pdf->SetXY($x + 90, $y); $pdf->MultiCell(15, 5, utf8_decode($tipo), 1, 1, 'L',0); $pdf->SetXY($x + 105, $y); $pdf->MultiCell(35, 5, utf8_decode($nombre), 1, 1, 'L',0); $pdf->SetXY($x + 140, $y); $pdf->MultiCell(35, 5, utf8_decode($apellido), 1, 1, 'L',0); $pdf->SetXY($x + 175, $y); $pdf->MultiCell(20, 5, utf8_decode($saldo), 1, 1, 'L',0); $pdf->SetXY($x + 200, $y); $pdf->Ln(); } $pdf->Output(); } function represerves(){ class PDF extends FPDF{} $pdf=new PDF ('P', 'mm', 'Letter'); $pdf->SetMargins(8, 10); $pdf->AliasNbPages(); $pdf->AddPage(); $query = mysql_query("SELECT cliente.nombre, horario.fecha, horario.inicio, horario.fin, espacio.nombre, factura.total FROM cliente INNER JOIN factura on idcliente=cliente_idcliente INNER JOIN reserva on idfactura=factura_idfactura INNER JOIN horario on idhorario=horario_idhorario INNER JOIN espacio on idespacio=espacio_idespacio"); $pdf->Image("img/letras.png"); $pdf->SetFont("Arial", "b", 12); $pdf->Cell(0, 19, utf8_decode("REPORTES RESERVA"), 0, 1,'C'); $x =$pdf->GetX(); $y =$pdf->GetY(); $pdf-> SetTextColor(255, 255, 255); $pdf->SetFont("Arial", "b", 10); $pdf->MultiCell(35, 5, utf8_decode("NOMBRE"), 0, 1, 'L',0); $pdf->SetXY($x + 35, $y); $pdf->MultiCell(25, 5, utf8_decode("FECHA"), 0, 1, 'L',0); $pdf->SetXY($x + 60, $y); $pdf->MultiCell(30, 5, utf8_decode("HORA INICIO"), 0, 1, 'L',0); $pdf->SetXY($x + 90, $y); $pdf->MultiCell(30, 5, utf8_decode("HORA FIN"), 0, 1, 'L',0); $pdf->SetXY($x + 120, $y); $pdf->MultiCell(50, 5, utf8_decode("ÁREA"), 0, 1, 'L',0); $pdf->SetXY($x + 170, $y); $pdf->MultiCell(35, 5, utf8_decode("COSTO TOTAL"), 0, 1, 'L',0); $pdf->SetXY($x + 205, $y); $pdf->Ln(); while($row = mysql_fetch_row($query)){ $nombre = $row['0']; $fecha = $row['1']; $horaini= $row['2']; $horafini = $row['3']; $area = $row['4']; $total = "$ ". $row['5']; $x =$pdf->GetX(); $y =$pdf->GetY(); $pdf-> SetFillColor(255, 255, 255); $pdf-> SetTextColor(0, 0, 0); $pdf->SetFont("Arial", "b", 9); $pdf->MultiCell(35, 5, utf8_decode($nombre), 1, 1, 'L',0); $pdf->SetXY($x + 35, $y); $pdf->MultiCell(25, 5, utf8_decode($fecha), 1, 1, 'L',0); $pdf->SetXY($x + 60, $y); $pdf->MultiCell(30, 5, utf8_decode($horaini), 1, 1, 'L',0); $pdf->SetXY($x + 90, $y); $pdf->MultiCell(30, 5, utf8_decode($horafini), 1, 1, 'L',0); $pdf->SetXY($x + 120, $y); $pdf->MultiCell(50, 5, utf8_decode($area), 1, 1, 'L',0); $pdf->SetXY($x + 170, $y); $pdf->MultiCell(35, 5, utf8_decode($total), 1, 1, 'L',0); $pdf->SetXY($x + 205, $y); $pdf->Ln(); } $pdf->Output(); } function represervin(){ class PDF extends FPDF{} $pdf=new PDF ('P', 'mm', 'Letter'); $pdf->SetMargins(8, 10); $pdf->AliasNbPages(); $pdf->AddPage(); $query = mysql_query("SELECT cliente.nombre, horario.fecha, horario.inicio, horario.fin, espacio.nombre, factura.total FROM cliente INNER JOIN factura on idcliente=cliente_idcliente INNER JOIN reserva on idfactura=factura_idfactura INNER JOIN horario on idhorario=horario_idhorario INNER JOIN espacio on idespacio=espacio_idespacio"); $pdf->Image("img/letras.png"); $pdf->SetFont("Arial", "b", 12); $pdf->Cell(0, 19, utf8_decode("RESERVATION REPORTS"), 0, 1,'C'); $x =$pdf->GetX(); $y =$pdf->GetY(); $pdf-> SetTextColor(255, 255, 255); $pdf->SetFont("Arial", "b", 10); $pdf->MultiCell(35, 5, utf8_decode("NAME"), 0, 1, 'L',0); $pdf->SetXY($x + 35, $y); $pdf->MultiCell(25, 5, utf8_decode("DATE"), 0, 1, 'L',0); $pdf->SetXY($x + 60, $y); $pdf->MultiCell(30, 5, utf8_decode("START HOUR"), 0, 1, 'L',0); $pdf->SetXY($x + 90, $y); $pdf->MultiCell(30, 5, utf8_decode("END HOUR"), 0, 1, 'L',0); $pdf->SetXY($x + 120, $y); $pdf->MultiCell(50, 5, utf8_decode("AREA"), 0, 1, 'L',0); $pdf->SetXY($x + 170, $y); $pdf->MultiCell(35, 5, utf8_decode("TOTAL"), 0, 1, 'L',0); $pdf->SetXY($x + 205, $y); $pdf->Ln(); while($row = mysql_fetch_row($query)){ $nombre = $row['0']; $fecha = $row['1']; $horaini= $row['2']; $horafini = $row['3']; $area = $row['4']; $total = "$ " .$row['5']; $x =$pdf->GetX(); $y =$pdf->GetY(); $pdf-> SetFillColor(255, 255, 255); $pdf-> SetTextColor(0, 0, 0); $pdf->SetFont("Arial", "b", 9); $pdf->MultiCell(35, 5, utf8_decode($nombre), 1, 1, 'L',0); $pdf->SetXY($x + 35, $y); $pdf->MultiCell(25, 5, utf8_decode($fecha), 1, 1, 'L',0); $pdf->SetXY($x + 60, $y); $pdf->MultiCell(30, 5, utf8_decode($horaini), 1, 1, 'L',0); $pdf->SetXY($x + 90, $y); $pdf->MultiCell(30, 5, utf8_decode($horafini), 1, 1, 'L',0); $pdf->SetXY($x + 120, $y); $pdf->MultiCell(50, 5, utf8_decode($area), 1, 1, 'L',0); $pdf->SetXY($x + 170, $y); $pdf->MultiCell(35, 5, utf8_decode($total), 1, 1, 'L',0); $pdf->SetXY($x + 205, $y); $pdf->Ln(); } $pdf->Output(); } function repcanchaes(){ class PDF extends FPDF{} $pdf=new PDF ('P', 'mm', 'Letter'); $pdf->SetMargins(8, 10); $pdf->AliasNbPages(); $pdf->AddPage(); $query = mysql_query("SELECT cliente.nombre, horario.fecha, horario.inicio, horario.fin, espacio.nombre, factura.total FROM cliente INNER JOIN factura on idcliente=cliente_idcliente INNER JOIN reserva on idfactura=factura_idfactura INNER JOIN horario on idhorario=horario_idhorario INNER JOIN espacio on idespacio=espacio_idespacio WHERE espacio.idespacio=1"); $pdf->Image("img/letras.png"); $pdf->SetFont("Arial", "b", 12); $pdf->Cell(0, 19, utf8_decode("REPORTES CANCHAS SINTETICAS"), 0, 1,'C'); $x =$pdf->GetX(); $y =$pdf->GetY(); $pdf-> SetTextColor(255, 255, 255); $pdf->SetFont("Arial", "b", 10); $pdf->MultiCell(35, 5, utf8_decode("NOMBRE"), 0, 1, 'L',0); $pdf->SetXY($x + 35, $y); $pdf->MultiCell(25, 5, utf8_decode("FECHA"), 0, 1, 'L',0); $pdf->SetXY($x + 60, $y); $pdf->MultiCell(30, 5, utf8_decode("HORA INICIO"), 0, 1, 'L',0); $pdf->SetXY($x + 90, $y); $pdf->MultiCell(30, 5, utf8_decode("HORA FIN"), 0, 1, 'L',0); $pdf->SetXY($x + 120, $y); $pdf->MultiCell(50, 5, utf8_decode("ÁREA"), 0, 1, 'L',0); $pdf->SetXY($x + 170, $y); $pdf->MultiCell(35, 5, utf8_decode("COSTO TOTAL"), 0, 1, 'L',0); $pdf->SetXY($x + 205, $y); $pdf->Ln(); while($row = mysql_fetch_row($query)){ $nombre = $row['0']; $fecha = $row['1']; $horaini= $row['2']; $horafini = $row['3']; $area = $row['4']; $total = "$ ". $row['5']; $x =$pdf->GetX(); $y =$pdf->GetY(); $pdf-> SetFillColor(255, 255, 255); $pdf-> SetTextColor(0, 0, 0); $pdf->SetFont("Arial", "b", 9); $pdf->MultiCell(35, 5, utf8_decode($nombre), 1, 1, 'L',0); $pdf->SetXY($x + 35, $y); $pdf->MultiCell(25, 5, utf8_decode($fecha), 1, 1, 'L',0); $pdf->SetXY($x + 60, $y); $pdf->MultiCell(30, 5, utf8_decode($horaini), 1, 1, 'L',0); $pdf->SetXY($x + 90, $y); $pdf->MultiCell(30, 5, utf8_decode($horafini), 1, 1, 'L',0); $pdf->SetXY($x + 120, $y); $pdf->MultiCell(50, 5, utf8_decode($area), 1, 1, 'L',0); $pdf->SetXY($x + 170, $y); $pdf->MultiCell(35, 5, utf8_decode($total), 1, 1, 'L',0); $pdf->SetXY($x + 205, $y); $pdf->Ln(); } $pdf->Output(); } function repcanchain(){ class PDF extends FPDF{} $pdf=new PDF ('P', 'mm', 'Letter'); $pdf->SetMargins(8, 10); $pdf->AliasNbPages(); $pdf->AddPage(); $query = mysql_query("SELECT cliente.nombre, horario.fecha, horario.inicio, horario.fin, espacio.nombre, factura.total FROM cliente INNER JOIN factura on idcliente=cliente_idcliente INNER JOIN reserva on idfactura=factura_idfactura INNER JOIN horario on idhorario=horario_idhorario INNER JOIN espacio on idespacio=espacio_idespacio WHERE espacio.idespacio=1"); $pdf->Image("img/letras.png"); $pdf->SetFont("Arial", "b", 12); $pdf->Cell(0, 19, utf8_decode("SOCCER FIELD REPORTS"), 0, 1,'C'); $x =$pdf->GetX(); $y =$pdf->GetY(); $pdf-> SetTextColor(255, 255, 255); $pdf->SetFont("Arial", "b", 10); $pdf->MultiCell(35, 5, utf8_decode("NAME"), 0, 1, 'L',0); $pdf->SetXY($x + 35, $y); $pdf->MultiCell(25, 5, utf8_decode("DATE"), 0, 1, 'L',0); $pdf->SetXY($x + 60, $y); $pdf->MultiCell(30, 5, utf8_decode("START HOUR"), 0, 1, 'L',0); $pdf->SetXY($x + 90, $y); $pdf->MultiCell(30, 5, utf8_decode("END HOUR"), 0, 1, 'L',0); $pdf->SetXY($x + 120, $y); $pdf->MultiCell(50, 5, utf8_decode("AREA"), 0, 1, 'L',0); $pdf->SetXY($x + 170, $y); $pdf->MultiCell(35, 5, utf8_decode("TOTAL"), 0, 1, 'L',0); $pdf->SetXY($x + 205, $y); $pdf->Ln(); while($row = mysql_fetch_row($query)){ $nombre = $row['0']; $fecha = $row['1']; $horaini= $row['2']; $horafini = $row['3']; $area = $row['4']; $total = "$ " .$row['5']; $x =$pdf->GetX(); $y =$pdf->GetY(); $pdf-> SetFillColor(255, 255, 255); $pdf-> SetTextColor(0, 0, 0); $pdf->SetFont("Arial", "b", 9); $pdf->MultiCell(35, 5, utf8_decode($nombre), 1, 1, 'L',0); $pdf->SetXY($x + 35, $y); $pdf->MultiCell(25, 5, utf8_decode($fecha), 1, 1, 'L',0); $pdf->SetXY($x + 60, $y); $pdf->MultiCell(30, 5, utf8_decode($horaini), 1, 1, 'L',0); $pdf->SetXY($x + 90, $y); $pdf->MultiCell(30, 5, utf8_decode($horafini), 1, 1, 'L',0); $pdf->SetXY($x + 120, $y); $pdf->MultiCell(50, 5, utf8_decode($area), 1, 1, 'L',0); $pdf->SetXY($x + 170, $y); $pdf->MultiCell(35, 5, utf8_decode($total), 1, 1, 'L',0); $pdf->SetXY($x + 205, $y); $pdf->Ln(); } $pdf->Output(); } function repteatroes(){ class PDF extends FPDF{} $pdf=new PDF ('P', 'mm', 'Letter'); $pdf->SetMargins(8, 10); $pdf->AliasNbPages(); $pdf->AddPage(); $query = mysql_query("SELECT cliente.nombre, horario.fecha, horario.inicio, horario.fin, espacio.nombre, factura.total FROM cliente INNER JOIN factura on idcliente=cliente_idcliente INNER JOIN reserva on idfactura=factura_idfactura INNER JOIN horario on idhorario=horario_idhorario INNER JOIN espacio on idespacio=espacio_idespacio WHERE espacio.idespacio=2"); $pdf->Image("img/letras.png"); $pdf->SetFont("Arial", "b", 12); $pdf->Cell(0, 19, utf8_decode("REPORTES TEATRO"), 0, 1,'C'); $x =$pdf->GetX(); $y =$pdf->GetY(); $pdf-> SetTextColor(255, 255, 255); $pdf->SetFont("Arial", "b", 10); $pdf->MultiCell(35, 5, utf8_decode("NOMBRE"), 0, 1, 'L',0); $pdf->SetXY($x + 35, $y); $pdf->MultiCell(25, 5, utf8_decode("FECHA"), 0, 1, 'L',0); $pdf->SetXY($x + 60, $y); $pdf->MultiCell(30, 5, utf8_decode("HORA INICIO"), 0, 1, 'L',0); $pdf->SetXY($x + 90, $y); $pdf->MultiCell(30, 5, utf8_decode("HORA FIN"), 0, 1, 'L',0); $pdf->SetXY($x + 120, $y); $pdf->MultiCell(50, 5, utf8_decode("ÁREA"), 0, 1, 'L',0); $pdf->SetXY($x + 170, $y); $pdf->MultiCell(35, 5, utf8_decode("COSTO TOTAL"), 0, 1, 'L',0); $pdf->SetXY($x + 205, $y); $pdf->Ln(); while($row = mysql_fetch_row($query)){ $nombre = $row['0']; $fecha = $row['1']; $horaini= $row['2']; $horafini = $row['3']; $area = $row['4']; $total = "$ ". $row['5']; $x =$pdf->GetX(); $y =$pdf->GetY(); $pdf-> SetFillColor(255, 255, 255); $pdf-> SetTextColor(0, 0, 0); $pdf->SetFont("Arial", "b", 9); $pdf->MultiCell(35, 5, utf8_decode($nombre), 1, 1, 'L',0); $pdf->SetXY($x + 35, $y); $pdf->MultiCell(25, 5, utf8_decode($fecha), 1, 1, 'L',0); $pdf->SetXY($x + 60, $y); $pdf->MultiCell(30, 5, utf8_decode($horaini), 1, 1, 'L',0); $pdf->SetXY($x + 90, $y); $pdf->MultiCell(30, 5, utf8_decode($horafini), 1, 1, 'L',0); $pdf->SetXY($x + 120, $y); $pdf->MultiCell(50, 5, utf8_decode($area), 1, 1, 'L',0); $pdf->SetXY($x + 170, $y); $pdf->MultiCell(35, 5, utf8_decode($total), 1, 1, 'L',0); $pdf->SetXY($x + 205, $y); $pdf->Ln(); } $pdf->Output(); } function repteatroin(){ class PDF extends FPDF{} $pdf=new PDF ('P', 'mm', 'Letter'); $pdf->SetMargins(8, 10); $pdf->AliasNbPages(); $pdf->AddPage(); $query = mysql_query("SELECT cliente.nombre, horario.fecha, horario.inicio, horario.fin, espacio.nombre, factura.total FROM cliente INNER JOIN factura on idcliente=cliente_idcliente INNER JOIN reserva on idfactura=factura_idfactura INNER JOIN horario on idhorario=horario_idhorario INNER JOIN espacio on idespacio=espacio_idespacio WHERE espacio.idespacio=2"); $pdf->Image("img/letras.png"); $pdf->SetFont("Arial", "b", 12); $pdf->Cell(0, 19, utf8_decode("THEATER REPORTS"), 0, 1,'C'); $x =$pdf->GetX(); $y =$pdf->GetY(); $pdf-> SetTextColor(255, 255, 255); $pdf->SetFont("Arial", "b", 10); $pdf->MultiCell(35, 5, utf8_decode("NAME"), 0, 1, 'L',0); $pdf->SetXY($x + 35, $y); $pdf->MultiCell(25, 5, utf8_decode("DATE"), 0, 1, 'L',0); $pdf->SetXY($x + 60, $y); $pdf->MultiCell(30, 5, utf8_decode("START HOUR"), 0, 1, 'L',0); $pdf->SetXY($x + 90, $y); $pdf->MultiCell(30, 5, utf8_decode("END HOUR"), 0, 1, 'L',0); $pdf->SetXY($x + 120, $y); $pdf->MultiCell(50, 5, utf8_decode("AREA"), 0, 1, 'L',0); $pdf->SetXY($x + 170, $y); $pdf->MultiCell(35, 5, utf8_decode("TOTAL"), 0, 1, 'L',0); $pdf->SetXY($x + 205, $y); $pdf->Ln(); while($row = mysql_fetch_row($query)){ $nombre = $row['0']; $fecha = $row['1']; $horaini= $row['2']; $horafini = $row['3']; $area = $row['4']; $total = "$ " .$row['5']; $x =$pdf->GetX(); $y =$pdf->GetY(); $pdf-> SetFillColor(255, 255, 255); $pdf-> SetTextColor(0, 0, 0); $pdf->SetFont("Arial", "b", 9); $pdf->MultiCell(35, 5, utf8_decode($nombre), 1, 1, 'L',0); $pdf->SetXY($x + 35, $y); $pdf->MultiCell(25, 5, utf8_decode($fecha), 1, 1, 'L',0); $pdf->SetXY($x + 60, $y); $pdf->MultiCell(30, 5, utf8_decode($horaini), 1, 1, 'L',0); $pdf->SetXY($x + 90, $y); $pdf->MultiCell(30, 5, utf8_decode($horafini), 1, 1, 'L',0); $pdf->SetXY($x + 120, $y); $pdf->MultiCell(50, 5, utf8_decode($area), 1, 1, 'L',0); $pdf->SetXY($x + 170, $y); $pdf->MultiCell(35, 5, utf8_decode($total), 1, 1, 'L',0); $pdf->SetXY($x + 205, $y); $pdf->Ln(); } $pdf->Output(); } function reppiscinaes(){ class PDF extends FPDF{} $pdf=new PDF ('P', 'mm', 'Letter'); $pdf->SetMargins(8, 10); $pdf->AliasNbPages(); $pdf->AddPage(); $query = mysql_query("SELECT cliente.nombre, horario.fecha, horario.inicio, horario.fin, espacio.nombre, factura.total FROM cliente INNER JOIN factura on idcliente=cliente_idcliente INNER JOIN reserva on idfactura=factura_idfactura INNER JOIN horario on idhorario=horario_idhorario INNER JOIN espacio on idespacio=espacio_idespacio WHERE espacio.idespacio=3"); $pdf->Image("img/letras.png"); $pdf->SetFont("Arial", "b", 12); $pdf->Cell(0, 19, utf8_decode("REPORTES PISCINA"), 0, 1,'C'); $x =$pdf->GetX(); $y =$pdf->GetY(); $pdf-> SetTextColor(255, 255, 255); $pdf->SetFont("Arial", "b", 10); $pdf->MultiCell(35, 5, utf8_decode("NOMBRE"), 0, 1, 'L',0); $pdf->SetXY($x + 35, $y); $pdf->MultiCell(25, 5, utf8_decode("FECHA"), 0, 1, 'L',0); $pdf->SetXY($x + 60, $y); $pdf->MultiCell(30, 5, utf8_decode("HORA INICIO"), 0, 1, 'L',0); $pdf->SetXY($x + 90, $y); $pdf->MultiCell(30, 5, utf8_decode("HORA FIN"), 0, 1, 'L',0); $pdf->SetXY($x + 120, $y); $pdf->MultiCell(50, 5, utf8_decode("ÁREA"), 0, 1, 'L',0); $pdf->SetXY($x + 170, $y); $pdf->MultiCell(35, 5, utf8_decode("COSTO TOTAL"), 0, 1, 'L',0); $pdf->SetXY($x + 205, $y); $pdf->Ln(); while($row = mysql_fetch_row($query)){ $nombre = $row['0']; $fecha = $row['1']; $horaini= $row['2']; $horafini = $row['3']; $area = $row['4']; $total = "$ ". $row['5']; $x =$pdf->GetX(); $y =$pdf->GetY(); $pdf-> SetFillColor(255, 255, 255); $pdf-> SetTextColor(0, 0, 0); $pdf->SetFont("Arial", "b", 9); $pdf->MultiCell(35, 5, utf8_decode($nombre), 1, 1, 'L',0); $pdf->SetXY($x + 35, $y); $pdf->MultiCell(25, 5, utf8_decode($fecha), 1, 1, 'L',0); $pdf->SetXY($x + 60, $y); $pdf->MultiCell(30, 5, utf8_decode($horaini), 1, 1, 'L',0); $pdf->SetXY($x + 90, $y); $pdf->MultiCell(30, 5, utf8_decode($horafini), 1, 1, 'L',0); $pdf->SetXY($x + 120, $y); $pdf->MultiCell(50, 5, utf8_decode($area), 1, 1, 'L',0); $pdf->SetXY($x + 170, $y); $pdf->MultiCell(35, 5, utf8_decode($total), 1, 1, 'L',0); $pdf->SetXY($x + 205, $y); $pdf->Ln(); } $pdf->Output(); } function reppiscinain(){ class PDF extends FPDF{} $pdf=new PDF ('P', 'mm', 'Letter'); $pdf->SetMargins(8, 10); $pdf->AliasNbPages(); $pdf->AddPage(); $query = mysql_query("SELECT cliente.nombre, horario.fecha, horario.inicio, horario.fin, espacio.nombre, factura.total FROM cliente INNER JOIN factura on idcliente=cliente_idcliente INNER JOIN reserva on idfactura=factura_idfactura INNER JOIN horario on idhorario=horario_idhorario INNER JOIN espacio on idespacio=espacio_idespacio WHERE espacio.idespacio=3"); $pdf->Image("img/letras.png"); $pdf->SetFont("Arial", "b", 12); $pdf->Cell(0, 19, utf8_decode("SWIMMING POOL REPORTS"), 0, 1,'C'); $x =$pdf->GetX(); $y =$pdf->GetY(); $pdf-> SetTextColor(255, 255, 255); $pdf->SetFont("Arial", "b", 10); $pdf->MultiCell(35, 5, utf8_decode("NAME"), 0, 1, 'L',0); $pdf->SetXY($x + 35, $y); $pdf->MultiCell(25, 5, utf8_decode("DATE"), 0, 1, 'L',0); $pdf->SetXY($x + 60, $y); $pdf->MultiCell(30, 5, utf8_decode("START HOUR"), 0, 1, 'L',0); $pdf->SetXY($x + 90, $y); $pdf->MultiCell(30, 5, utf8_decode("END HOUR"), 0, 1, 'L',0); $pdf->SetXY($x + 120, $y); $pdf->MultiCell(50, 5, utf8_decode("AREA"), 0, 1, 'L',0); $pdf->SetXY($x + 170, $y); $pdf->MultiCell(35, 5, utf8_decode("TOTAL"), 0, 1, 'L',0); $pdf->SetXY($x + 205, $y); $pdf->Ln(); while($row = mysql_fetch_row($query)){ $nombre = $row['0']; $fecha = $row['1']; $horaini= $row['2']; $horafini = $row['3']; $area = $row['4']; $total = "$ " .$row['5']; $x =$pdf->GetX(); $y =$pdf->GetY(); $pdf-> SetFillColor(255, 255, 255); $pdf-> SetTextColor(0, 0, 0); $pdf->SetFont("Arial", "b", 9); $pdf->MultiCell(35, 5, utf8_decode($nombre), 1, 1, 'L',0); $pdf->SetXY($x + 35, $y); $pdf->MultiCell(25, 5, utf8_decode($fecha), 1, 1, 'L',0); $pdf->SetXY($x + 60, $y); $pdf->MultiCell(30, 5, utf8_decode($horaini), 1, 1, 'L',0); $pdf->SetXY($x + 90, $y); $pdf->MultiCell(30, 5, utf8_decode($horafini), 1, 1, 'L',0); $pdf->SetXY($x + 120, $y); $pdf->MultiCell(50, 5, utf8_decode($area), 1, 1, 'L',0); $pdf->SetXY($x + 170, $y); $pdf->MultiCell(35, 5, utf8_decode($total), 1, 1, 'L',0); $pdf->SetXY($x + 205, $y); $pdf->Ln(); } $pdf->Output(); } function repiglesiaes(){ class PDF extends FPDF{} $pdf=new PDF ('P', 'mm', 'Letter'); $pdf->SetMargins(8, 10); $pdf->AliasNbPages(); $pdf->AddPage(); $query = mysql_query("SELECT cliente.nombre, horario.fecha, horario.inicio, horario.fin, espacio.nombre, factura.total FROM cliente INNER JOIN factura on idcliente=cliente_idcliente INNER JOIN reserva on idfactura=factura_idfactura INNER JOIN horario on idhorario=horario_idhorario INNER JOIN espacio on idespacio=espacio_idespacio WHERE espacio.idespacio=3"); $pdf->Image("img/letras.png"); $pdf->SetFont("Arial", "b", 12); $pdf->Cell(0, 19, utf8_decode("REPORTES IGLESIA"), 0, 1,'C'); $x =$pdf->GetX(); $y =$pdf->GetY(); $pdf-> SetTextColor(255, 255, 255); $pdf->SetFont("Arial", "b", 10); $pdf->MultiCell(35, 5, utf8_decode("NOMBRE"), 0, 1, 'L',0); $pdf->SetXY($x + 35, $y); $pdf->MultiCell(25, 5, utf8_decode("FECHA"), 0, 1, 'L',0); $pdf->SetXY($x + 60, $y); $pdf->MultiCell(30, 5, utf8_decode("HORA INICIO"), 0, 1, 'L',0); $pdf->SetXY($x + 90, $y); $pdf->MultiCell(30, 5, utf8_decode("HORA FIN"), 0, 1, 'L',0); $pdf->SetXY($x + 120, $y); $pdf->MultiCell(50, 5, utf8_decode("ÁREA"), 0, 1, 'L',0); $pdf->SetXY($x + 170, $y); $pdf->MultiCell(35, 5, utf8_decode("COSTO TOTAL"), 0, 1, 'L',0); $pdf->SetXY($x + 205, $y); $pdf->Ln(); while($row = mysql_fetch_row($query)){ $nombre = $row['0']; $fecha = $row['1']; $horaini= $row['2']; $horafini = $row['3']; $area = $row['4']; $total = "$ ". $row['5']; $x =$pdf->GetX(); $y =$pdf->GetY(); $pdf-> SetFillColor(255, 255, 255); $pdf-> SetTextColor(0, 0, 0); $pdf->SetFont("Arial", "b", 9); $pdf->MultiCell(35, 5, utf8_decode($nombre), 1, 1, 'L',0); $pdf->SetXY($x + 35, $y); $pdf->MultiCell(25, 5, utf8_decode($fecha), 1, 1, 'L',0); $pdf->SetXY($x + 60, $y); $pdf->MultiCell(30, 5, utf8_decode($horaini), 1, 1, 'L',0); $pdf->SetXY($x + 90, $y); $pdf->MultiCell(30, 5, utf8_decode($horafini), 1, 1, 'L',0); $pdf->SetXY($x + 120, $y); $pdf->MultiCell(50, 5, utf8_decode($area), 1, 1, 'L',0); $pdf->SetXY($x + 170, $y); $pdf->MultiCell(35, 5, utf8_decode($total), 1, 1, 'L',0); $pdf->SetXY($x + 205, $y); $pdf->Ln(); } $pdf->Output(); } function repiglesiain(){ class PDF extends FPDF{} $pdf=new PDF ('P', 'mm', 'Letter'); $pdf->SetMargins(8, 10); $pdf->AliasNbPages(); $pdf->AddPage(); $query = mysql_query("SELECT cliente.nombre, horario.fecha, horario.inicio, horario.fin, espacio.nombre, factura.total FROM cliente INNER JOIN factura on idcliente=cliente_idcliente INNER JOIN reserva on idfactura=factura_idfactura INNER JOIN horario on idhorario=horario_idhorario INNER JOIN espacio on idespacio=espacio_idespacio WHERE espacio.idespacio=3"); $pdf->Image("img/letras.png"); $pdf->SetFont("Arial", "b", 12); $pdf->Cell(0, 19, utf8_decode("CHURCH REPORTS"), 0, 1,'C'); $x =$pdf->GetX(); $y =$pdf->GetY(); $pdf-> SetTextColor(255, 255, 255); $pdf->SetFont("Arial", "b", 10); $pdf->MultiCell(35, 5, utf8_decode("NAME"), 0, 1, 'L',0); $pdf->SetXY($x + 35, $y); $pdf->MultiCell(25, 5, utf8_decode("DATE"), 0, 1, 'L',0); $pdf->SetXY($x + 60, $y); $pdf->MultiCell(30, 5, utf8_decode("START HOUR"), 0, 1, 'L',0); $pdf->SetXY($x + 90, $y); $pdf->MultiCell(30, 5, utf8_decode("END HOUR"), 0, 1, 'L',0); $pdf->SetXY($x + 120, $y); $pdf->MultiCell(50, 5, utf8_decode("AREA"), 0, 1, 'L',0); $pdf->SetXY($x + 170, $y); $pdf->MultiCell(35, 5, utf8_decode("TOTAL"), 0, 1, 'L',0); $pdf->SetXY($x + 205, $y); $pdf->Ln(); while($row = mysql_fetch_row($query)){ $nombre = $row['0']; $fecha = $row['1']; $horaini= $row['2']; $horafini = $row['3']; $area = $row['4']; $total = "$ " .$row['5']; $x =$pdf->GetX(); $y =$pdf->GetY(); $pdf-> SetFillColor(255, 255, 255); $pdf-> SetTextColor(0, 0, 0); $pdf->SetFont("Arial", "b", 9); $pdf->MultiCell(35, 5, utf8_decode($nombre), 1, 1, 'L',0); $pdf->SetXY($x + 35, $y); $pdf->MultiCell(25, 5, utf8_decode($fecha), 1, 1, 'L',0); $pdf->SetXY($x + 60, $y); $pdf->MultiCell(30, 5, utf8_decode($horaini), 1, 1, 'L',0); $pdf->SetXY($x + 90, $y); $pdf->MultiCell(30, 5, utf8_decode($horafini), 1, 1, 'L',0); $pdf->SetXY($x + 120, $y); $pdf->MultiCell(50, 5, utf8_decode($area), 1, 1, 'L',0); $pdf->SetXY($x + 170, $y); $pdf->MultiCell(35, 5, utf8_decode($total), 1, 1, 'L',0); $pdf->SetXY($x + 205, $y); $pdf->Ln(); } $pdf->Output(); } function reppropioses(){ class PDF extends FPDF{} $pdf=new PDF ('P', 'mm', 'Letter'); $pdf->SetMargins(8, 10); $pdf->AliasNbPages(); $pdf->AddPage(); $query = mysql_query("SELECT cliente.nombre, horario.fecha, horario.inicio, horario.fin, espacio.nombre FROM usuario join cliente on(idusuario=usuario_idusuario) join factura on(idcliente=cliente_idcliente) join reserva on(idfactura=factura_idfactura) join horario on(idhorario=horario_idhorario) join espacio on(idespacio=espacio_idespacio) WHERE usuario"); $pdf->Image("img/letras.png"); $pdf->SetFont("Arial", "b", 12); $pdf->Cell(0, 19, utf8_decode("REPORTE DE SU USUARIO"), 0, 1,'C'); $x =$pdf->GetX(); $y =$pdf->GetY(); $pdf-> SetTextColor(255, 255, 255); $pdf->SetFont("Arial", "b", 10); $pdf->MultiCell(35, 5, utf8_decode("NOMBRE"), 0, 1, 'L',0); $pdf->SetXY($x + 35, $y); $pdf->MultiCell(25, 5, utf8_decode("FECHA"), 0, 1, 'L',0); $pdf->SetXY($x + 60, $y); $pdf->MultiCell(30, 5, utf8_decode("HORA INICIO"), 0, 1, 'L',0); $pdf->SetXY($x + 90, $y); $pdf->MultiCell(30, 5, utf8_decode("HORA FIN"), 0, 1, 'L',0); $pdf->SetXY($x + 120, $y); $pdf->MultiCell(50, 5, utf8_decode("ÁREA"), 0, 1, 'L',0); $pdf->SetXY($x + 170, $y); $pdf->MultiCell(35, 5, utf8_decode("COSTO TOTAL"), 0, 1, 'L',0); $pdf->SetXY($x + 205, $y); $pdf->Ln(); while($row = mysql_fetch_row($query)){ $nombre = $row['0']; $fecha = $row['1']; $horaini= $row['2']; $horafini = $row['3']; $area = $row['4']; $total = "$ ". $row['5']; $x =$pdf->GetX(); $y =$pdf->GetY(); $pdf-> SetFillColor(255, 255, 255); $pdf-> SetTextColor(0, 0, 0); $pdf->SetFont("Arial", "b", 9); $pdf->MultiCell(35, 5, utf8_decode($nombre), 1, 1, 'L',0); $pdf->SetXY($x + 35, $y); $pdf->MultiCell(25, 5, utf8_decode($fecha), 1, 1, 'L',0); $pdf->SetXY($x + 60, $y); $pdf->MultiCell(30, 5, utf8_decode($horaini), 1, 1, 'L',0); $pdf->SetXY($x + 90, $y); $pdf->MultiCell(30, 5, utf8_decode($horafini), 1, 1, 'L',0); $pdf->SetXY($x + 120, $y); $pdf->MultiCell(50, 5, utf8_decode($area), 1, 1, 'L',0); $pdf->SetXY($x + 170, $y); $pdf->MultiCell(35, 5, utf8_decode($total), 1, 1, 'L',0); $pdf->SetXY($x + 205, $y); $pdf->Ln(); } $pdf->Output(); } function reppropiosin(){ class PDF extends FPDF{} $pdf=new PDF ('P', 'mm', 'Letter'); $pdf->SetMargins(8, 10); $pdf->AliasNbPages(); $pdf->AddPage(); $query = mysql_query("SELECT cliente.nombre, horario.fecha, horario.inicio, horario.fin, espacio.nombre FROM usuario join cliente on(idusuario=usuario_idusuario) join factura on(idcliente=cliente_idcliente) join reserva on(idfactura=factura_idfactura) join horario on(idhorario=horario_idhorario) join espacio on(idespacio=espacio_idespacio) WHERE usuario=usuario"); $pdf->Image("img/letras.png"); $pdf->SetFont("Arial", "b", 12); $pdf->Cell(0, 19, utf8_decode("USER REPORTS"), 0, 1,'C'); $x =$pdf->GetX(); $y =$pdf->GetY(); $pdf-> SetTextColor(255, 255, 255); $pdf->SetFont("Arial", "b", 10); $pdf->MultiCell(35, 5, utf8_decode("NAME"), 0, 1, 'L',0); $pdf->SetXY($x + 35, $y); $pdf->MultiCell(25, 5, utf8_decode("DATE"), 0, 1, 'L',0); $pdf->SetXY($x + 60, $y); $pdf->MultiCell(30, 5, utf8_decode("START HOUR"), 0, 1, 'L',0); $pdf->SetXY($x + 90, $y); $pdf->MultiCell(30, 5, utf8_decode("END HOUR"), 0, 1, 'L',0); $pdf->SetXY($x + 120, $y); $pdf->MultiCell(50, 5, utf8_decode("AREA"), 0, 1, 'L',0); $pdf->SetXY($x + 170, $y); $pdf->MultiCell(35, 5, utf8_decode("TOTAL"), 0, 1, 'L',0); $pdf->SetXY($x + 205, $y); $pdf->Ln(); while($row = mysql_fetch_row($query)){ $nombre = $row['0']; $fecha = $row['1']; $horaini= $row['2']; $horafini = $row['3']; $area = $row['4']; $total = "$ ". $row['5']; $x =$pdf->GetX(); $y =$pdf->GetY(); $pdf-> SetFillColor(255, 255, 255); $pdf-> SetTextColor(0, 0, 0); $pdf->SetFont("Arial", "b", 9); $pdf->MultiCell(35, 5, utf8_decode($nombre), 1, 1, 'L',0); $pdf->SetXY($x + 35, $y); $pdf->MultiCell(25, 5, utf8_decode($fecha), 1, 1, 'L',0); $pdf->SetXY($x + 60, $y); $pdf->MultiCell(30, 5, utf8_decode($horaini), 1, 1, 'L',0); $pdf->SetXY($x + 90, $y); $pdf->MultiCell(30, 5, utf8_decode($horafini), 1, 1, 'L',0); $pdf->SetXY($x + 120, $y); $pdf->MultiCell(50, 5, utf8_decode($area), 1, 1, 'L',0); $pdf->SetXY($x + 170, $y); $pdf->MultiCell(35, 5, utf8_decode($total), 1, 1, 'L',0); $pdf->SetXY($x + 205, $y); $pdf->Ln(); } $pdf->Output(); } switch($modo){ case "repclientees": repclientees(); break; case "repclientein": repclientein(); break; case "repusuarioes": repusuarioes(); break; case "repusuarioin": repusuarioin(); break; case "represerves": represerves(); break; case "represervin": represervin(); break; case "repcanchaes": repcanchaes(); break; case "repcanchain": repcanchain(); break; case "repteatroes": repteatroes(); break; case "repteatroin": repteatroin(); break; case "reppiscinaes": reppiscinaes(); break; case "reppiscinain": reppiscinain(); break; case "repiglesiaes": repiglesiaes(); break; case "repiglesiain": repiglesiain(); break; case "reppropioses": reppropioses(); break; case "reppropiosin": reppropioses(); break; } }else{ echo "<script>alert('hola')</script>"; } ?><file_sep> <?php setlocale(LC_ALL,"es_ES"); include_once('conn.php'); include_once 'carrito.php'; session_start(); $carrito; if (isset($_REQUEST['delete'])) { try { $dbh = conectarbase(); /*** echo a message saying we have connected ***/ //echo 'Connected to database'; $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); /*** prepare the SQL statement ***/ $stmt = $dbh->prepare("DELETE FROM horario where idhorario=:id "); $stmt->bindParam(':id', $_REQUEST['delete'], PDO::PARAM_INT); /*** execute the prepared statement ***/ $exito=$stmt->execute(); /*** close the database connection ***/ $dbh = null; } catch(PDOException $e) { echo $e->getMessage(); } } if (!isset($_SESSION['carrito'])) { $_SESSION['carrito']=serialize(new Carrito()); $carrito=unserialize($_SESSION['carrito']); }else{ $carrito=unserialize($_SESSION['carrito']); } if (isset($_REQUEST['espacio'])) { $var="?espacio=".$_REQUEST['espacio']."'"; }else{ $var="'"; } function fechaing($fecha){ $y=substr($fecha, 0,4); $m=substr($fecha, -5,-3); $d=substr($fecha, -2,10); $fr=$d."-".$m.'-'.$y; return $fr; } ?> <!doctype html> <html lang='es'> <?php include 'head.php'; ?> <body role="document"> <?php include 'cabecera.php'; ?> <div class="container-fluid col-md-6 col-md-offset-3"> <div class="panel panel-default"> <div class="panel-heading"> <h3> <center>HORARIOS</center></h3> </div> <div class="panel-body"> <div class='col-md-6'> <form action=<?= "'agregarCarrito.php".$var?> method="POST" role="form"> <label for="">Fecha</label> <div class="input-group"> <input type="text" class="form-control" id="fecha" name='fecha'placeholder="Fecha"> <span class="input-group-btn"><button type="submit" class="btn btn-default">Ver</button></span> </div> <div class="alignbutton" > <a id="btnver" href="verCarrito.php" class="btn btn-default">Ver reservas</a> </div> </form> </div> </br> </br> </br> <?php /* $fe = date("Y-m-d H:i"); echo $fe; $fe=strtotime('+1 day', strtotime($fe)); $fe=date("Y-m-d",$fe); echo'<br />'. $fe;*/ if (isset($_POST['fecha'])) { $fecha=$_POST['fecha']; }else{ $fecha=date("Y-m-d"); } try{ $dbh=conectarbase(); $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); /*** prepara la sentencia SQL ***/ $ids=$carrito->idhorarios(); $sql="SELECT * FROM horario WHERE fecha = :inicio and reservado=false and idhorario NOT IN($ids)"; if (isset($_REQUEST['espacio'])) { $sql.="and espacio_idespacio= :espacio"; } $fe=$fecha; $stmt = $dbh->prepare($sql); $stmt->bindParam(':inicio', $fe, PDO::PARAM_STR, 13); if (isset($_REQUEST['espacio'])) { $stmt->bindParam(':espacio', $_REQUEST['espacio'], PDO::PARAM_INT); } /*** executar sentencia preparada ***/ $stmt->execute(); /*** Mostrar resultado ***/ $result = $stmt->fetchAll(); echo "<table class='table table-bordered' border='1px' >"; echo"<tr><th>". fechaing($fecha) ."</th>"; // $f=$hoy; /* for ($i=0; $i <4 ; $i++) { $f=sumardia($f); echo"<th> ".date('l',strtotime($f))." $f </th>"; }*/ echo"</tr> "; foreach ($result as $row) { $lugar=''; switch ($row['espacio_idespacio']) { case '1': $lugar='Cancha'; break; case '2': $lugar='Teatro'; break;- $lugar='Piscina'; break; default: $lugar= 'Iglesia'; break; } echo '<tr> <td>'; echo 'Horario: '.$row['inicio'].' - '. $row['fin'].'<br /> Lugar:'. $lugar; //echo $row['espacio_idespacio']; echo"<br /><a href='verCarrito.php?id= ".$row['idhorario']."'>Reservar</a>"; if($_SESSION['tipo']==1) { echo"<br /><a href='agregarCarrito.php?delete=".$row['idhorario']."'>Eliminar</a>"; } echo '</td></tr>'; } echo '</table>'; /*** cerrar conexion de la base de datos ***/ $dbh = null; } catch(PDOException $e) { echo $e->getMessage(); } ?> <!-- <div class="col-sm-3 col-md-10 col-md-offset-1"> <div class="table-responsive "> <table class="table table-bordered" border="1px" > <!--table table-hover table-bordered--> <!-- <thead> <tr> <th><center>Horario</th> <th><center>Lunes</th> <th><center>Martes</th> <th><center>Miércoles</th> <th><center>Jueves</th> <th><center>Viernes</th> <th><center>Sábado</th> <th><center>Domingo</th> </tr> </thead> <tbody> <tr> <td>8:00 a.m. - 8:45 a.m. </td> <td class="tred" colspan="5"><center> No Disponible</td> <td class="tverde"> <center>Espacio Libre</td> <td class="tverde"> <center>Espacio Libre</td> <tr> <td>9:00 a.m. - 9:45 a.m. </td> <td class="tred" colspan="5"><center> No Disponible</td> <td class="tverde"> <center>Espacio Libre</td> <td class="tverde"> <center>Espacio Libre</td> </tr> <tr> <td>10:00 a.m. - 10:45 a.m. </td> <td class="tred" colspan="5"><center> No Disponible</td><td class="tverde"> <center>Espacio Libre</td> <td class="tverde"> <center>Espacio Libre</td> </tr> <tr> <td>11:00 a.m. - 11:45 a.m.</td> <td class="tred" colspan="5"><center> No Disponible</td><td class="tverde"> <center>Espacio Libre</td> <td class="tverde"> <center>Espacio Libre</td> </tr> <tr> <td>12:00 p.m. - 12:45 p.m.</td> <td class="tred" colspan="5"><center> No Disponible</td><td class="tverde"> <center>Espacio Libre</td> <td class="tverde"> <center>Espacio Libre</td> </tr> <tr> <td>1:00 p.m. - 1:45 p.m. </td> <td class="tred" colspan="5"><center> No Disponible</td><td class="tverde"> <center>Espacio Libre</td> <td class="tverde"> <center>Espacio Libre</td> </tr> <tr> <td>2:00 p.m. - 2:45 p.m.</td> <td class="tred" colspan="5"><center> No Disponible</td><td class="tverde"> <center>Espacio Libre</td> <td class="tverde"> <center>Espacio Libre</td> </tr> <tr> <td>3:00 p.m. - 3:45 p.m.</td> <td class="tred" colspan="5"><center> No Disponible</td><td class="tverde"> <center>Espacio Libre</td> <td class="tverde"> <center>Espacio Libre</td> </tr> <tr> <td>4:00 p.m. - 4:45 p.m.</td> <td class="tred" colspan="5"><center> No Disponible</td><td class="tverde"> <center>Espacio Libre</td> <td class="tverde"> <center>Espacio Libre</td> </tr> <tr> <td>5:00 p.m. - 5:45 p.m.</td> <td class="tverde"> <center>Espacio Libre</td> <td class="tverde"> <center>Espacio Libre</td><td class="tverde"> <center>Espacio Libre</td><td class="tverde"> <center>Espacio Libre</td><td class="tverde"> <center>Espacio Libre</td><td class="tverde"> <center>Espacio Libre</td><td class="tverde"> <center>Espacio Libre</td> </tr> <tr> <td>6:00 p.m. - 6:45 p.m.</td> <td class="tverde"> <center>Espacio Libre</td> <td class="tverde"> <center>Espacio Libre</td><td class="tverde"> <center>Espacio Libre</td><td class="tverde"> <center>Espacio Libre</td><td class="tverde"> <center>Espacio Libre</td><td class="tverde"> <center>Espacio Libre</td><td class="tverde"> <center>Espacio Libre</td> <tr> <td>7:00 p.m. - 7:45 p.m.</td> <td class="tverde"> <center>Espacio Libre</td><td class="tverde"> <center>Espacio Libre</td><td class="tverde"> <center>Espacio Libre</td><td class="tverde"> <center>Espacio Libre</td><td class="tverde"> <center>Espacio Libre</td><td class="tverde"> <center>Espacio Libre</td><td class="tverde"> <center>Espacio Libre</td> </tr> <tr> <td>8:00 p.m. - 8:45 p.m.</td><td class="tverde"> <center>Espacio Libre</td><td class="tverde"> <center>Espacio Libre</td><td class="tverde"> <center>Espacio Libre</td><td class="tverde"> <center>Espacio Libre</td><td class="tverde"> <center>Espacio Libre</td><td class="tverde"> <center>Espacio Libre</td><td class="tverde"> <center>Espacio Libre</td> </tr> <tr> <td>9:00 p.m. - 9:45 p.m.</td> <td class="tverde"> <center>Espacio Libre</td><td class="tverde"> <center>Espacio Libre</td><td class="tverde"> <center>Espacio Libre</td><td class="tverde"> <center>Espacio Libre</td><td class="tverde"> <center>Espacio Libre</td><td class="tverde"> <center>Espacio Libre</td><td class="tverde"> <center>Espacio Libre</td> </tbody> </table> </div> </div> </div> </div> --> <a id="btnreg" href="areas.php" class="btn btn-warning">Regresar</a> </div> <footer> <link rel="stylesheet" type="text/css" href="js/datetimepicker.css"/ > <script type="text/javascript" src="js/datetimepicker.js"></script> <script type="text/javascript"> //$(document).ready(function() { //$('#hinicio').clockpicker(); $('#fecha').datetimepicker({ minDate:0,lang:'es',format:'Y-m-d',timepicker:false, mask:true}); //$('#hinicio,#hfin').datetimepicker({lang:'es',mask:true,format:'H:i',datepicker:false,step:5}); //}); </script> </footer> </body> </html> <?php function sumardia($fe){ $fe=strtotime('+1 day', strtotime($fe)); $fe=date("Y-m-d",$fe); return $fe; } ?><file_sep><?php session_start(); if (isset($_SESSION['tipo'])){ if ($_SESSION['tipo']!=1){ header('Location: index.php'); } }else{ header('Location: index.php'); } if (isset($_REQUEST['usuario'])) { /*** mysql hostname ***/ $hostname = 'localhost'; /*** mysql username ***/ $username = 'root'; /*** mysql password ***/ $password = ''; try { $dbh = new PDO("mysql:host=" . $hostname . ";dbname=cssreservation", $username, $password); /*** echo a message saying we have connected ***/ //echo 'Connected to database'; $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); /*** prepare the SQL statement ***/ $stmt = $dbh->prepare("DELETE FROM cliente WHERE usuario_idusuario=(SELECT idusuario FROM USUARIO WHERE usuario=:usuario);DELETE FROM usuario WHERE usuario=:usuario"); $stmt->bindParam(':usuario', $_REQUEST['usuario'], PDO::PARAM_STR, 10); /*** execute the prepared statement ***/ $stmt->execute(); /*** close the database connection ***/ $dbh = null; } catch(PDOException $e) { echo $e->getMessage(); } } ?> <!doctype html> <html lang='es'> <?php include 'head.php'; ?> <body role="document"> <?php include 'cabecera.php'; ?> <div class="container-fluid col-md-6 col-md-offset-3"> <div class="panel panel-default"> <div class="panel-heading"> <h3 class="panel-title"><b><span class="glyphicon glyphicon-list-alt"></span> Show Users</b></h3> </div> <div class="panel-body"> <table class="table table-hover"> <thead> <tr> <th><span class="glyphicon glyphicon-user"></span> User</th> <th><span class="glyphicon glyphicon-question-sign"></span> Type</th> <th><span class="glyphicon glyphicon-envelope"></span> E-Mail</th> <th><span class="glyphicon glyphicon-refresh"></span> Update</th> <th><span class="glyphicon glyphicon-trash"></span> Delete</th> <th><span class="glyphicon glyphicon-usd"></span> Balance</th> </tr> </thead> <tbody> <?php //echo '<br /> <br /> <h1> ' . $_POST['usuario'] . '</h1>'; /*** mysql hostname ***/ $hostname = 'localhost'; /*** mysql username ***/ $username = 'root'; /*** mysql password ***/ $password = ''; try { $dbh = new PDO("mysql:host=" . $hostname . ";dbname=cssreservation", $username, $password); /*** echo a message saying we have connected ***/ //echo 'Connected to database'; $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); /*** prepare the SQL statement ***/ $stmt = $dbh->prepare("SELECT usuario,tipo,correo FROM usuario WHERE tipo!=1 "); /*** execute the prepared statement ***/ $stmt->execute(); /*** fetch the results ***/ $result = $stmt->fetchAll(); /*** loop of the results ***/ foreach ($result as $row) { ?> <tr> <td><?=$row ["usuario"]?></td><td><?=$row ["tipo"]==1?"Administrator":"Client"?></td> <td><?=$row ["correo"]?></td> <td><a <?="href='modificarUsuario.php?usuario=".$row ["usuario"]."'"?>>Update</a></td> <td><a <?="href='mostrarUsuario.php?usuario=".$row ["usuario"]."'"?> onclick="return confirm('Are you sure?');">Delete</a></td> <td><a <?="href='agregarsaldo.php?usuario=".$row ["usuario"]."'"?>>Add Balance</a></td> </tr> <?php } /*** close the database connection ***/ $dbh = null; } catch(PDOException $e) { echo $e->getMessage(); } ?> </tbody> </table> </div> </div> <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> <h4 class="modal-title" id="myModalLabel">Eliminar Usuario</h4> </div> <div class="modal-body"> ¿Está seguro de eliminar el usuario seleccionado? </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Cancelar</button> <button type="button" class="btn btn-danger">Eliminar</button> </div> </div> </div> </div> </div> <footer> </footer> </body> </html><file_sep> <div class="navbar navbar-custom " role="navigation"> <div class="container-fluid" > <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> <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="INDEX.php"><img src="img/crs.ico" width='15 px' alt="">CSSC RESERVATION SYSTEM</a> </div> <div class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <?php if (isset($_SESSION['tipo'])) if($_SESSION['tipo']!=1) { ?> <li> <a href="areas.php" ><span class="glyphicon glyphicon-picture"></span> AREAS</a> </li> <li><a href="repusuario.php"><span class="glyphicon glyphicon-pencil"></span> REPORTS</a></li> <?php } if(isset($_SESSION['tipo'])) if($_SESSION['tipo']==1) { ?> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"><span class="glyphicon glyphicon-user"></span> USER<b class="caret"></b></a> <ul class="dropdown-menu"> <li><a href="nuevoUsuario.php"><span class="glyphicon glyphicon-plus-sign"></span> NEW USER</a></li> <li><a href="mostrarUsuario.php"><span class="glyphicon glyphicon-list-alt"></span> SHOW USERS</a></li> </ul> </li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"><span class="glyphicon glyphicon-picture "></span> AREAS<b class="caret"></b></a> <ul class="dropdown-menu"> <li><a href="areas.php"><span class="glyphicon glyphicon-calendar"></span> AREAS AND SCHEDULE</a></li> <li><a href="inshorario.php"><span class="glyphicon glyphicon-plus"></span> ADD NEW SCHEDULE</a></li> <!--<li><a href=#><span class="glyphicon glyphicon-plus-sign"></span> ADD NEW AREA</a></li>--> <li><a href="repa.php"><span class="glyphicon glyphicon-pencil"></span> REPORTS</a></li> </ul> </li> <?php } ?> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"><span class="glyphicon glyphicon-flag"></span> LANGUAGE<b class="caret"></b></a> <ul class="dropdown-menu"> <li><a href="../CRS"><img src ="img/ESP.png" width="30" height="25"> ESPAÑOL</a></li> </ul> </li> <li> <a target=\"_blank\" href="csscres.pdf" title="Help"><span class="glyphicon glyphicon-question-sign"></span> HELP</a> </li> <?php if(isset($_SESSION['usuario'])){ ?> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"><span class="glyphicon glyphicon-pushpin"></span> ACCOUNT <b class="caret"></b></a> <ul class="dropdown-menu"> <li><a href="camcontra.php"><span class="glyphicon glyphicon-cog"></span> CHANGE PASSWORD</a></li> </ul> </li> </ul> <p class="navbar-text navbar-right"><span class="glyphicon glyphicon-user"></span> USER: <a href="home.php" class="navbar-link"> <?php echo $_SESSION['usuario'] ?> </a> , <a href="cerrar.php" class="dropdown-toggle"><span class="glyphicon glyphicon-off" ></span> LOG OUT</a></li> </p> <?php }else {?> </ul> <p class="navbar-text navbar-right"><span class="glyphicon glyphicon-user"></span><a href="home.php"> LOG IN</a> </p> <?php } ?> </div><!--/.nav-collapse <embed src="url_pdf.pdf" width="450" height="450" href="url_pdf.pdf"></embed> --> </div> </div> <?php date_default_timezone_set('America/El_Salvador'); ?><file_sep> <div class="navbar navbar-custom " role="navigation"> <div class="container-fluid" > <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> <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="INDEX.php"><b>CSSC RESERVATION SYSTEM</b></a> </div> <div class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <?php if (isset($_SESSION['tipo'])) if($_SESSION['tipo']!=1) { ?> <li> <a href="areas.php" ><i class="fa fa-picture-o"></i> ESPACIOS</a> </li> <li><a href="repusuario.php"><i class="fa fa-pencil-square-o"></i></span> REPORTES</a></li> <?php } if(isset($_SESSION['tipo'])) if($_SESSION['tipo']==1) { ?> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"><i class="fa fa-user"></i> USUARIO<b class="caret"></b></a> <ul class="dropdown-menu"> <li><a href="nuevoUsuario.php"><i class="fa fa-user-plus"></i> NUEVO USUARIO</a></li> <li><a href="mostrarUsuario.php"><i class="fa fa-users"></i> MOSTRAR USUARIOS</a></li> </ul> </li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"><i class="fa fa-picture-o"></i> ESPACIOS<b class="caret"></b></a> <ul class="dropdown-menu"> <li><a href="areas.php"><i class="fa fa-calendar"></i> ESPACIOS Y HORARIOS</a></li> <li><a href="inshorario.php"><i class="fa fa-clock-o"></i> AGREGAR NUEVO HORARIO</a></li> <!--<li><a href=#><span class="glyphicon glyphicon-plus-sign"></span> AGREGAR NUEVO ESPACIO</a></li>--> <li><a href="repa.php"><i class="fa fa-pencil-square-o"></i> REPORTES</a></li> </ul> </li> <?php } ?> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"><i class="fa fa-language"></i> IDIOMA<b class="caret"></b></a> <ul class="dropdown-menu"> <li><a href="../CRSING"><i class="fa fa-flag-o"></i> ENGLISH</a></li> </ul> </li> <li> <a target=\"_blank\" href="csscres.pdf" title="AYUDA"><i class="fa fa-question"></i> AYUDA</a> </li> <?php if(isset($_SESSION['usuario'])){ ?> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown"><i class="fa fa-cog"></i> CUENTA <b class="caret"></b></a> <ul class="dropdown-menu"> <li><a href="camcontra.php"><i class="fa fa-refresh"></i> CAMBIAR CONTRASEÑA</a></li> <li><a href="cerrar.php" class="dropdown-toggle"><i class="fa fa-power-off"></i> CERRAR SESIÓN</a></li> </ul> </li> </ul> <p class="navbar-text navbar-right"><span class="glyphicon glyphicon-user"></span> USUARIO: <a href="home.php" class="navbar-link"> <?php echo $_SESSION['usuario'] ?> </a></p> <?php }else {?> </ul> <p class="navbar-text navbar-right"><span class="glyphicon glyphicon-user"></span><a href="home.php"> INICIAR SESIÓN</a> </p> <?php } ?> </div><!--/.nav-collapse <embed src="url_pdf.pdf" width="450" height="450" href="url_pdf.pdf"></embed> --> </div> </div> <?php date_default_timezone_set('America/El_Salvador'); ?><file_sep><?php session_start(); ?> <!doctype html> <html lang='es'> <?php include 'head.php'; ?> <body role="document"> <?php include 'cabecera.php'; ?> <div class="container-fluid col-md-6 col-md-offset-3"> <div class="panel panel-default"> <div class="panel-heading"> <center> <h3 class="panel-title"><strong>INFORMACIÓN GENERAL</strong></h3> </div> <div class="panel-body"> <p>La piscina es Semi olímpica de 25 mts X 10 mts. y su profundidad va desde 1.25 a 2 metros en lo más hondo y puede ser usada para competiciones, recreación, entre otras</p><br> <strong><center>Restricciones</center></strong><br> <ul> <li> No se permite ingresar comida a la piscina.</li> <li> No se permite ingresar mascotas.</li> <li> Debe contar con el material adecuado (Gorro, Calzoneta o Licra, Lentes(opcional)).</li> <li> Ducharse antes de ingresar a la piscina.</li> <li> Respetar el horario establecido</li> </ul><br> <center><strong>Galería de Imágenes</strong></center> <div class="thumbnail"> <img src="img/Piscina1.jpg" heigth='300' class="img-rounded" alt="Piscina"><br> <img src="img/Piscina2.jpg" heigth='300' class="img-rounded" alt="Piscina"><br> <img src="img/Piscina3.jpg" heigth='300' class="img-rounded" alt="Piscina"> </div> </div> </div> <footer> </footer> </body> </html><file_sep><?php session_start(); ?> <!doctype html> <html lang='es'> <?php include 'head.php'; ?> <body role="document"> <?php include 'cabecera.php'; ?> <div class="container-fluid"> <div class="panel panel-default"> <div class="panel-heading"> <h3 class="panel-title"><b><center>VIEW REPORTS</center></b></h3> </div> <div class="panel-body"> <div class="col-sm-12 col-md-3 "> <div class="thumbnail"> <div class="caption"> <h3><center>User</center></h3><br> <p> <center><a href="reportes.php?modo=repusuarioin" class="btn btn-warning">User</a></center><br> </p> </div> </div> </div> <div class="col-sm-12 col-md-3"> <div class="thumbnail"> <div class="caption"> <h3><center>Client</center></h3><br> <p> <center><a href="reportes.php?modo=repclientein" class="btn btn-warning">Client</a></center><br> </p> </div> </div> </div> <div class="col-sm-12 col-md-3"> <div class="thumbnail"> <div class="caption"> <h3><center>Reservations</center></h3><br> <p> <center><a href="reportes.php?modo=represervin" class="btn btn-warning">Reservations</a></center><br> </p> </div> </div> </div> <div class="col-sm-12 col-md-3"> <div class="thumbnail"> <div class="caption"> <h3><center>Areas</center></h3> <p> <center><a href="reportes.php?modo=repcanchain" class="btn btn-warning">Soccer Fields</a> <a href="reportes.php?modo=repteatroin" class="btn btn-warning">Theater</a></center><br> <center><a href="reportes.php?modo=reppiscinain" class="btn btn-warning">Swimming Pool</a> <a href="reportes.php?modo=repiglesiain" class="btn btn-warning">Church</a></center> </p> </div> </div> </div> </div> </div> </div> </div> <footer> </footer> </body> </html><file_sep><?php session_start(); ?> <!doctype html> <html lang='es'> <?php include 'head.php'; ?> <body role="document"> <?php include 'cabecera.php'; ?> <div class="container-fluid col-md-6 col-md-offset-3"> <div class="panel panel-default"> <div class="panel-heading"> <center> <h3 class="panel-title"><strong>INFORMACIÓN GENERAL</strong></h3> </div> <div class="panel-body"> <p> La Iglesia tiene una capacidad de 1000 personas, puede ser utilizada para: quince años, primera comunión, misas de cuerpo presente, entre otras.</p><br> <strong><center>Restricciones</center></strong><br> <ul> <li> No se permite ingresar comida a la Iglesia.</li> <li> Mantener el respeto debido.</li> <li> No ingresar mascotas.</li> <li> No fumar ni ingresar bebidas alcoholicas.</li> <li> No dañar las instalaciones</li> <li> Mantener el celular en silencio durante la misa.</li> </ul><br> <center><strong>Galería de Imágenes</strong></center> <div class="thumbnail"> <img src="img/Iglesia1.jpg" heigth='300' class="img-rounded" alt="Iglesia"><br> <img src="img/Iglesia2.jpg" heigth='300' class="img-rounded" alt="Iglesia"><br> <img src="img/Iglesia3.jpg" heigth='300' class="img-rounded" alt="Iglesia"> </div> </div> </div> <footer> </footer> </body> </html><file_sep><?php $link = mysql_connect('localhost', 'root', ''); if ($link) { mysql_select_db("cssreservation", $link); } ?><file_sep><?php session_start(); if (isset($_SESSION['tipo'])){ if ($_SESSION['tipo']!=1){ header('Location: index.php'); } }else{ header('Location: index.php'); } $mensaje=""; function fechaesp($fecha){ $p = explode("-", $fecha); $y=$p[2]; $m=$p[1];; $d=$p[0];; $fr=$y.'-'.$m."-".$d; return $fr; } if (isset($_POST['fecha'])) { include 'conn.php'; $anio=fechaesp($_POST['fecha']); try { $dbh = conectarbase(); /*** echo a message saying we have connected ***/ //echo 'Connected to database'; $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); /*foreach ($_POST as $key ) { print $key; }*/ $hinicio = strtotime($_POST['hinicio']); $hinicio = date("H:i:00", $hinicio); $hfin = strtotime($_POST['hfin']); $hfin = date("H:i:00", $hfin); /*** prepare the SQL statement ***/ $stmt = $dbh->prepare("INSERT into horario (fecha,inicio,fin,espacio_idespacio) values (:fecha,:inicio,:fin,:espacio) "); $stmt->bindParam(':fecha', $anio, PDO::PARAM_STR, 10); $stmt->bindParam(':inicio', $hinicio, PDO::PARAM_STR, 9); $stmt->bindParam(':fin', $hfin, PDO::PARAM_STR, 9); $stmt->bindParam(':espacio', $_POST['espacio'], PDO::PARAM_INT); /*** execute the prepared statement ***/ $exito=$stmt->execute(); /*** close the database connection ***/ $dbh = null; $mensaje="<div class='alert alert-success'> <strong>¡Éxito! </strong>Horario insertado exitósamente </div>"; } catch(PDOException $e) { echo $e->getMessage(); $mensaje="<div class='alert alert-danger'> <strong>¡Alerta!</strong> error </div>"; } } ?> <!doctype html> <html lang='es'> <?php include 'head.php'; ?> <body role="document"> <?php include 'cabecera.php'; ?> <div class="container-fluid"> <div class="panel panel-default col-md-6 col-md-offset-3"> <div class="panel-heading"> <h3 class="panel-title"><b>Nuevo Horario</b></h3> </div> <div class="panel-body"> <?=$mensaje?> <form action="inshorario.php" method="POST" role="form"> <div class="form-group"> <label for="f1">Fecha</label> <input type="text" class="form-control" id="fecha" name='fecha' placeholder="Input field"required> </div> <div class="form-group"> <label for="hinicio">Inicio</label> <input type="text" class="form-control" id="hinicio" name='hinicio' placeholder="Hora Inicio"required> </div> <div class="form-group"> <label for="hfin">Fin</label> <input type="text" class="form-control" id="hfin" name='hfin' placeholder="Hora fin" required> </div> <div class='dhora'></div> <div class="form-group"> <label for="esp">Espacio</label> <select name="espacio" id="esp" class="form-control" required="required"> <option value="1">Cancha</option> <option value="2">Teatro</option> <option value="3">Piscina</option> <option value="4">Iglesia</option> </select></div> <button type="submit" id="enviar" disabled class="btn btn-warning">Insertar</button> </form> </div> </div> </div> <footer> <!--<link rel="stylesheet" type="text/css" href="js/clockpicker.css"/ > <script type="text/javascript" src="js/clockpicker.js"></script>--> <link rel="stylesheet" type="text/css" href="js/datetimepicker.css"/ > <script type="text/javascript" src="js/datetimepicker.js"></script> <script type="text/javascript"> //$(document).ready(function() { //$('#hinicio').clockpicker(); $('#fecha').datetimepicker({value: hoy() , minDate:0,lang:'es',format:'d-m-Y',timepicker:false, mask:true}); $('#hinicio,#hfin').datetimepicker({lang:'es',mask:true,format:'h:i:00 a',datepicker:false,step:5}); function hoy(){ var today = new Date(); var dd = today.getDate(); var mm = today.getMonth()+1; //January is 0! var yyyy = today.getFullYear(); if(dd<10) { dd='0'+dd } if(mm<10) { mm='0'+mm } today = dd +'-'+mm+'-'+ yyyy; return today; } function hora(){ var today = new Date(); var H = today.getHours(); var m = today.getMinutes(); var ampm = hours >= 12 ? 'pm' : 'am'; H = hours % 12; H = hours ? hours : 12; // the hour '0' should be '12' m = minutes < 10 ? '0'+minutes : minutes; hora = H+':'+m+':00'+ ' ' + ampm; return hora; } function compare_horas(hora1, hora2) { // si es true hora1 mayor var time1 = hora1; var hours1 = Number(time1.match(/^(\d+)/)[1]); var minutes1 = Number(time1.match(/:(\d+)/)[1]); var xsegundo=Number(time1.match(/:(\d+)/)[2]); //var AMPM1 = time1.match(/\s(.*)$/)[1]; var AMPM1 = hora1.search("pm"); //alert(AMPM1); var time2 = hora2; var hours2 = Number(time2.match(/^(\d+)/)[1]); var minutes2 = Number(time2.match(/:(\d+)/)[1]); var ysegundo=Number(time2.match(/:(\d+)/)[2]); //var AMPM2 = time2.match(/\s(.*)$/)[1]; var AMPM2 = hora2.search("am"); //alert(AMPM2); /* var xhora=hora1.substring(0, 2); var xminuto=hora1.substring(3, 5); var xsegundo=hora1.substring(6, 8); var yhora=hora2.substring(0, 2); var yminuto=hora2.substring(3, 5); var ysegundo=hora2.substring(6, 8); */ //var msg= "1:"+AMPM1+" 2:"+AMPM2; //alert(msg); if (AMPM2==AMPM1) { return(true); } if (hours1> hours2) { return(true); $('.dhora').text('true'); } else { if (hours1 == hours2) { if (minutes1> minutes2) { return(true) ; } else { if (minutes1 == minutes2) { if (xsegundo> ysegundo) return(true); else return(false); } else return(false); } } else return(false); $('.dhora').text('false'); } } //}); $('#hinicio,#hfin').change(function(){ var ini= $('#hinicio').val(); var fin= $('#hfin').val(); $('.dhora').text(''); var mayor=compare_horas(fin,ini); if (mayor) { $('.dhora').text(''); $("#enviar").removeAttr('disabled'); }else{ $('.dhora').text(''); $("#enviar").attr('disabled','disabled'); } }); </script> </footer> </body> </html><file_sep><?php include_once 'conn.php'; include_once 'carrito.php'; session_start(); $res['exito']=false; if (isset($_POST['reservar'])) { if ($_POST['reservar']) { if (isset($_SESSION['carrito'])) { $carrito=unserialize($_SESSION['carrito']); $res=$carrito->guardar(); } } } if ($res['exito']) { $_SESSION['carrito']=serialize(new Carrito()); } ?> <!DOCTYPE HTML> <html lang="es"> <?php include'head.php';?> <head> <title>CSSC RESERVATION</title> </head> <body role="document"> <?php include'cabecera.php';?> <div class="container-fluid"> <div class="col-md-6 col-md-offset-3"> <div class="panel panel-warning"> <div class="panel-heading"> </font><h3 class="panel-title3"><b>Reservation</b></h3> </div> <?php if ($res['exito']) { echo'<font color="green"><h3><center> Success! The reservation was made succesfully </h3></font>'; echo '<b>Ticket: </b>'.$res['factura']['idfactura']; echo '<br><b>Total: </b>'.$res['factura']['total']; echo '<br><b>Date: </b>'.$res['factura']['fecha']; echo $res['tabla']; }else { echo'<font color="#b41212"><h3><center> Sorry! The reservation cannot be made, please try again. </h3></font> '; } ?> <span class="center"><center><a href="javascript:window.print()" id="ocultar" onclick="hide();return false;">Print Ticket</a></center></span> </div> </div> </div> <footer> <script type="text/javascript"> function hide(){ document.getElementById('ocultar').style.display = 'none'; javascript:window.print(); document.getElementById('ocultar').style.display = 'block'; } </script> </footer> </body> </html><file_sep><?php if (isset($_POST['usuario']) ) { //echo '<br /> <br /> <h1> ' . $_POST['usuario'] . '</h1>'; /*** mysql hostname ***/ $hostname = 'localhost'; /*** mysql username ***/ $username = 'root'; /*** mysql password ***/ $password = ''; try { $dbh = new PDO("mysql:host=" . $hostname . ";dbname=cssreservation", $username, $password); /*** echo a message saying we have connected ***/ //echo 'Connected to database'; $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); /*** prepare the SQL statement ***/ $stmt = $dbh->prepare("SELECT usuario FROM usuario WHERE usuario = :usuario"); $stmt->bindParam(':usuario', $_POST['usuario'], PDO::PARAM_STR, 10); /*** execute the prepared statement ***/ $stmt->execute(); /*** fetch the results ***/ $result = $stmt->fetchAll(); if (count($result) != 0) { echo "si"; //existe } else { echo "no";//no existe } /*** close the database connection ***/ $dbh = null; } catch(PDOException $e) { echo $e->getMessage(); } }else{ echo "no if"; } ?><file_sep><?php include_once 'conn.php'; class Carrito{ public $idcliente; public $reservas=array(); public $total; public function __construct() { $this->total=0; try { $dbh = conectarbase(); /*** echo a message saying we have connected ***/ //echo 'Connected to database'; $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $sql="SELECT idcliente FROM cliente join usuario on(idusuario=usuario_idusuario) WHERE usuario='".$_SESSION['usuario']."'"; /*** prepare the SQL statement ***/ $stmt = $dbh->prepare($sql); /*** execute the prepared statement ***/ $stmt->execute(); $result = $stmt->fetch(PDO::FETCH_ASSOC); /*** close the database connection ***/ $dbh = null; $this->idcliente= $result['idcliente']; } catch(PDOException $e) { //echo $e->getMessage(); $exito=false; } } public static function porUsuario($usuario) { $instance = new self(); $instance->total=0; try { $dbh = conectarbase(); /*** echo a message saying we have connected ***/ //echo 'Connected to database'; $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $sql="SELECT idcliente FROM cliente join usuario on(idusuario=usuario_idusuario) WHERE usuario='".$usuario."'"; /*** prepare the SQL statement ***/ $stmt = $dbh->prepare($sql); /*** execute the prepared statement ***/ $stmt->execute(); $result = $stmt->fetch(PDO::FETCH_ASSOC); /*** close the database connection ***/ $dbh = null; $instance->idcliente= $result['idcliente']; } catch(PDOException $e) { //echo $e->getMessage(); $exito=false; } return $instance; } public function total(){ return $this->total; } public function add($id){ $existe=false; foreach ($this->reservas as $r) { if ($r->idhorario==$id) { $existe=true; } } if (!$existe) { $reserva= new Reserva($id); $this->reservas[]=$reserva; $suma=0; foreach ($this->reservas as $r) { $suma=$suma + $r->costo; } $this->total=$suma; } } public function delete($indice){ unset($this->reservas[$indice]); $this->reservas = array_values($this->reservas); $suma=0; foreach ($this->reservas as $r) { $suma=$suma + $r->costo; } $this->total=$suma; } public function guardar(){ $exito; try { $dbh = conectarbase(); /*** echo a message saying we have connected ***/ //echo 'Connected to database'; $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $fecha=date("Y-m-d H:i:s"); $sql="INSERT into factura (fecha,total, cliente_idcliente) values('$fecha','0','$this->idcliente')"; $sql2=" SELECT idfactura FROM factura WHERE fecha='$fecha' and cliente_idcliente='$this->idcliente'"; /*** prepare the SQL statement ***/ $stmt = $dbh->prepare($sql); /*** execute the prepared statement ***/ $stmt->execute(); $stmt = $dbh->prepare($sql2); $stmt->execute(); $result = $stmt->fetch(PDO::FETCH_ASSOC); $idfactura= $result['idfactura']; foreach ($this->reservas as $r) { $r->guardar($idfactura); } /*** close the database connection ***/ $sql3="SELECT idfactura,total,fecha FROM factura where idfactura=$idfactura"; $stmt = $dbh->prepare($sql3); $stmt->execute(); $dbh = null; $exito=true; $res['factura']= $stmt->fetch(); } catch(PDOException $e) { echo $e->getMessage(); $exito=false; } $res['exito']=$exito; $res['tabla']=$this->tablaFactura(PDO::FETCH_ASSOC); return $res; } public function getReservas(){ return $this->reservas; } public function tabla(){ $tabla="<table class='table table-hover'> <thead> <tr> <th>Area</th> <th>Cost</th> <th>Date</th> <th>Start</th> <th>End</th> <th>Delete</th> </tr> </thead> <tbody>"; $i=0; foreach ($this->reservas as $r) { $tabla=$tabla."<tr> <th>".$r->lugar."</th> <th>".$r->costo."</th> <th>".$r->fecha."</th> <th>".$r->inicio."</th> <th>$r->fin</th> <th><a href='verCarrito.php?quitar=$i' class='quitar'>Delete</a></th> </tr>"; $i++; } $tabla=$tabla."</tbody></table>"; return $tabla; } public function tablaFactura(){ $tabla="<table class='table table-hover'> <thead> <tr> <th>Area</th> <th>Cost</th> <th>Date</th> <th>Start</th> <th>End</th> </tr> </thead> <tbody>"; $i=0; foreach ($this->reservas as $r) { $tabla=$tabla."<tr> <td>".$r->lugar."</td> <td>".$r->costo."</td> <td>".$r->fecha."</td> <td>".$r->inicio."</td> <td>$r->fin</td> </tr>"; $i++; } $tabla=$tabla."</tbody></table>"; return $tabla; } public function idhorarios() { $respuesta=""; $i=0; foreach ($this->reservas as $r) { if ($i==0) { $respuesta.=$r->idhorario; }else{ $respuesta.=",".$r->idhorario; } $i++; } if (strcmp($respuesta,"")==0) { $respuesta="-1"; } return $respuesta; } } class Reserva{ public $idhorario; public $costo=0; public $inicio; public $fin; public $fecha; public $lugar; public function __construct($id){ $this->idhorario=$id; $r=$this->horario(); $this->inicio=$r['inicio']; $this->fin=$r['fin']; $this->fecha=$r['fecha']; $this->costo=$r['costo']; $this->lugar=$r['nombre']; } public function guardar($id){ try { $dbh = conectarbase(); /*** echo a message saying we have connected ***/ //echo 'Connected to database'; $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $sql="INSERT into reserva (factura_idfactura,horario_idhorario) values('$id','$this->idhorario')"; /*** prepare the SQL statement ***/ $stmt = $dbh->prepare($sql); /*** execute the prepared statement ***/ $stmt->execute(); /*** close the database connection ***/ $dbh = null; } catch(PDOException $e) { echo $e->getMessage(); $exito=false; } } public function horario(){ $respuesta; try { $dbh = conectarbase(); /*** echo a message saying we have connected ***/ //echo 'Connected to database'; $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $sql="SELECT inicio,fin,fecha,costo,nombre FROM horario,espacio WHERE idespacio=espacio_idespacio and idhorario='".$this->idhorario."'"; /*** prepare the SQL statement ***/ $stmt = $dbh->prepare($sql); /*** execute the prepared statement ***/ $stmt->execute(); $result = $stmt->fetch(PDO::FETCH_ASSOC); /*** close the database connection ***/ $dbh = null; return $result; } catch(PDOException $e) { //echo $e->getMessage(); $exito=false; } return NULL; } } <file_sep><?php session_start(); if (isset($_SESSION['tipo'])){ if ($_SESSION['tipo']!=1){ header('Location: index.php'); } }else{ header('Location: index.php'); } ?> <!doctype html> <html lang='es'> <?php include 'head.php'; ?> <body role="document"> <?php include 'cabecera.php'; ?> <div class="container-fluid"> <div class="panel panel-default"> <div class="panel-heading"> <h3 class="panel-title">Eliminar Usuario</h3> </div> <div class="panel-body"> ¿Está seguro de eliminar el usuario seleccionado? <br> <button type="button" class="btn btn-danger">Aceptar</button> <button type="button" class="btn btn-default">Cancelar</button> </div> </div> </div> <footer> </footer> </body> </html>
2a27aa2bc7fa3ddb3f2f483b6beffb460a6a72fb
[ "SQL", "PHP" ]
40
PHP
CarlosDubon/CRS
fe5df52215248d6ae164fc546f7e5bc36c6dd253
6a791c2e775db17b4477de20cdb694e214bff37d
refs/heads/master
<repo_name>matheusoliveiramota/SQL_SERVER<file_sep>/[SQL SERVER] Consultas Inteligentes/Funcoes+de+datas.sql -- DATA DO SISTEMA SELECT SYSDATETIME() -- 7 CASAS DECIMAIS EM MILISEGUNDOS SELECT GETDATE() -- 3 CASAS DECIMAS EM MILISEGUNDOS SELECT CURRENT_TIMESTAMP -- 3 CASAS DECIMAIS EM MILISEGUNDOS -- DATA EM RELAÇÃO À GREENWICH SELECT SYSDATETIMEOFFSET() -- DATA ATUAL COM A DIFERENÇA PARA A CONVENÇÃO DE GREENWICH SELECT SYSUTCDATETIME() -- DATA DE GREENWICH: 7 CASAS DECIMAIS EM MILISEGUNDOS SELECT GETUTCDATE() -- DATA DE GREENWICH: 3 CASAS DECIMAIS EM GREENWICH -- RETORNA STRING, EM CASO DE MÊS RETORNA O NOME DO MÊS SELECT DATENAME(YEAR,GETDATE()) SELECT DATENAME(MICROSECOND,GETDATE()) SELECT DATENAME(MINUTE,GETDATE()) SELECT DATENAME(MONTH,GETDATE()) -- RETORNA UMA DATA, DE ACORDO COM A PARTE DESEJADA SELECT DATEPART(MONTH,GETDATE()) SELECT DAY(GETDATE()) SELECT YEAR(GETDATE()) -- RETORNA UMA DATA A PARTIR DAS PARTES DESEJADAS SELECT DATEFROMPARTS(2015,9,1) -- RETORNA RETORNA UMA DATA A PARTIR DE PARTES, COM HORAS MINUTOS, SEGUNDOS, SEGUNDOS E Nº DE CASAS DESEJADAS SELECT DATETIME2FROMPARTS(2015,9,1,13,12,11,120,3) -- DIFERENÇA ENTRE MENOR / MAIOR DATA SELECT DATEDIFF(DAY, DATEFROMPARTS(2018,12,1), GETDATE()) -- ADICIONA A PARTE DA DATA DESEJADA, O ACRÉSCIMO E A DATA BASE SELECT DATEADD(MONTH, 5, GETDATE()) -- RETORNA 0 / 1: PARA VALIDAR SE É OU NÃO UMA DATA VAIDA SELECT ISDATE('2018-01-01')
ff2ab41f54864aaf244ca2716914b231da23ecca
[ "SQL" ]
1
SQL
matheusoliveiramota/SQL_SERVER
6a7b6a6bafe185b11d68c855b59c4c010bfd2d52
2ac6e5ed651d2cbf48053747b594c900fcdd619e
refs/heads/master
<repo_name>vishal5963/weather-temperature<file_sep>/src/TableData.js import React from "react"; const TableData = ({ temp_arr, city, country }) => { console.log(city, "*******"); return ( <div className="weather__info"> {console.log(temp_arr !== undefined && temp_arr.length !== 0, "===1====")} {temp_arr && temp_arr.length !== 0 && <table style={{color: "red", width: "700px", border: "2px solid red"}}> <tbody> { temp_arr.map((tempList,i) =>( <tr key={i} > <td>{city},{country}</td> <td>{tempList.main.temperature}</td> <td>{tempList.main.humidity}</td> <td>{tempList.weather[0].description}</td> <td>{tempList.dt_txt}</td> <td>{tempList.error}</td> </tr> )) } </tbody> </table>} </div> ); }; export default TableData;
45997eba886f544f2150a5b3224d19a016b14f93
[ "JavaScript" ]
1
JavaScript
vishal5963/weather-temperature
0ef25916d0f1c30c86c2d7922dac6d8849ed3cba
f7ce9b86b1666841def2d19ed18b5fb93aa74857
refs/heads/master
<file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> #define MAXTAM 100 typedef struct { float Item[MAXTAM]; int Topo; }TPilha; //inicia a pilha void TPilha_Inicia (TPilha *pPilha){ pPilha->Topo = 0; } //verifica pilha vazia float TPilha_EhVazia(TPilha *pPilha){ return (pPilha->Topo == 0); } //insere na pilha float TPilha_Empilha(TPilha *pPilha, float x) { if (pPilha->Topo == MAXTAM) return 0; /* pilha cheia */ pPilha->Item[pPilha->Topo] = x; pPilha->Topo++; return 1; } //retira na pilha float TPilha_Desempilha(TPilha *pPilha) { if (TPilha_EhVazia(pPilha)) return 0; float aux; pPilha->Topo--; aux = pPilha->Item[pPilha->Topo]; return aux; } //tamanho pilha float TPilha_Tamanho(TPilha *pPilha) { return (pPilha->Topo); } int main(){ int i=0; float j=0, k=0, l=0; TPilha *pPilha = (TPilha*)malloc(sizeof(TPilha)); TPilha_Inicia(pPilha); char expressao[50]; scanf("%s", expressao); //recebe a expressao for (i=0; i<strlen(expressao); i++){ //laco de tamnho "i" caracteres para avaliar os caracteres da expressao switch (expressao[i]){ //switch case para os casos "/", "*", "+", "-" ou caracter letra case '/': //para cada caso "/", "*", "+","-" desempilha os ultimos dois valores da pilha realiza a devida operacao e empilha o resultado j = TPilha_Desempilha(pPilha); k = TPilha_Desempilha(pPilha); l = k / j; TPilha_Empilha(pPilha, l); break; case '*': j = TPilha_Desempilha(pPilha); k = TPilha_Desempilha(pPilha); l = k * j; TPilha_Empilha(pPilha, l); break; case '+': j = TPilha_Desempilha(pPilha); k = TPilha_Desempilha(pPilha); l = k + j; TPilha_Empilha(pPilha, l); break; case '-': j = TPilha_Desempilha(pPilha); k = TPilha_Desempilha(pPilha); l = k - j; TPilha_Empilha(pPilha, l); break; default: // no caso de nao ser um caracter "/", "*", "+" ou "-" recebe um valor que e empilhado scanf("%f", &l); TPilha_Empilha(pPilha, l); break; } } j = TPilha_Desempilha(pPilha); printf("%f", j); //printa o resultado da expressao return 0; } <file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> #define INICIO 0 #define MAXTAM 1000 typedef struct { char nome[20]; } TItem; typedef struct { TItem Item[MAXTAM]; int Primeiro, Ultimo; int tamanho; } TLista; void TLista_Inicia(TLista *pLista) { pLista->Primeiro = INICIO; pLista->Ultimo = pLista->Primeiro; pLista->tamanho = 0; } /* TLista_Inicia */ int TLista_EhVazia(TLista *pLista) { return (pLista->Primeiro == pLista->Ultimo); } /* TLista_EhVazia */ int TLista_Tamanho(TLista *pLista) { return (pLista->Ultimo - pLista->Primeiro); } /* TLista_Tamanho */ int TLista_Insere(TLista *pLista, int p, TItem x) { int q; if ((pLista->Ultimo == MAXTAM) || (p < pLista->Primeiro) || (p > pLista->Ultimo)) return 0; for (q = pLista->Ultimo-1; q >= p; q--) pLista->Item[q+1] = pLista->Item[q]; pLista->Item[p] = x; pLista->Ultimo++; pLista->tamanho++; return 1; } /* TLista_Insere */ int TLista_Retira(TLista *pLista, int p, TItem *pX) { int q; if (TLista_EhVazia(pLista) || (p < pLista->Primeiro) || (p >= pLista->Ultimo)){ return 0; } *pX = pLista->Item[p]; for (q = p+1; q < pLista->Ultimo; q++){ pLista->Item[q-1] = pLista->Item[q]; } pLista->Ultimo--; pLista->tamanho--; return 1; } /* TLista_Retira */ int main(){ int i=0, n, k, K, aux; char nome[20]; TLista lista; TLista_Inicia(&lista); scanf("%d", &n); scanf("%d", &k); TItem crianca; K = k; for(i=0; i<n; i++){ scanf("%s", nome); strcpy(crianca.nome, nome); TLista_Insere(&lista, i, crianca); } int divisao; int Tamanho = lista.tamanho; while (lista.tamanho > 0){ divisao = k / Tamanho; k = k - (divisao * Tamanho); TLista_Retira(&lista, k, &crianca); aux = k + K; k = aux; Tamanho = Tamanho - 1; printf("%s\n", crianca.nome); } } <file_sep>#include <stdio.h> #include <stdlib.h> #define MAXVERTICES 100 typedef int TVertice; typedef int TAresta; typedef struct { int IncideAresta; TAresta Aresta; } TAdjacencia; typedef struct { TAdjacencia Adj[MAXVERTICES][MAXVERTICES]; int NVertices; int NArestas; } TGrafo; /* Inicia as variaveis do grafo */ int TGrafo_Inicia(TGrafo *pGrafo, int NVertices){ TVertice u, v; if (NVertices > MAXVERTICES) return 0; pGrafo->NVertices = NVertices; pGrafo->NArestas = 0; for (u = 0; u < pGrafo->NVertices; u++) for (v = 0; v < pGrafo->NVertices; v++) pGrafo->Adj[u][v].IncideAresta = 0; return 1; } /* Retorna se existe a aresta (u, v) no grafo */ int TGrafo_ExisteAresta(TGrafo *pGrafo, TVertice u, TVertice v) { return pGrafo->Adj[u][v].IncideAresta; } /* Insere a aresta e incidente aos vertices u e v no grafo */ int TGrafo_InsereAresta(TGrafo *pGrafo, TVertice u, TVertice v) { pGrafo->Adj[u][v].IncideAresta = 1; pGrafo->Adj[u][v].Aresta = 1; pGrafo->NArestas++; return 1; } /* Retira a aresta e incidente aos vertices u e v no grafo */ int TGrafo_RetiraAresta(TGrafo *pGrafo, TVertice u, TVertice v) { if (! TGrafo_ExisteAresta(pGrafo, u, v)) return 0; pGrafo->Adj[u][v].IncideAresta = 0; pGrafo->NArestas--; return 1; } /* Retorna o numero de vertices do grafo */ int TGrafo_NVertices(TGrafo *pGrafo) { return (pGrafo->NVertices); } /* Retorna o numero de arestas do grafo */ int TGrafo_NArestas(TGrafo *pGrafo) { return (pGrafo->NArestas); } int main() { int n, d, i=0, j=0, u, v, k=0, e; scanf("%d" "%d", &n, &d); TGrafo pGrafo; TGrafo_Inicia(&pGrafo, n); for(i=0; i<d; i++){ scanf("%d" "%d", &u, &v); TGrafo_InsereAresta(&pGrafo, u-1, v-1); } for(i=0; i<n; i++){ printf("%d ", i+1); for(j=0; j<n; j++){ if(pGrafo.Adj[j][i].IncideAresta != 0){ k++; } } printf("%d ", k); k=0; for(j=0; j<n; j++){ if(pGrafo.Adj[i][j].IncideAresta != 0){ k++; } } printf("%d ", k); k=0; for(j=0; j<n; j++){ if(TGrafo_ExisteAresta(&pGrafo, i, j) != 0){ printf("%d ", j+1); } } printf("\n"); } return 0; }<file_sep>#include <stdio.h> #include <stdlib.h> #include <math.h> #define MAXTAM 65536 typedef struct { int indice; int forca; } TItem; TItem dados(int indice, int forca){ TItem competidor; competidor.indice = indice; competidor.forca = forca; return competidor; } typedef struct { TItem Item[MAXTAM]; int Frente, Tras; int tamanho; } TFila; void TFila_Inicia(TFila *pFila) { pFila->Frente = 0; pFila->Tras = 0; pFila->tamanho = 0; } /* TFila_Inicia */ int TFila_EhVazia(TFila *pFila) { return (pFila->Frente == pFila->Tras); } /* TFila_EhVazia */ int TFila_Enfileira(TFila *pFila, TItem x) { pFila->Item[pFila->Tras] = x; pFila->Tras = (pFila->Tras + 1) % MAXTAM; pFila->tamanho++; return 1; } /* TFila_Enfileira */ int TFila_Desenfileira(TFila *pFila, TItem *pX) { if (TFila_EhVazia(pFila)) return 0; *pX = pFila->Item[pFila->Frente]; pFila->Frente = (pFila->Frente + 1) % MAXTAM; pFila->tamanho--; return 1; } /* TFila_Desenfileira */ int main(){ TFila pFila; int n, k, ncompetidores, i=0; int forca1; TItem a, b; TFila_Inicia(&pFila); scanf("%d %d", &n, &k); ncompetidores = pow(2,n); for (i=0; i<ncompetidores; i++){ scanf("%d",&forca1); TFila_Enfileira(&pFila, dados(i+1, forca1)); } while(pFila.tamanho > 1){ TFila_Desenfileira(&pFila, &a); TFila_Desenfileira(&pFila, &b); if (a.forca >= b.forca){ forca1 = a.forca - b.forca; forca1 = forca1 + k; TFila_Enfileira(&pFila, dados(a.indice, forca1)); } else{ forca1 = b.forca - a.forca; forca1 = forca1 + k; TFila_Enfileira(&pFila, dados(b.indice, forca1)); } } TFila_Desenfileira(&pFila, &a); printf("%d",a.indice); return 0; }<file_sep>#include <stdio.h> #include <stdlib.h> typedef struct { int codigo; int matricula; } TAluno; typedef struct { int codigo; int NAlunos; int cont; } TUnidade; int main() { int n, m, i = 0, a = 0, pergunta = 0; scanf("%d", &n); TUnidade *unidade = (TUnidade*) malloc(n * sizeof(TUnidade)); if(unidade == NULL){ printf("ERRO: sem memoria!\n"); exit(1); } for(i = 0; i < n; i++){ scanf("%d %d", &unidade[i].codigo, &unidade[i].NAlunos); } scanf("%d", &m); TAluno *bloco = (TAluno*) malloc(m * sizeof(TAluno)); if(bloco == NULL){ printf("ERRO: sem memoria!\n"); exit(1); } while(bloco[a - 1].codigo != -1){ if((a % m) == 0){ bloco = (TAluno*) realloc(bloco, (m * sizeof(TAluno))); } scanf("%d", &bloco[a].codigo); if(bloco[a].codigo != -1) scanf("%d", &bloco[a].matricula); a++; } int c = 0, d = 0, aux = 0; for(d = 0; d < n; d++){ for(c = 0; c < a; c++){ if(bloco[c].codigo == unidade[d].codigo){ aux++; unidade[d].cont = aux; } } aux = 0; } int e = 0, maior = 0; maior = unidade[0].cont; // assume que o primeiro é o maior for(e=0; e<n; e++){ if (unidade[e].cont > maior) maior = unidade[e].cont; } int g = 0, novo = 0; for (g=0; g<n; g++){ if(unidade[g].cont == maior){ printf("%d\n", unidade[g].codigo); novo = g; } } int b = 0; for(b=0; b<a; b++){ if(bloco[b].codigo == unidade[novo].codigo){ printf("%d\n", bloco[b].matricula); } } return 0; } <file_sep>#include <stdio.h> #include <stdlib.h> typedef int TIPOCHAVE; typedef struct no { TIPOCHAVE chave; struct no *primFilho; struct no *proxIrmao; } NO; typedef NO* PONT; /*cria um novo no na arvore*/ PONT criaNovoNO(TIPOCHAVE ch){ PONT novo = (PONT)malloc(sizeof(NO)); novo->primFilho = NULL; novo->chave = ch; return(novo); } /*inicializa uma nova arvore*/ PONT inicializa(TIPOCHAVE ch){ return(criaNovoNO(ch)); } PONT buscaChave(TIPOCHAVE ch, PONT raiz){ if (raiz == NULL) return NULL; if (raiz->chave == ch) return raiz; PONT p = raiz->primFilho; while(p) { PONT resp = buscaChave(ch, p); if (resp) return(resp); p = p->proxIrmao; } return(NULL); } /*insere novo vertice*/ int insere(PONT raiz, TIPOCHAVE novaChave, TIPOCHAVE chavePai){ PONT pai = buscaChave(chavePai,raiz); if (!pai) return(0); PONT filho = criaNovoNO(novaChave); PONT p = pai->primFilho; if (!p) pai->primFilho = filho; else { while (p->proxIrmao) p = p->proxIrmao; p->proxIrmao = filho; } return(1); } /*imprime a arvore*/ void exibirArvore(PONT raiz){ if (raiz == NULL) return; printf("(%d",raiz->chave); PONT p = raiz->primFilho; while (p) { exibirArvore(p); p = p->proxIrmao; } printf(")"); } int main() { int n, m, i = 0, p, f; scanf("%d" "%d", &n, &m); int r = 1; PONT pont; pont = inicializa(r); /*laço para inserir as relaçoes entre os membros da familia*/ for(i=0; i<m; i++){ scanf("%d" "%d", &p, &f); insere(pont, f, p); } exibirArvore(pont); return 0; }<file_sep>#include <stdio.h> #include <stdlib.h> struct NO{ int info; struct NO *esq; struct NO *dir; }; typedef struct NO* ArvBin; ArvBin* cria_ArvBin(){ ArvBin* raiz = (ArvBin*) malloc(sizeof(ArvBin)); if(raiz != NULL) *raiz = NULL; return raiz; } int insere_ArvBin(ArvBin* raiz, int valor){ if(raiz == NULL) return 0; struct NO* novo; novo = (struct NO*) malloc(sizeof(struct NO)); if(novo == NULL) return 0; novo->info = valor; novo->dir = NULL; novo->esq = NULL; if(*raiz == NULL) *raiz = novo; else{ struct NO* atual = *raiz; struct NO* ant = NULL; while(atual != NULL){ ant = atual; if(valor == atual->info){ free(novo); return 0;//elemento jŠ existe } if(valor > atual->info) atual = atual->dir; else atual = atual->esq; } if(valor > ant->info) ant->dir = novo; else ant->esq = novo; } return 1; } void posOrdem_ArvBin(ArvBin *raiz){ if(raiz == NULL) return; if(*raiz != NULL){ posOrdem_ArvBin(&((*raiz)->esq)); posOrdem_ArvBin(&((*raiz)->dir)); printf("%d\n",(*raiz)->info); } } int main() { int T, n, i=0; scanf("%d", &T); ArvBin* raiz = cria_ArvBin(); for(i=0; i<T; i++){ scanf("%d", &n); insere_ArvBin(raiz, n); } for(i=0; i<T; i++) scanf("%d", &n); posOrdem_ArvBin(raiz); return 0; } <file_sep>#include <stdio.h> #include <stdlib.h> struct NO{ int info; struct NO *esq; struct NO *dir; }; typedef struct NO* ArvBin; ArvBin* cria_ArvBin(){ ArvBin* raiz = (ArvBin*) malloc(sizeof(ArvBin)); if(raiz != NULL) *raiz = NULL; return raiz; } int insere_ArvBin(ArvBin* raiz, int valor){ if(raiz == NULL) return 0; struct NO* novo; novo = (struct NO*) malloc(sizeof(struct NO)); if(novo == NULL) return 0; novo->info = valor; novo->dir = NULL; novo->esq = NULL; if(*raiz == NULL) *raiz = novo; else{ struct NO* atual = *raiz; struct NO* ant = NULL; while(atual != NULL){ ant = atual; if(valor == atual->info){ free(novo); return 0;//elemento já existe } if(valor > atual->info) atual = atual->dir; else atual = atual->esq; } if(valor > ant->info) ant->dir = novo; else ant->esq = novo; } return 1; } struct NO* remove_atual(struct NO* atual) { struct NO *no1, *no2; if(atual->esq == NULL){ no2 = atual->dir; free(atual); return no2; } no1 = atual; no2 = atual->esq; while(no2->dir != NULL){ no1 = no2; no2 = no2->dir; } // no2 é o nó anterior a r na ordem e-r-d // no1 é o pai de no2 if(no1 != atual){ no1->dir = no2->esq; no2->esq = atual->esq; } no2->dir = atual->dir; free(atual); return no2; } int remove_ArvBin(ArvBin *raiz, int valor){ if(raiz == NULL) return 0; struct NO* ant = NULL; struct NO* atual = *raiz; while(atual != NULL){ if(valor == atual->info){ if(atual == *raiz) *raiz = remove_atual(atual); else{ if(ant->dir == atual) ant->dir = remove_atual(atual); else ant->esq = remove_atual(atual); } return 1; } ant = atual; if(valor > atual->info) atual = atual->dir; else atual = atual->esq; } return 0; } int consulta_ArvBin(ArvBin *raiz, int valor){ if(raiz == NULL) return 0; struct NO* atual = *raiz; while(atual != NULL){ if(valor == atual->info){ return 1; } if(valor > atual->info) atual = atual->dir; else atual = atual->esq; } return 0; } void preOrdem_ArvBin(ArvBin *raiz){ if(raiz == NULL){ return; } if(*raiz != NULL){ printf("(C%d",(*raiz)->info); preOrdem_ArvBin(&((*raiz)->esq)); if((*raiz)->esq == NULL) printf("()"); preOrdem_ArvBin(&((*raiz)->dir)); if((*raiz)->dir == NULL) printf("()"); printf(")"); } } int main() { int q, n, b, i=0; ArvBin* raiz = cria_ArvBin(); scanf("%d", &q); if(q==0){ printf("()"); return 0; } for(i=0; i<q; i++){ scanf("%d", &n); insere_ArvBin(raiz, n); } scanf("%d", &b); if(q==1 && n==b){ printf("()"); return 0; } if(consulta_ArvBin(raiz, b) == 1){ remove_ArvBin(raiz, b); } else{ insere_ArvBin(raiz, b); } preOrdem_ArvBin(raiz); return 0; }<file_sep># AED-1 Projetos realizadas na disciplina de Algoritmos e Estrutura de Dados 1 da UNIFESP
954132f70c9eca3cb53c5ae801b2ae3a36b173f8
[ "Markdown", "C" ]
9
C
miguel-freitas/AED-1
07947654448cf5bba1007fb428110f8d1e0276ea
50bb88b0631b03bb0c0f2660dd7c352f6dd22a51
refs/heads/master
<file_sep>#------------------------------------------------------------------------------- #NOT-SO EXTREME FIGHTING # <NAME>, <NAME>, <NAME>, <NAME> # Build Captain Falcon Module #------------------------------------------------------------------------------- # CaptFalcSheet cred: InfinitysEnd # http://infinitysend.deviantart.com/art/SSB-Melee-Captain-Falcon-26122435 from Classes import sprite import pygame def idleAnim(): captainSheet = pygame.image.load("CaptFalcSheet.gif").convert_alpha() captainStand1 = sprite("captainStand1",captainSheet,19,61,21,78,5,0,-45) return [captainStand1] def walkList(): captainSheet = pygame.image.load("CaptFalcSheet.gif").convert_alpha() captainWalk3 = sprite("captainWalk3",captainSheet,495,565,111,165,5,0,-20) captainWalk4 = sprite("captainWalk4",captainSheet,578,620,111,165,5,0,-20) captainWalk5 = sprite("captainWalk5",captainSheet,209,278,115,165,5,0,-20) captainWalk6 = sprite("captainWalk6",captainSheet,286,356,114,165,5,0,-20) return [captainWalk3,captainWalk4,\ captainWalk5,captainWalk6] def startStopAnim(): captainSheet = pygame.image.load("CaptFalcSheet.gif").convert_alpha() captainWalk1 = sprite("captainWalk1",captainSheet,367,414,111,165,5,0,-20) captainWalk2 = sprite("captainWalk2",captainSheet,419,488,115,165,5,0,-20) return [captainWalk1,captainWalk2] def jumpAnim(): captainSheet = pygame.image.load("CaptFalcSheet.gif").convert_alpha() captainJump1 = sprite("captainJump1",captainSheet,26,79,111,162,5,0,-40) captainJump2 = sprite("captainJump2",captainSheet,247,286,11,85,5,0,-40) captainJump3 = sprite("captainJump3",captainSheet,306,341,395,468,5,0,-40) captainJump4 = sprite("captainJump4",captainSheet,26,79,111,162,5,0,-40) return [captainJump1,captainJump2,captainJump2,captainJump2,\ captainJump3,captainJump3] def dashAnim(): captainSheet = pygame.image.load("CaptFalcSheet.gif").convert_alpha() captainDash1 = sprite("captainJab1",captainSheet,21,106,408,446,5,0,0) return [captainDash1] def attackAnim(): captainSheet = pygame.image.load("CaptFalcSheet.gif").convert_alpha() captainPunch1 = sprite("captainPunch1",captainSheet,26,79,111,162,5,0,-70) captainPunch2 = sprite("captainPunch2",captainSheet,414,516,194,260,5,0,-70) captainPunch3 = sprite("captainPunch3",captainSheet,530,640,195,260,5,0,-70) captainPunch4 = sprite("captainPunch4",captainSheet,270,391,194,260,5,0,-70) return [captainPunch1,captainPunch2,captainPunch3,captainPunch4] def widest(): captainSheet = pygame.image.load("CaptFalcSheet.gif").convert_alpha() captainStand1 = sprite("captainStand1",captainSheet,19,61,21,78,5,0,0) return captainStand1 def tallest(): captainSheet = pygame.image.load("CaptFalcSheet.gif").convert_alpha() captainJump4 = sprite("captainJump4",captainSheet,26,79,111,162,5,0,0) return captainJump4 def default(): captainSheet = pygame.image.load("CaptFalcSheet.gif").convert_alpha() captainStand1 = sprite("captainStand1",captainSheet,19,61,21,78,5,0,0) return captainStand1 <file_sep>from Classes import sprite import pygame #Creates sprite #BlueZero def idleAnim(): blueZeroSpriteSheet = pygame.image.load("Blue Zero Sprite Sheet.gif")\ .convert_alpha() blueZeroStand = sprite("blueZeroStand",blueZeroSpriteSheet,5,48,5,52,5,0,0) return [blueZeroStand] def walkList(): blueZeroSpriteSheet = pygame.image.load("Blue Zero Sprite Sheet.gif")\ .convert_alpha() blueZeroWalk3 = sprite("blueZeroWalk3",blueZeroSpriteSheet,206,254,164,\ 210,5,0,0) blueZeroWalk4 = sprite("blueZeroWalk4",blueZeroSpriteSheet,261,307,163,\ 210,5,0,0) blueZeroWalk5 = sprite("blueZeroWalk5",blueZeroSpriteSheet,315,359,161,\ 209,5,0,0) blueZeroWalk6 = sprite("blueZeroWalk6",blueZeroSpriteSheet,367,407,161,\ 209,5,0,0) blueZeroWalk7 = sprite("blueZeroWalk7",blueZeroSpriteSheet,419,464,164,\ 211,5,0,0) blueZeroWalk8 = sprite("blueZeroWalk8",blueZeroSpriteSheet,475,524,165,\ 210,5,0,0) blueZeroWalk9 = sprite("blueZeroWalk9",blueZeroSpriteSheet,531,576,166,\ 212,5,0,0) blueZeroWalk10 = sprite("blueZeroWalk10",blueZeroSpriteSheet,583,633,165,\ 212,5,0,0) blueZeroWalk11 = sprite("blueZeroWalk11",blueZeroSpriteSheet,640,686,164,\ 212,5,0,0) blueZeroWalk12 = sprite("blueZeroWalk12",blueZeroSpriteSheet,695,738,163,\ 212,5,0,0) blueZeroWalk13 = sprite("blueZeroWalk13",blueZeroSpriteSheet,745,787,163,\ 212,5,0,0) blueZeroWalk14 = sprite("blueZeroWalk14",blueZeroSpriteSheet,795,840,164,\ 212,5,0,0) return [blueZeroWalk3,blueZeroWalk4,blueZeroWalk5,blueZeroWalk6,blueZeroWalk7,\ blueZeroWalk8,blueZeroWalk9,blueZeroWalk10,blueZeroWalk11,\ blueZeroWalk12,blueZeroWalk13,blueZeroWalk14] def startStopAnim(): blueZeroSpriteSheet = pygame.image.load("Blue Zero Sprite Sheet.gif")\ .convert_alpha() blueZeroWalk1 = sprite("blueZeroWalk1",blueZeroSpriteSheet,93,144,164,\ 208,5,0,0) blueZeroWalk2 = sprite("blueZeroWalk2",blueZeroSpriteSheet,151,201,165,\ 210,5,0,0) return [blueZeroWalk1,blueZeroWalk2] def jumpAnim(): blueZeroSpriteSheet = pygame.image.load("Blue Zero Sprite Sheet.gif")\ .convert_alpha() blueZeroJump1 = sprite("blueZeroJump1",blueZeroSpriteSheet,14,53,89,137,\ 5,0,0) blueZeroJump2 = sprite("blueZeroJump2",blueZeroSpriteSheet,59,103,85,141,\ 5,0,0) blueZeroJump3 = sprite("blueZeroJump3",blueZeroSpriteSheet,110,153,85,141,\ 5,0,0) blueZeroJump4 = sprite("blueZeroJump4",blueZeroSpriteSheet,163,206,84,141,\ 5,0,0) blueZeroJump5 = sprite("blueZeroJump5",blueZeroSpriteSheet,213,256,84,140,\ 5,0,0) blueZeroJump6 = sprite("blueZeroJump6",blueZeroSpriteSheet,263,303,84,136,\ 5,0,0) blueZeroJump7 = sprite("blueZeroJump7",blueZeroSpriteSheet,308,348,84,139,\ 5,0,0) blueZeroJump8 = sprite("blueZeroJump8",blueZeroSpriteSheet,353,389,84,148,\ 5,0,0) blueZeroJump9 = sprite("blueZeroJump9",blueZeroSpriteSheet,398,433,75,152,\ 5,0,0) blueZeroJump10 = sprite("blueZeroJump10",blueZeroSpriteSheet,443,478,72,\ 151,5,0,0) blueZeroJump11 = sprite("blueZeroJump11",blueZeroSpriteSheet,488,528,90,\ 149,5,0,0) return [blueZeroJump1,blueZeroJump2,blueZeroJump3,blueZeroJump4,blueZeroJump5,blueZeroJump6,\ blueZeroJump7,blueZeroJump8,blueZeroJump9,blueZeroJump10,blueZeroJump11] def dashAnim(): blueZeroSpriteSheet = pygame.image.load("Blue Zero Sprite Sheet.gif")\ .convert_alpha() blueZeroDash1 = sprite("blueZeroDash1",blueZeroSpriteSheet,541,611,104,\ 149,5,-5,0) blueZeroDash2 = sprite("blueZeroDash2",blueZeroSpriteSheet,620,727,112,\ 148,5,-5,0) blueZeroDash3 = sprite("blueZeroDash3",blueZeroSpriteSheet,734,865,112,\ 150,5,-5,0) return [blueZeroDash1,blueZeroDash2,blueZeroDash3] def attackAnim(): blueZeroSpriteSheet = pygame.image.load("Blue Zero Sprite Sheet.gif")\ .convert_alpha() blueZeroSword1 = sprite("blueZeroSword1",blueZeroSpriteSheet,7,46,298,\ 344,5,0,0) blueZeroSword2 = sprite("blueZeroSword2",blueZeroSpriteSheet,52,98,294,\ 344,5,-6,0) blueZeroSword3 = sprite("blueZeroSword3",blueZeroSpriteSheet,102,151,283,\ 346,5,-3,-4) blueZeroSword4 = sprite("blueZeroSword4",blueZeroSpriteSheet,157,235,283,\ 346,5,-3,-17) blueZeroSword5 = sprite("blueZeroSword5",blueZeroSpriteSheet,242,329,283,\ 343,5,-5,-15) blueZeroSword6 = sprite("blueZeroSword6",blueZeroSpriteSheet,337,428,295,\ 343,5,-9,-6) blueZeroSword7 = sprite("blueZeroSword7",blueZeroSpriteSheet,437,520,294,\ 343,5,-2,-6) blueZeroSword8 = sprite("blueZeroSword8",blueZeroSpriteSheet,527,597,298,\ 343,5,-1,0) blueZeroSword9 = sprite("blueZeroSword9",blueZeroSpriteSheet,607,666,298,\ 342,5,0,0) blueZeroSword10 = sprite("blueZeroSword10",blueZeroSpriteSheet,677,729,\ 297,342,5,0,0) blueZeroSword11 = sprite("blueZeroSword11",blueZeroSpriteSheet,737,782,\ 297,342,5,0,0) return [blueZeroSword1,blueZeroSword2,blueZeroSword3,blueZeroSword4,\ blueZeroSword5,blueZeroSword6,blueZeroSword7,blueZeroSword8,\ blueZeroSword9,blueZeroSword10,blueZeroSword11] def widest(): blueZeroSpriteSheet = pygame.image.load("Blue Zero Sprite Sheet.gif")\ .convert_alpha() blueZeroStand = sprite("blueZeroStand",blueZeroSpriteSheet,5,48,5,52,5,0,0) return blueZeroStand def tallest(): blueZeroSpriteSheet =pygame.image.load("Blue Zero Sprite Sheet.gif")\ .convert_alpha() blueZeroStand = sprite("blueZeroStand",blueZeroSpriteSheet,5,48,5,52,5,0,0) return blueZeroStand def default(): blueZeroSpriteSheet = pygame.image.load("Blue Zero Sprite Sheet.gif")\ .convert_alpha() blueZeroStand = sprite("blueZeroStand",blueZeroSpriteSheet,5,48,5,52,5,0,0) return blueZeroStand <file_sep>"New_Zero_Fighting.py" is name of main game file run this file to run game. UPDATE: character select has been added, fixed sprite and controller plugins<file_sep>from Classes import sprite import pygame #KOOPASHEET CRED: nonononomo #http://www.deviantart.com/art/Star-Mario-Red-ninjakoopa-Sprites-368850154 def idleAnim(): koopaSheet = pygame.image.load("koopaSheet.png").convert_alpha() koopaStand1 = sprite("koopaStand1",koopaSheet,1102,1141,29,82,3,0,150) koopaStand2 = sprite("koopaStand2",koopaSheet,1056,1094,28,82,3,0,150) koopaStand3 = sprite("koopaStand3",koopaSheet,1009,1048,30,82,3,0,150) return [koopaStand1,koopaStand2,koopaStand3] def startStopAnim(): koopaSheet = pygame.image.load("koopaSheet.png").convert_alpha() koopaWalk1 = sprite("koopaWalk1",koopaSheet,994,1033,91,144,3,0,150) koopaWalk2 = sprite("koopaWalk2",koopaSheet,1036,1080,92,144,3,0,150) return [koopaWalk1,koopaWalk2] def walkList(): koopaSheet = pygame.image.load("koopaSheet.png").convert_alpha() koopaWalk3 = sprite("koopaWalk3",koopaSheet,1096,1143,94,144,3,0,140) koopaWalk4 = sprite("koopaWalk2",koopaSheet,1036,1080,92,144,3,0,140) koopaWalk5 = sprite("koopaWalk1",koopaSheet,994,1033,91,144,3,0,140) return [koopaWalk3,koopaWalk4,koopaWalk5] def crouchAnim(): koopaSheet = pygame.image.load("koopaSheet.png").convert_alpha() koopaCrouch1 = sprite("koopaCrouch1",koopaSheet,822,860,311,361,3,0,0) koopaCrouch2 = sprite("koopaCrouch2",koopaSheet,878,907,324,356,3,0,0) koopaCrouch3 = sprite("koopaCrouch3",koopaSheet,916,943,327,353,3,0,0) koopaCrouch4 = sprite("koopaCrouch4",koopaSheet,1101,1134,151,176,3,0,0) return [koopaCrouch1,koopaCrouch2,koopaCrouch3,koopaCrouch4] def jumpAnim(): koopaSheet = pygame.image.load("koopaSheet.png").convert_alpha() koopaJump1 = sprite("koopaJump1",koopaSheet,1031,1078,250,299,3,0,180) koopaJump2 = sprite("koopaJump2",koopaSheet,1031,1078,250,299,3,0,180) koopaJump3 = sprite("koopaJump3",koopaSheet,965,1016,242,296,3,0,180) koopaJump4 = sprite("koopaJump4",koopaSheet,965,1016,242,296,3,0,180) koopaJump5 = sprite("koopaJump5",koopaSheet,845,889,243,290,3,0,180) return [koopaJump1,koopaJump2,koopaJump3,koopaJump4,koopaJump5] def dashAnim(): koopaSheet = pygame.image.load("koopaSheet.png").convert_alpha() ## koopaDash1 = sprite("koopaDash1",koopaSheet,822,860,311,361,3,0,0) ## koopaDash2 = sprite("koopaDash2",koopaSheet,878,907,324,356,3,0,0) ## koopaDash3 = sprite("koopaDash3",koopaSheet,916,943,327,353,3,0,0) ## koopaDash4 = sprite("koopaDash4",koopaSheet,1101,1134,151,176,3,0,0) koopaDash5 = sprite("koopaDash5",koopaSheet,1058,1086,152,176,3,0,240) koopaDash6 = sprite("koopaDash6",koopaSheet,1058,1086,152,176,3,0,240) koopaDash7 = sprite("koopaDash7",koopaSheet,1018,1046,152,176,3,0,240) koopaDash8 = sprite("koopaDash8",koopaSheet,1018,1046,152,176,3,0,240) ## koopaDash9 = sprite("koopaDash9",koopaSheet,970,1002,151,176,3,0,0) ## koopaDash10 = sprite("koopaDash10",koopaSheet,970,1002,151,176,3,0,0) ## koopaDash11 = sprite("koopaDash11",koopaSheet,1018,1046,152,176,3,0,0) ## koopaDash12 = sprite("koopaDash12",koopaSheet,1057,1086,152,176,3,0,0) ## koopaDash13 = sprite("koopaDash13",koopaSheet,1101,1134,151,176,3,0,0) ## return [koopaDash1,koopaDash2,koopaDash3,koopaDash4,koopaDash5,\ ## koopaDash6,koopaDash7,koopaDash8,koopaDash9,koopaDash10,\ ## koopaDash11,koopaDash12,koopaDash13] return [koopaDash5,koopaDash6,koopaDash7,koopaDash8] def attackAnim(): koopaSheet = pygame.image.load("koopaSheet.png").convert_alpha() koopaAttack1 = sprite("koopaAttack1",koopaSheet,341,365,252,286,5,0,140) koopaAttack2 = sprite("koopaAttack2",koopaSheet,371,399,252,286,5,0,140) koopaAttack3 = sprite("koopaAttack3",koopaSheet,404,432,252,286,5,0,140) return [koopaAttack1,koopaAttack2,koopaAttack3] def widest(): koopaSheet = pygame.image.load("koopaSheet.png").convert_alpha() koopaJump1 = sprite("koopaJump1",koopaSheet,1072,1124,229,338,3,0,0) return koopaJump1 def tallest(): koopaSheet = pygame.image.load("koopaSheet.png").convert_alpha() koopaJump1 = sprite("koopaJump1",koopaSheet,1072,1124,229,338,3,0,0) return koopaJump1 def default(): koopaSheet = pygame.image.load("koopaSheet.png").convert_alpha() koopaStand1 = sprite("koopaStand1",koopaSheet,1096,1135,21,74,3,0,0) return koopaStand1 <file_sep>#=============================================================================== # Main Loop For Main Menu #=============================================================================== import GameWindow import MainMenu import sys from pygame import * from gamePad import * SCREEN_WIDTH = 1000 SCREEN_HEIGHT = 600 ##Narrative: Creates the main menu ##Preconditions: New_Zero_Fighting module calls mainMenu() ##Post conditions: Creates the screen with all drawn objects and images def mainMenu(): pygame.init() pygame.draw.rect(GameWindow.screen,(0,0,0),(20,20,20,20),0) running=True menuPause = True menuFlame = 1 flameCtr = 0 blinkCtr = 0 x=420 y=350 w=200 h=30 fullScreenBool = False #initializes game pad for main menu joystick1 = None joystick2 = None joystick_count = pygame.joystick.get_count() if joystick_count > 0: joystick1 = pygame.joystick.Joystick(0) if joystick_count > 1: joystick2 = pygame.joystick.Joystick(1) mixer.music.load("MainThemeMusic.ogg") mixer.music.play() while menuPause == True: gamePad(joystick1, joystick2) for event in pygame.event.get(): keys = pygame.key.get_pressed() #Continues through the main menu so long as 'enter' on a keyboard #is pressed or if start button pn game pad is pressed if joystick_count > 0 and joystick1.get_button(7) == 1: menuPause = False if joystick_count > 1 and joystick2.get_button(7) == 1: menuPause = False if keys[pygame.K_RETURN]: menuPause = False if event.type == pygame.QUIT or keys[pygame.K_ESCAPE]: sys.exit() quit() if keys[pygame.K_t] and fullScreenBool == True: screen = display.set_mode((SCREEN_WIDTH,SCREEN_HEIGHT)) fullScreenBool = False elif keys[pygame.K_t] and fullScreenBool == False: screen = display.set_mode(\ (SCREEN_WIDTH,SCREEN_HEIGHT),FULLSCREEN) fullScreenBool = True if joystick_count > 0: if joystick1.get_button(6) == 1 and joystick1.get_button(7)\ == 1: quit() sys.exit() if joystick1.get_button(6) == 1 and fullScreenBool == True: GameWindow.screen = pygame.display.set_mode(\ (SCREEN_WIDTH,SCREEN_HEIGHT)) fullScreenBool = False if joystick1.get_button(6) == 1 and fullScreenBool == False: GameWindow.screen = pygame.display.set_mode(\ (SCREEN_WIDTH,SCREEN_HEIGHT), FULLSCREEN) fullScreenBool = True if joystick_count > 1: if joystick2.get_button(6) == 1 and joystick2.get_button(7)\ == 1: quit() sys.exit() if joystick2.get_button(6) == 1 and fullScreenBool == True: GameWindow.screen = pygame.display.set_mode(\ (SCREEN_WIDTH,SCREEN_HEIGHT)) fullScreenBool = False if joystick2.get_button(6) == 1 and fullScreenBool == False: GameWindow.screen = pygame.display.set_mode(\ (SCREEN_WIDTH,SCREEN_HEIGHT), FULLSCREEN) fullScreenBool = True pygame.display.flip() if menuFlame ==1: surface = pygame.image.load("Menu1.JPG") GameWindow.screen.blit(surface,(0,0)) elif menuFlame == 2: surface = pygame.image.load("Menu2.JPG") GameWindow.screen.blit(surface,(0,0)) elif menuFlame == 3: surface = pygame.image.load("Menu3.JPG") GameWindow.screen.blit(surface,(0,0)) elif menuFlame == 4: surface = pygame.image.load("Menu4.JPG") GameWindow.screen.blit(surface,(0,0)) else: menuFlame = 0 if flameCtr % 4 ==0: menuFlame+=1 flameCtr+=1 if blinkCtr >= 0 and blinkCtr < 25: pygame.draw.rect(GameWindow.screen,(0,0,0),(x,y,w,h),0) elif blinkCtr >= 25 and blinkCtr < 50: pygame.draw.rect(GameWindow.screen,(0,0,0),(x+21,y,195,30),0) elif blinkCtr >= 50 and blinkCtr < 75: pygame.draw.rect(GameWindow.screen,(0,0,0),(x+36,y,185,30),0) elif blinkCtr >= 75 and blinkCtr < 100: pygame.draw.rect(GameWindow.screen,(0,0,0),(x+50,y,175,30),0) elif blinkCtr >= 100 and blinkCtr < 125: pygame.draw.rect(GameWindow.screen,(0,0,0),(x+65,y,165,30),0) elif blinkCtr >= 125 and blinkCtr < 150: pygame.draw.rect(GameWindow.screen,(0,0,0),(x+85,y,155,30),0) elif blinkCtr >= 150 and blinkCtr < 175: pygame.draw.rect(GameWindow.screen,(0,0,0),(x+116,y,145,30),0) elif blinkCtr >= 175 and blinkCtr < 200: pygame.draw.rect(GameWindow.screen,(0,0,0),(x+131,y,135,30),0) elif blinkCtr >= 200 and blinkCtr < 225: pygame.draw.rect(GameWindow.screen,(0,0,0),(x+143,y,125,30),0) elif blinkCtr >= 225 and blinkCtr < 250: pygame.draw.rect(GameWindow.screen,(0,0,0),(x+164,y,170,30),0) elif blinkCtr >= 250 and blinkCtr < 275: pygame.draw.rect(GameWindow.screen,(0,0,0),(x+185,y,1,30),0) elif blinkCtr >= 275 and blinkCtr < 300: pygame.draw.rect(GameWindow.screen,(0,0,0),(x,y,w,h),0) elif blinkCtr >= 300 and blinkCtr < 325: pygame.draw.rect(GameWindow.screen,(0,0,0),(x+185,y,w,h),0) elif blinkCtr >= 325 and blinkCtr < 350: pygame.draw.rect(GameWindow.screen,(0,0,0),(x,y,w,h),0) elif blinkCtr >= 350 and blinkCtr < 375: pygame.draw.rect(GameWindow.screen,(0,0,0),(x+185,y,w,h),0) elif blinkCtr >= 375 and blinkCtr < 400: pygame.draw.rect(GameWindow.screen,(0,0,0),(x,y,w,h),0) elif blinkCtr >= 400 and blinkCtr < 425: pygame.draw.rect(GameWindow.screen,(0,0,0),(x+185,y,w,h),0) elif blinkCtr >= 425 and blinkCtr < 450: pygame.draw.rect(GameWindow.screen,(0,0,0),(x,y,w,h),0) elif blinkCtr >= 450 and blinkCtr < 475: pygame.draw.rect(GameWindow.screen,(0,0,0),(x+185,y,w,h),0) else: blinkCtr=0 blinkCtr+=1 return running ##Narrative: Stage Selection screen is made; keyboard and joystick ## input is allowed ##Preconditions: Main menu window must be made ##Post conditions: User selects their desired stage def stageMenu(): running = True stagePause = True x=378 y=250 fullScreenBool = False #initializes game pad for stage select joystick1 = None joystick2 = None joystick_count = pygame.joystick.get_count() if joystick_count > 0: joystick1 = pygame.joystick.Joystick(0) if joystick_count > 1: joystick2 = pygame.joystick.Joystick(1) mixer.music.load("StageSelectMusic.mp3") mixer.music.play() while stagePause == True: gamePad(joystick1, joystick2) surface = pygame.image.load("StageSelect.JPG") GameWindow.screen.blit(surface,(0,0)) pygame.draw.rect(GameWindow.screen,(255,204,0),(x,y,250,150),5) for event in pygame.event.get(): keys = pygame.key.get_pressed() if joystick_count > 0 and joystick1.get_button(0) == 1: stagePause = False if joystick_count > 1 and joystick2.get_button(0) == 1: stagePause = False if keys[pygame.K_RETURN]: stagePause = False if event.type == pygame.QUIT or keys[pygame.K_ESCAPE]: sys.exit() quit() if keys[pygame.K_t] and fullScreenBool == True: screen = display.set_mode((SCREEN_WIDTH,SCREEN_HEIGHT)) fullScreenBool = False elif keys[pygame.K_t] and fullScreenBool == False: screen = display.set_mode(\ (SCREEN_WIDTH,SCREEN_HEIGHT),FULLSCREEN) fullScreenBool = True if joystick_count > 0: if joystick1.get_button(6) == 1 and \ joystick1.get_button(7) == 1: quit() sys.exit() if joystick1.get_button(6) == 1 and fullScreenBool == True: GameWindow.screen = pygame.display.set_mode((\ SCREEN_WIDTH,SCREEN_HEIGHT)) fullScreenBool = False if joystick1.get_button(6) == 1 and fullScreenBool == False: GameWindow.screen = pygame.display.set_mode((\ SCREEN_WIDTH,SCREEN_HEIGHT), FULLSCREEN) fullScreenBool = True if joystick_count > 1: if joystick2.get_button(6) == 1 and \ joystick2.get_button(7) == 1: quit() sys.exit() if joystick2.get_button(6) == 1 and fullScreenBool == True: GameWindow.screen = pygame.display.set_mode(\ (SCREEN_WIDTH,SCREEN_HEIGHT)) fullScreenBool = False if joystick2.get_button(6) == 1 and fullScreenBool == False: GameWindow.screen = pygame.display.set_mode(\ (SCREEN_WIDTH,SCREEN_HEIGHT), FULLSCREEN) fullScreenBool = True if keys[pygame.K_w] or joyUp(joystick1) or joyUp(joystick2): if y == 250: y=95 elif y == 95: y=405 else: y=250 if keys[pygame.K_s] or joyDown(joystick1) or joyDown(joystick2): if y == 250: y=405 elif y == 95: y=250 else: y=95 if keys[pygame.K_a] or joyLeft(joystick1) or joyLeft(joystick2): if x == 105: x = 652 elif x == 652: x=378 else: x = 105 if keys[pygame.K_d] or joyRight(joystick1) or joyRight(joystick2): if x == 105: x = 378 elif x == 378: x=652 else: x = 105 pygame.display.flip() return running,x,y <file_sep>from pygame import * import Health SCREEN_WIDTH=1000 SCREEN_HEIGHT=600 ##healthBar = Health.HealthBar() ##powerBar = Health.PowerBar() ##timer = Health.Timer() #Class for creating Sprites #Class for creating Sprites class sprite: def __init__(self,name,spriteSheet,spriteLeft,spriteRight,spriteTop,\ spriteBottom,scale,adjustX,adjustY): self.Name = name self.spriteSheet = spriteSheet self.Left = spriteLeft self.Right = spriteRight self.Top = spriteTop self.Bottom = spriteBottom self.Scale = scale self.Width = self.Right-self.Left self.Height = self.Bottom-self.Top self.spriteSheet.set_clip(Rect(self.Left,self.Top,self.Width,self.Height)) self.Picture = self.spriteSheet.subsurface(self.spriteSheet.get_clip()) self.ScaledWidth = self.Width * self.Scale self.ScaledHeight = self.Height * self.Scale self.Picture = transform.scale(self.Picture,\ (self.ScaledWidth,self.ScaledHeight)) self.adjustX = adjustX self.adjustY = adjustY ##Narrative: Makes sprite Scale times bigger ##Preconditions: Initialize scale, width, height, and picture ##Post conditions: Sprite is enlarged or minimized based on preferences def scale(self,scale): self.Scale = scale self.ScaledWidth = self.Width * self.Scale self.ScaledHeight = self.Height * self.Scale self.Picture = transform.scale(self.Picture,\ (self.ScaledWidth,self.ScaledHeight)) #=============================================================================== #=============================================================================== #Class for creating chatacters class Character: def __init__(self,idleAnimList,walkAnimList,\ startStopAnimList,\ jumpAnimList,dashAnimList,attack1AnimList,\ drawX,spriteDefault,animTimer,walkAnimCtr,\ walkAnimCount,idleAnimCtr,idleAnimCount,\ startStopAnimCtr,startStopAnimCount,\ jumpAnimCtr,jumpAnimCount,dashAnimCtr,\ dashAnimCount,attack1AnimCtr,attack1AnimCount,\ face,widestSprite,\ tallestSprite,speed,maxSpeed,rightSpeed,\ leftSpeed,upSpeed,downSpeed,x,y,\ jumps,jumpHeight,canLeaveScreen,\ isOffBottom,isOffTop,isOffRight,\ isOffLeft,isOffScreen,\ status,isOn,attackTime,\ name,speedStat,power,maxPower,\ damageStat,isCrouched,who): #Sprite Lists self.idleAnimList = idleAnimList self.walkAnimList = walkAnimList self.startStopAnimList = startStopAnimList self.jumpAnimList = jumpAnimList self.dashAnimList = dashAnimList self.attack1AnimList = attack1AnimList #Animation self.drawX = drawX self.sprite = spriteDefault self.animTimer = animTimer self.walkAnimCtr = walkAnimCtr self.walkAnimCount = walkAnimCount self.idleAnimCtr = idleAnimCtr self.idleAnimCount = idleAnimCount self.startStopAnimCtr = startStopAnimCtr self.startStopAnimCount = startStopAnimCount self.jumpAnimCtr = jumpAnimCtr self.jumpAnimCount = jumpAnimCount self.dashAnimCtr = dashAnimCtr self.dashAnimCount = dashAnimCount self.attack1AnimCtr = attack1AnimCtr self.attack1AnimCount = attack1AnimCount self.face = face self.widestSprite = widestSprite self.tallestSprite = tallestSprite #Movement self.speed = 1 self.maxSpeed = maxSpeed self.rightSpeed = rightSpeed self.leftSpeed = leftSpeed self.upSpeed = upSpeed self.downSpeed = downSpeed self.dy = (self.upSpeed - self.downSpeed) self.dx = (self.leftSpeed - self.rightSpeed) self.x = x self.y = y self.jumps = jumps self.jumpsLeft = self.jumps self.jumpHeight = jumpHeight self.canLeaveScreen = canLeaveScreen self.isOffBottom = isOffBottom self.isOffTop = isOffTop self.isOffRight = isOffRight self.isOffLeft = isOffLeft self.isOffScreen = isOffScreen self.status = status self.isOn = isOn self.attackTime = attackTime self.attackTimeLeft = 0 #Stats self.name = name self.speedStat = speedStat self.power = power self.maxPower = maxPower self.damageStat = damageStat self.isCrouched = isCrouched self.who = who ##Narrative: Character will be able to move right ##Preconditions: Speed attributes must be initialized ##Post conditions: Character is able to walk right based ## on their unique walk speed def moveRight(self): if self.rightSpeed < self.maxSpeed: self.rightSpeed += (self.speedStat * self.speed) ##Narrative: Character will be able to move left ##Preconditions: Speed attributes must be initialized ##Post conditions: Character is able to walk left based on ## their unique walk speed def moveLeft(self): if self.leftSpeed < self.maxSpeed: self.leftSpeed += (self.speedStat * self.speed) ##Narrative: Character is able to jump ##Preconditions: Initialize jump attributes ##Post conditions: Character is able to jump up to two times def jump(self): if self.isOn == "ground" or self.jumpsLeft > 0: self.jumpAnimCount = 0 self.downSpeed = 0 self.upSpeed = self.jumpHeight self.y -= 1 self.jumpsLeft -= 1 self.isOn = "nothing" ##Narrative:Character is able to dash left based on character direction ##Preconditions: Initialize speed, status, and power ##Post conditions: 25 power is used to dash left def leftDash(self): if self.status != "jumping" and self.power >= 25: self.power -= 25 self.rightSpeed = 0 self.upSpeed = 0 self.downSpeed = 0 self.status = "dashing" self.leftSpeed = 40 ##Narrative:Character is able to dash right basedon character direction ##Preconditions: Initialize speed, status, and power ##Post conditions: 25 power is used to dash right def rightDash(self): if self.status != "jumping" and self.power >= 25: self.power -= 25 self.rightSpeed = 0 self.upSpeed = 0 self.downSpeed = 0 self.status = "dashing" self.rightSpeed = 40 ##Narrative: Character is able to attack ##Preconditions: Attack attributes must be initialized ##Post conditions: Character attacks, 25 power is used def attack(self): if self.power - 25 >= 0 and self.attackTimeLeft <= \ self.attackTime/3: if self.status != "dashing": self.power -= 25 self.status = "attacking" self.attackTimeLeft = self.attackTime self.attack1AnimCtr = 0 self.attack1AnimCount = 0 ##Narrative: Gravity allows for user to fall back into place ##Preconditions: Initialize up and down speeds ##Post conditions: Characters lands after jumping def gravity(self): if self.isOn == "nothing" and self.status != "dashing": if self.downSpeed < 20: self.downSpeed += 1 elif self.upSpeed > 0: self.upSpeed -= 1 ##Narrative: Slows the player down after a key is left go of ##Preconditions: Initialize speed attributes ##Post conditions: Rules for being on the ground or in the air are made def slowDown(self,playerList): #Rules for on ground or in air for item in playerList: if self.isOn == "ground" or self.isOn == "nothing": if item.pushingRight == False: if self.rightSpeed > 0: self.rightSpeed -= 1 if item.pushingLeft == False: if self.leftSpeed > 0: self.leftSpeed -=1 ##Narrative: Makes the character replenish power every tick ##Preconditions: Initialize power and make full power 100 ##Post conditions: Power is replenished def generatePower(self): if self.power + 0. <= self.maxPower: self.power += 0.5 else: self.power = 100 ##Narrative: The player's status is updated depending on the key ## or button pressed ##Preconditions: Initialized attributes concerning character movement ##Post conditions: Status is updated def updateStatus(self): if self.attackTimeLeft > 0: self.attackTimeLeft -= 1 self.status = "attacking" elif self.isOn == "nothing": self.status = "jumping" elif (self.rightSpeed == 0 and self.leftSpeed == 0) or \ self.rightSpeed == self.leftSpeed: self.status = "idle" elif self.status != "dashing": if (self.rightSpeed != 0 or self.leftSpeed != 0) and \ self.rightSpeed != self.leftSpeed: self.status = "walking" ##Narrative: Updates where the character is on ##Preconditions: Ground attribute ##Post conditions: Status is updated def updateIsOn(self): if self.isOn != "ground": if self.y > SCREEN_HEIGHT - self.tallestSprite.ScaledHeight: self.isOn = "ground" self.downSpeed = 0 self.upSpeed = 0 self.jumpsLeft = self.jumps ##Narrative: Handles all animation for characters ##Preconditions: Sprites and their attributes ##Post conditions: Character is animated def animation(self): #Walking Animation if self.status == "walking": #Start/Stop Animations if self.startStopAnimCount != (len(self.startStopAnimList)): self.sprite=self.startStopAnimList[self.startStopAnimCount] self.startStopAnimCtr += 1 if self.startStopAnimCtr == self.animTimer: self.startStopAnimCount += 1 self.startStopAnimCtr = 0 else: self.sprite = self.walkAnimList[self.walkAnimCount] self.walkAnimCtr += 1 if self.walkAnimCtr == self.animTimer: self.walkAnimCount += 1 if self.walkAnimCount > (len(self.walkAnimList) - 1): self.walkAnimCount = 0 self.walkAnimCtr = 0 #Idle Animation elif self.status == "idle": self.startStopAnimCount = 0 self.sprite = self.idleAnimList[self.idleAnimCount] self.idleAnimCtr += 1 if self.idleAnimCtr/2 == self.animTimer: self.idleAnimCount += 1 if self.idleAnimCount > (len(self.idleAnimList) - 1): self.idleAnimCount = 0 self.idleAnimCtr = 0 #Jumping Animation elif self.status == "jumping": self.sprite = self.jumpAnimList[self.jumpAnimCount] self.jumpAnimCtr += 1 if self.jumpAnimCtr == self.animTimer: self.jumpAnimCount += 1 if self.jumpAnimCount > (len(self.jumpAnimList) - 1): self.jumpAnimCount -= 1 self.jumpAnimCtr = 0 #Dashing Animation elif self.status == "dashing": self.sprite = self.dashAnimList[self.dashAnimCount] self.dashAnimCtr += 1 if self.dashAnimCtr == self.animTimer*2: self.dashAnimCount += 1 if self.dashAnimCount > (len(self.dashAnimList) - 1): self.dashAnimCount -= 1 self.dashAnimCtr = 0 #Attacking Animation elif self.status == "attacking": self.sprite = self.attack1AnimList[self.attack1AnimCount] self.attack1AnimCtr += 1 if self.attack1AnimCtr == self.animTimer: self.attack1AnimCount += 1 if self.attack1AnimCount > (len(self.attack1AnimList) - 1): self.attack1AnimCount -= 1 self.attack1AnimCtr = 0 if self.status != "dashing": self.dashAnimCount = 0 self.dashAnimCtr = 0 ##Narrative: Handles possibility of character walking off the screen ##Preconditions: Window height and width ##Post conditions:Character remains within the boundaries of the window def updateIsOffScreen(self): #Right of screen if (self.x + self.widestSprite.ScaledWidth)+self.dx>= SCREEN_WIDTH: self.isOffRight = True else: self.isOffRight = False #Left of screen if self.x + self.dx <= 0: self.isOffLeft = True else: self.isOffLeft = False #Top of screen if self.y + self.dy < 0: self.isOffTop = True else: self.isOffTop = False #Bottom of screen if (self.y + self.tallestSprite.ScaledHeight) + self.dy > \ SCREEN_HEIGHT: self.isOffBottom = True else: self.isOffBottom = False #Update isOffSceen if self.isOffRight == True or self.isOffLeft == True or \ self.isOffTop == True or self.isOffBottom == True: self.isOffScreen = True else: self.isOffScreen = False ##Narrative: Updates the coordinates of the character ##Preconditions: Coordinate attributes ##Post conditions: Collision is updated and accounted for def updateCoords(self,system,playerList): #Updates whether or not the player is off the screen self.updateIsOffScreen() #Update Cracters Colliding system.updateCharacterCollision(playerList) #Updates dx and dy self.dx = (self.rightSpeed - self.leftSpeed) self.dy = (self.upSpeed - self.downSpeed) #If character can go off the screen if self.canLeaveScreen == True: self.x += self.dx self.y += self.dy #If character can't go off the screen else: if self.isOffScreen == True: if self.isOffRight == True: self.rightSpeed = 0 elif self.isOffLeft == True: self.leftSpeed = 0 if self.isOffBottom == True: self.downSpeed = 0 #Updates dx and dy self.dx = (self.rightSpeed - self.leftSpeed) self.dy = (self.downSpeed - self.upSpeed) self.x += self.dx self.y += self.dy ##Narrative: Draws character onto the screen using their sprite images ##Preconditions: Character sprites ##Post conditions:Character is drawn on the specified window coordinate def draw(self,screen,bubble): if self.face == "right": screen.blit(self.sprite.Picture,(self.x+self.sprite.adjustX,\ self.y+self.sprite.adjustY)) elif self.face == "left": if self.sprite.adjustX != 0: self.drawX = self.x - 100 else: self.drawX = self.x screen.blit(transform.flip((self.sprite.Picture),True,False),\ (self.drawX,self.y+self.sprite.adjustY)) if self.isCrouched == True: if self.power - 4 >= 0: self.power -= 0.50 if self.who == "zero" or self.who == "captain": screen.blit(bubble,(self.x,self.y)) elif self.who == "koopa": screen.blit(bubble,(self.x-40,self.y+100)) elif self.who == "jade": screen.blit(bubble,(self.x-50,self.y-120)) else: self.isCrouched = False self.power = 0 ##Narrative: Runs through all character updates ##Preconditions: Attributes that need to be updated ##Post conditions: Character is updated def update(self,pushingPause,playerList,system,screen,healthBar,bubble): if pushingPause == False: self.generatePower() self.slowDown(playerList) self.updateStatus() system.updateFace(playerList) self.updateIsOn() self.gravity() self.updateCoords(system,playerList) self.animation() self.draw(screen,bubble) if pushingPause == False: system.damage(playerList,healthBar) def __str__(self): return("\n\nSprite Lists:"+\ "\nidleAnimList: "+str(self.idleAnimList)+\ "\nwalkAnimList: "+str(self.walkAnimList)+\ "\nstartStopAnimList: "+str(self.startStopAnimList)+\ "\njumpAnimList: "+str(self.jumpAnimList)+\ "\n\nAnimation"+\ "\nanimTimer: "+str(self.animTimer)+\ "\nwalkAnimCtr: "+str(self.walkAnimCtr)+\ "\nwalkAnimCount: "+str(self.walkAnimCount)+\ "\nidleAnimCtr: "+str(self.idleAnimCtr)+\ "\nidleAnimCount: "+str(self.idleAnimCount)+\ "\njumpAnimCtr: "+str(self.jumpAnimCtr)+\ "\njumpAnimCount: "+str(self.jumpAnimCount)+\ "\ndashAnimCtr: "+str(self.dashAnimCtr)+\ "\ndashAnimCount: "+str(self.dashAnimCount)+\ "\nface: "+str(self.face)+\ "\nwidestSprite: "+str(self.widestSprite)+\ "\ntallestSprite: "+str(self.tallestSprite)+\ "\ncurrentSprite: "+str(self.sprite.Name)+\ "\n\nMovement"+\ "\nspeed: "+str(self.speed)+\ "\nmaxSpeed: "+str(self.maxSpeed)+\ "\nrightSpeed: "+str(self.rightSpeed)+\ "\nleftSpeed: "+str(self.leftSpeed)+\ "\nupSpeed: "+str(self.upSpeed)+\ "\ndownSpeed: "+str(self.downSpeed)+\ "\ndy: "+str(self.dy)+\ "\ndx: "+str(self.dx)+\ "\nx: "+str(self.x)+\ "\ny: "+str(self.y)+\ "\njumps: "+str(self.jumps)+\ "\njumpsLeft: "+str(self.jumpsLeft)+\ "\ncanLeaveScreen: "+str(self.canLeaveScreen)+\ "\nisOffBottom: "+str(self.isOffBottom)+\ "\nisOffTop: "+str(self.isOffTop)+\ "\nisOffRight: "+str(self.isOffRight)+\ "\nisOffLeft: "+str(self.isOffLeft)+\ "\nstatus: "+str(self.status)+\ "\nisOn: "+str(self.isOn)+\ "\n\nStats"+\ "\nname: "+str(self.name)) #=============================================================================== #=============================================================================== #Player class class Player(Character): def __init__(self,number,character="",pushingRight=False,\ pushingLeft=False,pushingUp=False,pushingDown=False,\ pushingRightDash=False,pushingLeftDash=False,pushingAttack1=False): self.number = number self.character = character self.pushingRight = pushingRight self.pushingLeft = pushingLeft self.pushingUp = pushingUp self.pushingDown = pushingDown self.pushingRightDash = pushingRightDash self.pushingLeftDash = pushingLeftDash self.pushingAttack1 = pushingAttack1 #=============================================================================== #=============================================================================== #System Class: handles all collisions and ui class System: def __init__(self,fontList=["Digital Desolation",24]): self.fontList = fontList self.defaultFont = font.SysFont(self.fontList[0],self.fontList[1]) self.alphSurface = 0 self.alphaText = 0 self.mainLoop = True self.result = "none" ##Narrative: Draws text of player 1 and player 2 above their head ##Preconditions: Player 1 and Player 2 are drawn to screen ##Post conditions: Blits the text to the player's head def updateHalo(self,playerList,screen): for item in playerList: if item.character.who == "zero" or item.character.who == "captain": screen.blit(self.defaultFont.render("Player "+str(item.number),\ 100,(255,255,255)),(item.character.x+50,item.character.y-25)) elif item.character.who == "jade": screen.blit(self.defaultFont.render("Player "+str(item.number),\ 100,(255,255,255)),(item.character.x+5,item.character.y-145)) elif item.character.who == "koopa": screen.blit(self.defaultFont.render("Player "+str(item.number),\ 100,(255,255,255)),(item.character.x+50,item.character.y+130)) ##Narrative: Updates the direction the character is facing ##Preconditions: The character for Player 1 and Player 2 ##Post conditions: Character direction is changed depending ## on their side of the screen def updateFace(self,playerList): player1 = playerList[0] player2 = playerList[1] if player1.character.x > player2.character.x: player1.character.face = "left" player2.character.face = "right" else: player1.character.face = "right" player2.character.face = "left" ##Narrative: Damage calculator ##Preconditions: Character attack sprites such as punches or kicks ##Post conditions: Damage is inflicted; if player is blocking, ## turn damage into weaker "chip" damage def damage(self,playerList,healthBar): player1=playerList[0] player2=playerList[1] if player1.character.attackTimeLeft > 0: damageDone = player1.character.damageStat if player2.character.isCrouched == True: damageDone *= .1 if player1.character.face == "right": if player1.character.x+\ player1.character.sprite.ScaledWidth > \ player2.character.x and player1.character.y \ + player1.character.sprite.ScaledHeight + \ player1.character.dy > player2.character.y and \ player1.character.y + player1.character.dy < \ player2.character.y + \ player2.character.sprite.ScaledHeight: healthBar.player2Dam(damageDone) if player2.character.isCrouched == False: player2.character.rightSpeed += 2 elif player1.character.face == "left": if player1.character.drawX < player2.character.x+\ player2.character.sprite.ScaledWidth and \ player1.character.y + \ player1.character.sprite.ScaledHeight + \ player1.character.dy > player2.character.y and \ player1.character.y + player1.character.dy < \ player2.character.y + \ player2.character.sprite.ScaledHeight: healthBar.player2Dam(damageDone) if player2.character.isCrouched == False: player2.character.leftSpeed += 2 if player2.character.attackTimeLeft > 0: damageDone = player2.character.damageStat if player1.character.isCrouched == True: damageDone *= .1 if player2.character.face == "right": if player2.character.x+\ player2.character.sprite.ScaledWidth > \ player1.character.x and player2.character.y \ + player2.character.sprite.ScaledHeight + \ player2.character.dy > player1.character.y and \ player2.character.y + player2.character.dy < \ player1.character.y + \ player1.character.sprite.ScaledHeight: healthBar.player1Dam(damageDone) if player1.character.isCrouched == False: player1.character.rightSpeed += 2 elif player2.character.face == "left": if player2.character.drawX < \ player1.character.x+player1.character.sprite.ScaledWidth\ and player2.character.y + \ player2.character.sprite.ScaledHeight + \ player2.character.dy > player1.character.y and \ player2.character.y + player2.character.dy < \ player1.character.y + \ player1.character.sprite.ScaledHeight: healthBar.player1Dam(damageDone) if player1.character.isCrouched == False: player1.character.leftSpeed += 2 ##Narrative: Updates character collision ##Preconditions: Player 1 and Player 2 coordinates ##Post conditions: Sprites don't phase through each other def updateCharacterCollision(self,playerList): player1 = playerList[0] player2 = playerList[1] if player1.character.x + player1.character.sprite.ScaledWidth\ + player1.character.dx > player2.character.x and \ player1.character.x + player1.character.dx < player2.character.x\ + player2.character.sprite.ScaledWidth: if player1.character.y + player1.character.sprite.ScaledHeight\ + player1.character.dy > player2.character.y and \ player1.character.y + player1.character.dy < \ player2.character.y + player2.character.sprite.ScaledHeight: if player1.character.face == "right": player1.character.rightSpeed = 0 if player1.character.face == "left": player1.character.leftSpeed = 0 if player2.character.x + player2.character.sprite.ScaledWidth\ + player2.character.dx > player1.character.x and \ player2.character.x + player2.character.dx < \ player1.character.x + player1.character.sprite.ScaledWidth: if player2.character.y + player2.character.sprite.ScaledHeight\ + player2.character.dy > player1.character.y and \ player2.character.y + player2.character.dy < \ player1.character.y + player1.character.sprite.ScaledHeight: if player2.character.face == "right": player2.character.rightSpeed = 0 if player2.character.face == "left": player2.character.leftSpeed = 0 ##Narrative: Starts the beginning of the end of the game ##Preconditions: Player 1 or Player 2 health must be 0 or below ##Post conditions: Calls fadeToBlack() function def gameWinScreen(self,healthBar,system,player1Win,player2Win,screen): if healthBar.p2H < healthBar.p1H-200: self.result = "p1" else: self.result = "p2" system.fadeInText(player1Win,player2Win,screen) ##Narrative: Creates the end game screen ##Preconditions: gameWinScreen() function calls this ##Post conditions: Increases opacity of winScreen to block main screen def fadeInText(self,player1Win,player2Win,screen): if self.alphaText < 255: self.alphaText += 2.5 else: time.delay(2000) self.mainLoop = False if self.result == "p1": player1Win.set_alpha(self.alphaText) screen.blit(player1Win,(0,0)) elif self.result == "p2": player2Win.set_alpha(self.alphaText) screen.blit(player2Win,(0,0)) <file_sep>import pygame ##REFERENCE: http://www.pygame.org/docs/ref/joystick.html ##Interprets gamepad input and converts it to readable lists and tuples ##Narrative: Initializes game pads as objects ##Preconditions: Game pad must be plugged in to USB ##Post conditions: Reads the I/O of computer for game pads and updates values def gamePad(joystick1, joystick2): joystick_count = pygame.joystick.get_count() if joystick_count > 0: joystick1.init() name = joystick1.get_name() axes = joystick1.get_numaxes() for i in range( axes ): axis = joystick1.get_axis( i ) buttons = joystick1.get_numbuttons() for i in range( buttons ): button = joystick1.get_button( i ) hats = joystick1.get_numhats() for i in range( hats ): hat = joystick1.get_hat( i ) if joystick_count > 1: joystick2.init() name = joystick2.get_name() axes = joystick2.get_numaxes() for i in range( axes ): axis = joystick2.get_axis( i ) buttons = joystick2.get_numbuttons() for i in range( buttons ): button = joystick2.get_button( i ) hats = joystick2.get_numhats() for i in range( hats ): hat = joystick2.get_hat( i ) #Button list maps to the following on the game pad itself #get_button(0) = A button #get_button(1) = B button #get_button(2) = X button #get_button(3) = Y button #get_button(4) = LB button #get_button(5) = RB button #get_button(6) = back button #get_button(7) = start button #get_button(8) = left joystick downpress #get_button(9) = right joystick downpress ##Narrative: Determines which way a joystick's axis should face ##Preconditions: joystick(s) must not be None type ##Post conditions: Returns tuple of joystick's axes def axround(axis): if axis > .5: return 1 if axis < -.5: return -1 return 0 ##Narrative: Updates the axes of game pads ##Preconditions: Game pad must not be None type ##Post conditions: Updates game pad's axes def getAxisDir(joy): #if joy stick does not exist, return 0,0 (false) if joy == None: return 0,0 ax0 = joy.get_axis(0) #up down lanalog ax1 = joy.get_axis(1) #left right lanalog ax2 = joy.get_axis(2) #triggers ax3 = joy.get_axis(3) #up down ranalog ax4 = joy.get_axis(4) #left right ranalog ax0 = axround(ax0) ax1 = axround(ax1) ax2 = axround(ax2) ax3 = axround(ax3) ax4 = axround(ax4) return (ax0, ax1) ##Narrative: Moves up based on D-Pad or joystick ##Preconditions: Game pad must not be None type ##Post conditions: Returns true for moving upwards def joyUp(joy): if joy == None: return False if joy.get_hat(0) == (0, 1) or getAxisDir(joy) == (0, -1): return True return False ##Narrative: Moves up based on D-Pad or joystick ##Preconditions: Game pad must not be None type ##Post conditions: Returns true for moving downwards def joyDown(joy): if joy == None: return False if joy.get_hat(0) == (0, -1) or getAxisDir(joy) == (0, 1): return True return False ##Narrative: Moves up based on D-Pad or joystick ##Preconditions: Game pad must not be None type ##Post conditions: Returns true for moving right def joyRight(joy): if joy == None: return False if joy.get_hat(0) == (1, 0) or getAxisDir(joy) == (1,0): return True return False ##Narrative: Moves up based on D-Pad or joystick ##Preconditions: Game pad must not be None type ##Post conditions: Returns true for moving left def joyLeft(joy): if joy == None: return False if joy.get_hat(0) == (-1, 0) or getAxisDir(joy) == (-1,0): return True return False<file_sep>import pygame import random pygame.init() black = 0,0,0 white = 255,255,255 screen = pygame.display.set_mode((1000,600)) pygame.display.set_icon(pygame.image.load('Logo.png')) pygame.display.set_caption("Not So Extreme Fighting") ##Narrative: User chooses between 9 background stages ##Preconditions: User input going through the main menu ##Post conditions: A stage is chosen def stageSelect(x,y): stage="" if x==105: if y==95: stage = "Stage1.jpg" elif y== 250: stage = "Stage7.jpg" else: stage = "Stage3.jpg" elif x == 378: if y== 95: stage = "Stage5.jpg" elif y == 250: stage = "Stage8.jpg" else: stage = "Stage0.jpg" else: if y== 95: stage = "Stage6.jpg" elif y== 250: stage = "Stage2.jpg" else: stage = "Stage9.jpg" return stage ##Narrative: Draws chosen stage onto the screen ##Preconditions: User input of stage ##Post conditions: Background is changed, stage is set for the fight def drawWindow(): screen.blit(background,(0,0)) <file_sep>import GameWindow from pygame import * import time init() CONVERT_POWER = 2.9833 class Stopwatch: def __init__(self): self.startTime = time.time() def reset(self): self.startTime = time.time() def getTime(self): return(int(format(time.time() - self.startTime,'.0f'))) class Timer: def __init__(self): self.countDown = 99 self.countDown = None self.stopWatch = Stopwatch() self.myfont = font.SysFont("Helvetica", 50) def drawTimer(self): self.countDown = 99 - self.stopWatch.getTime() if self.countDown <= 0: self.countDown = 0 draw.circle(GameWindow.screen, (225,225,225), (500,16), 44,0) draw.circle(GameWindow.screen, (0,0,0), (500,16), 40,0) label = self.myfont.render(str(self.countDown), 1, (255, 204, 0)) if self.countDown >= 10: GameWindow.screen.blit(label, (471, 2)) else: GameWindow.screen.blit(label, (487, 2)) class HealthBar: def __init__(self): self.countDown = 99 self.p1H = 450 self.p2H = 450 self.p1Coord = 12 self.p2Coord = 538 self.myfont = font.SysFont("Small Fonts", 55) ##Narrative: Draws the health bars and sets the fight timer to 99 ticks ##Preconditions: Initalize the countdown attribute ##Post conditions:Health bars and timer are drawn onto the top of the screen def drawHealth(self): #Player 1 HealthBar draw.rect(GameWindow.screen,(225,225,225),(9,5,455,25),0) draw.rect(GameWindow.screen,(225,0,0),(12,7,450,20),0) draw.rect(GameWindow.screen,(0,255,0),(self.p1Coord,7,self.p1H,20),0) draw.rect(GameWindow.screen,(225,225,225),(0,5,9,25),0) draw.polygon(GameWindow.screen,(225,225,225),[(9,5),(49,5),(9,30)]) #Player 2 HealthBar draw.rect(GameWindow.screen,(225,225,225),(535,5,455,25),0) draw.rect(GameWindow.screen,(225,0,0),(538,7,450,20),0) draw.rect(GameWindow.screen,(0,255,0),(self.p2Coord,7,self.p2H+20,20),0) draw.rect(GameWindow.screen,(225,225,225),(535+455,5,10,25),0) draw.polygon(GameWindow.screen,(225,225,225),[(535+455-40,5),(535+455,5),(535+455,30)]) #Timer draw.circle(GameWindow.screen, (0,0,0), (500,16), 40,0) label = self.myfont.render(str(self.countDown), 1, (255, 204, 0)) GameWindow.screen.blit(label, (479, 4)) ##Narrative: Player 1 Health Bar ##Preconditions: Health Bar drawn onto the screen ##Post conditions: Damage is deducted from the health bar def player1Dam(self,dam): self.p1Bar = self.p1H - dam self.p1H -= dam self.p1Coord = self.p1Coord - dam ##Narrative: Player 2 Health Bar ##Preconditions: Health Bar drawn onto the screen ##Post conditions: Damage is deducted from the health bar def player2Dam(self,dam): self.p2Bar = self.p2H - dam self.p2H -= dam self.p2Coord = self.p2Coord + dam class PowerBar: ##Narrative: Draws the power bars ##Preconditions: Main game window must be intialized ##Post conditions: Power bars are drawn and updated on screen def drawPowerBar(self,player1Power=100,player2Power=100): self.player1Power = player1Power self.player2Power = player2Power #Update Player 1 Powerbar Length self.p1Width = self.player1Power * CONVERT_POWER #Player 1 Powerbar draw.rect(GameWindow.screen,(225,225,225),(150,30,455/1.5,25/2),0) draw.rect(GameWindow.screen,(122,145,169),(153,31,455/1.5-5,25/2-4),0) draw.rect(GameWindow.screen,( 46, 46,254),(153,31,self.p1Width,25/2-4),0) draw.polygon(GameWindow.screen,(225,225,225),[(150,30),(175,30),\ (150,30+25/2)]) #Update Player 2 Powerbar Length self.p2Width = self.player2Power * CONVERT_POWER #Player 2 PowerBar draw.rect(GameWindow.screen,(225,225,225),(542,30,455/1.5,25/2),0) draw.rect(GameWindow.screen,(122,145,169),(545,31,455/1.5-5,25/2-4),0) draw.rect(GameWindow.screen,( 46, 46,254),(545+(100*CONVERT_POWER)\ ,31,-self.p2Width,25/2-4),0) draw.polygon(GameWindow.screen,(225,225,225),[(517+455/1.5,30),\ (542+455/1.5,30),\ (542+455/1.5,30+25/2)]) <file_sep>from Classes import sprite import pygame #Creates sprites #Zero def idleAnim(): zeroSpriteSheet = pygame.image.load("Zero Sprite Sheet.gif").convert_alpha() zeroStand =sprite("zeroStand",zeroSpriteSheet,5,48,5,52,5,0,0) return [zeroStand] def walkList(): zeroSpriteSheet = pygame.image.load("Zero Sprite Sheet.gif").convert_alpha() zeroWalk3 =sprite("zeroWalk3",zeroSpriteSheet,206,254,164,210,5,0,0) zeroWalk4 =sprite("zeroWalk4",zeroSpriteSheet,261,307,163,210,5,0,0) zeroWalk5 = sprite("zeroWalk5",zeroSpriteSheet,315,359,161,209,5,0,0) zeroWalk6 = sprite("zeroWalk6",zeroSpriteSheet,367,407,161,209,5,0,0) zeroWalk7 = sprite("zeroWalk7",zeroSpriteSheet,419,464,164,211,5,0,0) zeroWalk8 = sprite("zeroWalk8",zeroSpriteSheet,475,524,165,210,5,0,0) zeroWalk9 = sprite("zeroWalk9",zeroSpriteSheet,531,576,166,212,5,0,0) zeroWalk10 = sprite("zeroWalk10",zeroSpriteSheet,583,633,165,212,5,0,0) zeroWalk11 = sprite("zeroWalk11",zeroSpriteSheet,640,686,164,212,5,0,0) zeroWalk12 = sprite("zeroWalk12",zeroSpriteSheet,695,738,163,212,5,0,0) zeroWalk13 = sprite("zeroWalk13",zeroSpriteSheet,745,787,163,212,5,0,0) zeroWalk14 = sprite("zeroWalk14",zeroSpriteSheet,795,840,164,212,5,0,0) return [zeroWalk3,zeroWalk4,zeroWalk5,zeroWalk6,zeroWalk7,\ zeroWalk8,zeroWalk9,zeroWalk10,zeroWalk11,\ zeroWalk12,zeroWalk13,zeroWalk14] def startStopAnim(): zeroSpriteSheet = pygame.image.load("Zero Sprite Sheet.gif").convert_alpha() zeroWalk1 = sprite("zeroWalk1",zeroSpriteSheet,93,144,164,208,5,0,0) zeroWalk2 = sprite("zeroWalk2",zeroSpriteSheet,151,201,165,210,5,0,0) return [zeroWalk1,zeroWalk2] def jumpAnim(): zeroSpriteSheet = pygame.image.load("Zero Sprite Sheet.gif").convert_alpha() zeroJump1 = sprite("zeroJump1",zeroSpriteSheet,14,53,89,137,5,0,0) zeroJump2 = sprite("zeroJump2",zeroSpriteSheet,59,103,85,141,5,0,0) zeroJump3 = sprite("zeroJump3",zeroSpriteSheet,110,153,85,141,5,0,0) zeroJump4 = sprite("zeroJump4",zeroSpriteSheet,163,206,84,141,5,0,0) zeroJump5 = sprite("zeroJump5",zeroSpriteSheet,213,256,84,140,5,0,0) zeroJump6 = sprite("zeroJump6",zeroSpriteSheet,263,303,84,136,5,0,0) zeroJump7 = sprite("zeroJump7",zeroSpriteSheet,308,348,84,139,5,0,0) zeroJump8 = sprite("zeroJump8",zeroSpriteSheet,353,389,84,148,5,0,0) zeroJump9 = sprite("zeroJump9",zeroSpriteSheet,398,433,75,152,5,0,0) zeroJump10 = sprite("zeroJump10",zeroSpriteSheet,443,478,72,151,5,0,0) zeroJump11 = sprite("zeroJump11",zeroSpriteSheet,488,528,90,149,5,0,0) return [zeroJump1,zeroJump2,zeroJump3,zeroJump4,zeroJump5,zeroJump6,\ zeroJump7,zeroJump8,zeroJump9,zeroJump10,zeroJump11] def dashAnim(): zeroSpriteSheet = pygame.image.load("Zero Sprite Sheet.gif").convert_alpha() zeroDash1 = sprite("zeroDash1",zeroSpriteSheet,541,611,104,149,5,-5,0) zeroDash2 = sprite("zeroDash2",zeroSpriteSheet,620,727,112,148,5,-5,0) zeroDash3 = sprite("zeroDash3",zeroSpriteSheet,734,865,112,150,5,-5,0) return [zeroDash1,zeroDash2,zeroDash3] def attackAnim(): zeroSpriteSheet = pygame.image.load("Zero Sprite Sheet.gif").convert_alpha() zeroSword1 = sprite("zeroSword1",zeroSpriteSheet,7,46,298,344,5,0,0) zeroSword2 = sprite("zeroSword2",zeroSpriteSheet,52,98,294,344,5,-6,0) zeroSword3 = sprite("zeroSword3",zeroSpriteSheet,102,151,283,346,5,-3,-4) zeroSword4 = sprite("zeroSword4",zeroSpriteSheet,157,235,283,346,5,-3,-17) zeroSword5 = sprite("zeroSword5",zeroSpriteSheet,242,329,283,343,5,-5,-15) zeroSword6 = sprite("zeroSword6",zeroSpriteSheet,337,428,295,343,5,-9,-6) zeroSword7 = sprite("zeroSword7",zeroSpriteSheet,437,520,294,343,5,-2,-6) zeroSword8 = sprite("zeroSword8",zeroSpriteSheet,527,597,298,343,5,-1,0) zeroSword9 = sprite("zeroSword9",zeroSpriteSheet,607,666,298,342,5,0,0) zeroSword10 = sprite("zeroSword10",zeroSpriteSheet,677,729,297,342,5,0,0) zeroSword11 = sprite("zeroSword11",zeroSpriteSheet,737,782,297,342,5,0,0) return [zeroSword1,zeroSword2,zeroSword3,zeroSword4,\ zeroSword5,zeroSword6,zeroSword7,zeroSword8,\ zeroSword9,zeroSword10,zeroSword11] def widest(): zeroSpriteSheet = pygame.image.load("Zero Sprite Sheet.gif").convert_alpha() zeroStand = sprite("zeroStand",zeroSpriteSheet,5,48,5,52,5,0,0) return zeroStand def tallest(): zeroSpriteSheet = pygame.image.load("Zero Sprite Sheet.gif").convert_alpha() zeroStand = sprite("zeroStand",zeroSpriteSheet,5,48,5,52,5,0,0) return zeroStand def default(): zeroSpriteSheet = pygame.image.load("Zero Sprite Sheet.gif").convert_alpha() zeroStand = sprite("zeroStand",zeroSpriteSheet,5,48,5,52,5,0,0) return zeroStand <file_sep>from pygame import * from pygame.locals import * import MainMenu import GameWindow import Health import sys from gamePad import * from Classes import * import CharMenu import zeroBuild import jadeBuild import koopaBuild import captainBuild import blueZeroBuild #New Zero Fighting! #Initializes fonts font.init() #Screen Resolution SCREEN_WIDTH = 1000 SCREEN_HEIGHT = 600 #Makes Screen #Remeber fullscreen screen = display.set_mode((SCREEN_WIDTH,SCREEN_HEIGHT)) keepGoing = True while keepGoing == True: #Defines initial values FPS = 60 pushingPause = False #Loads images backgroundCheat = image.load("LaughingAnimuGirls.bmp").convert() bubble = image.load("bubble.png").convert_alpha() bubble = transform.scale(bubble,(74*3,65*3)) player1WinText = image.load("Player1WinText.png").convert_alpha() player2WinText = image.load("Player2WinText.png").convert_alpha() #Create Surfaces player1Win = pygame.Surface((SCREEN_WIDTH, SCREEN_HEIGHT)) player1Win.set_alpha(0) player1Win.blit(player1WinText,(200,150)) player2Win = pygame.Surface((SCREEN_WIDTH, SCREEN_HEIGHT)) player2Win.set_alpha(0) player2Win.blit(player2WinText,(200,150)) #Creates Healthbar and Power Bar healthBar = Health.HealthBar() powerBar = Health.PowerBar() timer = Health.Timer() #Loads Sprites #Zero zeroIdleAnimList = zeroBuild.idleAnim() zeroWalkAnimList = zeroBuild.walkList() zeroStartStopAnimList = zeroBuild.startStopAnim() zeroJumpAnimList = zeroBuild.jumpAnim() zeroDashAnimList = zeroBuild.dashAnim() zeroAttack1List = zeroBuild.attackAnim() zeroTallest = zeroBuild.tallest() zeroWidest = zeroBuild.widest() zeroDefault = zeroBuild.default() #BlueZero blueZeroIdleAnimList = blueZeroBuild.idleAnim() blueZeroWalkAnimList = blueZeroBuild.walkList() blueZeroStartStopAnimList = blueZeroBuild.startStopAnim() blueZeroJumpAnimList = blueZeroBuild.jumpAnim() blueZeroDashAnimList = blueZeroBuild.dashAnim() blueZeroAttack1List = blueZeroBuild.attackAnim() blueZeroTallest = blueZeroBuild.tallest() blueZeroWidest = blueZeroBuild.widest() blueZeroDefault = blueZeroBuild.default() #Jade jadeIdleAnimList = jadeBuild.idleAnim() jadeWalkAnimList=jadeBuild.walkList() jadeStartStopAnimList = jadeBuild.startStopAnim() jadeJumpAnimList = jadeBuild.jumpAnim() jadeDashAnimList = jadeBuild.dashAnim() jadeAttack1List = jadeBuild.attackAnim() jadeTallest = jadeBuild.tallest() jadeWidest = jadeBuild.widest() jadeDefault = jadeBuild.default() #Koopa koopaIdleAnimList = koopaBuild.idleAnim() koopaWalkAnimList = koopaBuild.walkList() koopaStartStopAnimList = koopaBuild.startStopAnim() koopaJumpAnimList = koopaBuild.jumpAnim() koopaDashAnimList = koopaBuild.dashAnim() koopaAttack1List = koopaBuild.attackAnim() koopaTallest = koopaBuild.tallest() koopaWidest = koopaBuild.widest() koopaDefault = koopaBuild.default() #Captain captainIdleAnimList = captainBuild.idleAnim() captainWalkAnimList= captainBuild.walkList() captainStartStopAnimList = captainBuild.startStopAnim() captainJumpAnimList = captainBuild.jumpAnim() captainDashAnimList = captainBuild.dashAnim() captainAttack1List = captainBuild.attackAnim() captainTallest = captainBuild.tallest() captainWidest = captainBuild.widest() captainDefault = captainBuild.default() #Creates an instance of each character for each player zero1 = Character(zeroIdleAnimList,zeroWalkAnimList,zeroStartStopAnimList,zeroJumpAnimList,zeroDashAnimList,zeroAttack1List,\ 0,zeroDefault,5,0,0,0,0,0,0,0,0,0,0,0,0,"right",zeroWidest,zeroTallest,\ 1,20,0,0,0,0,200,SCREEN_HEIGHT-zeroTallest.ScaledHeight,\ 2,23,False,False,False,False,False,False,"idle","ground",25,"zero",5,100,100.0,1.2,False,"zero") jade1 = Character(jadeIdleAnimList,jadeWalkAnimList,jadeStartStopAnimList,jadeJumpAnimList,jadeDashAnimList,jadeAttack1List,\ 0,jadeDefault,5,0,0,0,0,0,0,0,0,0,0,0,0,"right",jadeWidest,jadeTallest,\ 1,20,0,0,0,0,200,SCREEN_HEIGHT-jadeTallest.ScaledHeight,\ 2,23,False,False,False,False,False,False,"idle","ground",25,"zero",5,100,100.0,1.2,False,"jade") koopa1 = Character(koopaIdleAnimList,koopaWalkAnimList,koopaStartStopAnimList,koopaJumpAnimList,koopaDashAnimList,koopaAttack1List,\ 0,koopaDefault,5,0,0,0,0,0,0,0,0,0,0,0,0,"right",koopaWidest,koopaTallest,\ 1,20,0,0,0,0,200,SCREEN_HEIGHT-koopaTallest.ScaledHeight,\ 2,23,False,False,False,False,False,False,"idle","ground",25,"zero",5,100,100.0,1.2,False,"koopa") captain1 = Character(captainIdleAnimList,captainWalkAnimList,captainStartStopAnimList,captainJumpAnimList,captainDashAnimList,captainAttack1List,\ 0,captainDefault,5,0,0,0,0,0,0,0,0,0,0,0,0,"right",captainWidest,captainTallest,\ 1,20,0,0,0,0,200,SCREEN_HEIGHT-captainTallest.ScaledHeight,\ 2,23,False,False,False,False,False,False,"idle","ground",25,"zero",5,100,100.0,1.2,False,"captain") zero2 = Character(blueZeroIdleAnimList,blueZeroWalkAnimList,blueZeroStartStopAnimList,blueZeroJumpAnimList,blueZeroDashAnimList,blueZeroAttack1List,\ 0,blueZeroDefault,5,0,0,0,0,0,0,0,0,0,0,0,0,"left",blueZeroWidest,blueZeroTallest,\ 1,20,0,0,0,0,SCREEN_WIDTH-200,SCREEN_HEIGHT-blueZeroTallest.ScaledHeight,\ 2,23,False,False,False,False,False,False,"idle","ground",25,"zero",5,100,100.0,1.2,False,"zero") jade2 = Character(jadeIdleAnimList,jadeWalkAnimList,jadeStartStopAnimList,jadeJumpAnimList,jadeDashAnimList,jadeAttack1List,\ 0,jadeDefault,5,0,0,0,0,0,0,0,0,0,0,0,0,"left",jadeWidest,jadeTallest,\ 1,20,0,0,0,0,SCREEN_WIDTH-200,SCREEN_HEIGHT-jadeTallest.ScaledHeight,\ 2,23,False,False,False,False,False,False,"idle","ground",25,"zero",5,100,100.0,1.2,False,"jade") koopa2 = Character(koopaIdleAnimList,koopaWalkAnimList,koopaStartStopAnimList,koopaJumpAnimList,koopaDashAnimList,koopaAttack1List,\ 0,koopaDefault,5,0,0,0,0,0,0,0,0,0,0,0,0,"left",koopaWidest,koopaTallest,\ 1,20,0,0,0,0,SCREEN_WIDTH-200,SCREEN_HEIGHT-koopaTallest.ScaledHeight,\ 2,23,False,False,False,False,False,False,"idle","ground",25,"zero",5,100,100.0,1.2,False,"koopa") captain2 = Character(captainIdleAnimList,captainWalkAnimList,captainStartStopAnimList,captainJumpAnimList,captainDashAnimList,captainAttack1List,\ 0,captainDefault,5,0,0,0,0,0,0,0,0,0,0,0,0,"left",captainWidest,captainTallest,\ 1,20,0,0,0,0,SCREEN_WIDTH-200,SCREEN_HEIGHT-captainTallest.ScaledHeight,\ 2,23,False,False,False,False,False,False,"idle","ground",25,"zero",5,100,100.0,1.2,False,"captain") #Creates System system = System() #Creates Player(s) playerList = [] mainLoop = MainMenu.mainMenu() mainLoop,char1,char2 = CharMenu.characterSelect() #Character Select if char1 == "koopa": player1Character = koopa1 elif char1 == "captain": player1Character = captain1 elif char1 == "jade": player1Character = jade1 else: player1Character = zero1 if char2 == "koopa": player2Character = koopa2 elif char2 == "captain": player2Character = captain2 elif char2 == "jade": player2Character = jade2 else: player2Character = zero2 #Creates Players player1 = Player(1,player1Character) player2 = Player(2,player2Character) playerList.append(player1) playerList.append(player2) mainLoop,x,y = MainMenu.stageMenu() stage = GameWindow.stageSelect(x,y) background = image.load(stage).convert() fullScreenBool = True mixer.music.stop() #Gets correct stage music if stage == "Stage1.jpg": stageSong = "CreepyWoodsMusic.ogg" elif stage == "Stage2.jpg": stageSong = "MortalCombatMusic.ogg" elif stage == "Stage3.jpg": stageSong = "HellMusic.ogg" elif stage == "Stage0.jpg": stageSong = "FullMoonMusic.ogg" elif stage == "Stage5.jpg": stageSong = "AbandonedTownMusic.ogg" elif stage == "Stage6.jpg": stageSong = "ChinatownMusic.ogg" elif stage == "Stage7.jpg": stageSong = "DigitalWorldMusic.ogg" elif stage == "Stage8.jpg": stageSong = "AncientSpringMusic.ogg" elif stage == "Stage9.jpg": stageSong = "RoadMusic.ogg" mixer.music.load(stageSong) mixer.music.play() #initializes game pads joystick1 = None joystick2 = None joystick_count = joystick.get_count() if joystick_count > 0: joystick1 = joystick.Joystick(0) if joystick_count > 1: joystick2 = joystick.Joystick(1) timer.stopWatch.reset() #Main Loop while system.mainLoop == True: gamePad(joystick1, joystick2) #Event Handler for Event in event.get(): #Exit if Event.type == QUIT: quit() sys.exit() #Press Key elif Event.type == KEYDOWN: #A (Player 1) if Event.key == K_a: player1.pushingLeft = True #D (Player 1) if Event.key == K_d: player1.pushingRight = True #W (Player 1) if Event.key == K_w: player1.pushingUp = True #S (Player 1) if Event.key == K_s: player1.pushingDown = True #F (Player 1) if Event.key == K_f: player1.pushingRightDash = True #CapsLock (Player 1) if Event.key == K_CAPSLOCK: player1.pushingLeftDash = True #Squigly Key (Player 1) if Event.key == K_BACKQUOTE: print(player1.character) #E (Player 1) if Event.key == K_e: player1.pushingAttack1 = True #P if Event.key == K_p: pushingPause = True if len(playerList) > 1: #Left (Player 2) if Event.key == K_LEFT: player2.pushingLeft = True #Right (Player 2) if Event.key == K_RIGHT: player2.pushingRight = True #Up (Player 2) if Event.key == K_UP: player2.pushingUp = True #Down (Player 2) if Event.key == K_DOWN: player2.pushingDown = True #Keypad 0 (Player 2) if Event.key == K_KP0: player2.pushingRightDash = True #Right Ctrl (Player 2) if Event.key == K_RCTRL: player2.pushingLeftDash = True #Home (Player 2) if Event.key == K_HOME: print(player2.character) #Right Shift (Player 2) if Event.key == K_RSHIFT: player2.pushingAttack1 = True #Release Key elif Event.type == KEYUP: if Event.key == K_ESCAPE: quit() sys.exit() if Event.key == K_t and fullScreenBool == True: screen = display.set_mode((SCREEN_WIDTH,SCREEN_HEIGHT)) fullScreenBool = False elif Event.key == K_t and fullScreenBool == False: screen = display.set_mode(\ (SCREEN_WIDTH,SCREEN_HEIGHT),FULLSCREEN) fullScreenBool = True #A (Player 1) if Event.key == K_a: player1.pushingLeft = False #D (Player 1) if Event.key == K_d: player1.pushingRight = False #W (Player 1) if Event.key == K_w: player1.pushingUp = False #S (Player 1) if Event.key == K_s: player1.pushingDown = False #P if Event.key == K_p: pushingPause = False if len(playerList) > 1: #Left (Player 2) if Event.key == K_LEFT: player2.pushingLeft = False #Right (Player 2) if Event.key == K_RIGHT: player2.pushingRight = False #Up (Player 2) if Event.key == K_UP: player2.pushingUp = False #Down (Player 2) if Event.key == K_DOWN: player2.pushingDown = False #Game pad keys for moving elif Event.type == JOYAXISMOTION: if joyLeft(joystick1): player1.pushingLeft = True if joyRight(joystick1): player1.pushingRight = True if not joyLeft(joystick1): player1.pushingLeft = False if not joyRight(joystick1): player1.pushingRight = False if len(playerList) > 1 and joystick_count > 1: if joyLeft(joystick2): player2.pushingLeft = True if joyRight(joystick2): player2.pushingRight = True if not joyLeft(joystick2): player2.pushingLeft = False if not joyRight(joystick2): player2.pushingRight = False elif Event.type == JOYBUTTONDOWN: if joystick1.get_button(0) == 1: player1.pushingUp = True if joystick1.get_button(1) == 1: player1.pushingDown = True if joystick1.get_button(2) == 1: player1.pushingAttack1 = True if joystick1.get_button(4) == 1: player1.pushingLeftDash = True if joystick1.get_button(5) == 1: player1.pushingRightDash = True if len(playerList) > 1 and joystick_count > 1: if joystick2.get_button(0) == 1: player2.pushingUp = True if joystick2.get_button(1) == 1: player2.pushingDown = True if joystick2.get_button(2) == 1: player2.pushingAttack1 = True if joystick2.get_button(4) == 1: player2.pushingLeftDash = True if joystick2.get_button(5) == 1: player2.pushingRightDash = True elif Event.type == JOYBUTTONUP: if joystick1.get_button(0) == 0: player1.pushingUp = False if joystick1.get_button(2) == 0: player1.pushingDown = False if len(playerList) > 1 and joystick_count > 1: if joystick2.get_button(0) == 0: player2.pushingUp = False if joystick2.get_button(2) == 0: player2.pushingDown = False if joystick_count > 0: if joystick1.get_button(6) == 1 and joystick1.get_button(7) == 1: quit() sys.exit() if joystick1.get_button(6) == 1 and fullScreenBool == True: screen = display.set_mode((SCREEN_WIDTH,SCREEN_HEIGHT)) fullScreenBool = False if joystick1.get_button(6) == 1 and fullScreenBool == False: screen = display.set_mode((\ SCREEN_WIDTH,SCREEN_HEIGHT), FULLSCREEN) fullScreenBool = True if joystick_count > 1: if joystick2.get_button(6) == 1 and joystick2.get_button(7) == 1: quit() sys.exit() if joystick2.get_button(6) == 1 and fullScreenBool == True: screen = display.set_mode((SCREEN_WIDTH,SCREEN_HEIGHT)) fullScreenBool = False if joystick2.get_button(6) == 1 and fullScreenBool == False: screen = display.set_mode((\ SCREEN_WIDTH,SCREEN_HEIGHT), FULLSCREEN) fullScreenBool = True #Movement #(Player 1) A (Left) if player1.pushingLeft == True and player1.pushingRight == False: if player1.character.status != "dashing": player1.character.moveLeft() #(Player 1) D (Right) if player1.pushingRight == True and player1.pushingLeft == False: if player1.character.status != "dashing": player1.character.moveRight() #(Player 1) W (Up) if player1.pushingUp == True: player1.pushingUp = False player1.character.jump() #(Player 1) S (Down) if player1.pushingDown == True and player1.character.status == "idle": player1.character.isCrouched = True else: player1.character.isCrouched = False #(Player 1) CapsLock/F (Dash) if player1.pushingRightDash == True: player1.pushingRightDash = False player1.character.rightDash() if player1.pushingLeftDash == True: player1.pushingLeftDash = False player1.character.leftDash() #(Player 1) E (Attack 1) if player1.pushingAttack1 == True: player1.pushingAttack1 = False player1.character.attack() if len(playerList) > 1: #(Player 2) RightArrow (Right) if player2.pushingRight == True and player2.pushingLeft == False: if player2.character.status != "dashing": player2.character.moveRight() #(Player 2) LeftArrow (Left) if player2.pushingLeft == True and player2.pushingRight == False: if player2.character.status != "dashing": player2.character.moveLeft() #(Player 2) UpArrow (Up) if player2.pushingUp == True: player2.pushingUp = False player2.character.jump() #(Player 2) DownArrow (Down) if player2.pushingDown == True and \ player2.character.status == "idle": player2.character.isCrouched = True else: player2.character.isCrouched = False #(Player 2) LeftCtrl/Keypad0 (Dash)0. if player2.pushingRightDash == True: player2.pushingRightDash = False player2.character.rightDash() if player2.pushingLeftDash == True: player2.pushingLeftDash = False player2.character.leftDash() #(Player 2) RightShift (Attack 1): if player2.pushingAttack1 == True: player2.pushingAttack1 = False player2.character.attack() #Draws Background screen.blit(background,(0,0)) healthBar.drawHealth() powerBar.drawPowerBar(player1.character.power,player2.character.power) timer.drawTimer() #Updates Player for item in playerList: item.character.update(pushingPause,playerList,system,screen,healthBar,bubble) #Updates Player Halo system.updateHalo(playerList,screen) #If Win if timer.countDown == 0 or healthBar.p1H <= 200 or healthBar.p2H <= 0: #Calls back to the system class method system.gameWinScreen(healthBar,system,player1Win,player2Win,screen) #Locks FPS time.Clock().tick(FPS) #Updates screen display.flip() <file_sep>import GameWindow import MainMenu import sys from pygame import * from gamePad import * jadeBox = [0,74,216,387] captainBox = [216,99,212,354] koopaBox = [425,118,250,337] zeroBox = [670,94,317,390] SCREEN_WIDTH = 1000 SCREEN_HEIGHT = 600 class playerRect: def __init__(self,val,player1): self.myfont = pygame.font.SysFont("Terminal", 29) self.val = val self.player1 = player1 if player1 == True: self.char = "jade" self.color = (255,0,0) else: self.char="zero" self.color = (0,0,255) self.x = val[0] self.y = val[1] self.w = val[2] self.h = val[3] self.yLabel = val[1] def setVal(self,val,char): self.val = val self.x = val[0] self.y = val[1] self.w = val[2] self.h = val[3] self.yLabel = val[1] self.char = char def draw(self): pygame.draw.rect(GameWindow.screen,self.color,\ (self.x,self.y,self.w,self.h),8) def drawLabel(self): if self.player1==True: pygame.draw.rect(GameWindow.screen,(255,0,0),\ (self.x,self.y,100,25),0) label = self.myfont.render("Player1", 1, (255, 225, 225)) GameWindow.screen.blit(label, (self.x+6, self.y+6)) else: pygame.draw.rect(GameWindow.screen,(0,0,225),\ (self.x+100,self.yLabel,100,25),0) label = self.myfont.render("Player2", 1, (255, 225, 225)) GameWindow.screen.blit(label, (self.x+106, self.yLabel+6)) p1Box = playerRect(jadeBox,True) p2Box = playerRect(zeroBox,False) def characterSelect(): charPause = True running=True joystick1 = None joystick2 = None fullScreenBool = False joystick_count = pygame.joystick.get_count() if joystick_count > 0: joystick1 = pygame.joystick.Joystick(0) if joystick_count > 1: joystick2 = pygame.joystick.Joystick(1) blinkCtr = 0 while charPause == True: surface = pygame.image.load("characterMenu.png") GameWindow.screen.blit(surface,(0,0)) #pygame.draw.rect(GameWindow.screen,(255,0,0),(x,y,w,h),8) p1Box.drawLabel() p2Box.drawLabel() p1Box.draw() p2Box.draw() if p1Box.val == p2Box.val: if blinkCtr >= 0 and blinkCtr < 25: p2Box.y = p2Box.y + 600 else: p2Box.y = p2Box.val[1] else: p2Box.y = p2Box.val[1] for event in pygame.event.get(): keys = pygame.key.get_pressed() if joystick_count > 0 and joystick1.get_button(0) == 1: charPause = False if joystick_count > 1 and joystick2.get_button(0) == 1: charPause = False if keys[pygame.K_RETURN]: charPause = False if event.type == pygame.QUIT or keys[pygame.K_ESCAPE]: sys.exit() quit() if keys[pygame.K_t] and fullScreenBool == True: screen = display.set_mode((SCREEN_WIDTH,SCREEN_HEIGHT)) fullScreenBool = False elif keys[pygame.K_t] and fullScreenBool == False: screen = display.set_mode(\ (SCREEN_WIDTH,SCREEN_HEIGHT),FULLSCREEN) fullScreenBool = True if joystick_count > 0: if joystick1.get_button(6) == 1 and \ joystick1.get_button(7) == 1: quit() sys.exit() if joystick1.get_button(6) == 1 and fullScreenBool == True: GameWindow.screen = pygame.display.set_mode((\ SCREEN_WIDTH,SCREEN_HEIGHT)) fullScreenBool = False if joystick1.get_button(6) == 1 and fullScreenBool == False: GameWindow.screen = pygame.display.set_mode((\ SCREEN_WIDTH,SCREEN_HEIGHT), FULLSCREEN) fullScreenBool = True if joystick_count > 1: if joystick2.get_button(6) == 1 and \ joystick2.get_button(7) == 1: quit() sys.exit() if joystick2.get_button(6) == 1 and fullScreenBool == True: GameWindow.screen = pygame.display.set_mode(\ (SCREEN_WIDTH,SCREEN_HEIGHT)) fullScreenBool = False if joystick2.get_button(6) == 1 and fullScreenBool == False: GameWindow.screen = pygame.display.set_mode(\ (SCREEN_WIDTH,SCREEN_HEIGHT), FULLSCREEN) fullScreenBool = True if keys[pygame.K_a] or joyLeft(joystick1): if p1Box.x == zeroBox[0]: p1Box.setVal(koopaBox,"koopa") elif p1Box.x == koopaBox[0]: p1Box.setVal(captainBox,"captain") elif p1Box.x == captainBox[0]: p1Box.setVal(jadeBox,"jade") else: p1Box.setVal(zeroBox,"zero") if keys[pygame.K_d] or joyRight(joystick1): if p1Box.x == jadeBox[0]: p1Box.setVal(captainBox,"captain") elif p1Box.x == captainBox[0]: p1Box.setVal(koopaBox,"koopa") elif p1Box.x == koopaBox[0]: p1Box.setVal(zeroBox,"zero") else: p1Box.setVal(jadeBox,"jade") if keys[pygame.K_RIGHT] or joyRight(joystick2): if p2Box.x == jadeBox[0]: p2Box.setVal(captainBox,"captain") elif p2Box.x == captainBox[0]: p2Box.setVal(koopaBox,"koopa") elif p2Box.x == koopaBox[0]: p2Box.setVal(zeroBox,"zero") else: p2Box.setVal(jadeBox,"jade") if keys[pygame.K_LEFT] or joyLeft(joystick2): if p2Box.x == zeroBox[0]: p2Box.setVal(koopaBox,"koopa") elif p2Box.x == koopaBox[0]: p2Box.setVal(captainBox,"captain") elif p2Box.x == captainBox[0]: p2Box.setVal(jadeBox,"jade") else: p2Box.setVal(zeroBox,"zero") if blinkCtr < 50: blinkCtr+=1 else: blinkCtr = 0 pygame.display.flip() return running,p1Box.char,p2Box.char <file_sep>from Classes import sprite import pygame def idleAnim(): jadeSheet = pygame.image.load("jadeSheet.png").convert_alpha() jadeStand1 = sprite("jadeStand1",jadeSheet,66,99,2,88,3,0,-100) jadeStand2 = sprite("jadeStand2",jadeSheet,101,132,4,87,3,0,-100) jadeStand3 = sprite("jadeStand3",jadeSheet,132,163,4,87,3,0,-100) return [jadeStand1,jadeStand2,jadeStand3] def walkList(): jadeSheet = pygame.image.load("jadeSheet.png").convert_alpha() jadeWalk3 = sprite("jadeWalk3",jadeSheet,140,164,89,168,3,0,-100) jadeWalk4 = sprite("jadeWalk4",jadeSheet,173,208,89,167,3,0,-100) jadeWalk5 = sprite("jadeWalk5",jadeSheet,213,241,89,167,3,0,-100) jadeWalk6 = sprite("jadeWalk6",jadeSheet,246,271,89,169,3,0,-100) return [jadeWalk3,jadeWalk4,jadeWalk5,jadeWalk6] def startStopAnim(): jadeSheet = pygame.image.load("jadeSheet.png").convert_alpha() jadeWalk1 = sprite("jadeWalk1",jadeSheet,57,92,90,168,3,0,-100) jadeWalk2 = sprite("jadeWalk2",jadeSheet,101,128,88,167,3,0,-100) return [jadeWalk1,jadeWalk2] def jumpAnim(): jadeSheet = pygame.image.load("jadeSheet.png").convert_alpha() jadeJump1 = sprite("jadeJump1",jadeSheet,290,325,99,164,3,0,-100) jadeJump2 = sprite("jadeJump2",jadeSheet,329,365,101,199,3,0,-100) jadeJump3 = sprite("jadeJump3",jadeSheet,378,414,116,179,3,0,-100) jadeJump4 = sprite("jadeJump4",jadeSheet,424,455,115,172,3,0,-100) jadeJump5 = sprite("jadeJump5",jadeSheet,465,498,102,209,3,0,-100) return [jadeJump3,jadeJump3,jadeJump3,jadeJump3,jadeJump5] #jadeCrouch1 = sprite("jadeCrouch1",jadeSheet,239,275,47,87,3) def dashAnim(): jadeSheet = pygame.image.load("jadeSheet.png").convert_alpha() ## jadeBackflip1 = sprite("jadeBackflip1",jadeSheet,169,226,296,366,4,0,-100) ## jadeBackflip2 = sprite("jadeBackflip2",jadeSheet,282,361,343,382,4,0,-50) jadeDash1 = sprite("jadeDash1",jadeSheet,548,620,119,175,3,0,0) return [jadeDash1,jadeDash1] def attackAnim(): jadeSheet = pygame.image.load("jadeSheet.png").convert_alpha() jadeStaff1 = sprite("jadeStaff1",jadeSheet,225,299,186,256,3,0,-70) jadeStaff2 = sprite("jadeStaff2",jadeSheet,400,484,303,375,3,0,-70) jadeStaff3 = sprite("jadeStaff3",jadeSheet,493,568,309,379,3,0,-70) return [jadeStaff1,jadeStaff2,jadeStaff3] def widest(): jadeSheet = pygame.image.load("jadeSheet.png").convert_alpha() jadeBackflip3 = sprite("jadeBackflip3",jadeSheet,142,217,189,254,3,0,0) return jadeBackflip3 def tallest(): jadeSheet = pygame.image.load("jadeSheet.png").convert_alpha() jadeJump3 = sprite("jadeJump5",jadeSheet,423,455,114,172,3,0,0) return jadeJump3 def default(): jadeSheet = pygame.image.load("jadeSheet.png").convert_alpha() jadeStand1 = sprite("jadeStand1",jadeSheet,66,99,2,88,3,0,0) return jadeStand1
ce23670d41ada511041200d2622004f55e6a6e5a
[ "Python", "Text" ]
13
Python
B1anky/Not-So-Extreme-Fighting
b95a12bb4b0ff5fc8819ad5fe2e2e36d39a3db35
480e707d46b11ef9c97abe1ca3a9f8137aa110b9
refs/heads/master
<repo_name>mike-north/ts-ember-addon-demo<file_sep>/my-addon/components/x-foo.d.ts import Component from '@ember/component'; declare const XFoo_base: Readonly<typeof Component> & (new (properties?: object | undefined) => Component) & (new (...args: any[]) => Component); export default class XFoo extends XFoo_base { layout: any; } export {};
e9e810f09687984340c2f70482edf73b5bafd232
[ "TypeScript" ]
1
TypeScript
mike-north/ts-ember-addon-demo
54eb1b40397dbbea40c5f9f85e6bfc3c92c29ecc
0842fbbf370783c572f2e2df13d9a903bfbb9d0e
refs/heads/master
<file_sep>package IoCTest.IO; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * Created by vic on 24.11.16. */ public class Main { public static void main(String[] args) { ApplicationContext applicationContext = new ClassPathXmlApplicationContext(new String[]{"appContext.xml"}); DataHandler dataHandler = (DataHandler) applicationContext.getBean("dataHandler"); DataHandler dataHandler2 = (DataHandler) applicationContext.getBean("dataHandler"); DataHandler dataHandler3 = new DataHandler(); DataHandler dataHandler4 = (DataHandler) new ClassPathXmlApplicationContext(new String[]{"appContext.xml"}).getBean("dataHandler"); System.out.println(dataHandler == dataHandler2); System.out.println(dataHandler == dataHandler3); System.out.println(dataHandler == dataHandler4); /*DataHandler dataHandler = new DataHandler(); dataHandler.setDownloader(new FileDownloader()); dataHandler.setUploader(new FileUploader());*/ dataHandler.handleData("someSrcPath", "someDestPath"); } }
88d69886f10917291e55f0377cc5ad02cff2dc21
[ "Java" ]
1
Java
borzenkov/lecture_17
b87eec21ee1881022d354f36d4fbfb521d1da2da
d0dd42afc299083a7c70f3050fb5a8f43602302f
refs/heads/master
<repo_name>luluco250/GTAIV_LShiftSprintFix<file_sep>/LShiftSprintFix.ini [Settings] ; How often (in milliseconds) should the mod script ; check if the shift key is being pressed in time. TickInterval=100 ; How many milliseconds are allowed to pass ; before sprinting is disabled in-between ; left shift key presses. SprintInterval=300 ; Use caps lock to revert to vanilla behavior? ; This makes it so any time the caps lock key ; is enabled (it's light is on) the mod will ; enable sprinting without repeated key presses. UseCapsLock=true <file_sep>/ModScript.cs using System; using System.Collections.Generic; using System.Windows.Forms; using GTA; using GTA.Native; public class ModScript : Script { //==========// // Settings // //==========// readonly int tickInterval; readonly int sprintInterval; readonly bool useCapsLock; //=======// // State // //=======// int lastClickTime = Game.GameTime; bool isSprinting = false; //=============// // Constructor // //=============// public ModScript() { // Read settings... tickInterval = Settings.GetValueInteger("TickInterval", "Settings", 100); sprintInterval = Settings.GetValueInteger("SprintInterval", "Settings", 300); useCapsLock = Settings.GetValueBool("UseCapsLock", "Settings", true); // Setup events... KeyDown += new GTA.KeyEventHandler(OnKeyDown); Interval = tickInterval; Tick += new EventHandler(OnTick); } //========// // Events // //========// void OnTick(object sender, EventArgs args) { bool sprint = useCapsLock && Control.IsKeyLocked(Keys.CapsLock); sprint = sprint || ((Game.GameTime - lastClickTime) < sprintInterval); // Check in case player wasn't sprinting already // so that the (correct) jogging animation starts // upon the first press of left shift. CanSprint(isSprinting && sprint); isSprinting = sprint; } void OnKeyDown(object sender, GTA.KeyEventArgs args) { if (args.Key == Keys.LShiftKey) lastClickTime = Game.GameTime; } //=========// // Helpers // //=========// void CanSprint(bool b) { Function.Call("DISABLE_PLAYER_SPRINT", Player.Index, !b); } } <file_sep>/README.md # GTA IV: Left Shift Sprint Fix Mod This a tiny mod that fixes an oversight in Grand Theft Auto IV where the left shift key *always* sprints, regardless of whether it's being held or pressed repeatedly, unlike other keys. This behavior is corrected through mod by making a call to a native function of the game that disables sprinting for a given player, thus it is used when the key is not being pressed repeatedly. There is also a feature where you can use the caps lock to revert to vanilla behavior, so you won't have hand cramps at the end of the day. Be aware that this won't work well in case "sticky keys" is enabled in your system. To check if it's enabled, simply hit the shift key a few times to see if a window about "sticky keys" pops up, if it does then follow the instructions in it to disable it. ## How to install Get the latest release [here](https://github.com/luluco250/GTAIV_LShiftSprintFix/releases), extract the files to ```(...)\Grand Theft Auto IV\GTAIV\scripts``` and make sure you have the .NET Scripthook installed. If you don't, get it [here](http://hazardx.com/files/gta4_net_scripthook-83). You can then change the settings in ```LShiftSprintFix.ini```. ## How to build To build, simply use either the .NET CLI tools with the command ```dotnet build``` or through Visual Studio (though I haven't tested with it). Requires that you place a copy or link to ```ScriptHookDotNet.dll``` in the project folder, which is added as an assembly reference. You must then change the extension of the output to ```.net.dll``` for the .NET scripthook to recognize it. Then simply copy/link it and the .ini file to the ```scripts``` folder in your GTA IV folder. ## The future... I'm planning to make an option to make sprinting behave like it does in GTA V, but I need a way to make the game "think" you're pressing the shift. If anyone knows how to do that, feel free to make an issue report or even a pull request.
26f186bbfd9b85feeecde63b7c002ee45b4e624e
[ "Markdown", "C#", "INI" ]
3
INI
luluco250/GTAIV_LShiftSprintFix
b3ffdb20f5c53a39193fefef9661232f396846ac
1031465324bb52a11336f114772843e39494f941
refs/heads/master
<repo_name>yusuke-matsu/testbot<file_sep>/README.md # testbo botkitのお勉強用 <file_sep>/app.js /*eslint-env node*/ //------------------------------------------------------------------------------ // node.js starter application for Bluemix //------------------------------------------------------------------------------ // This application uses express as its web server // for more info, see: http://expressjs.com var express = require('express'); // cfenv provides access to your Cloud Foundry environment // for more info, see: https://www.npmjs.com/package/cfenv var cfenv = require('cfenv'); // create a new express server var app = express(); // serve the files out of ./public as our main files app.use(express.static(__dirname + '/public')); // provide static access for AngularJS and Angular Material. app.use('/node_modules', express.static(__dirname + '/node_modules')); // get the app environment from Cloud Foundry var appEnv = cfenv.getAppEnv(); // body-parser var bodyParser = require("body-parser"); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({extended: true})); // date-util var dateutil = require("date-utils"); try { var ibcCredentials = require("./mycreds.json").credentials; console.log("hardcord credentials: ", ibcCredentials); console.log("loading hardcoded peers"); //need to define peers data var peers = ibcCredentials.peers; var users = null; // users are only found if security is on if(ibcCredentials.users) { console.log("loading hardcoded users"); // need to define users data users = ibcCredentials.users; } // need to define chaincode var deployed_cc = ibcCredentials.chaincode; console.log(deployed_cc); } catch (e) { console.log("Error - could not find hardcoded peers/users, this is okay if running in bluemix"); } // load peers from VCAP, VCAP will overwrite hardcoded list! // ---- Load From VCAP aka Bluemix Services ---- // if (process.env.VCAP_SERVICES) { // load from vcap, search for service, 1 of the 3 should be found... var servicesObject = JSON.parse(process.env.VCAP_SERVICES); for (var i in servicesObject) { if (i.indexOf("ibm-blockchain-5-prod") >= 0) { // looks close enough if (servicesObject[i][0].credentials.error) { console.log("!\n!\n! Error from Bluemix: \n", servicesObject[i][0].credentials.error, "!\n!\n"); peers = null; users = null; process.error = { type: "network", msg: "Due to overwhelming demand the IBM Blockchain Network service is at maximum capacity. Please try recreating this service at a later date." }; } if (servicesObject[i][0].credentials && servicesObject[i][0].credentials.peers) { // found the blob, copy it to 'peers' console.log("overwritting peers, loading from a vcap service: ", i); peers = servicesObject[i][0].credentials.peers; if (servicesObject[i][0].credentials.users) { // user field may or maynot exist, depends on if there is membership services or not for the network console.log("overwritting users, loading from a vcap service: ", i); users = servicesObject[i][0].credentials.users; } break; } } } } // Blockchain //cred var opt = { network:{ peers: [{ api_host: peers[0].api_host, // Validating Peer 0 api_port: peers[0].api_port, // Validating Peer 0 api_port_tls: peers[0].api_port_tls, // Validating Peer 0 id: peers[0].id // Validating Peer 0 }], users: [{ enrollId: users[2].enrollId, // user id enrollSecret: users[2].enrollSecret // password }], options: { quiet: true, // detailed debug messages on/off true/false tls: true, // should app to peer communication use tls? maxRetry: 3 // how many times should we retry register before giving up } }, chaincode: { zip_url: "https://github.com/yusuke-matsu/testApp/archive/master.zip", unzip_dir: "testApp-master/",     // subdirectroy name of chaincode after unzipped git_url: "https://github.com/yusuke-matsu/testApp", // GO get http url deployed_name: deployed_cc } }; var Ibc1 = require("ibm-blockchain-js"); var ibc = new Ibc1(); var chaincode = null; // sdk will populate this var in time, lets give it high scope by creating it here ibc.load (opt, function (err, cc) { // parse/load chaincode, response has chaincode functions! console.log("loading chaincode", JSON.stringify(opt)); if (err != null) { console.log("! looks like an error loading the chaincode or network, app will fail\n", err); if (!process.error) process.error = { type: "load", msg: err.details }; // if it already exist, keep the last error } else { chaincode = cc; // ---- To Deploy or Not to Deploy ---- // if (!cc.details.deployed_name || cc.details.deployed_name === "") { // yes, go deploy cc.deploy("init", [], null, cb_deployed); console.log("chaincode deployed: ", cc.details.deployed_name); } else { // no, already deployed console.log("chaincode summary file indicates chaincode has been previously deployed", cc.details.deployed_name); } function cb_deployed(){ console.log(JSON.stringify(chaincode)); console.log("sdk has deployed code and waited"); } } }); app.get("/deploy", function(req, res) { console.log("call chaincode for /deploy"); opt.chaincode.deployed_name = ""; ibc.load (opt, function (err, cc) { // parse/load chaincode, response has chaincode functions! console.log("loading chaincode", JSON.stringify(opt)); if (err != null) { console.log("! looks like an error loading the chaincode or network, app will fail\n", err); if (!process.error) process.error = { type: "load", msg: err.details }; // if it already exist, keep the last error res.sendStatus(500); } else { chaincode = cc; // ---- To Deploy or Not to Deploy ---- // if (!cc.details.deployed_name || cc.details.deployed_name === "") { // yes, go deploy cc.deploy("init", [], null, cb_deployed); console.log("chaincode deployed: ", cc.details.deployed_name); } else { // no, already deployed console.log("chaincode summary file indicates chaincode has been previously deployed", cc.details.deployed_name); } res.sendStatus(200); function cb_deployed(){ console.log(JSON.stringify(chaincode)); console.log("sdk has deployed code and waited"); } } }); }); app.post("/invoke/issue", function(req, res) { console.log("call chaincode for /invoke/issue: " + JSON.stringify(req.body)); //chaincode = opt.chaincode.deployed_name; console.log(chaincode); if (!chaincode) { console.log(req.body); console.log("chaincode has not been prepared"); res.sendStatus(500); } else { // invoke.issue console.log(chaincode); var data = {}; data = req.body; console.log(req.body); console.log("calling invoke.issue: " + data.personName + ", " + data.amount); chaincode.invoke.issue([ data.personName, data.amount ], function(err, result) { if (err) { // 既にissueが登録済みの場合、エラーが返されるはずだが、正常終了する // ただし、ブロックチェーンのログにはエラーが記録されている console.log("invoke.issue failed: ", req.params.id, err); res.sendStatus(204); } }); res.json(data); } }); app.post("/invoke/change", function(req, res) { console.log("call chaincode for /query/" + JSON.stringify(req.params)); if (!chaincode) { console.log("chaincode has not been prepared"); res.sendStatus(500); } else { //query.getIssue chaincode.query.getIssue([req.params.personName],function(err,result){ if (err !== null){ console.log("alliss is faild"); res.sendStatus(204); }else{ console.log("alliss is success"); res.send(JSON.parse(result)); } }); } }); app.get("/query/allissue", function(req, res) { console.log("call chaincode for /query/allIssue: " + JSON.stringify(req.body)); console.log(chaincode); if (!chaincode) { console.log(req.body); console.log("chaincode has not been prepared"); res.sendStatus(500); } else { //query.allIssue chaincode.query.getAllIssues([],function(err,result){ if (err){ console.log("alliss is faild"); res.sendStatus(204); }else{ console.log("alliss is success"); res.send(JSON.parse(result)); } }); } }); app.get("/query/:personName", function(req, res) { console.log("call chaincode for /query/" + JSON.stringify(req.params)); if (!chaincode) { console.log("chaincode has not been prepared"); res.sendStatus(500); } else { //query.getIssue chaincode.query.getIssue([req.params.personName],function(err,result){ if (err !== null){ console.log("alliss is faild"); res.sendStatus(204); }else{ console.log("alliss is success"); console.log(result); res.send(JSON.parse(result)); } }); } }); // start server on the specified port and binding host app.listen(appEnv.port, '0.0.0.0', function() { // print a message when the server starts listening console.log("server starting on " + appEnv.url); });
fc56e9b9f89972f55f33fa5555585d3a71aa072e
[ "Markdown", "JavaScript" ]
2
Markdown
yusuke-matsu/testbot
e9f811eb71009e9d1712b97299f99a665aeafcd8
eeba9fb8d801511c1675d8e1d78becec933ea00b
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace Calculator.CheckBook { /// <summary> /// Interaction logic for LoginWindow.xaml /// </summary> public partial class LoginWindow : Window { public LoginWindow() { InitializeComponent(); } TaskCompletionSource<string> tSource = new TaskCompletionSource<string>(); public Task<string> Login() { Show(); //var loginUrl = "https://accounts.google.com/AddSession?sacu=1&continue=https%3A%2F%2Faccounts.google.com%2FManageAccount"; var loginUrl = "https://www.facebook.com/dialog/oauth?client_id=1438926676407670&redirect_uri=https://www.facebook.com/connect/login_success.html&response_type=token"; wb.Navigate(loginUrl); return tSource.Task; } private void wb_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e) { var match = System.Text.RegularExpressions.Regex.Match(e.Uri.Fragment, "token=(.*)&"); if (match.Success) { tSource.SetResult(match.Groups[1].Value); this.Close(); } } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace Calculator.CheckBook { /// <summary> /// Interaction logic for CheckBookWindow.xaml /// </summary> public partial class CheckBookWindow : Window { public CheckBookWindow() { InitializeComponent(); } private void Window_Loaded(object sender, RoutedEventArgs e) { var VM = new CheckBookVM(); DataContext = VM; VM.Fill(); System.Windows.Data.CollectionViewSource transactionViewSource = ((System.Windows.Data.CollectionViewSource)(this.FindResource("transactionViewSource"))); // Load data by setting the CollectionViewSource.Source property: // transactionViewSource.Source = [generic data source] } private void Button_Click(object sender, RoutedEventArgs e) { ReportForm rp = new ReportForm(); rp.Show(); } private bool ismaxAmount = true; public void Background() { if(ismaxAmount) { Brush newColor = Brushes.Red; Tsction.Background = (SolidColorBrush)newColor; } } } } <file_sep># Calculator Created in 2014 Simulate a calculator using CSharp <file_sep>using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; using System.Windows.Input; namespace Calculator { public class Operation: BaseVM { private string _Operator = "+"; public string Operator { get { return _Operator; } set { _Operator = value; OnPropertyChanged(); OnPropertyChanged("DisplayText"); } } private float _PreviousTotal; public float PreviousTotal { get { return _PreviousTotal; } set { _PreviousTotal = value; OnPropertyChanged(); OnPropertyChanged("DisplayText"); } } public virtual string DisplayText { get { return Results.ToString(); } } public virtual ICommand Number { get { return new DeadCommand(); } } public virtual ICommand BackSpace { get { return new DeadCommand(); } } public virtual float Results { get { switch (Operator) { case "sq": return PreviousTotal * PreviousTotal; case "sqrt": return (float) Math.Sqrt( (double)PreviousTotal ); case "+/-": return -PreviousTotal; case "=": return PreviousTotal; } return PreviousTotal; } } public override string ToString() { return Operator.ToString() + " " + PreviousTotal.ToString(); } } public class BinaryOperation : Operation { public override ICommand BackSpace { get { return new BackSpaceCommand(this); } } public override ICommand Number { get { return new DelegateCommand { ExecuteFunction = p => StrOperand += p }; } } public override string DisplayText { get { if (string.IsNullOrWhiteSpace(StrOperand)) return PreviousTotal.ToString(); else return StrOperand; } } private string _StrOperand; public string StrOperand { get { return _StrOperand; } set { _StrOperand = value; OnPropertyChanged(); OnPropertyChanged("Operand"); OnPropertyChanged("Results"); OnPropertyChanged("DisplayText"); } } private float _Operand; public float Operand { get { if (!float.TryParse(StrOperand, out _Operand)) { return 0; } return _Operand; } } public override float Results { get { switch (Operator) { case "+": return PreviousTotal + Operand; case "-": return PreviousTotal - Operand; case "x": return PreviousTotal * Operand; case "/": return PreviousTotal / Operand; } return PreviousTotal; } } public override string ToString() { return Operator.ToString() + " " + Operand.ToString(); } } public class BaseVM: INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; public void OnPropertyChanged([CallerMemberName]string propertyName = null) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } } public class BackSpaceCommand : ICommand { public BackSpaceCommand(BinaryOperation op) { _Op = op; _Op.PropertyChanged += (s, e) => { if (CanExecuteChanged != null) { CanExecuteChanged(this, EventArgs.Empty); } }; } private BinaryOperation _Op; public bool CanExecute(object parameter) { return !string.IsNullOrEmpty(_Op.StrOperand); } public event EventHandler CanExecuteChanged; public void Execute(object parameter) { _Op.StrOperand = _Op.StrOperand.Substring(0, _Op.StrOperand.Length - 1); } } public class DelegateCommand: ICommand { public Predicate<object> CanExecuteFunction { get; set; } public Action<object> ExecuteFunction { get; set; } public bool CanExecute(object parameter) { if (CanExecuteFunction != null) return CanExecuteFunction(parameter); else return true; } public event EventHandler CanExecuteChanged { add { CommandManager.RequerySuggested += value; } remove { CommandManager.RequerySuggested -= value; } } public void OnCanExecuteChanged() { CommandManager.InvalidateRequerySuggested(); } public void Execute(object parameter) { if (ExecuteFunction != null) ExecuteFunction(parameter); } } public class DeadCommand : ICommand { public bool CanExecute(object parameter) { return false; } public event EventHandler CanExecuteChanged; public void Execute(object parameter) { throw new NotImplementedException(); } } }
4640b18613759fdf5fc082dd1f3222ab6a775623
[ "Markdown", "C#" ]
4
C#
ValerieRen/CSharp-Calculator
64b445d68e35ada0d91b48e9f84a99b73754e41b
6439bd998aa710100d68e6a07760958600a68535
refs/heads/master
<file_sep># kepler_ages A catalog of ages for Kepler stars <file_sep>import numpy as np import pandas as pd import matplotlib.pyplot as plt from matplotlib import gridspec import re import lightkurve as lk import exoarch import starspot as ss import starspot.rotation_tools as rt from stardate.lhf import gk_age_model from stardate import load_samples, read_samples from isochrones import get_ichrone import kepler_data as kd import kplr client = kplr.API() def get_index_from_filename(df, filename): kepid = re.findall(r'\d+', filename)[0] m = df.kepid == int(kepid) return int(np.arange(len(df))[m]), kepid def load_lc(starname, timespan=200): # # lcfs = lk.search_lightcurvefile(starname).download_all() # lc1 = lk.search_lightcurvefile(starname, quarter=2) # lc2 = lk.search_lightcurvefile(starname, quarter=3) # # lc = lcf.PDCSAP_FLUX # # lc = lcfs.PDCSAP_FLUX.stitch() # lc_collection = lk.LightCurveCollection([lc1, lc2]) # lc = lc_collection.stitch() star = client.star(starname) star.get_light_curves(fetch=True, short_cadence=False) LC_DIR = "/Users/rangus/.kplr/data/lightcurves/{}".format(starname) x, y, yerr = kd.load_and_join(LC_DIR) m = x < x[0] + timespan lc = lk.LightCurve(time=x[m], flux=y[m], flux_err=yerr[m]) # Remove NaNs and sigma clip to remove flares. # no_nan_lc = lc.remove_nans() clipped_lc = lc.remove_outliers(sigma=4) return clipped_lc.time, clipped_lc.flux, clipped_lc.flux_err def get_koi_properties(kid): kois = exoarch.KOICatalog().df k = kois.kepid == kid # "K00092.01" dur = kois.koi_duration.values[k] porb = kois.koi_period.values[k] t0 = kois.koi_time0bk.values[k] nplanets = kois.koi_count.values[k] return dur, porb, t0, nplanets def make_rotation_plots(time, flux, flux_err, interval=0.02043365, period_grid=np.linspace(1, 50, 2000)): rotate = ss.RotationModel(time, flux, flux_err) ls_period = rotate.ls_rotation() acf_period = rotate.acf_rotation(interval) # pdm_period, period_err = rotate.pdm_rotation(rotate.lags, pdm_nbins=10) pdm_period, period_err = rotate.pdm_rotation(period_grid, pdm_nbins=10) fig = rotate.big_plot() return ls_period, acf_period, pdm_period, period_err, fig def transit_mask_plot(time, flux, flux_err, kepid): dur, porb, t0, nplanets = get_koi_properties(kepid) mask = rt.transit_mask(time, t0[0], dur[0]*2, porb[0]) fig = plt.figure(figsize=(16, 3)) plt.plot(time, flux, "C1", lw=.5) plt.xlabel("Time - 2454833 [BKJD days]") plt.ylabel("Flux"); plt.plot(time[mask], flux[mask], "C0", lw=.5) plt.xlabel("Time - 2454833 [BKJD days]") plt.ylabel("Normalized Flux"); plt.tight_layout() return dur, porb, t0, nplanets, fig, mask def cmd_gyro_plots(ro, period, age_gyr): mc = pd.read_csv("mcquillan_gaia.csv") # Calculate a simple gyro age. # log_age = gk_age_model(np.log10(ro.Prot), ro.bp_dered-ro.rp_dered) # age_gyr = (10**log_age)*1e-9 fig = plt.figure(figsize=(16, 16), dpi=200) ax1 = fig.add_subplot(211) # Remove spurious very old stars! m = mc.ages_gyr.values < 15 cb = ax1.scatter(mc.Teff[m], mc.Prot[m], c=mc.ages_gyr.values[m], alpha=.1, vmin=0, vmax=5, edgecolor="none", zorder=0, cmap="plasma",label="$\mathrm{McQuillan~+~(2014)}$") ax1.plot(ro.Teff, ro.period, "ko", ms=20, zorder=4) ax1.scatter([ro.Teff], [ro.period], c=[float(age_gyr)], s=200, vmin=0, vmax=5, edgecolor="w", cmap="plasma", zorder=5) ax1.scatter([5778], [26], c=[4.567], s=200, vmin=0, vmax=5, edgecolor="k", lw=2, zorder=2, cmap="plasma", label="$\mathrm{Sun}$") ax1.plot(5778, 26, "k.", zorder=3) color_bar = plt.colorbar(cb, ax=ax1, label="$\mathrm{Age~[Gyr]}$") color_bar.set_alpha(1) color_bar.draw_all() ax1.set_xlim(6500, 3000) ax1.set_yscale("log") ax1.set_ylabel("$\mathrm{Rotation~period~[days]}$") ax1.set_xlabel("$\mathrm{T_{eff}}$") # Add Praesepe cl = pd.read_csv("clean_clusters.csv") ax1.scatter(cl.teff, cl.period, c=cl.age_gyr, edgecolor="w", vmin=0, vmax=5, s=50, cmap="plasma", lw=.5, label="$\mathrm{Cluster~stars}$", zorder=1) # ax1.legend(fontsize=20) ax2 = fig.add_subplot(212) cb = ax2.scatter(mc.phot_bp_mean_mag - mc.phot_rp_mean_mag, mc.abs_G, c=mc.Prot, s=50, alpha=.1, vmin=0, vmax=40, edgecolor="none", zorder=0, label="$\mathrm{McQuillan~+~(2014)}$"); ax2.plot(ro.bp_dered - ro.rp_dered, ro.abs_G, "ko", ms=20, zorder=4) ax2.scatter([ro.bp_dered - ro.rp_dered], [ro.abs_G], c=[period], s=250, vmin=0, vmax=40, edgecolor="w", zorder=5); # Sun's Gaia mags from https://arxiv.org/pdf/1806.01953.pdf ax2.scatter([.82], [4.67], c=[26], s=300, edgecolor="k", zorder=2, vmin=0, vmax=40, label="$\mathrm{Sun}$") ax2.plot(.82, 4.67, "k.", zorder=3) ax2.scatter(cl.phot_bp_mean_mag - cl.phot_rp_mean_mag, m_to_M(cl.phot_g_mean_mag, 1./cl.parallax*1e3), c=cl.period, s = 100, vmin=0, vmax=40, edgecolor="w", lw=.5, label="$\mathrm{Cluster~stars}$", zorder=1) color_bar = plt.colorbar(cb, ax=ax2, label="$\mathrm{Rotation~period~[days]}$") color_bar.set_alpha(1) color_bar.draw_all() ax2.set_ylim(7, 2) ax2.set_xlim(.6, 1.5) ax2.set_xlabel("$G_{BP} - G_{RP}$") ax2.set_ylabel("$\mathrm{Absolute~G~magnitude}$"); # ax2.legend(fontsize=20) plt.tight_layout() return fig def m_to_M(m, D): """ Convert apparent magnitude to absolute magnitude. """ return m - 5*np.log10(abs(D)) + 5 def get_inits(bp, rp, period, mass, feh, parallax_mas): # Get gyro age log10_age_yrs = gk_age_model(np.log10(period), bp-rp) gyro_age = (10**log10_age_yrs)*1e-9 # Get initial EEP: mist = get_ichrone('mist') try: eep = mist.get_eep(mass, log10_age_yrs, feh, accurate=True) except: eep = 355 distance_pc = 1./(parallax_mas*1e-3) inits = [eep, log10_age_yrs, feh, np.log(distance_pc), .1] return inits def make_sample_comparison_plot(gyro_samples, iso_samples, inits, sigma): gs = gridspec.GridSpec(2, 4) fig = plt.figure(figsize=(16, 10), dpi=200) ax1 = fig.add_subplot(gs[0, :]) ax1.hist((10**gyro_samples[:, 1])*1e-9, 50, density=True, alpha=.5, color="k", label="$\mathrm{Gyro}$"); ax1.hist((10**iso_samples[:, 1])*1e-9, 50, density=True, alpha=.5, label="$\mathrm{Iso}$"); ax1.set_xlabel("$\mathrm{Age~[Gyr]}$") ax1.axvline((10**inits[1])*1e-9, color="C1", ls="--", zorder=10, label="$\mathrm{Initial~value}$") ax1.axvline((10**np.median(gyro_samples[:, 1])*1e-9), color="k", ls="--") ax1.axvline((10**np.median(iso_samples[:, 1])*1e-9), color="C0", ls="--") ax1.set_xlim(0, 14) ax1.legend(fontsize=15); plt.setp(ax1.get_yticklabels(), visible=False); plt.title("Sigma = {0}".format(sigma)) def add_ax(i, init, gsamps, isamps, label): ax = fig.add_subplot(gs[1, i]) ax.hist(gsamps, 50, density=True, alpha=.5, color="k", label="$\mathrm{Gyro}$"); ax.hist(isamps, 50, density=True, alpha=.5, label="$\mathrm{Iso}$"); ax.set_xlabel(label) ax.axvline(init, color="C1", ls="--", zorder=10) ax.axvline(np.median(gsamps), color="k", ls="--") ax.axvline(np.median(isamps), color="C0", ls="--") plt.setp(ax.get_yticklabels(), visible=False); inds = [0, 2, 3, 4] labels = ["$\mathrm{EEP}$", "$\mathrm{[Fe/H]}$", "$\mathrm{ln(Distance~[pc])}$", "$\mathrm{A_v}$"] for i in range(4): add_ax(i, inits[inds[i]], gyro_samples[:, inds[i]], iso_samples[:, inds[i]], labels[i]) plt.subplots_adjust(wspace=.02, hspace=.25) return fig <file_sep>#!/usr/bin/python3 import os import sys import numpy as np import pandas as pd import h5py import tqdm import emcee import stardate as sd from stardate.lhf import age_model from isochrones import get_ichrone mist = get_ichrone('mist') from multiprocessing import Pool # Necessary to add cwd to path when script run # by SLURM (since it executes a copy) sys.path.append(os.getcwd()) def infer_stellar_age(df): # Set up the parameter dictionary. iso_params = {"G": (df["phot_g_mean_mag"], df["G_err"]), "BP": (df["phot_bp_mean_mag"], df["bp_err"]), "RP": (df["phot_rp_mean_mag"], df["rp_err"]), "teff": (df["cks_steff"], df["cks_steff_err1"]), "feh": (df["cks_smet"], df["cks_smet_err1"]), "logg": (df["cks_slogg"], df["cks_slogg_err1"]), "parallax": (df["parallax"], df["parallax_error"])} # Infer an age with isochrones and gyrochronology. gyro_fn = "samples/{}_gyro".format(str(int(df["kepid"])).zfill(9)) iso_fn = "samples/{}_iso".format(str(int(df["kepid"])).zfill(9)) # Get initialization bprp = df["phot_bp_mean_mag"] - df["phot_rp_mean_mag"] log10_period = np.log10(df["Prot"]) log10_age_yrs = age_model(log10_period, bprp) gyro_age = (10**log10_age_yrs)*1e-9 eep = mist.get_eep(df["koi_smass"], np.log10(gyro_age*1e9), df["cks_smet"], accurate=True) inits = [eep, np.log10(gyro_age*1e9), df["cks_smet"], (1./df["parallax"])*1e3, df["Av"]] # Set up the star object iso_star = sd.Star(iso_params, Av=df["Av"], Av_err=df["Av_std"], filename=iso_fn) gyro_star = sd.Star(iso_params, prot=df["Prot"], prot_err=df["e_Prot"], Av=df["Av"], Av_err=df["Av_std"], filename=gyro_fn) # Run the MCMC iso_sampler = iso_star.fit(inits=inits, max_n=300000, save_samples=True) gyro_sampler = gyro_star.fit(inits=inits, max_n=300000, save_samples=True) if __name__ == "__main__": # Load the data file. df = pd.read_csv("cks_gaia_mazeh.csv") list_of_dicts = [] for i in range(len(df)): list_of_dicts.append(df.iloc[i].to_dict()) print(list_of_dicts[0]) print(len(list_of_dicts)) p = Pool(24) list(p.map(infer_stellar_age, list_of_dicts)) <file_sep>""" Script for checking the results of age inference. """ import numpy as np import matplotlib.pyplot as plt import pandas as pd import glob import check_code as cc # Load file with info for all CKS stars ro = pd.read_csv("cks_gaia_mazeh.csv") # Load successful posteriors gyro_filenames = glob.glob("samples/*gyro.h5") iso_filenames = glob.glob("samples/*iso.h5") print(len(gyro_filenames), len(iso_filenames)) gyro_inds, iso_inds = [], [] for i in range(len(gyro_filenames)): ind = cc.get_index_from_filename(ro, gyro_filenames[i])[0] gyro_inds.append(ind) for i in range(len(iso_filenames)): ind = cc.get_index_from_filename(ro, iso_filenames[i])[0] iso_inds.append(ind) # Merge so you're only looking at stars where both gyro and iso ran. gyro_ro = ro.iloc[gyro_inds] iso_ro = ro.iloc[iso_inds] iso_df = pd.DataFrame(dict({"kepid": iso_ro.kepid.values})) df = pd.merge(gyro_ro, iso_df, on="kepid", how="inner") <file_sep>""" Check that the KOI rotation periods and ages seem reasonable. """ import numpy as np import matplotlib.pyplot as plt import pandas as pd import glob import corner import check_code as cc from starspot import rotation_tools as rt import starspot as ss from stardate import load_samples, read_samples from stardate.lhf import sigma def make_period_plots_for_one_star(df, timespan, mask_transit_plot=True): print("Load light curve, sigma clip and remove NaNs.") kepid = df.kepid starname1 = "KIC {}".format(kepid) starname = str(int(df.kepid)).zfill(9) time, flux, flux_err = cc.load_lc(starname, timespan=timespan) if mask_transit_plot: print("Mask transits") d, p, t0, n, fig0, mask = cc.transit_mask_plot(time, flux, flux_err, kepid) print("duration = ", d, "t0 = ", t0, "porb = ", p) fig0.savefig("plots/{}_atransit_mask_plot".format(starname)) plt.close() time, flux, flux_err = time[mask], flux[mask], flux_err[mask] print("Make period plots") ls_period, acf_period, pdm_period, period_err, fig = \ cc.make_rotation_plots(time, flux, flux_err) plt.axvline(df.Prot, color="C1") fig.savefig("plots/{}_big_plot".format(starname)) plt.close() return ls_period, acf_period, pdm_period, period_err, starname def make_age_plots_for_one_star(df, period, period_err, cmd_gyro=True, corner_plot=True, age_plot=True): starname = str(int(df.kepid)).zfill(9) print("starname = ", starname) print("Load samples_and_results") gfilename = "samples/{0}_gyro.h5".format(starname) ifilename = "samples/{0}_iso.h5".format(starname) gflatsamples, _, _, _ = load_samples(gfilename, burnin=100) gresults = read_samples(gflatsamples) iflatsamples, _, _, _ = load_samples(ifilename, burnin=100) iresults = read_samples(iflatsamples) if cmd_gyro: print("Make CMD plot") age_gyr = gresults.age_med_gyr.values fig1 = cc.cmd_gyro_plots(df, period, age_gyr) fig1.savefig("plots/{}_cmd_plot".format(starname)) plt.close() inits = cc.get_inits(df.bp_dered, df.rp_dered, period, df.koi_smass, df.cks_smet, df.parallax) print("inits = ", inits) if corner_plot: labels = ["EEP", "log10(Age [yr])", "[Fe/H]", "ln(Distance)", "Av", "ln(probability)"] inits.append("None") fig2 = corner.corner(gflatsamples, labels=labels, truths=inits); fig2.savefig("plots/{}_gyro_corner".format(starname)) plt.close() fig3 = corner.corner(iflatsamples, labels=labels, truths=inits); fig3.savefig("plots/{}_iso_corner".format(starname)) plt.close() print("Calculate sigma") sig = sigma(gresults.EEP_med.values, np.log10(gresults.age_med_gyr.values*1e9), gresults.feh_med.values, df.bp_dered-df.rp_dered) print("Sigma = ", sig) if age_plot: fig4 = cc.make_sample_comparison_plot(gflatsamples, iflatsamples, inits, sig) fig4.savefig("plots/{}_comparison_plot".format(starname)) plt.close() return gresults def get_successful_df(): """ Use glob to get a list of h5 filenames and return a dataframe containing only stars with samples. """ # Load file with info for all CKS stars ro = pd.read_csv("cks_gaia_mazeh.csv") # Load filenames of successful posteriors gyro_filenames = glob.glob("samples/*gyro.h5") iso_filenames = glob.glob("samples/*iso.h5") gyro_inds, iso_inds = [], [] for i in range(len(gyro_filenames)): ind = cc.get_index_from_filename(ro, gyro_filenames[i])[0] gyro_inds.append(ind) for i in range(len(iso_filenames)): ind = cc.get_index_from_filename(ro, iso_filenames[i])[0] iso_inds.append(ind) # Merge so you're only looking at stars where both gyro and iso ran. gyro_ro = ro.iloc[gyro_inds] iso_ro = ro.iloc[iso_inds] iso_df = pd.DataFrame(dict({"kepid": iso_ro.kepid.values})) df = pd.merge(gyro_ro, iso_df, on="kepid", how="inner") df.to_csv("success.csv") return df if __name__ == "__main__": # df = get_successful_df() df = pd.read_csv("success.csv") timespan = 300 ls_period, acf_period, pdm_period, period_err, kepid = \ make_period_plots_for_one_star(df.iloc[0], timespan) results = make_age_plots_for_one_star(df.iloc[0], df.Prot.values[0], df.e_Prot.values[0], corner_plot=False) results["ls_period"] = ls_period results["acf_period"] = acf_period results["pdm_period"] = pdm_period results["period_err"] = period_err results["kepid"] = kepid for i in range(1, len(df)): ls_period, acf_period, pdm_period, period_err, kepid = \ make_period_plots_for_one_star(df.iloc[i], timespan) new_results = make_age_plots_for_one_star(df.iloc[i], df.Prot.values[i], df.e_Prot.values[i], corner_plot=False) new_results["ls_period"] = ls_period new_results["acf_period"] = acf_period new_results["pdm_period"] = pdm_period new_results["period_err"] = period_err new_results["kepid"] = kepid results = pd.concat((results, new_results)) results.to_csv("results.csv")
ee8d95f9fcb603a7f03565c42e124ef6a2c0b4f2
[ "Markdown", "Python" ]
5
Markdown
RuthAngus/kepler_ages
23a184c91dbe6437412e3db7650b62972444e701
1d2142157342a298ec939e5af3740f750e37fca0
refs/heads/main
<file_sep>const call = () => console.log("hello") function dizHello(callback) { callback() } dizHello(call)<file_sep># Cine House by <NAME> <file_sep>console.log("tela de login")
55aad7cc5d4e77a1ca16e02676a93d7a21a163e9
[ "JavaScript", "Markdown" ]
3
JavaScript
iaMoreira/CineHouse
9ac262859a687038c095e5a2377fe2cc945b250d
fe4b936db9f771f20e517c608ca0e02061d245d4
refs/heads/master
<file_sep>// Copyright 2019-2020 go-gtp authors. All rights reserved. // Use of this source code is governed by a MIT-style license that can be // found in the LICENSE file. package ie import ( "encoding/binary" "io" ) // NewAggregateMaximumBitRate creates a new AggregateMaximumBitRate IE. func NewAggregateMaximumBitRate(up, down uint32) *IE { return newUint64ValIE(AggregateMaximumBitRate, (uint64(up)<<32 | uint64(down))) } // AggregateMaximumBitRateUp returns AggregateMaximumBitRate for Uplink // if the type of IE matches. func (i *IE) AggregateMaximumBitRateUp() (uint32, error) { if i.Type != AggregateMaximumBitRate { return 0, &InvalidTypeError{Type: i.Type} } if len(i.Payload) < 4 { return 0, io.ErrUnexpectedEOF } return binary.BigEndian.Uint32(i.Payload[0:4]), nil } // MustAggregateMaximumBitRateUp returns AggregateMaximumBitRateUp in uint32, ignoring errors. // This should only be used if it is assured to have the value. func (i *IE) MustAggregateMaximumBitRateUp() uint32 { v, _ := i.AggregateMaximumBitRateUp() return v } // AggregateMaximumBitRateDown returns AggregateMaximumBitRate for Downlink // if the type of IE matches. func (i *IE) AggregateMaximumBitRateDown() (uint32, error) { if i.Type != AggregateMaximumBitRate { return 0, &InvalidTypeError{Type: i.Type} } if len(i.Payload) < 8 { return 0, io.ErrUnexpectedEOF } return binary.BigEndian.Uint32(i.Payload[4:8]), nil } // MustAggregateMaximumBitRateDown returns AggregateMaximumBitRateDown in uint32, ignoring errors. // This should only be used if it is assured to have the value. func (i *IE) MustAggregateMaximumBitRateDown() uint32 { v, _ := i.AggregateMaximumBitRateDown() return v } <file_sep>// Copyright 2019-2020 go-gtp authors. All rights reserved. // Use of this source code is governed by a MIT-style license that can be // found in the LICENSE file. package ie import ( "encoding/binary" "io" "github.com/wmnsk/go-gtp/utils" ) // NewUserCSGInformation creates a new UserCSGInformation IE. func NewUserCSGInformation(mcc, mnc string, csgID uint32, mode, lcsg, cmi uint8) *IE { i := New(UserCSGInformation, 0x00, make([]byte, 8)) plmn, err := utils.EncodePLMN(mcc, mnc) if err != nil { return nil } copy(i.Payload[0:3], plmn) binary.BigEndian.PutUint32(i.Payload[3:7], csgID&0x7ffffff) i.Payload[7] = (mode << 6) | ((lcsg << 1) & 0x02) | (cmi & 0x01) return i } // AccessMode returns AccessMode in uint8 if the type of IE matches. func (i *IE) AccessMode() (uint8, error) { switch i.Type { case UserCSGInformation: if len(i.Payload) < 8 { return 0, io.ErrUnexpectedEOF } return i.Payload[7] >> 6, nil default: return 0, &InvalidTypeError{Type: i.Type} } } // MustAccessMode returns AccessMode in uint8, ignoring errors. // This should only be used if it is assured to have the value. func (i *IE) MustAccessMode() uint8 { v, _ := i.AccessMode() return v } <file_sep>// Copyright 2019-2020 go-gtp authors. All rights reserved. // Use of this source code is governed by a MIT-style license that can be // found in the LICENSE file. package ie /* // NewRANNASCause creates a new RANNASCause IE. // // The cause parameter is set to 0xff automatically if the proto is not ProtoTypeS1AP. func NewRANNASCause(proto, cause uint8, value uint64) *IE { i := New(RANNASCause, 0x00, nil) i.Payload[0] = proto switch proto { case ProtoTypeS1APCause: i.Payload[1] = cause case ProtoTypeEMMCause, ProtoTypeESMCause: i.Payload[1] = 0xff i.Payload[2:] case ProtoTypeDiameterCause: i.Payload[1] = 0xff i.Payload[2:] case ProtoTypeIKEv2Cause: i.Payload[1] = 0xff i.Payload[2:] default: i.Payload[1] = cause binary.BigEndian.PutUint64(i.Payload, value) } return i } */ <file_sep>// Copyright 2019-2020 go-gtp authors. All rights reserved. // Use of this source code is governed by a MIT-style license that can be // found in the LICENSE file. package ie import ( "encoding/binary" "io" "net" ) // NewS103PDNDataForwardingInfo creates a new S103PDNDataForwardingInfo IE. func NewS103PDNDataForwardingInfo(hsgwAddr string, greKey uint32, ebis ...uint8) *IE { addr := net.ParseIP(hsgwAddr) if addr == nil { return nil } // HSGW Address: IPv4 if v4 := addr.To4(); v4 != nil { i := New(S103PDNDataForwardingInfo, 0x00, make([]byte, 1+4+4+1+len(ebis))) i.Payload[0] = 4 copy(i.Payload[1:5], v4) binary.BigEndian.PutUint32(i.Payload[5:9], greKey) i.Payload[9] = uint8(len(ebis)) for n, e := range ebis { i.Payload[10+n] = e & 0x0f } return i } // HSGW Address: IPv6 i := New(S103PDNDataForwardingInfo, 0x00, make([]byte, 1+16+4+1+len(ebis))) i.Payload[0] = 16 copy(i.Payload[1:17], addr) binary.BigEndian.PutUint32(i.Payload[17:21], greKey) i.Payload[21] = uint8(len(ebis)) for n, e := range ebis { i.Payload[22+n] = e & 0x0f } return i } // HSGWAddress returns IP address of HSGW in string if the type of IE matches. func (i *IE) HSGWAddress() (string, error) { if i.Type != S103PDNDataForwardingInfo { return "", &InvalidTypeError{Type: i.Type} } return i.IPAddress() } // MustHSGWAddress returns HSGWAddress in string, ignoring errors. // This should only be used if it is assured to have the value. func (i *IE) MustHSGWAddress() string { v, _ := i.HSGWAddress() return v } // EBIs returns the EBIs in []uint8 if the type of IE matches. func (i *IE) EBIs() ([]uint8, error) { if i.Type != S103PDNDataForwardingInfo { return nil, &InvalidTypeError{Type: i.Type} } if len(i.Payload) == 0 { return nil, io.ErrUnexpectedEOF } var n, offset int switch i.Payload[0] { case 4: if len(i.Payload) < 9 { return nil, io.ErrUnexpectedEOF } n = int(i.Payload[9]) offset = 10 case 16: if len(i.Payload) < 21 { return nil, io.ErrUnexpectedEOF } n = int(i.Payload[21]) offset = 22 default: return nil, ErrMalformed } var ebis []uint8 for x := 0; x < n; x++ { if len(i.Payload) <= offset+x { break } ebis = append(ebis, i.Payload[offset+x]) } return ebis, nil } // MustEBIs returns EBIs in []uint8, ignoring errors. // This should only be used if it is assured to have the value. func (i *IE) MustEBIs() []uint8 { v, _ := i.EBIs() return v } <file_sep>// Copyright 2019-2020 go-gtp authors. All rights reserved. // Use of this source code is governed by a MIT-style license that can be // found in the LICENSE file. package ie import "io" // NewCause creates a new Cause IE. func NewCause(cause uint8, pce, bce, cs uint8, offendingIE *IE) *IE { i := New(Cause, 0x00, make([]byte, 2)) i.Payload[0] = cause i.Payload[1] = ((pce << 2) & 0x04) | ((bce << 1) & 0x02) | cs&0x01 if offendingIE != nil { i.Payload = append(i.Payload, offendingIE.Type) i.SetLength() } return i } // Cause returns Cause in uint8 if the type of IE matches. func (i *IE) Cause() (uint8, error) { if i.Type != Cause { return 0, &InvalidTypeError{Type: i.Type} } if len(i.Payload) == 0 { return 0, io.ErrUnexpectedEOF } return i.Payload[0], nil } // MustCause returns Cause in uint8, ignoring errors. // This should only be used if it is assured to have the value. func (i *IE) MustCause() uint8 { v, _ := i.Cause() return v } // IsRemoteCause returns IsRemoteCause in bool if the type of IE matches. func (i *IE) IsRemoteCause() bool { if i.Type != Cause { return false } if len(i.Payload) < 2 { return false } if i.Payload[1]>>2&0x01 == 1 { return true } return false } // IsBearerContextIEError returns IsBearerContextIEError in bool if the type of IE matches. func (i *IE) IsBearerContextIEError() bool { if i.Type != Cause { return false } if len(i.Payload) < 2 { return false } if i.Payload[1]>>1&0x01 == 1 { return true } return false } // IsPDNConnectionIEError returns IsPDNConnectionIEError in bool if the type of IE matches. func (i *IE) IsPDNConnectionIEError() bool { if i.Type != Cause { return false } if len(i.Payload) < 2 { return false } if i.Payload[1]&0x01 == 1 { return true } return false } <file_sep>// Copyright 2019-2020 go-gtp authors. All rights reserved. // Use of this source code is governed by a MIT-style license that can be // found in the LICENSE file. package ie import ( "io" "net" ) // NewIPAddress creates a new IPAddress IE from string. func NewIPAddress(addr string) *IE { ip := net.ParseIP(addr) v4 := ip.To4() // IPv4 if v4 != nil { return New(IPAddress, 0x00, v4) } //IPv6 return New(IPAddress, 0x00, ip) } // IPAddress returns IPAddress value if the type of IE matches. func (i *IE) IPAddress() (string, error) { if len(i.Payload) == 0 { return "", io.ErrUnexpectedEOF } switch i.Type { case IPAddress: return net.IP(i.Payload).String(), nil case PDNAddressAllocation: if len(i.Payload) < 5 { return "", io.ErrUnexpectedEOF } pdnType, err := i.PDNType() if err != nil { return "", err } switch pdnType { case 0x01: return net.IP(i.Payload[1:]).String(), nil case 0x02: return net.IP(i.Payload[2:]).String(), nil default: return "", ErrMalformed } case S103PDNDataForwardingInfo, S1UDataForwarding: switch i.Payload[0] { case 4: if len(i.Payload) < 5 { return "", io.ErrUnexpectedEOF } return net.IP(i.Payload[1:5]).String(), nil case 16: if len(i.Payload) < 17 { return "", io.ErrUnexpectedEOF } return net.IP(i.Payload[1:17]).String(), nil default: return "", ErrMalformed } case FullyQualifiedTEID: if i.HasIPv4() { if len(i.Payload) < 9 { return "", io.ErrUnexpectedEOF } return net.IP(i.Payload[5:9]).String(), nil } else if i.HasIPv6() { if len(i.Payload) < 21 { return "", io.ErrUnexpectedEOF } return net.IP(i.Payload[5:21]).String(), nil } else { return "", ErrMalformed } default: return "", &InvalidTypeError{Type: i.Type} } } // MustIPAddress returns IPAddress in string, ignoring errors. // This should only be used if it is assured to have the value. func (i *IE) MustIPAddress() string { v, _ := i.IPAddress() return v } <file_sep>// Copyright 2019-2020 go-gtp authors. All rights reserved. // Use of this source code is governed by a MIT-style license that can be // found in the LICENSE file. package ie import ( "io" "github.com/wmnsk/go-gtp/utils" ) // NewBearerQoS creates a new BearerQoS IE. func NewBearerQoS(pci, pl, pvi, qci uint8, umbr, dmbr, ugbr, dgbr uint64) *IE { i := New(BearerQoS, 0x00, make([]byte, 22)) i.Payload[0] |= (pci << 6 & 0x40) | (pl << 2 & 0x3c) | (pvi & 0x01) i.Payload[1] = qci copy(i.Payload[2:7], utils.Uint64To40(umbr)) copy(i.Payload[7:12], utils.Uint64To40(dmbr)) copy(i.Payload[12:17], utils.Uint64To40(ugbr)) copy(i.Payload[17:22], utils.Uint64To40(dgbr)) return i } // QCILabel returns QCILabel in uint8 if the type of IE matches. func (i *IE) QCILabel() (uint8, error) { switch i.Type { case BearerQoS: if len(i.Payload) < 2 { return 0, io.ErrUnexpectedEOF } return i.Payload[1], nil case FlowQoS: if len(i.Payload) < 1 { return 0, io.ErrUnexpectedEOF } return i.Payload[0], nil default: return 0, &InvalidTypeError{Type: i.Type} } } // MBRForUplink returns MBRForUplink in uint64 if the type of IE matches. func (i *IE) MBRForUplink() (uint64, error) { switch i.Type { case BearerQoS: if len(i.Payload) < 7 { return 0, io.ErrUnexpectedEOF } return utils.Uint40To64(i.Payload[2:7]), nil case FlowQoS: if len(i.Payload) < 6 { return 0, io.ErrUnexpectedEOF } return utils.Uint40To64(i.Payload[2:6]), nil default: return 0, io.ErrUnexpectedEOF } } // MustMBRForUplink returns MBRForUplink in uint64, ignoring errors. // This should only be used if it is assured to have the value. func (i *IE) MustMBRForUplink() uint64 { v, _ := i.MBRForUplink() return v } // MBRForDownlink returns MBRForDownlink in uint64 if the type of IE matches. func (i *IE) MBRForDownlink() (uint64, error) { switch i.Type { case BearerQoS: if len(i.Payload) < 12 { return 0, io.ErrUnexpectedEOF } return utils.Uint40To64(i.Payload[7:12]), nil case FlowQoS: if len(i.Payload) < 11 { return 0, io.ErrUnexpectedEOF } return utils.Uint40To64(i.Payload[6:11]), nil default: return 0, io.ErrUnexpectedEOF } } // MustMBRForDownlink returns MBRForDownlink in uint64, ignoring errors. // This should only be used if it is assured to have the value. func (i *IE) MustMBRForDownlink() uint64 { v, _ := i.MBRForDownlink() return v } // GBRForUplink returns GBRForUplink in uint64 if the type of IE matches. func (i *IE) GBRForUplink() (uint64, error) { switch i.Type { case BearerQoS: if len(i.Payload) < 17 { return 0, io.ErrUnexpectedEOF } return utils.Uint40To64(i.Payload[12:17]), nil case FlowQoS: if len(i.Payload) < 16 { return 0, io.ErrUnexpectedEOF } return utils.Uint40To64(i.Payload[11:16]), nil default: return 0, io.ErrUnexpectedEOF } } // MustGBRForUplink returns GBRForUplink in uint64, ignoring errors. // This should only be used if it is assured to have the value. func (i *IE) MustGBRForUplink() uint64 { v, _ := i.GBRForUplink() return v } // GBRForDownlink returns GBRForDownlink in uint64 if the type of IE matches. func (i *IE) GBRForDownlink() (uint64, error) { switch i.Type { case BearerQoS: if len(i.Payload) < 22 { return 0, io.ErrUnexpectedEOF } return utils.Uint40To64(i.Payload[17:22]), nil case FlowQoS: if len(i.Payload) < 21 { return 0, io.ErrUnexpectedEOF } return utils.Uint40To64(i.Payload[16:21]), nil default: return 0, io.ErrUnexpectedEOF } } // MustGBRForDownlink returns GBRForDownlink in uint64, ignoring errors. // This should only be used if it is assured to have the value. func (i *IE) MustGBRForDownlink() uint64 { v, _ := i.GBRForDownlink() return v } <file_sep>// Copyright 2019-2020 go-gtp authors. All rights reserved. // Use of this source code is governed by a MIT-style license that can be // found in the LICENSE file. package ie import ( "encoding/binary" "io" "github.com/wmnsk/go-gtp/utils" ) // NewGUTI creates a new GUTI IE. func NewGUTI(mcc, mnc string, groupID uint16, code uint8, mTMSI uint32) *IE { i := New(GUTI, 0x00, make([]byte, 10)) plmn, err := utils.EncodePLMN(mcc, mnc) if err != nil { return nil } copy(i.Payload[0:3], plmn) binary.BigEndian.PutUint16(i.Payload[3:5], groupID) i.Payload[5] = code binary.BigEndian.PutUint32(i.Payload[6:10], mTMSI) return i } // MMEGroupID returns MMEGroupID in uint16 if the type of IE matches. func (i *IE) MMEGroupID() (uint16, error) { switch i.Type { case GUTI: if len(i.Payload) < 5 { return 0, io.ErrUnexpectedEOF } return binary.BigEndian.Uint16(i.Payload[3:5]), nil default: return 0, &InvalidTypeError{Type: i.Type} } } // MustMMEGroupID returns MMEGroupID in uint16, ignoring errors. // This should only be used if it is assured to have the value. func (i *IE) MustMMEGroupID() uint16 { v, _ := i.MMEGroupID() return v } // MMECode returns MMECode in uint8 if the type of IE matches. func (i *IE) MMECode() (uint8, error) { switch i.Type { case GUTI: if len(i.Payload) < 6 { return 0, io.ErrUnexpectedEOF } return i.Payload[5], nil default: return 0, &InvalidTypeError{Type: i.Type} } } // MustMMECode returns MMECode in uint8, ignoring errors. // This should only be used if it is assured to have the value. func (i *IE) MustMMECode() uint8 { v, _ := i.MMECode() return v } // MTMSI returns MTMSI in uint32 if the type of IE matches. func (i *IE) MTMSI() (uint32, error) { switch i.Type { case GUTI: if len(i.Payload) < 10 { return 0, io.ErrUnexpectedEOF } return binary.BigEndian.Uint32(i.Payload[6:10]), nil default: return 0, &InvalidTypeError{Type: i.Type} } } // MustMTMSI returns MTMSI in uint32, ignoring errors. // This should only be used if it is assured to have the value. func (i *IE) MustMTMSI() uint32 { v, _ := i.MTMSI() return v } <file_sep>// Copyright 2019-2020 go-gtp authors. All rights reserved. // Use of this source code is governed by a MIT-style license that can be // found in the LICENSE file. package ie import ( "strconv" ) // TODO: add getter/setters // TODO: consider using struct // NewIndication creates a new Indication IE. // Note that each parameters should be 0 if false and 1 if true. Otherwise, // the value won't be set as expected in the bitwise operations. func NewIndication( daf, dtf, hi, dfi, oi, isrsi, israi, sgwci, sqci, uimsi, cfsi, crsi, ps, pt, si, msv, retLoc, pbic, srni, s6af, s4af, mbmdt, israu, ccrsi, cprai, arrl, ppoff, ppon, ppsi, csfbi, clii, cpsr, nsi, uasi, dtci, bdwi, psci, pcri, aosi, aopi, roaai, epcosi, cpopci, pmtmsi, s11tf, pnsi, unaccsi, wpmsi, eevrsi, ltemui, ltempi, enbcrsi, tspcmi uint8, ) *IE { i := New(Indication, 0x00, make([]byte, 7)) i.Payload[0] |= sgwci i.Payload[0] |= (israi << 1) i.Payload[0] |= (isrsi << 2) i.Payload[0] |= (oi << 3) i.Payload[0] |= (dfi << 4) i.Payload[0] |= (hi << 5) i.Payload[0] |= (dtf << 6) i.Payload[0] |= (daf << 7) i.Payload[1] |= msv i.Payload[1] |= (si << 1) i.Payload[1] |= (pt << 2) i.Payload[1] |= (ps << 3) i.Payload[1] |= (crsi << 4) i.Payload[1] |= (cfsi << 5) i.Payload[1] |= (uimsi << 6) i.Payload[1] |= (sqci << 7) i.Payload[2] |= ccrsi i.Payload[2] |= (israu << 1) i.Payload[2] |= (mbmdt << 2) i.Payload[2] |= (s4af << 3) i.Payload[2] |= (s6af << 4) i.Payload[2] |= (srni << 5) i.Payload[2] |= (pbic << 6) i.Payload[2] |= (retLoc << 7) i.Payload[3] |= cpsr i.Payload[3] |= (clii << 1) i.Payload[3] |= (csfbi << 2) i.Payload[3] |= (ppsi << 3) i.Payload[3] |= (ppon << 4) i.Payload[3] |= (ppoff << 5) i.Payload[3] |= (arrl << 6) i.Payload[3] |= (cprai << 7) i.Payload[4] |= aopi i.Payload[4] |= (aosi << 1) i.Payload[4] |= (pcri << 2) i.Payload[4] |= (psci << 3) i.Payload[4] |= (bdwi << 4) i.Payload[4] |= (dtci << 5) i.Payload[4] |= (uasi << 6) i.Payload[4] |= (nsi << 7) i.Payload[5] |= wpmsi i.Payload[5] |= (unaccsi << 1) i.Payload[5] |= (pnsi << 2) i.Payload[5] |= (s11tf << 3) i.Payload[5] |= (pmtmsi << 4) i.Payload[5] |= (cpopci << 5) i.Payload[5] |= (epcosi << 6) i.Payload[5] |= (roaai << 7) i.Payload[6] |= (tspcmi << 3) i.Payload[6] |= (enbcrsi << 4) i.Payload[6] |= (ltempi << 5) i.Payload[6] |= (ltemui << 6) i.Payload[6] |= (eevrsi << 7) return i } // NewIndicationFromBitSequence creates a new Indication IE from string-formatted // sequence of bits. The sequence should look the same as Wireshark appearance. // The input is to be like "10100001000010000001010100010000100010001000000101000". func NewIndicationFromBitSequence(bitSequence string) *IE { if len(bitSequence) != 53 { return nil } ie := New(Indication, 0x00, make([]byte, 7)) for i, r := range bitSequence { bit, err := strconv.Atoi(string(r)) if err != nil { return nil } if bit > 1 { bit = 1 } // index: // 0 =< i < 8 : set bits in first octet // 8 =< i < 16: set bits in second octet ... // bit shift: // 0 =< i < 8 : shift i to left // 8 =< i < 16: shift i - 8 to left ... ie.Payload[i/8] |= uint8(bit << uint8(8*(i/8+1)-i-1)) } return ie } // NewIndicationFromOctets creates a new IndicationFromOctets IE from the set of octets. func NewIndicationFromOctets(octs ...uint8) *IE { ie := New(Indication, 0x00, make([]byte, 0)) for i, o := range octs { if i >= 7 { break } ie.Payload = append(ie.Payload, o) } ie.SetLength() return ie } <file_sep>// Copyright 2019-2020 go-gtp authors. All rights reserved. // Use of this source code is governed by a MIT-style license that can be // found in the LICENSE file. package ie import ( "encoding/binary" "net" ) // NewS1UDataForwarding creates a new S1UDataForwarding IE. func NewS1UDataForwarding(sgwAddr string, sgwTEID uint32) *IE { addr := net.ParseIP(sgwAddr) if addr == nil { return nil } // SGW Address: IPv4 if v4 := addr.To4(); v4 != nil { i := New(S1UDataForwarding, 0x00, make([]byte, 1+4+4)) i.Payload[0] = 4 copy(i.Payload[1:5], v4) binary.BigEndian.PutUint32(i.Payload[5:9], sgwTEID) return i } // SGW Address: IPv6 i := New(S1UDataForwarding, 0x00, make([]byte, 1+16+4)) i.Payload[0] = 16 copy(i.Payload[1:17], addr) binary.BigEndian.PutUint32(i.Payload[17:21], sgwTEID) return i } // SGWAddress returns IP address of SGW in string if the type of IE matches. func (i *IE) SGWAddress() (string, error) { if i.Type != S1UDataForwarding { return "", &InvalidTypeError{Type: i.Type} } return i.IPAddress() } // MustSGWAddress returns SGWAddress in string, ignoring errors. // This should only be used if it is assured to have the value. func (i *IE) MustSGWAddress() string { v, _ := i.SGWAddress() return v } <file_sep>// Copyright 2019-2020 go-gtp authors. All rights reserved. // Use of this source code is governed by a MIT-style license that can be // found in the LICENSE file. package ie import ( "encoding/binary" "io" "net" ) // NewFullyQualifiedTEID creates a new FullyQualifiedTEID IE. func NewFullyQualifiedTEID(ifType uint8, teid uint32, v4, v6 string) *IE { i := New(FullyQualifiedTEID, 0x00, make([]byte, 5)) i.Payload[0] = ifType binary.BigEndian.PutUint32(i.Payload[1:5], teid) if v4addr := net.ParseIP(v4); v4addr != nil { i.Payload[0] |= 0x80 i.Payload = append(i.Payload, []byte(v4addr.To4())...) } if v6addr := net.ParseIP(v6); v6addr != nil { i.Payload[0] |= 0x40 i.Payload = append(i.Payload, []byte(v6addr.To16())...) } i.SetLength() return i } // HasIPv4 reports whether the IE has IPv4 address in its payload or not. func (i *IE) HasIPv4() bool { if i.Type != FullyQualifiedTEID { return false } if len(i.Payload) == 0 { return false } return i.Payload[0]&0x80>>7 == 1 } // HasIPv6 reports whether the IE has IPv6 address in its payload or not. func (i *IE) HasIPv6() bool { if i.Type != FullyQualifiedTEID { return false } if len(i.Payload) == 0 { return false } return i.Payload[0]&0x48>>6 == 1 } // InterfaceType returns InterfaceType in uint8 if the type of IE matches. func (i *IE) InterfaceType() (uint8, error) { if i.Type != FullyQualifiedTEID { return 0, &InvalidTypeError{Type: i.Type} } if len(i.Payload) == 0 { return 0, io.ErrUnexpectedEOF } return i.Payload[0] & 0x3f, nil } // MustInterfaceType returns InterfaceType in uint8, ignoring errors. // This should only be used if it is assured to have the value. func (i *IE) MustInterfaceType() uint8 { v, _ := i.InterfaceType() return v } // GREKey returns GREKey in uint32 if the type of IE matches. func (i *IE) GREKey() (uint32, error) { if len(i.Payload) < 6 { return 0, io.ErrUnexpectedEOF } switch i.Type { case FullyQualifiedTEID: return binary.BigEndian.Uint32(i.Payload[1:5]), nil case S103PDNDataForwardingInfo: switch i.Payload[0] { case 4: if len(i.Payload) < 9 { return 0, io.ErrUnexpectedEOF } return binary.BigEndian.Uint32(i.Payload[5:9]), nil case 16: if len(i.Payload) < 21 { return 0, io.ErrUnexpectedEOF } return binary.BigEndian.Uint32(i.Payload[17:21]), nil default: return 0, ErrMalformed } default: return 0, &InvalidTypeError{Type: i.Type} } } // MustGREKey returns GREKey in uint32, ignoring errors. // This should only be used if it is assured to have the value. func (i *IE) MustGREKey() uint32 { v, _ := i.GREKey() return v } // TEID returns TEID in uint32 if the type of IE matches. func (i *IE) TEID() (uint32, error) { if len(i.Payload) < 5 { return 0, io.ErrUnexpectedEOF } switch i.Type { case FullyQualifiedTEID: return binary.BigEndian.Uint32(i.Payload[1:5]), nil case S1UDataForwarding: switch i.Payload[0] { case 4: if len(i.Payload) < 9 { return 0, io.ErrUnexpectedEOF } return binary.BigEndian.Uint32(i.Payload[5:9]), nil case 16: if len(i.Payload) < 21 { return 0, io.ErrUnexpectedEOF } return binary.BigEndian.Uint32(i.Payload[17:21]), nil default: return 0, ErrMalformed } default: return 0, &InvalidTypeError{Type: i.Type} } } // MustTEID returns TEID in uint32, ignoring errors. // This should only be used if it is assured to have the value. func (i *IE) MustTEID() uint32 { v, _ := i.TEID() return v } <file_sep>// Copyright 2019-2020 go-gtp authors. All rights reserved. // Use of this source code is governed by a MIT-style license that can be // found in the LICENSE file. package ie import "io" // NewAllocationRetensionPriority creates a new AllocationRetensionPriority IE. func NewAllocationRetensionPriority(pci, pl, pvi uint8) *IE { i := New(AllocationRetensionPriority, 0x00, make([]byte, 1)) i.Payload[0] |= (pci << 6 & 0x40) | (pl << 2 & 0x3c) | (pvi & 0x01) return i } // PreemptionCapability reports whether the preemption capability is set to enabled if the type of IE matches. func (i *IE) PreemptionCapability() bool { if len(i.Payload) == 0 { return false } switch i.Type { case AllocationRetensionPriority, BearerQoS: return (i.Payload[0] & 0x40) != 1 default: return false } } // PriorityLevel returns PriorityLevel in uint8 if the type of IE matches. func (i *IE) PriorityLevel() (uint8, error) { if len(i.Payload) == 0 { return 0, io.ErrUnexpectedEOF } switch i.Type { case AllocationRetensionPriority, BearerQoS: return (i.Payload[0] & 0x3c) >> 2, nil default: return 0, &InvalidTypeError{Type: i.Type} } } // PreemptionVulnerability reports whether the preemption vulnerability is set to enabled if the type of IE matches. func (i *IE) PreemptionVulnerability() bool { if len(i.Payload) == 0 { return false } switch i.Type { case AllocationRetensionPriority, BearerQoS: return (i.Payload[0] & 0x01) != 1 default: return false } } <file_sep>// Copyright 2019-2020 go-gtp authors. All rights reserved. // Use of this source code is governed by a MIT-style license that can be // found in the LICENSE file. package ie import "io" // NewFullyQualifiedDomainName creates a new FullyQualifiedDomainName IE. func NewFullyQualifiedDomainName(fqdn string) *IE { return newStringIE(FullyQualifiedDomainName, fqdn) } // FullyQualifiedDomainName returns FullyQualifiedDomainName in string if the type of IE matches. func (i *IE) FullyQualifiedDomainName() (string, error) { if i.Type != FullyQualifiedDomainName { return "", &InvalidTypeError{Type: i.Type} } if len(i.Payload) == 0 { return "", io.ErrUnexpectedEOF } return string(i.Payload), nil } // MustFullyQualifiedDomainName returns FullyQualifiedDomainName in string, ignoring errors. // This should only be used if it is assured to have the value. func (i *IE) MustFullyQualifiedDomainName() string { v, _ := i.FullyQualifiedDomainName() return v } <file_sep>// Copyright 2019-2020 go-gtp authors. All rights reserved. // Use of this source code is governed by a MIT-style license that can be // found in the LICENSE file. package ie import "net" // PDN Type definitions. const ( _ uint8 = iota pdnTypeIPv4 pdnTypeIPv6 pdnTypeIPv4v6 pdnTypeNonIP ) // NewPDNAddressAllocation creates a new PDNAddressAllocation IE. // // The PDN Type field is automatically judged by the format of given addr, // If it cannot be converted as neither IPv4 nor IPv6, PDN Type will be Non-IP. func NewPDNAddressAllocation(addr string) *IE { ip := net.ParseIP(addr) v4 := ip.To4() // IPv4 if v4 != nil { i := New(PDNAddressAllocation, 0x00, make([]byte, 5)) i.Payload[0] = pdnTypeIPv4 copy(i.Payload[1:], v4) return i } // IPv6 // XXX - prefix value should be handled properly. if ip != nil { i := New(PDNAddressAllocation, 0x00, make([]byte, 18)) i.Payload[0] = pdnTypeIPv6 i.Payload[1] = 0x00 copy(i.Payload[2:], ip) return i } // Non-IP return New(PDNAddressAllocation, 0x00, []byte{pdnTypeNonIP}) } // NewPDNAddressAllocationDual creates a new PDNAddressAllocation IE with // IPv4 address and IPv6 address given. // // If they cannot be converted as IPv4/IPv6, PDN Type will be Non-IP. func NewPDNAddressAllocationDual(v4addr, v6addr string) *IE { v4 := net.ParseIP(v4addr).To4() if v4 == nil { return New(PDNAddressAllocation, 0x00, []byte{pdnTypeNonIP}) } v6 := net.ParseIP(v6addr).To16() if v6 == nil { return New(PDNAddressAllocation, 0x00, []byte{pdnTypeNonIP}) } i := New(PDNAddressAllocation, 0x00, make([]byte, 23)) i.Payload[0] = pdnTypeIPv4v6 copy(i.Payload[1:5], v4) i.Payload[5] = 0x00 copy(i.Payload[6:], v6) return i } <file_sep>// Copyright 2019-2020 go-gtp authors. All rights reserved. // Use of this source code is governed by a MIT-style license that can be // found in the LICENSE file. package ie import ( "github.com/wmnsk/go-gtp/utils" ) // NewFlowQoS creates a new FlowQoS IE. func NewFlowQoS(qci uint8, umbr, dmbr, ugbr, dgbr uint64) *IE { i := New(FlowQoS, 0x00, make([]byte, 21)) i.Payload[0] = qci copy(i.Payload[1:6], utils.Uint64To40(umbr)) copy(i.Payload[6:11], utils.Uint64To40(dmbr)) copy(i.Payload[11:16], utils.Uint64To40(ugbr)) copy(i.Payload[16:21], utils.Uint64To40(dgbr)) return i }
f92b18dbbd1fa1d6c265ad06b21abc3a335203c3
[ "Go" ]
15
Go
thakurajayL/go-gtp
08234c2a26e59fa0850793d1de5b5841b0f26f99
a918335ecbb71130cf5ea97c66801736ee737415
refs/heads/master
<repo_name>Austin-Tan/CoolCardGamesBot<file_sep>/Program.cs using Discord; using Discord.Rest; using Discord.WebSocket; using DiscordBot.Games; using System; using System.Collections.Generic; using System.Threading.Tasks; namespace DiscordBot { public enum DiscardGames { NoThanks, IncanGold, NOTFOUND } class Program { public static void Main(string[] args) => new Program().MainAsync().GetAwaiter().GetResult(); private DiscordSocketClient _client; // Dictionary mapping IDs to active channels public Dictionary<ulong, ChannelHandler> activeChannels; public async Task MainAsync() { DiscordSocketConfig config = new DiscordSocketConfig { MessageCacheSize = 64, GuildSubscriptions = false }; // When Discord.Net.WebSocket receives a stable update to include GatewayIntents, add here // and unsub from typing, etc. instead of guildsubscriptions _client = new DiscordSocketClient(config); _client.MessageReceived += MessageHandler; _client.ReactionAdded += ReactionAdder; _client.ReactionRemoved += ReactionRemover; _client.Log += Log; // Copy-Paste your token in Environment Variables under User. // Can select System-wide Env Variables instead of User, just change the 2nd Param for targeting. var token = Environment.GetEnvironmentVariable("DISCORD_TOKEN", EnvironmentVariableTarget.User); activeChannels = new Dictionary<ulong, ChannelHandler>(); await _client.LoginAsync(TokenType.Bot, token); await _client.StartAsync(); await _client.SetStatusAsync(UserStatus.Online); await _client.SetActivityAsync(new Game("!help", ActivityType.Listening, ActivityProperties.Spectate, "details??")); // Block this task until the program is closed. await Task.Delay(-1); } private Task Log(LogMessage message) { Console.WriteLine($"[General/{message.Severity}] {message}"); return Task.CompletedTask; } private ChannelHandler GetChannelHandler(ISocketMessageChannel channel) { // check that we're in a server text channel if (channel.GetType() != typeof(SocketTextChannel)) { channel.SendMessageAsync( "Sorry, **Discard Games Bot** is not available for" + "channels of type " + channel.GetType()); return null; } ulong id = channel.Id; if (!activeChannels.ContainsKey(id)) { activeChannels.Add(id, new ChannelHandler(channel)); } return activeChannels[id]; } private Task ReactionRouter(ISocketMessageChannel channel, SocketReaction reaction, bool adding) { // this is a reaction we added ourselves. Ignore it. if (reaction.UserId == _client.CurrentUser.Id) { return Task.CompletedTask; } ChannelHandler handler = GetChannelHandler(channel); if (handler != null) { handler.ProcessReaction(reaction.MessageId, reaction.Emote.Name, reaction.UserId, adding); } return Task.CompletedTask; } private Task ReactionAdder(Cacheable<IUserMessage, ulong> cache, ISocketMessageChannel channel, SocketReaction reaction) { return ReactionRouter(channel, reaction, true); } private Task ReactionRemover(Cacheable<IUserMessage, ulong> cache, ISocketMessageChannel channel, SocketReaction reaction) { return ReactionRouter(channel, reaction, false); } private Task MessageHandler(SocketMessage message) { if (!message.Content.StartsWith('!')) { return Task.CompletedTask; } if (message.Author.IsBot) { return Task.CompletedTask; } string command = message.Content.Substring(1).ToLower().Trim(); if (command.StartsWith("test")) { // any test things do here } else if (command.StartsWith("help")) { message.Channel.SendMessageAsync(null, false, HelpMessage()); } else if (command.StartsWith("bugsnax")) { SendBugsnax(message); } else { ChannelHandler handler = GetChannelHandler(message.Channel); if (handler != null) { handler.ProcessMessage(message, command); } } return Task.CompletedTask; } private Embed HelpMessage() { EmbedBuilder builder = new EmbedBuilder { Title = "HELP - Discard Bot", Description = "List of commands:", }; builder.WithAuthor(_client.CurrentUser) .AddField("!help", "gives you this messsage!") .AddField("!play GameName", "WIP. Hopefully starts a game of GameName for you.") .AddField("List of games for !play:", "***No Thanks!***, ***Incan Gold***") .AddField("!rules", "NOT IMPLEMENTED") .AddField("!status", "NOTIMPLEMENTED") .WithColor(Color.Orange); return builder.Build(); } private void SendBugsnax(SocketMessage message) { message.Channel.SendMessageAsync("it's bugsnax, " + message.Author.Mention); message.AddReactionAsync(new Emoji("\U0001f495")); Task<RestUserMessage> sent = message.Channel.SendFileAsync("bugsnax.jpg"); sent.Result.AddReactionsAsync(new IEmote[] { new Emoji("🇧"), new Emoji("🇺"), new Emoji("🇬") }); } public static DiscardGames FindGameFromString(string toFind) { toFind = toFind.Replace(" ", string.Empty); if (toFind == "nothanks" || toFind == "nothanks!") { return DiscardGames.NoThanks; } else if (toFind == "incangold") { return DiscardGames.IncanGold; } return DiscardGames.NOTFOUND; } } } <file_sep>/Games/IncanGold.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Discord; using Discord.Rest; namespace DiscordBot.Games { public class IncanGoldGame : GameInterface { public int MinPlayers { get => 2; } public int MaxPlayers { get => 8; } public string Name { get => "<NAME>"; } public string ImageURL { get => "https://images-na.ssl-images-amazon.com/images/I/71tVfX5NoBL._AC_SL1166_.jpg"; } public IncanGoldGame(ChannelHandler handler) { parentChannel = handler; } public Embed Blurb() { EmbedBuilder builder = new EmbedBuilder { Title = "Incan Gold", Description = "***Incan Gold*** (also released as *Diamant*) is a game for 2-8 players designed by <NAME> and <NAME>," + "published in 2005 in Germany by <NAME>." }; builder.WithImageUrl(ImageURL) .AddField("Playtime", "Twenty minutes.") .AddField("Overview", "Players are adventurers hoarding treasure in an ancient temple. On every turn, " + "you choose to either:\n" + "1) Descend one card deeper into the temple, sharing any gems earned, but risk" + " flipping a hazardous card and losing every gem nabbed this round.\n" + "2) Safely exit the temple, banking every gem earned this round but sitting out til the next one.\n" + "The **GOAL of the game** is to amass the most gems over five rounds!"); return builder.Build(); } private ChannelHandler parentChannel; private Player[] players; private int numPlayers; private List<Card> deck; private List<Card> revealedCards; private int round = 0; private Player[] remainingPlayers; private HashSet<HazardType> trippedHazards; private RestUserMessage roundMessage; private RestUserMessage reactMessage; public void StartGame() { // Add Players numPlayers = parentChannel.players.Count; players = new Player[numPlayers]; KeyValuePair<ulong, IUser>[] importPlayers = parentChannel.players.ToArray(); idToPlayer = new Dictionary<ulong, Player>(); for (int i = 0; i < numPlayers; i ++) { players[i] = new Player( importPlayers[i].Value.Username, importPlayers[i].Key); idToPlayer.Add(players[i].id, players[i]); } // prepare deck StartingDeck(); NewRound(); } public async void NewRound() { if (round != 5) { if (round != 0) { foreach (Card card in revealedCards) { if (card.type == CardType.Hazard) { deck.Add(card); } else if (card.type == CardType.Treasure) { card.remainder = 0; deck.Add(card); } } } round++; deck.Add(new Card(CardType.Relic)); ShuffleDeck(); foreach (Player player in players) { player.heldGems = 0; } remainingPlayers = players; trippedHazards = new HashSet<HazardType>(); revealedCards = new List<Card>(); roundMessage = await parentChannel.channel.SendMessageAsync(null, false, PrettyPrint()); DrawCard(true); } else { EndGame(); } } public Embed PrettyPrint() { EmbedBuilder builder = new EmbedBuilder { Title = "Round " + round }; remainingPlayers.Select<Player, string>(o => o.username); string explorers = remainingPlayers[0].username + ((remainingPlayers[0].heldGems == 0) ? "" : $" ({remainingPlayers[0].heldGems})"); for (int i = 1; i < remainingPlayers.Length; i++) { explorers += $"\n{remainingPlayers[i].username}"; if (remainingPlayers[i].heldGems > 0) { explorers += $" ({remainingPlayers[i].heldGems})"; } } string revealed = "🚪"; for (int i = 0; i < revealedCards.Count(); i++ ) { revealed += " --- " + PrintCard(revealedCards[i]); } builder.AddField("Explorers still in the temple", explorers) .AddField("Revealed cards and leftover gems", revealed); return builder.Build(); } private string PrintCard(Card card, bool drawn = false) { switch (card.type) { case CardType.Treasure: int value = drawn ? card.value : card.remainder; return $"[{value}💎]"; case CardType.Hazard: if (drawn) { return $"[{card.hazardType} {hazardEmoji(card.hazardType)}]"; } else { return $"[{hazardEmoji(card.hazardType)}]"; } case CardType.Relic: if (drawn) { return $"[RELIC 💎🌞💎]"; } else { return $"[💎🌞💎]"; } } return ""; } private string hazardEmoji(HazardType type) { if (type == HazardType.Chungus) { return "🐰"; } else if (type == HazardType.Mummy) { return "🧟"; } else if (type == HazardType.Spiders) { return "🕸️"; } else if (type == HazardType.Snakes) { return "🐍"; } else if (type == HazardType.Quake) { return "💥"; } return "didn't find right hazard this is broken you should not see this message"; } private Dictionary<ulong, Player> idToPlayer; private Dictionary<ulong, bool> idToAction; public async void DrawCard(bool roundStart = false) { Card drawn = deck[0]; deck.RemoveAt(0); bool killed = false; switch (drawn.type) { case CardType.Treasure: drawn.remainder = drawn.value % remainingPlayers.Count(); foreach (Player player in remainingPlayers) { player.heldGems += drawn.value / remainingPlayers.Count(); } break; case CardType.Hazard: if (trippedHazards.Contains(drawn.hazardType)) { await parentChannel.channel.SendMessageAsync("Uh oh fucky wucky we hit two " + hazardEmoji(drawn.hazardType)); killed = true; } else { trippedHazards.Add(drawn.hazardType); } break; case CardType.Relic: break; } revealedCards.Add(drawn); string drawMessage = "Just drawn: " + PrintCard(drawn, true); if (killed) { await reactMessage.ModifyAsync(m => m.Content = drawMessage + "\n" + string.Join<string>(", ", remainingPlayers.Select<Player, string>(o => o.username)) + " all lose their banked gems!"); parentChannel.messages.Remove(reactMessage.Id); revealedCards.RemoveAt(revealedCards.Count - 1); NewRound(); } else { if (roundStart) { reactMessage = await parentChannel.channel.SendMessageAsync(drawMessage + "\n⛺ to go home and bank your gems. 🤠 to continue delving."); parentChannel.messages.Add(reactMessage.Id, DelveMessage); } else { await reactMessage.ModifyAsync(m => m.Content = drawMessage + "\n⛺ to go home and bank your gems. 🤠 to continue delving."); } idToAction = new Dictionary<ulong, bool>(); await roundMessage.ModifyAsync(m => m.Embed = PrettyPrint()); await reactMessage.RemoveAllReactionsAsync(); await reactMessage.AddReactionsAsync(new IEmote[] { new Emoji("⛺"), new Emoji("🤠") }); } } private void EndTurn() { List<Player> newRemaining = new List<Player>(); List<Player> goingHome = new List<Player>(); foreach(Player player in remainingPlayers) { if (idToAction.ContainsKey(player.id) && idToAction[player.id]) { // player remains! newRemaining.Add(player); } else { player.bankedGems += player.heldGems; player.heldGems = 0; goingHome.Add(player); } } foreach (Card card in revealedCards) { if (goingHome.Count > 0) { if (card.type == CardType.Treasure) { foreach (Player player in goingHome) { player.bankedGems += card.remainder / goingHome.Count(); } card.remainder = card.remainder % goingHome.Count(); } else if (card.type == CardType.Relic) { if (goingHome.Count() == 1) { card.type = CardType.Treasure; card.value = 0; card.remainder = 0; goingHome.First().bankedGems += relicValue(); } } } } remainingPlayers = newRemaining.ToArray(); if (remainingPlayers.Length == 0) { NewRound(); } else { DrawCard(); } } public int relicsGotten = 0; public int relicValue() { relicsGotten++; return (relicsGotten < 4) ? 5 : 10; } bool secretTimerOn = false; bool realTimerOn = false; private void BackgroundLoop() { int realCounter = 10; while (true) { Thread.Sleep(1000); realCounter--; if (realTimerOn) { if (realCounter > 3) { realCounter = 3; } } if (realCounter > 0 && realCounter <= 5) { reactMessage.ModifyAsync(m => m.Content += $" {realCounter}..."); } else if (realCounter == 0) { EndTurn(); break; } } realTimerOn = false; secretTimerOn = false; } private void DelveMessage(ulong messageId, string emote, ulong userId, bool adding) { if (idToPlayer.ContainsKey(userId) && remainingPlayers.Contains<Player>(idToPlayer[userId])) { if (emote == "⛺" || emote == "🤠") { if (adding) { if (idToAction.Remove(userId)) { reactMessage.RemoveReactionAsync(new Emoji((emote == "🤠") ? "⛺": "🤠"), userId); } idToAction.Add(userId, emote == "🤠"); if (remainingPlayers.Count() == 1) { EndTurn(); } else if (idToAction.Count == remainingPlayers.Count()) { realTimerOn = true; } else if (!secretTimerOn) { secretTimerOn = true; Task bar = new Task(BackgroundLoop); bar.Start(); } } else { idToAction.Remove(userId); } } } } public readonly int[] gemsDistribution = { 1, 2, 3, 4, 5, 5, 7, 7, 9, 11, 11, 13, 14, 15, 17 }; public void StartingDeck() { deck = new List<Card>(); for (int i = 0; i < 3; i ++) { deck.Add(new Card(CardType.Hazard, HazardType.Snakes)); deck.Add(new Card(CardType.Hazard, HazardType.Quake)); deck.Add(new Card(CardType.Hazard, HazardType.Mummy)); deck.Add(new Card(CardType.Hazard, HazardType.Spiders)); deck.Add(new Card(CardType.Hazard, HazardType.Chungus)); } foreach (int value in gemsDistribution) { deck.Add(new Card(CardType.Treasure, value)); } ShuffleDeck(); } private Random random = new Random(); public void ShuffleDeck() { int n = deck.Count; while (n > 1) { n--; int k = random.Next(n + 1); Card value = deck[k]; deck[k] = deck[n]; deck[n] = value; } } public void EndGame() { foreach (Player player in players) { player.bankedGems += player.heldGems; player.heldGems = 0; } IEnumerable<Player> query = players.OrderBy(player => -1 * player.bankedGems); EmbedBuilder bd = new EmbedBuilder(); bd.Title = $"Game Over - {query.First().username} wins!"; string scoreboard = ""; for (int i = 1; i <= query.Count(); i++) { scoreboard += $"\n{i}. {query.ElementAt(i - 1).username}: **{query.ElementAt(i - 1).bankedGems}** gems!"; } bd.AddField("Scoreboard", scoreboard); parentChannel.channel.SendMessageAsync(null, false, bd.Build()); parentChannel.EndGame(true); } public enum CardType { Hazard, Treasure, Relic } public enum HazardType { Snakes, Quake, Mummy, Spiders, Chungus } private class Player { // discord name public string username; // discord unique ID public ulong id; public bool inTemple; public int bankedGems; public int heldGems; public Player(string username, ulong id) { this.username = username; this.id = id; inTemple = false; bankedGems = 0; heldGems = 0; } public override string ToString() { return $"{username}: {heldGems} {bankedGems}"; } } private class Card { public CardType type; public int value; public int remainder; public HazardType hazardType; // only used with relics pretty much public Card(CardType type) { this.type = type; } // ctor for treasure cards public Card(CardType type, int value) { this.type = type; this.value = value; } // ctor for hazard cards public Card(CardType type, HazardType hazardType) { this.type = type; this.hazardType = hazardType; } } } } <file_sep>/GameInterface.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Discord; namespace DiscordBot { interface GameInterface { public int MinPlayers { get; } public int MaxPlayers { get; } public string Name { get; } public string ImageURL { get; } public Embed Blurb(); public void StartGame(); public void EndGame(); } } <file_sep>/Games/NoThanks.cs using Discord; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading.Tasks; namespace DiscordBot.Games { public class NoThanksGame : GameInterface { public int MinPlayers { get => 3; } public int MaxPlayers { get => 7; } public string Name { get => "No Thanks!"; } public string ImageURL { get => "https://crystal-cdn3.crystalcommerce.com/photos/5202483/pic2602161_md.jpg"; } private ChannelHandler parentChannel; public NoThanksGame(ChannelHandler handler) { parentChannel = handler; } public Embed Blurb() { EmbedBuilder builder = new EmbedBuilder { Title = "No Thanks!", Description = "***No Thanks!*** is a card game for three to seven players designed by <NAME>." }; builder.WithImageUrl(ImageURL) .AddField("Playtime", "Twenty minutes.") .AddField("Overview", "A deck of cards numbered 3 to 35 is shuffled with nine removed at random. " + "You are given a number of chips, each worth negative one point. " + "Every turn, you are presented with a card from the deck and have to either:\n" + "1) Sacrifice a chip to pass the card to the next player.\n" + "2) Take the card and add its value to your total score. You keep any chips on the card for later use.\n" + "The **GOAL of the game** is to have the fewest points, so minimize taking cards and maximize your number of chips!"); return builder.Build(); } public void StartGame() { // Add players // prepare deck // queue or array of players } public void EndGame() { parentChannel.EndGame(true); } } } <file_sep>/ChannelHandler.cs using Discord; using Discord.Rest; using Discord.WebSocket; using DiscordBot.Games; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DiscordBot { public enum ChannelStatus { Listening, WaitingLobby, Playing, KillMessage } public class ChannelHandler { // We could choose to go to a higher interface like ISocketMessageChannel // but I think we always want this more specific scope. public SocketTextChannel channel; public ChannelStatus status; // the keys are the messageIds - delegates for handling reactions public Dictionary<ulong, Action<ulong, string, ulong, bool>> messages; // discord userIds and Users playing the game! public Dictionary<ulong, IUser> players; // these two are just used for the lobby private LinkedList<string> orderedPlayers; private RestUserMessage lobbyRestMessage; // only used for !kill, super clunky private GameInterface runningGame; public ChannelHandler(ISocketMessageChannel newChannel) { var castedChannel = newChannel as SocketTextChannel; if (castedChannel == null) { throw new InvalidCastException( "Could not cast passed channel " + "to SocketTextChannel"); } channel = castedChannel; messages = new Dictionary<ulong, Action<ulong, string, ulong, bool>>(); players = new Dictionary<ulong, IUser>(); orderedPlayers = new LinkedList<string>(); status = ChannelStatus.Listening; } public void EndGame(bool concluded = false) { status = ChannelStatus.Listening; players = new Dictionary<ulong, IUser>(); orderedPlayers = new LinkedList<string>(); if (!concluded) { runningGame.EndGame(); } runningGame = null; } public void ProcessReaction(ulong messageId, string emote, ulong userId, bool adding) { if (messages.ContainsKey(messageId)) { messages[messageId](messageId, emote, userId, adding); } } // string command has already been trimmed and lower-cased public void ProcessMessage(SocketMessage message, string command) { if (command.StartsWith("kill")) { _ = SendKillMessage(); } else if (command.StartsWith("play")) { _ = PlayGame(message, command.Substring(command.IndexOf("play") + "play".Length).Trim()); } else { _ = channel.SendMessageAsync( "Sorry, !" + command.Split(' ')[0] + " has not been " + "implemented 😓 Try !help for a list of commands."); } } private async Task PlayGame(SocketMessage message, string gameToFind) { if (status != ChannelStatus.Listening) { await channel.SendMessageAsync( "Please end the current game or lobby before " + "starting a new one!"); return; } DiscardGames game = Program.FindGameFromString(gameToFind); if (game == DiscardGames.NOTFOUND) { await channel.SendMessageAsync( "Sorry, I couldn't find " + gameToFind + " 😓 Please try" + "again or run !help for a list of games you can !play."); } else { _ = StartLobby(game); } } private static string JoinGameMessage = "React to this message with 👍 to join! Current Players:\n"; // make sure you don't pass DiscardGames.NOTFOUND to this method private async Task StartLobby(DiscardGames targetGame) { if (targetGame == DiscardGames.NoThanks) { runningGame = new NoThanksGame(this); } else if (targetGame == DiscardGames.IncanGold) { runningGame = new IncanGoldGame(this); } status = ChannelStatus.WaitingLobby; await channel.SendMessageAsync("Starting a game of " + runningGame.Name, false, runningGame.Blurb()); var reactTo = await channel.SendMessageAsync(JoinGameMessage); await reactTo.AddReactionAsync(new Emoji("👍")); messages.Add(reactTo.Id, ReactJoinMessage); lobbyRestMessage = reactTo; } private Task<IMessage> GetMessage(ulong messageId) { var castedChannel = channel as IMessageChannel; if (castedChannel == null) { throw new InvalidCastException("Couldn't cast SocketTextChannel to IMessageChannel"); } return castedChannel.GetMessageAsync(messageId, CacheMode.AllowDownload); } private async void ReactJoinMessage(ulong messageId, string emote, ulong userId, bool adding) { if (emote == "👍" && status == ChannelStatus.WaitingLobby) { if (adding) { players.Add(userId, await GetUser(userId)); orderedPlayers.AddLast(GetUsername(userId)); } else { players.Remove(userId); orderedPlayers.Remove(GetUsername(userId)); } UpdateLobbyMessage(); /// *** STARTS THE GAME *** /// This needs to be updated so that it only works when we have enough players to start /// the game } else if (emote == "✅" && adding && status == ChannelStatus.WaitingLobby && playerAuthorizedToStart != null && playerAuthorizedToStart == GetUsername(userId)) { await channel.DeleteMessageAsync(messageId); messages.Remove(messageId); await channel.SendMessageAsync( "Starting a game of " + runningGame.Name + " with " + string.Join<string>(", ", orderedPlayers) + " 🎉"); runningGame.StartGame(); status = ChannelStatus.Playing; } } private string playerAuthorizedToStart; private async void UpdateLobbyMessage() { if (lobbyRestMessage != null) { string playerString = string.Join<string>(", ", orderedPlayers); int count = players.Count; playerString += $"\nWe have {count} players."; if (count >= runningGame.MinPlayers && count <= runningGame.MaxPlayers) { playerString += $" {orderedPlayers.First.Value}, react with ✅ to begin!"; await lobbyRestMessage.AddReactionAsync(new Emoji("✅")); playerAuthorizedToStart = orderedPlayers.First.Value; } else { playerAuthorizedToStart = null; } await lobbyRestMessage.ModifyAsync(x => x.Content = JoinGameMessage + playerString); } else { Console.WriteLine("Error! Couldn't cast or find Lobby message"); } } private async Task SendKillMessage() { if (status == ChannelStatus.Playing) { var sentMsg = await channel.SendMessageAsync( "Do you really want to kill this game?\n" + "👎 to keep playing. 🗑️ to confirm deletion."); await sentMsg.AddReactionsAsync(new IEmote[] { new Emoji("👎"), new Emoji("🗑️") }); messages.Add(sentMsg.Id, ReactKillMessage); } else if (status == ChannelStatus.KillMessage) { await channel.SendMessageAsync("We are already trying to kill the game, please react above."); } else if (status == ChannelStatus.WaitingLobby) { await lobbyRestMessage.ModifyAsync(x => x.Content = "This lobby has been canceled by the command !kill."); await channel.SendMessageAsync("The lobby for " + runningGame.Name + " has been canceled."); runningGame = null; status = ChannelStatus.Listening; } else if (status == ChannelStatus.Listening) { await channel.SendMessageAsync("No active game found to kill."); } } // this method is synchronous. we may have some issues there. private void ReactKillMessage(ulong messageId, string emote, ulong userId, bool adding) { if (adding && (emote == "👎" || emote == "🗑️")) { if (emote == "🗑️") { channel.SendMessageAsync(GetUsername(userId) + " has ended the game!"); EndGame(); } else { channel.SendMessageAsync(GetUsername(userId) + " has resumed, we'll keep playing!"); } channel.DeleteMessageAsync(messageId); messages.Remove(messageId); } } private async Task<IUser> GetUser(ulong userId) { var castChannel = channel as ISocketMessageChannel; if (castChannel != null) { var user = await castChannel.GetUserAsync(userId, CacheMode.AllowDownload); var castUser = user as IUser; if (castUser != null) { return castUser; } throw new InvalidCastException("Can't cast user as IUser"); } throw new InvalidCastException("Can't cast channel to ISocketMessageChannel"); } private string GetUsername(ulong userId) { if (players.ContainsKey(userId)) { return players[userId].Username; } return channel.GetUser(userId).Username; } } }
233815eecc4610e080bf8acee16905c296eefd08
[ "C#" ]
5
C#
Austin-Tan/CoolCardGamesBot
6366a2fafbdebd680dbe4f44eaab012e1613ae64
cc98836ceacfe4e72b9c5d52668f9590a221e39b
refs/heads/master
<file_sep>using System; using TechTalk.SpecFlow; namespace UnitTestProject1 { [Binding] public class GoogleSteps { [Given(@"I am on google")] public void GivenIAmOnGoogle() { Console.WriteLine("DDDD"); } [When(@"I search ""(.*)""")] public void WhenISearch(string p0) { // ScenarioContext.Current.Pending(); } [Then(@"I should see the result")] public void ThenIShouldSeeTheResult() { //ScenarioContext.Current.Pending(); } } } <file_sep>using NUnit.Framework; using RestSharp; using System; using TechTalk.SpecFlow; namespace Specflow.Steps { [Binding] public class AppbuilderServiceSteps { string content; IRestResponse response; [Given(@"I get appbuilder authentication service endpoint")] public void GivenIGetAppbuilderAuthenticationServiceEndpoint() { var client = new RestClient("https://dev.supplychainsoft.com/scpapi/DataGuruEngineService/actions"); var request = new RestRequest(Method.GET); response = client.Execute(request); content = response.Content; } [Then(@"I expect to see status (.*)")] public void ThenIExpectToSeeStatus(int status) { System.Net.HttpStatusCode statusCode = response.StatusCode; int numericStatusCode = (int)statusCode; Console.WriteLine(numericStatusCode); Assert.AreEqual(status, numericStatusCode); } [Then(@"I expect to see ""(.*)"" in the response body")] public void ThenIExpectToSeeInTheResponseBody(string keyword) { Assert.IsTrue(content.Contains(keyword)); } } } <file_sep>#Thu Feb 21 10:24:13 GMT 2019 org.eclipse.core.runtime=2 org.eclipse.platform=4.4.2.v20150204-1700
2d0b938939aed72f43d3c64175a2884e27255c2d
[ "C#", "INI" ]
3
C#
ebbe03/Nunit
bfffbf9e0698a8e7805c32b2594aa958acb8dc27
45f9e060f19405eb7de368bbb765075fa82d4d13
refs/heads/master
<file_sep>package com.example.cameralibrary.camera import android.support.v4.util.ArrayMap import java.util.* /** * Created by liuxuan on 2019/1/2 * * 从宽高比到图像size的映射,key是宽高比,value是满足这个宽高比的图像size集合 */ class CameraSizeMap { private val mRatios = ArrayMap<AspectRatio, SortedSet<CameraSize>>() val isEmpty: Boolean get() = mRatios.isEmpty /** * Add a new [Size] to this collection. * * @param size The size to add. * @return `true` if it is added, `false` if it already exists and is not added. */ fun add(size: CameraSize): Boolean { /* for (ratio in mRatios.keys) { if (ratio.matches(size)) { val sizes = mRatios[ratio] if (sizes != null) { return if (sizes.contains(size)) { false } else { sizes.add(size) true } } } }*/ mRatios.keys .filter { it.matches(size) } .mapNotNull { mRatios[it] } .forEach { return if (it.contains(size)) { false } else { it.add(size) true } } // None of the existing ratio matches the provided size; add a new key val sizes = TreeSet<CameraSize>() sizes.add(size) mRatios.put(AspectRatio.of(size.getWidth(), size.getHeight()), sizes) return true } /** * Removes the specified aspect ratio and all sizes associated with it. */ fun remove(ratio: AspectRatio) { mRatios.remove(ratio) } fun ratios(): Set<AspectRatio> { return mRatios.keys } fun sizes(ratio: AspectRatio?): SortedSet<CameraSize>? { if(ratio != null) { return mRatios[ratio] } return null } fun clear() { mRatios.clear() } override fun toString(): String { val builder = StringBuilder("") val ratioSet = ratios() for (ratio in ratioSet) { val sizeSet = sizes(ratio) builder.append("[").append(ratio.toString()).append("]:{") if (sizeSet != null) { for (size in sizeSet) { builder.append(size.toString()).append(", ") } } builder.append("}; ") } return builder.toString() } } <file_sep>// // Created by 刘轩 on 2019/1/27. // #include <jni.h> #include <FilterGroup.h> #include <Filter.h> using namespace GCVBase; extern "C" { jlong Java_com_example_filterlibrary_FilterGroup_nativeFilterGroupInit(JNIEnv * env, jobject obj){ auto * filterGroup = new FilterGroup(); return (jlong)filterGroup; } void Java_com_example_filterlibrary_FilterGroup_nativeFilterGroupAddFilter(JNIEnv * env, jobject obj, jlong filterGroupAddress, jlong filterAddress){ auto * filter = (Filter *)filterAddress; auto * filterGroup = (FilterGroup *)filterGroupAddress; filterGroup->addFilter(filter); } void Java_com_example_filterlibrary_FilterGroup_nativeFilterGroupRemoveFilter(JNIEnv * env, jobject obj, jlong filterGroupAddress, jlong filterAddress){ auto * filter = (Filter *)filterAddress; auto * filterGroup = (FilterGroup *)filterGroupAddress; filterGroup->removeFilter(filter); } }<file_sep>// // Created by 刘轩 on 2019/2/5. // #include "MediaBuffer.hpp" #include "MediaPlayer.h" GCVBase::MediaPlayer::MediaPlayer(std::string readPath, ANativeWindow * nativeWindow) { mediaDecoder = new MediaDecoder(readPath, nativeWindow); } GCVBase::MediaPlayer::~MediaPlayer() { delete mediaDecoder; } void GCVBase::MediaPlayer::startPlayer(const std::function<void ()> &handler) { mIsPlaying = true; startCallback = handler; while(mIsPlaying && !mediaDecoder->decodingIsFinished()){ if(mediaDecoder->decodIsSurfacePlayer()){ mediaDecoder->getCodecFrameVideoBuffer(); } else { readNextVideoFrame(); } // readNextAudioFrame(); } } void GCVBase::MediaPlayer::pausePlayer(const std::function<void ()> &handler) { mIsPlaying = false; pauseCallback = handler; } void GCVBase::MediaPlayer::cancelPlayer(const std::function<void ()> &handler) { mIsPlaying = false; cancelCallback = handler; } void GCVBase::MediaPlayer::readNextVideoFrame() { runSyncContextLooper(Context::getShareContext()->getContextLooper(), [=] { MediaBuffer<FrameBuffer * > * videoBuffer = mediaDecoder->decodeNewFrameVideo(); if (videoBuffer) { FrameBuffer *resultFbo = videoBuffer->mediaData; int rotation = (int) videoBuffer->metaData[RotationKey]; RotationMode rotationMode = rotation0; switch (rotation) { case 90: rotationMode = rotation0; break; case 180: rotationMode = rotation90; break; case -90: rotationMode = rotation270; break; default: break; } rotationPlayer = Rotation(rotationMode, FacingMode::FacingBack); newFrameReadyAtTime(rotationPlayer, resultFbo, videoBuffer->time); } }); } void GCVBase::MediaPlayer::readNextAudioFrame() { if(mIsPlaying){ MediaBuffer<uint8_t * > * audioBuffer = mediaDecoder->decodeNewFrameAudio(); } } void GCVBase::MediaPlayer::newFrameReadyAtTime(const Rotation &mRotation, FrameBuffer *resultFbo, const MediaTime &time) { for(auto i = mTargets.begin(); i < mTargets.end(); i++){ auto currentTarget = * i; currentTarget->_setOutputRotation(mRotation); currentTarget->_setOutputFramebuffer(resultFbo); // currentTarget->_newFrameReadyAtTime(time); } } void GCVBase::MediaPlayer::setFilePath(std::string readPath) { mediaDecoder->setFilePath(readPath); } void GCVBase::MediaPlayer::setNativeSurface(ANativeWindow *nativeWindow) { mediaDecoder->setNativeSurface(nativeWindow); } <file_sep>package com.example.cameralibrary.camera /** * Created by liuxuan on 2019/1/2 */ object CameraParam { val DEFAULT_ASPECT_RATIO = AspectRatio.of(16, 9)//如果是16:9的话显示图片的时候可以填充整个屏幕 val SECOND_ASPECT_RATIO = AspectRatio.of(4, 3)//如果是4:3的话显示图片的时候会上下留黑很多空间 val FACING_BACK = 0 val FACING_FRONT = 1 val FLASH_OFF = 0 val FLASH_ON = 1 val FLASH_TORCH = 2 val FLASH_AUTO = 3 val FLASH_RED_EYE = 4 val LANDSCAPE_90 = 90 val LANDSCAPE_270 = 270 }<file_sep>// // Created by 刘轩 on 2019/1/11. // #ifndef GPUCAMERAVIDEO_MEDIAENCODER_H #define GPUCAMERAVIDEO_MEDIAENCODER_H #include <media/NdkMediaCodec.h> #include <media/NdkMediaMuxer.h> #include <android/log.h> #include "Encoder.hpp" #include "Looper.h" #include "EncoderConfig.hpp" namespace GCVBase { class MediaEncoder : Encoder { private: bool mStop = true; bool mIsYUV420SP = false; Looper * encoderLooper = nullptr; EncoderConfig mEncoderConfig; uint64_t startTime = 0; uint64_t writeSampleDataTime = 0; AMediaCodec *mVideoMediaCodec = nullptr; AMediaCodec *mAudioMediaCodec = nullptr; AMediaMuxer *mMuxer = nullptr; ssize_t mVideoTrackIndex = -1; ssize_t mAudioTrackIndex = -1; FILE * saveFile = nullptr; bool mVideoIsWritten = false; //必须先让视频帧先写入,不然开始会黑屏的 bool mIsRunning = false; int mStartCount = 0; void initVideoCodec(); void initAudioCodec(); void startMediaMuxer(); void stopMediaMuxer(AMediaCodec *codec); public: MediaEncoder(const GCVBase::EncoderConfig &config); ~MediaEncoder(); void startEncoder(std::function<void(void)> startHandler = nullptr); void pauseEncoder(std::function<void(void)> pauseHandler = nullptr); void cancelEncoder(std::function<void(void)> cancelHandler = nullptr); void finishEncoder(std::function<void(void)> finishHandler = nullptr); template <class T_> void newFrameReadyAtTime(MediaBuffer<T_> * mediaBuffer){ if(mStop){ return; } if (mediaBuffer->mediaType == MediaType::Audio) { newFrameEncodeAudio(mediaBuffer); } if (mediaBuffer->mediaType == MediaType::Video) { newFrameEncodeVideo(mediaBuffer); } } void newFrameEncodeAudio(MediaBuffer<uint8_t *> *audioBuffer); //音频数据 void newFrameEncodeVideo(MediaBuffer<uint8_t *> *videoBuffer); //视频数据 void recordCodecBuffer(AMediaCodecBufferInfo *bufferInfo, AMediaCodec *codec, int trackIndex); }; } #endif //GPUCAMERAVIDEO_MEDIAENCODER_H <file_sep>package com.example.cameralibrary.preview import android.content.Context import android.util.AttributeSet import android.view.MotionEvent import android.view.View import android.widget.FrameLayout import com.example.baselib.GCVInput import com.example.baselib.GCVOutput import com.example.cameralibrary.camera.CameraParam import com.example.cameralibrary.effects.FocusMarkerView import com.example.cameralibrary.preview.surfaceview.SurfaceViewPreview import java.nio.ByteBuffer /** * Created by liuxuan on 2019/1/2 */ class Preview : FrameLayout { private val mPreviewImpl: PreviewImpl private val mFocusMarkerView: FocusMarkerView companion object { val FLASH_OFF = CameraParam.FLASH_OFF val FLASH_ON = CameraParam.FLASH_ON val FLASH_TORCH = CameraParam.FLASH_TORCH//手电筒状态 val FLASH_AUTO = CameraParam.FLASH_AUTO val FLASH_RED_EYE = CameraParam.FLASH_RED_EYE } constructor(context: Context) : this(context, null) constructor(context: Context, attributeSet: AttributeSet?) : this(context, attributeSet, 0) constructor(context: Context, attributeSet: AttributeSet?, defStyleAttr: Int) : super(context, attributeSet, defStyleAttr) { mPreviewImpl = creatPreview(context, attributeSet, defStyleAttr) mFocusMarkerView = FocusMarkerView(getContext()) addView(mFocusMarkerView) addViewListener() } private fun addViewListener() { mFocusMarkerView.setOnTouchListener { _, motionEvent -> if (motionEvent.action == MotionEvent.ACTION_UP) { mFocusMarkerView.focus(motionEvent.x, motionEvent.y) } if (mPreviewImpl.getView() != null) { mPreviewImpl.getView()!!.dispatchTouchEvent(motionEvent) } true } } fun setFilterGroup(filterGroup: GCVInput){ mPreviewImpl.setFilterGroup(filterGroup) } fun addPreviewLifeListener(previewLife: PreviewLifeListener){ mPreviewImpl.setPreviewLifeListener(previewLife) } fun addPreviewDataListener(previewData: PreviewDataListener){ mPreviewImpl.setPreviewDataListener(previewData) } private fun creatPreview(context: Context, attributeSet: AttributeSet?, defStyleAttr: Int): PreviewImpl { return SurfaceViewPreview(context, this, attributeSet, defStyleAttr) } fun getView(): View? { return mPreviewImpl.getView() } fun getFacing(): Int { return mPreviewImpl.getFacing() } fun setFacing(facing: Int){ mPreviewImpl.setFacing(facing) } fun setRecorder(output : GCVOutput){ mPreviewImpl.setRecorder(output) } fun takePicture(){ mPreviewImpl.takePicture() } interface PreviewLifeListener { fun onPreviewCreated() fun onPreviewChanged(width: Int, height: Int) fun onPreviewReady() fun onPreviewDestory() } interface PreviewDataListener { fun onPreviewFrame(previewFrameData: ByteBuffer) fun onPictureTaken(cameraPictureData: ByteBuffer) } }<file_sep>// // Created by 刘轩 on 2018/12/27. // #ifndef GPUCAMERAVIDEO_GLPROGRAM_H #define GPUCAMERAVIDEO_GLPROGRAM_H #include <GLES2/gl2.h> #include <GLES2/gl2ext.h> #include <EGL/egl.h> #include <string> namespace GCVBase { class GLProgram { private: GLuint mProgram; GLuint mVertShader; GLuint mFragShader; std::string mProgramLinkLog; std::string mVertexCompileLog; std::string mFragmentCompileLog; bool isLinked = false; bool compileShader(GLuint *shader, GLenum type, const std::string &shaderString); public: GLProgram(const std::string &vertexShaderString, const std::string &fragmentShaderString); bool linkProgram(); void useProgram(); const std::string vertexCompileLog(){ return mVertexCompileLog; } const std::string &fragmentCompileLog(){ return mFragmentCompileLog; } const std::string &programLinkLog(){ return mProgramLinkLog; } bool isProgramLinked(){ return isLinked; } GLuint getProgram(){ return mProgram; } GLuint getAttributeIndex(const std::string &attribute); GLuint getuniformIndex(const std::string &uniformName); }; } #endif //GPUCAMERAVIDEO_GLPROGRAM_H <file_sep>package com.example.cameralibrary.camera import android.content.Context import android.graphics.SurfaceTexture import android.hardware.Camera import android.util.Log import android.view.WindowManager import com.example.baselib.GCVInput import com.example.cameralibrary.camera.api.Camera1 import com.example.cameralibrary.camera.api.CameraImpl import com.example.cameralibrary.preview.PreviewImpl import com.example.cameralibrary.preview.PreviewImpl.CameraOpenListener import com.example.cameralibrary.preview.PreviewImpl.CameraPreviewListener import com.example.cameralibrary.preview.PreviewImpl.CameraTakePictureListener import java.nio.ByteBuffer /** * Created by liuxuan on 2018/12/27 */ class Camera(context: Context): GCVInput() { private val cameraImpl: CameraImpl private val windowManager: WindowManager private var mCamera: Camera? = null private var mSurfaceTexture: SurfaceTexture? = null private var mPreviewListener: CameraPreviewListener? = null private var state: CameraState = CameraState.RELEASED private var mFacing: Int = 0 private var mFlash: Int = 0 private var mAutoFocus: Boolean = false init { cameraImpl = Camera1() //暂时不考虑Camera2接口,但保留 windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager } private enum class CameraState { OPENED, STARTED, STOPPED, RELEASED; } interface FacingChangedCallback { fun onFacingChanged() } fun isCameraOpened(): Boolean { return state == CameraState.OPENED || state == CameraState.STARTED } fun creatNativeCamera(): Long { inputObjectAdress = nativeCameraInit(mFacing) return inputObjectAdress } fun setPreviewImpl(previewImpl: PreviewImpl){ cameraImpl.setPreviewImpl(previewImpl) } /************************************** 相机生命周期函数 **********************************************/ fun openCamera(mFacing: Int, surfaceTexture: SurfaceTexture? = null, cameraOpen: CameraOpenListener? = null, previewListener: CameraPreviewListener? = null) { if(surfaceTexture != null) { mSurfaceTexture = surfaceTexture } if(previewListener != null){ mPreviewListener = previewListener } cameraImpl.openCamera(mFacing, object : CameraImpl.CameraOpenCallback { override fun onOpen(mCamera:Camera) { this@Camera.mCamera = mCamera state = CameraState.OPENED cameraOpen?.onCameraOpen() if(surfaceTexture != null){ startPreview(surfaceTexture, mPreviewListener) } } override fun onError() { // TODO "添加报错 log" cameraOpen?.onOpenError() } }) } fun startPreview(surfaceTexture: SurfaceTexture, previewListener: CameraPreviewListener? = null) { if(state != CameraState.OPENED){ // TODO 打log,Camera还没有正常打开,不应该进行 Preview 操作 return } /** * 这里是一个"偷懒"的操作,正确的姿势应当在外部通过 OrientationEventListener 接口监听旋转事件。 * 在手机从横向(90°)转到另一个横向(270°)时,并不会引起Activity的重建,因此这里会有漏洞。 */ val displayOrientation = windowManager.defaultDisplay.rotation * 90 setDisplayOrientation(displayOrientation) cameraImpl.startPreview(surfaceTexture, object : CameraImpl.PreviewStartCallback { override fun onStart() { state = CameraState.STARTED previewListener?.onPreviewStart() } override fun onPreviewFrame(previewData: ByteBuffer) { previewListener?.onPreviewFrame(previewData) } override fun onError() { } }) } fun stopPreview(faceChangedCallback: FacingChangedCallback? = null) { cameraImpl.stopPreview(object : CameraImpl.PreviewStopCallback { override fun onStop() { state = CameraState.STOPPED closeCamera(faceChangedCallback) } override fun onError() { } }) } fun closeCamera(faceChangedCallback: FacingChangedCallback? = null) { cameraImpl.closeCamera(object : CameraImpl.CameraCloseCallback { override fun onClose() { state = CameraState.RELEASED faceChangedCallback?.onFacingChanged() } override fun onError() { } }) } fun takePicture(cameraTakePicture: CameraTakePictureListener){ cameraImpl.takePicture(cameraTakePicture) } /************************************** 切换相机参数函数 **********************************************/ fun setFlash(flash: Int) { if (mFlash == flash) { return } cameraImpl.setFlash(flash) } fun getCameraFacing(): Int{ return mFacing } fun setFacing(facing: Int) { if (mFacing == facing) { return } mFacing = facing cameraImpl.setFacing(facing) nativeChangeCameraFacing(inputObjectAdress, facing) if (isCameraOpened()) { //前后置镜头切换的时候要关闭预览再打开 stopPreview(object: FacingChangedCallback { override fun onFacingChanged() { if(mSurfaceTexture != null) { openCamera(facing, mSurfaceTexture) } } }) } } fun setAutoFocus(autoFocus: Boolean) { if (mAutoFocus == autoFocus) { return } cameraImpl.setAutoFocus(autoFocus) } fun setAspectRatio(ratio: AspectRatio): Boolean { return cameraImpl.setAspectRatio(ratio) } fun getSupportedAspectRatios(): Set<AspectRatio>{ return cameraImpl.getSupportedAspectRatios() } fun setDisplayOrientation(displayOrientation: Int){ // cameraImpl.setDisplayOrientation(displayOrientation) nativeChangeCamerOrientation(inputObjectAdress, displayOrientation) } /****************************************** native函数 **********************************************/ private external fun nativeCameraInit(mFacing: Int): Long private external fun nativeChangeCameraFacing(nativeCamera: Long, mFacing: Int) private external fun nativeChangeCamerOrientation(nativeCamera: Long, orientation: Int) }<file_sep>package com.example.filterlibrary /** * Created by liuxuan on 2019/1/27 */ abstract class Filter constructor( width: Int = 0, height: Int = 0) { private var nativeFilterAdress: Long = 0L init { initFilter(width, height) } private fun initFilter(width: Int = 0, height: Int = 0){ nativeFilterAdress = nativeFilterInit(getVertexShader(), getFragmentShader(), width, height) } fun getNativeFilterAdress(): Long{ return nativeFilterAdress } abstract fun getVertexShader(): String abstract fun getFragmentShader(): String private external fun nativeFilterInit(vertexShader: String, fragmentShader: String, width: Int, height: Int): Long }<file_sep>// // Created by 刘轩 on 2019/2/5. // #include <jni.h> #include <android/native_window_jni.h> #include "MediaPlayer.h" using namespace GCVBase; extern "C" { jlong Java_com_example_codeclibrary_MoviePlayer_nativePlayerInit(JNIEnv * env, jobject obj, jstring readPath, jobject surface){ MediaPlayer *mediaPlayer = nullptr; ANativeWindow * nativeWindow = nullptr; if(readPath) { const char *readString = env->GetStringUTFChars(readPath, nullptr); if(surface){ nativeWindow = ANativeWindow_fromSurface(env, surface); } mediaPlayer = new MediaPlayer(readString, nativeWindow); env->ReleaseStringChars(readPath, reinterpret_cast<const jchar *>(readString)); } else{ mediaPlayer = new MediaPlayer(); } return (jlong)mediaPlayer; } void Java_com_example_codeclibrary_MoviePlayer_nativeSetFilePath(JNIEnv * env, jobject obj, jlong nativePlayerAddress, jstring readPath){ if(!nativePlayerAddress){ return; } if(!readPath){ return; } const char *readString = env->GetStringUTFChars(readPath, nullptr); MediaPlayer * mediaPlayer = (MediaPlayer * )nativePlayerAddress; mediaPlayer->setFilePath(readString); env->ReleaseStringChars(readPath, reinterpret_cast<const jchar *>(readString)); } void Java_com_example_codeclibrary_MoviePlayer_nativeStartPlayer(JNIEnv * env, jobject obj, jlong nativePlayerAddress){ if(!nativePlayerAddress){ return; } MediaPlayer * mediaPlayer = (MediaPlayer * )nativePlayerAddress; mediaPlayer -> startPlayer([=]{ }); } void Java_com_example_codeclibrary_MoviePlayer_nativePausePlayer(JNIEnv * env, jobject obj, jlong nativePlayerAddress){ if(!nativePlayerAddress){ return; } MediaPlayer * mediaPlayer = (MediaPlayer * )nativePlayerAddress; mediaPlayer ->pausePlayer([=]{ }); } void Java_com_example_codeclibrary_MoviePlayer_nativeCancelPalyer(JNIEnv * env, jobject obj, jlong nativePlayerAddress){ if(!nativePlayerAddress){ return; } MediaPlayer * mediaPlayer = (MediaPlayer * )nativePlayerAddress; mediaPlayer ->cancelPlayer([=]{ }); } void Java_com_example_codeclibrary_MoviePlayer_nativeSetPlayerSurface(JNIEnv * env, jobject obj, jlong nativePlayerAddress, jobject surface){ ANativeWindow * nativeWindow = ANativeWindow_fromSurface(env, surface); MediaPlayer * mediaPlayer = (MediaPlayer * )nativePlayerAddress; mediaPlayer->setNativeSurface(nativeWindow); } void Java_com_example_codeclibrary_MoviePlayer_nativeSurfaceDestroyed(JNIEnv * env, jobject obj, jlong nativePlayerAddress){ MediaPlayer * mediaPlayer = (MediaPlayer * )nativePlayerAddress; delete mediaPlayer; } } <file_sep>// // Created by 刘轩 on 2019/1/7. // #ifndef GPUCAMERAVIDEO_NATIVEOUTPUT_H #define GPUCAMERAVIDEO_NATIVEOUTPUT_H #include "Rotation.hpp" #include "Time.hpp" #include "FrameBuffer.h" namespace GCVBase { class NativeOutput { public: virtual void _setOutputFramebuffer(FrameBuffer *framebuffer) = 0; virtual void _setOutputRotation(const Rotation &rotation) = 0; virtual void _newFrameReadyAtTime() = 0; }; } #endif //GPUCAMERAVIDEO_NATIVEOUTPUT_H <file_sep>// // Created by 刘轩 on 2019/1/8. // <file_sep>// // Created by 刘轩 on 2018/12/20. // #include <android/log.h> #include "Looper.h" void GCVBase::Looper::runFunctionInLock(const std::function<void()> &function) { mFunctionLock.lock(); function(); mFunctionLock.unlock(); } GCVBase::Looper::Looper(const std::string &name) { mLooperName = name; mMessageQueue = new MessageQueue(mLooperName, mLooperName); queueConditionLock = new ConditionLock([&]() -> bool{ return !mMessageQueue->isMessageQueueEmpty() || mQuit; }); mWorkThread = new std::thread(&Looper::loop, this); threadId = mWorkThread->get_id(); } GCVBase::Looper::~Looper() { mQuit = true; queueConditionLock ->notifyOne(); //有可能此时Looper线程还在wait,唤醒之,这句只能在 mQuit = true; 之后 mWorkThread->join(); //让当前运行线程等待Looper线程执行完毕,再销毁 // Message::clearMessagePool(); delete(mWorkThread); delete(mMessageQueue); delete(queueConditionLock); } std::string GCVBase::Looper::getLooperName() { return mLooperName; } /** * 首先要明确,这个addMessage是在别的线程中添加的,相当于生产者 * @param function */ void GCVBase::Looper::addMessageAsync(const std::function<void()> &function) { addMessage(function, true); } void GCVBase::Looper::addMessageSync(const std::function<void()> &function) { addMessage(function, false); } void GCVBase::Looper::addMessage(const std::function<void()> &function, bool async) { if(mQuit){ return; } Function * fun = nullptr; Message * message = nullptr; runFunctionInLock([&]{ message = Message::obtain(); if(!message->mMessageFunction) { fun = new Function(function, async); message->mMessageFunction = fun; } else{ message->mMessageFunction->setFunction(function, async); fun = message->mMessageFunction; } message->mMessageQueueName = mMessageQueue->getMessageQueueName(); mMessageQueue->addMessage(message); queueConditionLock->notifyOne(); //加入MessageQueue之后,唤醒等待的Looper线程,loop()方法就开始循环 }); if(!async){ /** * 同步意味着必须等这个Function执行完毕,当前线程才能继续运行。 * 注意此时是对functionConditionLock加的锁,所以addMessage线程会被阻塞在这个condition上, * looper线程已经被queueConditionLock唤醒了,所以正常执行。 * 而且这个functionConditionLock是每一个Function对象独有的,所以必须等待该fun对象执行完后, * 这边才能被唤醒,然后执行fun->forceWaitFunctionFinish();后面的语句 */ fun->forceWaitFunctionFinish(); runFunctionInLock([&]{ mMessageQueue->recycleMessage(message); //执行完毕后回收同步消息 }); } } /** * loop()这个方法是在Looper对应的线程中运行,相当于消费者。 * * 我们规定一个Looper对象对应一个线程,且在Looper的构造函数中创建了条件锁对象,也就是说一个Looper对象拥有一个 * queueConditionLock对象,该condition锁只能用来阻塞当前的Looper线程和addMessage线程 * 因此,不管你new几个Looper,其实这里通过queueConditionLock条件等待的只有两个线程:Looper(消费者)线程和 * addMessage(生产者)线程,其中消费的消息队列也只是他们两个人的。 */ void GCVBase::Looper::loop() { while(!mQuit) { Message * message = nullptr; Function * function = nullptr; runFunctionInLock([&]{ message = mMessageQueue->getNextMessage(); if(message != nullptr){ function = message->mMessageFunction; } }); if(function){ bool isAsync = function->isAsync(); function->run(); //run完了就finish了 function->notifyOne(); //唤醒functionConditionLock上等待的addMessage线程,继续执行fun->forceWaitFunctionFinish()之后的代码 runFunctionInLock([&]{ if(isAsync){ //这里是回收异步线程的message,同步消息上面已经回收过了 mMessageQueue->recycleMessage(message); } }); } queueConditionLock->verificationCondition(); //如果这个Queue的消息队列为空,阻塞本线程,不然这个while就没完没了了 } runFunctionInLock([=]{ //循环停掉后MessageQueue可能还有消息,应当全部回收 mMessageQueue->recycleAllMessage(); }); } <file_sep>package com.example.codeclibrary /** * Created by liuxuan on 2019/2/5 */ class AudioPlayer { }<file_sep>// // Created by 刘轩 on 2019/1/11. // #ifndef GPUCAMERAVIDEO_MEDIABUFFER_H #define GPUCAMERAVIDEO_MEDIABUFFER_H #include <stdio.h> #include <string> #include <unordered_map> #include "Time.hpp" typedef std::string MetaDataKey; const MetaDataKey RotationKey = "Rotation"; const MetaDataKey IsVideoKey = "IsVideo"; const MetaDataKey WidthKey = "Width"; const MetaDataKey HeightKey = "Height"; const MetaDataKey PixelFormatKey = "PixelFormat"; const MetaDataKey AudioChannelKey = "AudioChannel"; const MetaDataKey FrameSize = "FrameSize"; const MetaDataKey SampleRateKey = "SampleRate"; const MetaDataKey SampleFormatKey = "SampleFormat"; namespace GCVBase { enum MediaType{ Audio = 0, Video = 1, }; enum SampleFormat{ S16 = 0, //有符号16位 U8 , //无符号8位 FLTP, //float ZERO, //Zero }; enum AudioChannel{ SINGLE = 0, //单通道 DOUBLE, }; template <class T_> struct MediaBuffer { public: T_ mediaData; MediaTime time = MediaTime::Zero(); MediaType mediaType = MediaType::Audio; std::unordered_map<MetaDataKey, const void *> metaData; }; static inline uint8_t getChannelCount(AudioChannel channel){ uint8_t count = 0; switch(channel){ case SINGLE: count = 1; break; case DOUBLE: count = 2; break; default: break; } return count; } } #endif //GPUCAMERAVIDEO_MEDIABUFFER_H <file_sep>package com.example.cameralibrary.preview import android.content.Context import android.graphics.SurfaceTexture import android.view.View import com.example.baselib.GCVInput import com.example.baselib.GCVOutput import com.example.cameralibrary.camera.Camera import java.nio.ByteBuffer /** * Created by liuxuan on 2019/1/2 */ abstract class PreviewImpl(context: Context) { private var mWidth: Int = 0 private var mHeight: Int = 0 /* * 可以看到,这里我们强制使SurfaceView或者TextureView这些预览控件持有Camera的引用,这样设计的初衷是为了在 * SurfaceView的生命周期中管理Camera的生命周期,而SurfaceView的生命周期则有activity或者fragment来管理 */ protected val mCamera: Camera = Camera(context) // TODO 这里应该预留参数,让用户可以选择到底用Canera1还是Camera2 abstract fun getView(): View? abstract fun setRecorder(movieRecorder : GCVOutput) abstract fun setFacing(facing: Int) abstract fun getFacing(): Int abstract fun takePicture() abstract fun previewIsReady(): Boolean abstract fun setPreviewLifeListener(previewLife: Preview.PreviewLifeListener) abstract fun setPreviewDataListener(previewData: Preview.PreviewDataListener) abstract fun setFilterGroup(filterGroup: GCVInput) fun setPreviewSize(width: Int, height: Int) { mWidth = width mHeight = height } fun getWidth(): Int { return mWidth } fun getHeight(): Int { return mHeight } interface SurfaceListener { fun onSurfaceCreated(nativeOutputAddress: Long) fun onSurfaceChanged(surfaceTexture: SurfaceTexture?, width: Int, height: Int) fun onSurfaceDestory() } interface CameraOpenListener { fun onCameraOpen() fun onOpenError() } interface CameraPreviewListener { fun onPreviewStart() fun onPreviewFrame(previewFrameData: ByteBuffer) fun onPreviewError() } interface CameraTakePictureListener { fun onPictureTaken(cameraPictureData: ByteBuffer) fun onPictureError() } }<file_sep>// // Created by 刘轩 on 2018/12/18. // #ifndef GPUCAMERAVIDEO_FILTERCONTEXT_H #define GPUCAMERAVIDEO_FILTERCONTEXT_H #include <string> class FilterContext { public: std::string hello; void setString(); }; #endif //GPUCAMERAVIDEO_FILTERCONTEXT_H <file_sep>// // Created by 刘轩 on 2019/2/5. // #include "MediaDecoder.h" #include "Rotation.hpp" #include <fcntl.h> #include <unistd.h> #include <android/log.h> static inline uint64_t getCurrentTime() { return (uint64_t) (GCVBase::currentTimeOfNanoseconds() / 1000UL); } GCVBase::MediaDecoder::MediaDecoder(const std::string &filePath, ANativeWindow * nativeWindow) { mNativeWindow = nativeWindow; if(filePath.empty()){ __android_log_print(ANDROID_LOG_DEBUG, "MediaDecoder init", "MediaDecoder init without filePath"); } else{ mFilePath = filePath; } frameAudioBuffer = new MediaBuffer<uint8_t *>(); frameVideoBuffer = new MediaBuffer<uint8_t *>(); yuvFrameBuffer = new YUVFrameBuffer(); if(loadFile()){ if(!initVideoCodec(mNativeWindow)){ __android_log_print(ANDROID_LOG_ERROR, "initVideoCodec", "initVideoCodec failed"); return ; } if(!initAudioCodec()){ __android_log_print(ANDROID_LOG_ERROR, "initAudioCodec", "initAudioCodec failed"); return ; } } } GCVBase::MediaDecoder::~MediaDecoder() { if(mVideoDecodeCodec){ AMediaExtractor_delete(videoEx); AMediaCodec_stop(mVideoDecodeCodec); AMediaCodec_delete(mVideoDecodeCodec); } if(mAudioDecodeCodec){ AMediaExtractor_delete(audioEx); AMediaCodec_stop(mAudioDecodeCodec); AMediaCodec_delete(mAudioDecodeCodec); } delete mNativeWindow; delete frameAudioBuffer; delete frameAudioBuffer; delete yuvFrameBuffer; } bool GCVBase::MediaDecoder::loadFile() { if(mFilePath.empty()){ __android_log_print(ANDROID_LOG_ERROR, "loadFile", "loadFile failed bacause the filePath is null"); return false; } bool reslut = false; runSyncContextLooper(Context::getShareContext()->getContextLooper(), [&]{ off_t offset = 0, fileLen = 0; const char *fileSTR = mFilePath.c_str(); int fd = open(fileSTR, O_RDONLY); if(fd <0){ return NULL; } fileLen = lseek(fd, 0, SEEK_END); if (fileLen < 0) { ::close(fd); return NULL; } (void) lseek(fd, 0, SEEK_SET); videoEx = AMediaExtractor_new(); media_status_t videoStatus = AMediaExtractor_setDataSourceFd(videoEx, fd, static_cast<off64_t>(offset), static_cast<off64_t>(fileLen)); audioEx = AMediaExtractor_new(); media_status_t audioStatus = AMediaExtractor_setDataSourceFd(audioEx, fd, static_cast<off64_t>(offset), static_cast<off64_t>(fileLen)); close(fd); if (videoStatus != AMEDIA_OK) { __android_log_print(ANDROID_LOG_ERROR, "setVideoDataSourceFd", "Set vedio data source error: %d", videoStatus); return NULL; } if (audioStatus != AMEDIA_OK) { __android_log_print(ANDROID_LOG_ERROR, "setAudioDataSourceFd", "Set Audio data source error: %d", audioStatus); return NULL; } reslut = true; return NULL; }); return reslut; } bool GCVBase::MediaDecoder::initVideoCodec(ANativeWindow * nativeWindow) { int vedioTrackNum = AMediaExtractor_getTrackCount(videoEx); for (int i = 0; i < vedioTrackNum; i++) { AMediaFormat *vedioformat = AMediaExtractor_getTrackFormat(videoEx, i); //分离轨道 const char *mime; if (!AMediaFormat_getString(vedioformat, AMEDIAFORMAT_KEY_MIME, &mime)) { __android_log_print(ANDROID_LOG_DEBUG, "Vedio AMediaFormat_getString", "No this MIME type = %s", mime); } else if (!strncmp(mime, "video/", 6)) { //说明视频轨道是有的,分离视频轨道 AMediaExtractor_selectTrack(videoEx, i); mVideoDecodeCodec = AMediaCodec_createDecoderByType(mime); //创建视频解码器 int32_t videoMaxInputSize, videoDuration; AMediaFormat_getInt32(vedioformat, AMEDIAFORMAT_KEY_MAX_INPUT_SIZE, &videoMaxInputSize); // 就是 AMediaCodec_getInputBuffer 中的 bufferSize AMediaFormat_getInt32(vedioformat, AMEDIAFORMAT_KEY_DURATION, &videoDuration); __android_log_print(ANDROID_LOG_DEBUG, "AMediaExtractor_getVideoTrack", "videoMaxInputSize is: %i videoDuration is: %i", videoMaxInputSize, videoDuration); if(nativeWindow){ mIsSurfacePlayer = true; AMediaCodec_configure(mVideoDecodeCodec, vedioformat, nativeWindow, NULL, 0); } else { AMediaCodec_configure(mVideoDecodeCodec, vedioformat, NULL, NULL, 0); // 初始化解码器,这里暂时不指定播放的window } AMediaCodec_start(mVideoDecodeCodec); //启动解码器 } AMediaFormat_delete(vedioformat); } return false; } bool GCVBase::MediaDecoder::initAudioCodec() { int audioTrackNum = AMediaExtractor_getTrackCount(audioEx); for (int i = 0; i < audioTrackNum; i++) { AMediaFormat *audioformat = AMediaExtractor_getTrackFormat(audioEx, i); //分离轨道 const char *mime; if (!AMediaFormat_getString(audioformat, AMEDIAFORMAT_KEY_MIME, &mime)) { __android_log_print(ANDROID_LOG_DEBUG, "Audio AMediaFormat_getString", "No this MIME type = %s", mime); } else if (!strncmp(mime, "audio/", 6)) { AMediaExtractor_selectTrack(audioEx, i); mAudioDecodeCodec = AMediaCodec_createDecoderByType(mime); //创建音频解码器 int32_t audioMaxInputSize, audioDuration; AMediaFormat_getInt32(audioformat, AMEDIAFORMAT_KEY_MAX_INPUT_SIZE, &audioMaxInputSize); AMediaFormat_getInt32(audioformat, AMEDIAFORMAT_KEY_DURATION, &audioDuration); __android_log_print(ANDROID_LOG_DEBUG, "AMediaExtractor_getVideoTrack", "videoMaxInputSize is: %i videoDuration is: %i", audioMaxInputSize, audioDuration); AMediaCodec_configure(mAudioDecodeCodec, audioformat, NULL, NULL, 0); AMediaCodec_start(mAudioDecodeCodec); //启动解码器 } AMediaFormat_delete(audioformat); } return false; } GCVBase::MediaBuffer<uint8_t *> *GCVBase::MediaDecoder::decodeNewFrameAudio() { return nullptr; } GCVBase::MediaBuffer<GCVBase::FrameBuffer *> *GCVBase::MediaDecoder::decodeNewFrameVideo() { MediaBuffer<uint8_t *> * frameBuffer = getCodecFrameVideoBuffer(); if(!frameBuffer){ //TODO 报错 return nullptr; } MediaBuffer<GCVBase::FrameBuffer *> * outputVideoBuffer = yuvFrameBuffer->decodeYUVBuffer(frameBuffer); return outputVideoBuffer; } GCVBase::MediaBuffer<uint8_t *> *GCVBase::MediaDecoder::getCodecFrameVideoBuffer() { ssize_t bufferIndex = -1; if (!sawInput) { bufferIndex = AMediaCodec_dequeueInputBuffer(mVideoDecodeCodec, 2000); if (bufferIndex >= 0) { size_t buffsize; auto buf = AMediaCodec_getInputBuffer(mVideoDecodeCodec, bufferIndex, &buffsize); auto samplesize = AMediaExtractor_readSampleData(videoEx, buf, buffsize); if (samplesize < 0) { __android_log_print(ANDROID_LOG_ERROR, "AMediaCodec_dequeueInputBuffer", "InputBuffer stream is end"); sawInput = true; } /** * AMediaExtractor_getSampleTime 以微妙为单位返回当前采样的 pts(显示时间戳) */ auto presentationTimeUs = AMediaExtractor_getSampleTime(videoEx) ; /** * 必须在 samplesize < 0 也就是解码结束时,传入AMEDIACODEC_BUFFER_FLAG_END_OF_STREAM这个标志位,下面才好判断是否结束 */ AMediaCodec_queueInputBuffer(mVideoDecodeCodec, bufferIndex, 0, buffsize, presentationTimeUs , sawInput ? AMEDIACODEC_BUFFER_FLAG_END_OF_STREAM : 0); AMediaExtractor_advance(videoEx); } } if(!sawOutput) { AMediaCodecBufferInfo info; auto index = AMediaCodec_dequeueOutputBuffer(mVideoDecodeCodec, &info, 2000); if (index >= 0) { if (info.flags & AMEDIACODEC_BUFFER_FLAG_END_OF_STREAM ) { //输出流结束 __android_log_print(ANDROID_LOG_ERROR, "AMediaCodec_dequeueOutputBuffer", "OutputBuffer stream is end"); sawOutput = true; } int64_t presentationNano = info.presentationTimeUs * 1000; // presentationTimeUs就是应当播放的时间戳,用来控制播放线程 if (renderStartTime < 0) { //renderStart初始化的时候,也就是第一帧解码出的时候,presentationNano = 0 renderStartTime = (int64_t)currentTimeOfNanoseconds() - presentationNano; //也就是说renderStart代表第一帧解码出来时的时间 __android_log_print(ANDROID_LOG_DEBUG, "AMediaCodec_getOutputBuffer", "renderStart time === %llu ", renderStartTime); } /** * 这里的 usleep 逻辑实际上就是以当前系统时间为标准进行同步显示,由于我们一般录制这种视频时是全I帧录制,因此DTS与PTS是相同的, * 如果不加以限制,则info.presentationTimeUs没有任何指导意义,那实际显示的时间就是Mediaplayer类中的while()循环执行的速度, * 每一个循环调用过来,直接进行解码渲染上屏,这个速度也是加倍速时最快的速度了。 * * 现在我们根据系统 AMediaExtractor_getSampleTime 得出的 pts 进行同步,在正常速度下播放(也就是录像时的速度),usleep() * 中的时间是正值,说明需要解码出来不能立即播放(不然就不是录像时的速度了)。 * * 如果要慢速播放,只需要给 AMediaExtractor_getSampleTime 得出的 pts 加倍即可,这样就 usleep()中等待的时间就更长了, * 也就是每一帧的时间变长(倍速过长会导致播放便的卡顿,类似ppt); 如果要倍速播放,则给 pts变小(x0.5等),这样usleep()中 * 等待的时间就变短了,播放速度就加快了,但这个是有极限的,如果 usleep()中的 delay是负值,那就是最快了,此时的速度就是前面 * 说的Mediaplayer类中的while()循环执行的速度,除非解码能够更快一点。 * * 如有音频轨道,按照一般以音频轨道时间为基准做音频同步的原则,这里就需要跟音频的pts作比较了,而不是当前系统时间,都是一个道理。 * * 因此 renderStartTime + presentationNano 代表显示时间戳(pts),这个时间戳用来告诉播放器该在什么时候显示这一帧的数据。 * 如果 pts > currentTimeOfNanoseconds(), 也就是当前帧应当展示的时间超前于系统当前时间,则等一阵再展示 * 如果 pts < currentTimeOfNanoseconds(), 此时当前帧应当展示的时间落后于系统时间,则应当立即展示该帧 */ int64_t delay = (renderStartTime + presentationNano) - (int64_t)currentTimeOfNanoseconds(); if (delay > 0) { //延时操作,如果缓冲区里的可展示时间 > 当前视频播放的进度,就休眠一下 useconds_t time = static_cast<useconds_t>(delay / 1000); __android_log_print(ANDROID_LOG_DEBUG, "AMediaCodec_dequeueOutputBuffer", "usleep time is %u", time); usleep(time); } else{ __android_log_print(ANDROID_LOG_ERROR, "AMediaCodec_dequeueOutputBuffer", "usleep Fall Behind currentTime %lli", delay / 1000); } if(!mIsSurfacePlayer) { /** * 用AMediaCodec_getOutputFormat接口得到Format对象,并且不能设置surface数据的,此时才能得到正确的颜色空间等数据,不过这样的话这个接口设计的也是很匪夷所思 */ float rotation; int32_t colorFormat, width, height, stride, framerate, bitrate; auto format = AMediaCodec_getOutputFormat(mVideoDecodeCodec); AMediaFormat_getInt32(format, AMEDIAFORMAT_KEY_COLOR_FORMAT, &colorFormat); AMediaFormat_getInt32(format, AMEDIAFORMAT_KEY_BIT_RATE, &bitrate); AMediaFormat_getInt32(format, AMEDIAFORMAT_KEY_FRAME_RATE, &framerate); AMediaFormat_getInt32(format, AMEDIAFORMAT_KEY_I_FRAME_INTERVAL, &framerate); AMediaFormat_getFloat(format, "rotation", &rotation); AMediaFormat_getInt32(format, "width", &width); AMediaFormat_getInt32(format, "height", &height); AMediaFormat_getInt32(format, "stride", &stride); __android_log_print(ANDROID_LOG_DEBUG, "AMediaCodec_dequeueOutputBuffer", "color Format = %d width = %d height = %d stride = %d rotation = %d framerate = %d bitrate = %d", colorFormat, width, height, stride, (int) rotation, framerate, bitrate); __android_log_print(ANDROID_LOG_DEBUG, "AMediaCodec_dequeueOutputBuffer", "AMediaFormat_toString: %s", AMediaFormat_toString(format)); AMediaFormat_delete(format); std::unordered_map<MetaDataKey, const void *> metaData; metaData[RotationKey] = (const void *) (long) rotation; metaData[WidthKey] = (const void *) (long) width; metaData[HeightKey] = (const void *) (long) height; metaData[PixelFormatKey] = (const void *) (long) colorFormat; frameVideoBuffer->mediaType = Video; frameVideoBuffer->metaData = metaData; size_t out_size; uint8_t * outputBuf = AMediaCodec_getOutputBuffer(mVideoDecodeCodec, index, &out_size); outputBuffer = (uint8_t *)(malloc(out_size)); memset(outputBuffer, 0, out_size); memcpy(outputBuffer, outputBuf, out_size); //复制outputBuffer数据 frameVideoBuffer->mediaData = outputBuffer; frameVideoBuffer->time = *(MediaTime *) &info.presentationTimeUs; AMediaCodec_releaseOutputBuffer(mVideoDecodeCodec, index, false); return frameVideoBuffer; } else{ AMediaCodec_releaseOutputBuffer(mVideoDecodeCodec, index, true); //第三个参数为true就会渲染到surface上 } }else if(index == AMEDIACODEC_INFO_OUTPUT_BUFFERS_CHANGED){ //缓冲区的数据发生变化 __android_log_print(ANDROID_LOG_DEBUG, "AMediaCodec_dequeueOutputBuffer", "output buffers changed"); } else if (index == AMEDIACODEC_INFO_OUTPUT_FORMAT_CHANGED) { //format格式参数发生变化 auto format = AMediaCodec_getOutputFormat(mVideoDecodeCodec); __android_log_print(ANDROID_LOG_DEBUG, "AMediaCodec_dequeueOutputBuffer", "format changed to: %s", AMediaFormat_toString(format)); AMediaFormat_delete(format); } else if (index == AMEDIACODEC_INFO_TRY_AGAIN_LATER) { //当前没有数据输出,稍后重试 __android_log_print(ANDROID_LOG_DEBUG, "AMediaCodec_dequeueOutputBuffer", "no output buffer right now"); } else { mIsFinished = true; __android_log_print(ANDROID_LOG_DEBUG, "AMediaCodec_dequeueOutputBuffer", "unexpected info code: %zd", index); } } if(sawInput && sawOutput){ mIsFinished = true; __android_log_print(ANDROID_LOG_DEBUG, "AMediaCodec_dequeueOutputBuffer", "decode finished"); return nullptr; } return nullptr; } void GCVBase::MediaDecoder::setFilePath(const std::string &readPath) { mFilePath = readPath; } void GCVBase::MediaDecoder::setNativeSurface(ANativeWindow *nativeWindow) { mNativeWindow = nativeWindow; } <file_sep>// // Created by 刘轩 on 2019/1/27. // #include <jni.h> #include <Filter.h> using namespace GCVBase; extern "C" { jlong Java_com_example_filterlibrary_Filter_nativeFilterInit(JNIEnv * env, jobject thiz, jstring vertexShader, jstring fragmentShader, jint width, jint height){ const char * vertex = env->GetStringUTFChars(vertexShader, NULL); const char * fragment = env->GetStringUTFChars(fragmentShader, NULL); Filter * filter; if(vertex == NULL && fragment == NULL){ filter = new Filter(width, height); } else{ filter = new Filter(vertex, fragment, width, height); } return (jlong)filter; } } <file_sep>// // Created by 刘轩 on 2018/12/20. // #ifndef GPUCAMERAVIDEO_MESSAGE_H #define GPUCAMERAVIDEO_MESSAGE_H #include <string> #include <thread> #include "Function.h" namespace GCVBase { /** * Message类就是主要的消息结构,该结构中应该有: * 1.MessageQueueName 记录当前该Message属于哪个MessageQueue * 2.messageFunction 需要进行的各种操作,一般传进来的是Function函数 * * 除了上面的两个基本信息外,Message类还应当维护一个消息缓存池(也用链表实现),用于避免多次重复创建Message对象 */ class Message { private: /* * 下面这几个静态的元素都是用于对消息池进行操作的 */ static int maxSize; static int nowSize; static Message * poolHead; public: std::string mMessageQueueName; Function *mMessageFunction = NULL; Message * next = NULL; Message(); Message(std::string messageQueueName, Function *messageFunction); ~Message(); void setMessageFunction(Function *mMessageFunction); void setMessageQueueName(std::string messageQueueName); std::string getMessageQueueName(); static void setMaxPoolSize(int maxSize); static int getNowPoolSize(); static bool isNowMaxPool(); //现在缓存池是最大容量吗? static Message * obtain(); static void recycle(Message * message); static void clearMessagePool(); //用于在项目销毁时释放Message缓存池中的Message对象 static void resetMessage(Message * message); //重置Message中的信息 }; } #endif //GPUCAMERAVIDEO_MESSAGE_H <file_sep>// // Created by 刘轩 on 2018/12/27. // #ifndef GPUCAMERAVIDEO_CAMERA_H #define GPUCAMERAVIDEO_CAMERA_H #include "Rotation.hpp" #include "Time.hpp" #include "Context.h" #include "GLProgram.h" #include "NativeInput.h" namespace GCVBase { class Camera : NativeInput{ private: GLuint aPositionAttribute = 0; GLuint aTexCoordAttribute = 0; GLuint uTextureuniform = 0; int mPreviewWidth = 0; int mPreviewHeight = 0; FacingMode mFacingMode; RotationMode rotationMode; Rotation rotationCamera = Rotation::defaultRotation(); GLuint mOESTexture = 0; EglCore * mEglInstance = NULL; GLProgram * mCameraProgram = NULL; static std::string VertexShared(); static std::string FragmentShared(); void newFrameReadyAtTime(); public: Camera(int mFacing); ~Camera(); EglCore * getEglInstance(); void onSurfaceChanged(); void facingChanged(int facing); void orientationChanged(int orientation); void setPreviewWidth(int previewWidth){ mPreviewWidth = previewWidth; } void setPreviewHeight(int previewHeight){ mPreviewHeight = previewHeight; } void genSurfaceTexture(); GLuint getSurfaceTexture(); void surfaceTextureAvailable(); }; } #endif //GPUCAMERAVIDEO_CAMERA_H <file_sep>package com.example.cameralibrary.camera import android.os.Handler import android.os.HandlerThread /** * Created by liuxuan on 2018/12/27 */ class CameraHandler(private val handlerThread: HandlerThread): Handler(handlerThread.looper) { companion object { /** * 重载运算符,重载invoke函数,相当于重载CameraHandler(),也就是创建一个CameraHandler实例 */ operator fun invoke(): CameraHandler{ val handlerThread = HandlerThread("CameraImpl") handlerThread.start() return CameraHandler(handlerThread) } } fun postRunnable(runnable: Runnable){ post { runnable.run() } } }<file_sep>// // Created by 刘轩 on 2019/2/5. // #ifndef GPUCAMERAVIDEO_YUVFRAMEBUFFER_H #define GPUCAMERAVIDEO_YUVFRAMEBUFFER_H #include <FrameBuffer.h> #include <Rotation.hpp> #include <MediaBuffer.hpp> #include <GLProgram.h> namespace GCVBase { class YUVFrameBuffer { public: YUVFrameBuffer(int mFrameWidth = 0,int mFrameHeight = 0); ~YUVFrameBuffer(); MediaBuffer<FrameBuffer *> * fboBuffer = nullptr; FrameBuffer * getyuv420Framebuffer(GLuint luma, GLuint cb, GLuint cr); MediaBuffer<FrameBuffer *> * decodeYUVBuffer(MediaBuffer<uint8_t *> *videoBuffer); private: int mFrameWidth = 0; int mFrameHeight = 0; FrameBuffer *mTextureY = nullptr; FrameBuffer *mTextureCb = nullptr; FrameBuffer *mTextureCr = nullptr; FrameBuffer *mYUVFramebuffer = nullptr; GLProgram *mYUVfboProgram; GLuint mYUVPositionAttribute; GLuint mYUVTexCoordAttribute; GLuint mYUVLuminanceTextureUniform; GLuint mYUVCbTextureUniform; GLuint mYUVCrTextureUniform; GLuint mYUVMatrixUniform; //yuv数据 char *yBuffer; size_t yBufferSize; char *uBuffer; char *vBuffer; size_t uvBufferSize; //uv大小是一致的 bool checkUpdateFrameBuffer(MediaBuffer<uint8_t *> *videoBuffer); }; } #endif //GPUCAMERAVIDEO_YUVFRAMEBUFFER_H <file_sep>// // Created by 刘轩 on 2019/1/27. // #ifndef GPUCAMERAVIDEO_FILTER_H #define GPUCAMERAVIDEO_FILTER_H #include <string> #include "Rotation.hpp" #include "Time.hpp" #include "GLProgram.h" #include "FrameBuffer.h" namespace GCVBase { class Filter { public: Filter(int width, int height); Filter(const std::string & vertexShader, const std::string & fragmentShader, int width, int height); ~Filter(); void setPreviousFramebuffer(FrameBuffer *framebuffer); void newFrameReadyAtTime(); private: GLuint aPositionAttribute = 0; GLuint aTexCoordAttribute = 0; GLuint uTextureuniform = 0; int mFilterWidth; int mFilterHeight; GLProgram * mFilterProgram = NULL; FrameBuffer *mFilterFramebuffer = NULL; }; } #endif //GPUCAMERAVIDEO_FILTER_H <file_sep>// // Created by 刘轩 on 2018/12/24. // #include <android/log.h> #include "Context.h" GCVBase::Context * GCVBase::Context::mShareContext = nullptr; GCVBase::Context::Context(JNIEnv *env, std::string looperName) { mContextLooper = new Looper(looperName); env->GetJavaVM(&mContextJavaVM); mContextLooper->addMessageSync([=]{ int result = mContextJavaVM->GetEnv((void **)&mContextEnv, JNI_VERSION_1_6); if (result == JNI_EDETACHED) { /* JNIEnv指针仅在创建它的线程有效。如果我们需要在其他线程访问JVM,那么必须先调用AttachCurrentThread将 * 当前线程与JVM进行关联,然后才能获得JNIEnv对象。当然,我们在必要时需要调用DetachCurrentThread来解除链接。 */ if (mContextJavaVM->AttachCurrentThread(&mContextEnv, nullptr) != 0) { // TODO 报错 "Failed to attach"; } } else if (result == JNI_OK) { // TODO 提示成功 } else if (result == JNI_EVERSION) { // TODO 报错 "GetEnv: version not supported"; } }); } GCVBase::Context::~Context() { if(mContextLooper->isCurrentThread()){ delete mEglInstance; } else{ mContextLooper->addMessageAsync([=]{ delete mEglInstance; }); } delete mContextLooper; } void GCVBase::Context::setNativeWindow(ANativeWindow *window) { if(!window){ //TODO 报错 } // 这里要做线程转换,因为 setNativeWindow 函数是在 SurfaceHolder.Callback 线程中的 runSyncContextLooper(Context::getShareContext()->getContextLooper(), [&]{ mEglInstance = new EglCore(NULL, window, 0, 0); //这里我们是设置Native层的window,shareContext直接置空就可以了 }); } void GCVBase::Context::setEglInstance(GCVBase::EglCore *eglInstance) { if(!eglInstance){ // TODO 报错 } mEglInstance = eglInstance; } GCVBase::EglCore *GCVBase::Context::getEglInstance() { return mEglInstance; } JNIEnv *GCVBase::Context::getEnv() const { if(!mContextLooper->isCurrentThread()){ // TODO 报错并提示 } return mContextEnv; } void GCVBase::Context::initSharedContext(JNIEnv *env) { static std::once_flag flag; std::call_once(flag, [=]{ mShareContext = new Context(env, "mainLooper"); }); } GCVBase::Context *GCVBase::Context::getShareContext() { return mShareContext; } GCVBase::Looper *GCVBase::Context::getContextLooper() { return mContextLooper; } void GCVBase::Context::makeShareContextAsCurrent() { Context * shareContext = Context::getShareContext(); EglCore * shareEglContext = shareContext->getEglInstance(); if(!shareEglContext->isCurrentContext()){ shareEglContext->makeAsCurrent(); } } void GCVBase::Context::useAsCurrentContext() { EglCore * mEglContext = getEglInstance(); if(!mEglContext->isCurrentContext()){ mEglContext->makeAsCurrent(); } } /** * 一个Context对应一个Looper,一个Looper对应一个线程,因此这个函数的作用是往不同Looper对应线程的MessageQueue中添加任务 * * @param mLooper 需要将任务添加到哪个Looper中,这个Looper可以使Context中的Looper,也可以是单独new出来的Looper * @param function 需要执行的任务,一般传进来的多是Lamda表达式 */ void GCVBase::runSyncContextLooper(Looper * mLooper, const std::function<void()> &function) { if(mLooper->isCurrentThread()){ function(); } else{ mLooper->addMessageSync(function); } } void GCVBase::runAsyncContextLooper(Looper * mLooper, const std::function<void()> &function) { if(mLooper->isCurrentThread()){ function(); } else{ mLooper->addMessageAsync(function); } } <file_sep># GPUCameraVideo An Android video editor that includes video recording, cropping, adding BGM, whitening, adding filters, watermarking, and more. <file_sep>// // Created by 刘轩 on 2019/1/7. // #include "DisplayView.h" std::string displayVertexShader = "attribute vec4 aPosition;\n" "attribute vec4 aTexCoord;\n" "varying vec2 vTexCoord;\n" "void main() {\n" " gl_Position = aPosition;\n" " vTexCoord = aTexCoord.xy;\n" "}\n"; std::string displayFragmentShader = "precision mediump float;\n" "varying vec2 vTexCoord;\n" "uniform sampler2D uTexture;\n" "void main() {\n" " gl_FragColor = texture2D(uTexture, vTexCoord);\n" "}\n"; GCVBase::DisplayView::DisplayView(int width, int height) { mDisplayWidth = width; mDisplayHeight = height; runSyncContextLooper(Context::getShareContext()->getContextLooper(), [=]{ Context::makeShareContextAsCurrent(); mDisplayProgram = new GLProgram(displayVertexShader, displayFragmentShader); if(!mDisplayProgram->isProgramLinked()){ if(!mDisplayProgram->linkProgram()){ // TODO 获取program连接日志` } } aPositionAttribute = mDisplayProgram->getAttributeIndex("aPosition"); aTexCoordAttribute = mDisplayProgram->getAttributeIndex("aTexCoord"); uTextureuniform = mDisplayProgram->getuniformIndex("uTexture"); }); } GCVBase::DisplayView::~DisplayView() { delete mDisplayProgram; delete mOutputDisplayFramebuffer; //作为最终的展示窗口,DisplayView有义务销毁外部绘制链传入的fbo对象 } void GCVBase::DisplayView::_newFrameReadyAtTime() { if (!mOutputDisplayFramebuffer) { return; } runSyncContextLooper(Context::getShareContext()->getContextLooper(), [=]{ Context::makeShareContextAsCurrent(); mDisplayProgram->useProgram(); glViewport(0, 0, mDisplayWidth, mDisplayHeight); glEnableVertexAttribArray(aPositionAttribute); glEnableVertexAttribArray(aTexCoordAttribute); glClearColor(0, 0, 0, 0); glClear(GL_COLOR_BUFFER_BIT); /** * 必须在这一步之前解绑 mOutputDisplayFramebuffer 的帧缓冲 */ glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, mOutputDisplayFramebuffer->texture()); static const GLfloat vertices[] = { -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 1.0f, }; //static变量只会初始化一次,也就是说这个texCoord如果是static那么这个方法只会被调用一次!!! const GLfloat * texCoord = CalculateDisplayRotation(rotationDisplayView); glUniform1i(uTextureuniform, 1); glVertexAttribPointer(aPositionAttribute, 2, GL_FLOAT, 0, 0, vertices); glVertexAttribPointer(aTexCoordAttribute, 2, GL_FLOAT, 0, 0, texCoord); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); Context::getShareContext()->getEglInstance()->swapToScreen(); glDisableVertexAttribArray(aPositionAttribute); glDisableVertexAttribArray(aTexCoordAttribute); }); } void GCVBase::DisplayView::_setOutputFramebuffer(GCVBase::FrameBuffer *framebuffer) { mOutputDisplayFramebuffer = framebuffer; } void GCVBase::DisplayView::_setOutputRotation(const GCVBase::Rotation &rotation) { rotationDisplayView = rotation; } <file_sep>// // Created by 刘轩 on 2018/12/22. // #ifndef GPUCAMERAVIDEO_MESSAGEQUEUE_H #define GPUCAMERAVIDEO_MESSAGEQUEUE_H #include "Message.h" namespace GCVBase { /** * 每一个线程持有一个Looper,每个Looper持有一个MessageQueue对象, * Message由MessageQueue管理,而MessageQueue由Looper管理,因此Looper不直接持有Message的引用 * * MessageQueue类主要用于维护一个Message链表组成的消息队列,包括出队、入队、循环遍历等操作: * 1.mLooperName 主要标识该MessageQueue所在的Looper名称 * 2.mMessageQueueName 主要用于标识messageQueue中的message * 3.queueHead 指针用于表示这个MessageQueue中Message链表的头结点 */ class MessageQueue { private: std::string mLooperName; std::string mMessageQueueName; Message * queueHead = NULL; public: MessageQueue(std::string looperName, std::string messageQueueName); //这两个参数是必须指定的 ~MessageQueue(); void setMessageQueueName(std::string messageQueueName); std::string getMessageQueueName(); void addMessage(Message * message); bool isMessageQueueEmpty(); Message * getNextMessage(); //获得消息队列中下一个Message对象,并从链表中删除 void recycleMessage(Message * message); //用于处理完Message中的内容后回收并缓存Message对象 void recycleAllMessage(); }; } #endif //GPUCAMERAVIDEO_MESSAGEQUEUE_H <file_sep>package com.example.filterlibrary.effects import com.example.filterlibrary.Filter import java.util.logging.LogRecord /** * Created by liuxuan on 2019/1/29 */ class ColorFilter : Filter() { companion object { private val kFilterVertex: String = "attribute vec4 aPosition;\n" + "attribute vec4 aTexCoord;\n" + "varying vec2 vTexCoord;\n" + "void main() {\n" + " gl_Position = aPosition;\n" + " vTexCoord = aTexCoord.xy;\n" + "}\n" private val kColorFilterFragment: String = "varying highp vec2 vTexCoord;\n" + "uniform sampler2D uTexture;\n" + "void main() {\n" + " vec4 color = texture2D(uTexture, vTexCoord);\n" + " gl_FragColor = vec4(1.0 -color.rgb, color.a);" + "}" } override fun getVertexShader(): String { return kFilterVertex } override fun getFragmentShader(): String { return kColorFilterFragment } }<file_sep>// // Created by 刘轩 on 2018/12/18. // #include <jni.h> #include "camera.h" using namespace GCVBase; extern "C" { jlong Java_com_example_cameralibrary_camera_Camera_nativeCameraInit(JNIEnv *env, jobject obj, jint mFacing) { Camera * camera = new Camera(mFacing); // TODO 需要用智能指针替换之 return (jlong) camera; } void Java_com_example_cameralibrary_camera_Camera_nativeChangeCameraFacing(JNIEnv *env, jobject obj, jlong nativeCamera, jint mFacing) { Camera * camera = (Camera *) nativeCamera; camera->facingChanged(mFacing); } void Java_com_example_cameralibrary_camera_Camera_nativeChangeCamerOrientation(JNIEnv *env, jobject obj, jlong nativeCamera, jint orientation) { Camera * camera = (Camera *) nativeCamera; camera->orientationChanged(orientation); } } <file_sep>// // Created by 刘轩 on 2019/2/5. // #ifndef GPUCAMERAVIDEO_MEDIADECODER_H #define GPUCAMERAVIDEO_MEDIADECODER_H #include <string> #include <media/NdkMediaCodec.h> #include <media/NdkMediaExtractor.h> #include <MediaBuffer.hpp> #include <FrameBuffer.h> #include "YUVFrameBuffer.h" namespace GCVBase { class MediaDecoder { public: MediaDecoder(const std::string &filePath, ANativeWindow * nativeWindow = nullptr); ~MediaDecoder(); void setFilePath(const std::string &readPath); void setNativeSurface(ANativeWindow * nativeWindow); MediaBuffer<uint8_t *> * decodeNewFrameAudio(); //音频数据 MediaBuffer<FrameBuffer *> * decodeNewFrameVideo(); //视频数据 MediaBuffer<uint8_t *> * getCodecFrameVideoBuffer(); bool decodingIsFinished() const { return mIsFinished; }; bool decodIsSurfacePlayer() const { return mIsSurfacePlayer; } private: std::string mFilePath; uint8_t * outputBuffer; ANativeWindow *mNativeWindow; AMediaExtractor *videoEx; AMediaExtractor *audioEx; AMediaCodec *mVideoDecodeCodec = NULL; AMediaCodec *mAudioDecodeCodec = NULL; YUVFrameBuffer * yuvFrameBuffer = NULL; MediaBuffer<uint8_t *> * frameAudioBuffer = NULL; MediaBuffer<uint8_t *> * frameVideoBuffer = NULL; int64_t renderStartTime = -1; //开始渲染时间,用来控制播放速率 bool mIsSurfacePlayer = false; // 是否使用surface直接作为输出(不用gl合成) bool mIsFinished = false; bool sawInput = false; //输入流是否结束 bool sawOutput = false; //输出流是否结束 bool loadFile(); bool initVideoCodec(ANativeWindow * nativeWindow = nullptr); bool initAudioCodec(); }; } #endif //GPUCAMERAVIDEO_MEDIADECODER_H <file_sep>// // Created by 刘轩 on 2018/12/24. // #ifndef GPUCAMERAVIDEO_CONTEXT_H #define GPUCAMERAVIDEO_CONTEXT_H #include <Looper.h> #include <EglCore.h> #include <jni.h> namespace GCVBase { class Context { private: JNIEnv *mContextEnv = NULL; JavaVM *mContextJavaVM = NULL; EglCore * mEglInstance = NULL; Looper * mContextLooper = NULL; static Context * mShareContext; public: Context(JNIEnv *env, std::string looperName); ~Context(); Looper *getContextLooper(); void setNativeWindow(ANativeWindow * window); void setEglInstance(EglCore * eglInstance); EglCore * getEglInstance(); void useAsCurrentContext(); JNIEnv * getEnv() const; static void makeShareContextAsCurrent(); static void initSharedContext(JNIEnv * env); static Context * getShareContext(); }; extern "C"{ void runSyncContextLooper(Looper * mLooper, const std::function<void()> &function); void runAsyncContextLooper(Looper * mLooper, const std::function<void()> &function); } } #endif //GPUCAMERAVIDEO_CONTEXT_H <file_sep>package com.example.cameralibrary.camera /** * Created by liuxuan on 2018/12/28 */ class CameraSizeCalculator(private val sizes: Array<CameraSize>) { fun findBestPreviewSize(target: CameraSize): CameraSize { sizes.sort() //支持的预览尺寸从小到大排列 var bestSize = sizes.last() //在宽高比一定的情况下,拍摄帧往往选择尺寸最大的,那样拍摄的图片更清楚 var bestArea = Int.MAX_VALUE sizes.forEach { //从选定的长宽比支持的尺寸中,找到长和宽都大于或等于预览控件尺寸的,若是小于预览控件的宽高则会导致图像被拉伸了。 if (it.mWidth >= target.mWidth && it.mHeight >= target.mHeight && it.getArea() < bestArea) { bestSize = it bestArea = it.getArea() } } return bestSize } }<file_sep>package com.example.baselib /** * Created by liuxuan on 2019/1/7 */ open class GCVInput { protected var inputObjectAdress: Long = 0L fun addTarget(output: GCVOutput){ if(inputObjectAdress == 0L){ throw Exception("nativeOutput == 0") } nativeAddTarget(inputObjectAdress, output.nativeOutput()) } fun removeTarget(output: GCVOutput){ if(inputObjectAdress == 0L){ throw Exception("nativeOutput == 0") } nativeRemoveTarget(inputObjectAdress, output.nativeOutput()) } private external fun nativeAddTarget(input: Long, output: Long) private external fun nativeRemoveTarget(input: Long, output: Long) }<file_sep>// // Created by 刘轩 on 2019/1/27. // #include "FilterGroup.h" GCVBase::FilterGroup::FilterGroup() { } GCVBase::FilterGroup::~FilterGroup() { } void GCVBase::FilterGroup::_newFrameReadyAtTime() { if(mOutputFilterGroupFramebuffer == nullptr){ return; } //逐个绘制Filter到 mOutputFilterGroupFramebuffer中的Texture上 if(!mFilterGroup.empty()) { for (auto i = mFilterGroup.begin(); i < mFilterGroup.end(); i++) { auto currentFilter = *i; currentFilter->setPreviousFramebuffer(mOutputFilterGroupFramebuffer); currentFilter->newFrameReadyAtTime(); } } for(auto i = mTargets.begin(); i < mTargets.end(); i++){ auto currentTarget = * i; currentTarget->_setOutputRotation(rotationFilterGroup); currentTarget->_setOutputFramebuffer(mOutputFilterGroupFramebuffer); currentTarget->_newFrameReadyAtTime(); } } void GCVBase::FilterGroup::_setOutputRotation(const GCVBase::Rotation &mRotation) { rotationFilterGroup = mRotation; } void GCVBase::FilterGroup::_setOutputFramebuffer(GCVBase::FrameBuffer *framebuffer) { mOutputFilterGroupFramebuffer = framebuffer; } void GCVBase::FilterGroup::addFilter(GCVBase::Filter *filter) { runSyncContextLooper(Context::getShareContext()->getContextLooper(),[=]{ mFilterGroup.push_back(filter); }); } void GCVBase::FilterGroup::removeFilter(GCVBase::Filter *filter) { } <file_sep>package com.example.mat.gpucameravideo import android.Manifest import android.content.pm.PackageManager import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.os.Environment import android.support.design.widget.FloatingActionButton import android.support.v4.app.ActivityCompat import android.support.v4.content.PermissionChecker import android.support.v7.widget.Toolbar import android.util.Log import android.view.Menu import android.view.MenuItem import android.view.View import com.example.cameralibrary.camera.CameraParam import com.example.cameralibrary.preview.Preview import com.example.cameralibrary.preview.Preview.PreviewLifeListener import com.example.cameralibrary.preview.Preview.PreviewDataListener import com.example.codeclibrary.MovieRecorder import com.example.filterlibrary.FilterGroup import com.example.filterlibrary.effects.BlackFilter import com.example.filterlibrary.effects.ColorFilter import java.nio.ByteBuffer class MainActivity : AppCompatActivity(), PreviewLifeListener, PreviewDataListener, View.OnClickListener { private var preview: Preview? = null private var movieRecorder: MovieRecorder? = null private var mFilterGroup: FilterGroup? = null private val FLASH_OPTIONS = intArrayOf(Preview.FLASH_AUTO, Preview.FLASH_OFF, Preview.FLASH_ON) private val FLASH_ICONS = intArrayOf(R.drawable.ic_flash_auto, R.drawable.ic_flash_off, R.drawable.ic_flash_on) private val FLASH_TITLES = intArrayOf(R.string.flash_auto, R.string.flash_off, R.string.flash_on) private val filePath = Environment.getExternalStorageDirectory().path + "/test" private val savePath = filePath + System.currentTimeMillis() + ".mp4" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) preview = findViewById(R.id.cameraview) preview?.addPreviewLifeListener(this) //设置PreView生命周期监听 preview?.addPreviewDataListener(this) //设置Preview数据监听,获取拍照后的数据和预览数据 val toolbar = findViewById<View>(R.id.toolbar) as Toolbar setSupportActionBar(toolbar) val actionBar = supportActionBar actionBar?.setDisplayShowTitleEnabled(false) val pictureButton = findViewById<FloatingActionButton>(R.id.take_picture) pictureButton.setOnClickListener(this) if (PermissionChecker.checkSelfPermission(this@MainActivity, Manifest.permission.CAMERA) == PackageManager.PERMISSION_DENIED) { ActivityCompat.requestPermissions(this@MainActivity, arrayOf(Manifest.permission.CAMERA), 100) } if (PermissionChecker.checkSelfPermission(this@MainActivity, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) { ActivityCompat.requestPermissions(this@MainActivity, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), 100) } } /**************************************** Preview的生命周期 *****************************************/ override fun onPreviewCreated() { //对应onSurfaceCreate } override fun onPreviewChanged(width: Int, height: Int) { //对应onSurfaceChange TODO 这里还应该回调Camera支持的颜色格式 movieRecorder = MovieRecorder(savePath, width, height, (width * height * 6.51).toLong(), 0) } override fun onPreviewReady() { //对应 startPreview 成功 mFilterGroup = FilterGroup().apply { // addFilter(BlackFilter()) // addFilter(ColorFilter()) } preview?.setFilterGroup(mFilterGroup!!) } override fun onPreviewDestory() { //对应onSurfaceDestory movieRecorder?.onSurfaceDestory() } /****************************************************************************************************/ /**************************************** Preview的数据回调 *****************************************/ override fun onPreviewFrame(previewFrameData: ByteBuffer) { //每一帧预览的数据 } override fun onPictureTaken(cameraPictureData: ByteBuffer) { //拍照后的图片数据 Log.e("onPictureTaken", cameraPictureData.long.toString()) } /****************************************************************************************************/ override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.main, menu) return true } override fun onOptionsItemSelected(item: MenuItem?): Boolean { when(item?.itemId){ R.id.aspect_ratio -> { preview?.setRecorder(movieRecorder!!) movieRecorder?.startRecorder() return true } R.id.switch_flash -> { movieRecorder?.finishRecorder() return true } R.id.switch_camera -> { val facing = preview?.getFacing() preview?.setFacing( if (facing == CameraParam.FACING_FRONT) CameraParam.FACING_BACK else CameraParam.FACING_FRONT ) return true } } return super.onOptionsItemSelected(item) } override fun onClick(v: View?) { when(v?.id){ R.id.take_picture -> { preview?.takePicture() } } } /** * 在Activity的生命周期中,对SurfaceView的可见性进行设置,触发surfaceView的生命周期变化(surfaceView在可见时, * 会执行surfaceCreated方法,不可见时会自动销毁,执行surfaceDestroyed方法),从而更好的管理Camera的生命周期, * 在相机不可见时释放相机资源 */ override fun onResume() { super.onResume() preview?.getView()?.visibility = View.VISIBLE } override fun onPause() { super.onPause() preview?.getView()?.visibility = View.INVISIBLE } companion object { init { System.loadLibrary("codec-lib") System.loadLibrary("yuv") } } } <file_sep>// // Created by 刘轩 on 2018/12/30. // #include "FrameBuffer.h" GCVBase::FrameBuffer::FrameBuffer(const GCVBase::Size &size, const GCVBase::TextureOptions &options, GCVBase::Context *context) { mSize = size; mTextureOptions = options; mContext = context; runSyncContextLooper(mContext->getContextLooper(),[=]{ mContext->useAsCurrentContext(); glGenTextures(1, &mTexture); mTextureOptions.bindTexture(GL_TEXTURE_2D, mTexture); glTexImage2D(GL_TEXTURE_2D, 0, mTextureOptions.internalFormat, mSize.width, mSize.height, 0, mTextureOptions.format, mTextureOptions.type, NULL); glGenFramebuffers(1, &mFrameBuffer); glBindFramebuffer(GL_FRAMEBUFFER, mFrameBuffer); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, mTexture, 0); GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER); if(status != GL_FRAMEBUFFER_COMPLETE){ // TODO 报错 return; } glBindTexture(GL_TEXTURE_2D, 0); glBindFramebuffer(GL_FRAMEBUFFER, 0); }); } void GCVBase::FrameBuffer::bindFramebuffer() { glBindFramebuffer(GL_FRAMEBUFFER, mFrameBuffer); glViewport(0, 0, mSize.width, mSize.height); } void GCVBase::FrameBuffer::unbindFramebuffer() { /* * 由于我们的帧缓冲不是默认的帧缓冲,渲染命令对窗口的视频输出不会产生任何影响。出于这个原因,它被称为离屏渲染,就 * 是渲染到一个另外的缓冲中。为了后续让所有的渲染操作对主窗口产生影响我们必须通过绑定为0来使 "默认帧缓冲" 被激活 */ glBindFramebuffer(GL_FRAMEBUFFER, 0); } const GCVBase::TextureOptions &GCVBase::FrameBuffer::textureOptions() const { return mTextureOptions; } const GCVBase::Context *GCVBase::FrameBuffer::context() const { return mContext; } int GCVBase::FrameBuffer::framebuffer() const { return mFrameBuffer; } GLuint GCVBase::FrameBuffer::texture() const { return mTexture; } <file_sep>include ':app', ':camera', ':filter', ':codec', ':image', ':base', ':baselib' <file_sep>// // Created by 刘轩 on 2019/1/8. // #ifndef GPUCAMERAVIDEO_MATH_H #define GPUCAMERAVIDEO_MATH_H namespace GCVBase{ union Vec2{ struct{ float x; float y; }; struct{ float width; float height; }; Vec2(float mx, float my){ x = mx; y = my; } static const Vec2 & zero(){ static const Vec2 zero(0,0); return zero; } bool isZero() const { return *this == zero(); } float size() const { return width * height; } bool operator == (const Vec2 & vec2) const { return (x == vec2.x && y == vec2.y); } }; typedef Vec2 Size; /* * 以下两个函数均来源于 LIUNX include/linux/kernel.h文件中的 ALIGN宏,主要用于内存对齐: */ /* * 计算n以size为倍数的上界数(上进): * 举个例子4k页面边界的例子,即size=4096: 如果n = 3888;那么以上界对齐,执行结果就是4096。 * 如果n = 4096;结果是4096. 如果n = 4222; 则结果为8192. */ static inline unsigned long alignment_up(unsigned long n,unsigned int size) { return ((n + size - 1) & (~(size - 1))); } /* * 计算n以size为倍数的下界数(丢弃): * size=4096: 若n = 3888; 结果为0. 如果n = 4096;结果是4096. 如果n = 4222; 则结果为4096. */ static inline unsigned long alignment_down(unsigned long n,unsigned int size) { return (n & (~(size - 1))); } } #endif //GPUCAMERAVIDEO_MATH_H <file_sep>package com.example.cameralibrary.preview.surfaceview import android.graphics.SurfaceTexture import android.view.SurfaceHolder import com.example.cameralibrary.camera.Camera import com.example.cameralibrary.preview.PreviewImpl.SurfaceListener /** * Created by liuxuan on 2019/1/2 */ class SurfaceCallback(camera: Camera, surfaceListener: SurfaceListener) : SurfaceHolder.Callback{ private val mCamera : Camera = camera private var surfaceTexture: SurfaceTexture? = null private val mSurfaceChangedListener = surfaceListener private var nativeTextureId: Int = 0 private var nativeOutputSurfaceAddress: Long = 0 private var nativeInputCameraAddress: Long = 0 private fun genTexture(textureCallback : (nativeCamera: Long, surfaceTexture: Int) -> Unit){ nativeInputCameraAddress = mCamera.creatNativeCamera() nativeTextureId = nativeGenTexture(nativeInputCameraAddress) textureCallback(nativeInputCameraAddress, nativeTextureId) } override fun surfaceCreated(holder: SurfaceHolder?) { if(holder != null) { nativeOutputSurfaceAddress = nativeSurfaceWindowInit(holder.surface) //初始化native层egl的surface表面 } mSurfaceChangedListener.onSurfaceCreated(nativeOutputSurfaceAddress) genTexture { nativeCamera, surfaceTexture -> this.surfaceTexture = SurfaceTexture(surfaceTexture) this.surfaceTexture?.setOnFrameAvailableListener{ onSurfaceTextureAvailable(nativeCamera) it.updateTexImage() surfaceTextureAvailable(nativeCamera) } } } override fun surfaceChanged(holder: SurfaceHolder?, format: Int, width: Int, height: Int) { nativeOnSurfaceChanged(nativeInputCameraAddress, width, height) mSurfaceChangedListener.onSurfaceChanged(surfaceTexture, width, height) } override fun surfaceDestroyed(holder: SurfaceHolder?) { mSurfaceChangedListener.onSurfaceDestory() } private external fun onSurfaceTextureAvailable(nativeCameraAddress: Long) private external fun surfaceTextureAvailable(nativeCameraAddress: Long) private external fun nativeOnSurfaceChanged(nativeCameraAddress: Long, width: Int, height: Int) private external fun nativeSurfaceWindowInit(surface: Any): Long private external fun nativeGenTexture(nativeCameraAddress: Long) : Int }<file_sep>// // Created by 刘轩 on 2019/1/11. // #ifndef GPUCAMERAVIDEO_ENCODERCONFIGURATION_H #define GPUCAMERAVIDEO_ENCODERCONFIGURATION_H #include <string> #include <Size.hpp> #include "MediaBuffer.hpp" namespace GCVBase { class EncoderConfig { public: int frameRate = 30; int outputOrientation = 0; int colorYUVFormat = 0; int bitRateMode = -1; int sampleRate = 44100; unsigned long videoBitRate = 0; unsigned long audioBitRate = 6400; Size outputSize = Size::zero(); std::string outputPath; AudioChannel audioChannel = DOUBLE; //双声道 SampleFormat sampleFormat = S16; //有符号16位 int getChannelCount() const { return GCVBase::getChannelCount(audioChannel); } void setOutputSize(Size size){ int newWidth = (int)(ceilf(size.width / 16) * 16); int newHeight = (int)(ceilf(size.height / 16) * 16); outputSize = Size(newWidth, newHeight); } Size getOutputSize(){ return outputSize; } }; } #endif //GPUCAMERAVIDEO_ENCODERCONFIGURATION_H <file_sep>package com.example.filterlibrary import com.example.baselib.GCVInput import com.example.baselib.GCVOutput /** * Created by liuxuan on 2019/1/27 */ class FilterGroup : GCVInput(), GCVOutput{ var filterGroupAddress: Long = 0L init { filterGroupAddress = nativeFilterGroupInit() inputObjectAdress = filterGroupAddress } override fun nativeOutput(): Long { return filterGroupAddress } fun addFilter(filter: Filter){ nativeFilterGroupAddFilter(filterGroupAddress, filter.getNativeFilterAdress()) } fun removeFilter(filter: Filter){ nativeFilterGroupRemoveFilter(filterGroupAddress, filter.getNativeFilterAdress()) } private external fun nativeFilterGroupInit(): Long private external fun nativeFilterGroupAddFilter(filterGroupAddress: Long, nativeFilter: Long) private external fun nativeFilterGroupRemoveFilter(filterGroupAddress: Long, nativeFilter: Long) }<file_sep>// // Created by 刘轩 on 2018/12/20. // #ifndef GPUCAMERAVIDEO_LOOPER_H #define GPUCAMERAVIDEO_LOOPER_H #include "MessageQueue.h" #include "Function.h" namespace GCVBase { class Looper { private: std::string mLooperName; std::thread::id threadId; std::mutex mFunctionLock; std::thread * mWorkThread = NULL; ConditionLock *queueConditionLock = NULL; MessageQueue * mMessageQueue; bool mQuit = false; void loop(); void runFunctionInLock(const std::function<void()> &function); public: Looper(const std::string &name); ~Looper(); std::string getLooperName(); void addMessageAsync(const std::function<void()> &function); void addMessageSync(const std::function<void()> &function); void addMessage(const std::function<void()> &function, bool async); bool isCurrentThread(){ return std::this_thread::get_id() == mWorkThread->get_id(); } }; } #endif //GPUCAMERAVIDEO_LOOPER_H <file_sep>// // Created by 刘轩 on 2018/12/27. // #include <thread> #include "GLProgram.h" GCVBase::GLProgram::GLProgram(const std::string &vertexShaderString, const std::string &fragmentShaderString) { mProgram = glCreateProgram(); if(!compileShader(&mVertShader, GL_VERTEX_SHADER, vertexShaderString)){ // TODO 上报顶点着色器编译错误 } if(!compileShader(&mFragShader, GL_FRAGMENT_SHADER, fragmentShaderString)){ // TODO 上报片段着色器编译错误 } glAttachShader(mProgram, mVertShader); glAttachShader(mProgram, mFragShader); } bool GCVBase::GLProgram::compileShader(GLuint *shader, GLenum type, const std::string &shaderString) { *shader = glCreateShader(type); if(*shader == 0){ GLenum err = glGetError(); } const GLchar *source = shaderString.c_str(); glShaderSource(*shader, 1, &source, NULL); glCompileShader(*shader); GLint compileSatuts; glGetShaderiv(*shader, GL_COMPILE_STATUS, &compileSatuts); //查询编译成功与否的信息 if(compileSatuts != GL_TRUE){ GLint compileLogLength = 0; glGetShaderiv(*shader, GL_INFO_LOG_LENGTH, &compileLogLength); //查询编译日志长度 if(compileLogLength>0){ GLchar *compileLog = new GLchar[compileLogLength]; glGetShaderInfoLog(*shader, compileLogLength, &compileLogLength, compileLog); char logBuffer[compileLogLength]; sprintf(logBuffer,"%s", compileLog); if (*shader == mVertShader) { mVertexCompileLog = logBuffer; } else { mFragmentCompileLog = logBuffer; } delete [] compileLog; } return false; } return true; } bool GCVBase::GLProgram::linkProgram() { glLinkProgram(mProgram); GLint linkStatus; glGetProgramiv(mProgram, GL_LINK_STATUS, &linkStatus); if (linkStatus == GL_FALSE) { GLint linkLogLength; glGetProgramiv(mProgram, GL_INFO_LOG_LENGTH, &linkLogLength); if (linkLogLength > 0) { GLchar *log = new GLchar[linkLogLength]; glGetProgramInfoLog(mProgram, linkLogLength, &linkLogLength, log); char logBuffer[linkLogLength]; sprintf(logBuffer,"%s", log); mProgramLinkLog = logBuffer; delete [] log; } return false; } isLinked = true; return true; } GLuint GCVBase::GLProgram::getuniformIndex(const std::string &uniformName) { return (GLuint) glGetUniformLocation(mProgram, uniformName.c_str()); } GLuint GCVBase::GLProgram::getAttributeIndex(const std::string &attribute) { return (GLuint) glGetAttribLocation(mProgram, attribute.c_str()); } void GCVBase::GLProgram::useProgram() { glUseProgram(mProgram); } <file_sep>// // Created by 刘轩 on 2019/1/7. // #ifndef GPUCAMERAVIDEO_NATIVEINPUT_H #define GPUCAMERAVIDEO_NATIVEINPUT_H #include <vector> #include "NativeOutput.h" #include "FrameBuffer.h" namespace GCVBase { class NativeInput { protected: std::vector<NativeOutput *> mTargets; //这里已经创建了一个 std::vector<NativeOutput *> 对象 FrameBuffer * mOutputFrameBuffer = NULL; // TODO FrameBuffer引用需要优化为智能指针 TextureOptions mOutputTextureOptions; public: virtual FrameBuffer * getOutputFrameBuffer(); virtual void removeOutputFrameBuffer(); virtual void addTarget(NativeOutput *newTarget); virtual const std::vector<const NativeOutput * > & getTargets(); virtual void removeTarget(NativeOutput *target); virtual void removeAllTargets(); }; } #endif //GPUCAMERAVIDEO_NATIVEINPUT_H <file_sep>// // Created by 刘轩 on 2019/1/27. // #ifndef GPUCAMERAVIDEO_FILTERGROUP_H #define GPUCAMERAVIDEO_FILTERGROUP_H #include "NativeInput.h" #include "Filter.h" namespace GCVBase { /** * 这个NativeOutput 其实就相当于Java中的接口,我们在其中只写了很多抽象方法 */ class FilterGroup: NativeInput, NativeOutput { public: FilterGroup(); ~FilterGroup(); void addFilter(Filter * filter); void removeFilter(Filter * filter); void _setOutputRotation(const Rotation &rotation) override; void _setOutputFramebuffer(FrameBuffer *framebuffer) override; void _newFrameReadyAtTime() override; private: Rotation rotationFilterGroup = Rotation::defaultRotation(); std::vector<Filter * > mFilterGroup; FrameBuffer *mOutputFilterGroupFramebuffer = nullptr; }; } #endif //GPUCAMERAVIDEO_FILTERGROUP_H <file_sep>// // Created by 刘轩 on 2019/1/8. // #ifndef GPUCAMERAVIDEO_TEXTUREOPTIONS_H #define GPUCAMERAVIDEO_TEXTUREOPTIONS_H #include <GLES2/gl2.h> namespace GCVBase{ typedef struct OptionTexture { GLenum minFilter = GL_LINEAR; GLenum maxFilter = GL_LINEAR; GLenum wrapS = GL_CLAMP_TO_EDGE; GLenum wrapT = GL_CLAMP_TO_EDGE; GLenum internalFormat = GL_RGBA; GLenum format = GL_RGBA; GLenum type = GL_UNSIGNED_BYTE; void bindTexture(GLenum target, GLuint texture){ glBindTexture(target, texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, minFilter); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, maxFilter); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapS); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapT); } } TextureOptions; } #endif //GPUCAMERAVIDEO_TEXTUREOPTIONS_H <file_sep>// // Created by 刘轩 on 2019/1/8. // #include <jni.h> #include <NativeOutput.h> #include <NativeInput.h> using namespace GCVBase; extern "C" { void Java_com_example_baselib_GCVInput_nativeAddTarget(JNIEnv *env, jobject obj, jlong inputAddress, jlong outputAddress) { if(inputAddress == NULL){ // TODO 报错 return; } NativeInput * input = (NativeInput *)inputAddress; NativeOutput * output = (NativeOutput *) outputAddress; input->addTarget(output); } void Java_com_example_baselib_GCVInput_nativeRemoveTarget(JNIEnv *env, jobject obj, jlong inputAddress, jlong outputAddress) { if(inputAddress == NULL){ // TODO 报错 return; } NativeInput * input = (NativeInput *)inputAddress; NativeOutput * output = (NativeOutput *) outputAddress; input->removeTarget(output); } } <file_sep>// // Created by 刘轩 on 2018/12/17. // #include "GLContext.hpp" //std::string GLContext::getString(){ // return hello; //} void GLContext::setString() { hello = "hello GLCodecContext"; } <file_sep>// // Created by 刘轩 on 2019/2/5. // #include <android/log.h> #include "YUVFrameBuffer.h" using namespace GCVBase; std::string yuvFrameBufferVertexShader = "attribute vec4 aPosition;\n" "attribute vec4 aTexCoord;\n" "varying vec2 vTexCoord;\n" "void main() {\n" " gl_Position = aPosition;\n" " vTexCoord = aTexCoord.xy;\n" "}\n"; std::string yuvFrameBufferFragmentShader = "varying highp vec2 vTexCoord;\n" "uniform sampler2D luminanceTexture;\n" "uniform sampler2D CbTexture;\n" "uniform sampler2D CrTexture;\n" "uniform mediump mat3 colorConversionMatrix;\n" "void main() {\n" " mediump vec3 yuv;\n" " lowp vec3 rgb;\n" " \n" " yuv.x = (texture2D(luminanceTexture, vTexCoord).r - (16.0 / 255.0));\n" " yuv.y = (texture2D(CbTexture, vTexCoord).r - 0.5);\n" " yuv.z = (texture2D(CrTexture, vTexCoord).r - 0.5);\n" " rgb = colorConversionMatrix * yuv;\n" " gl_FragColor = vec4(rgb, 1);\n" "}\n"; GCVBase::YUVFrameBuffer::YUVFrameBuffer(int frameWidth, int frameHeight) { mFrameWidth = frameWidth; mFrameWidth = frameHeight; fboBuffer = new MediaBuffer<FrameBuffer *>(); runSyncContextLooper(Context::getShareContext()->getContextLooper(), [=] { mYUVfboProgram = new GLProgram(yuvFrameBufferVertexShader, yuvFrameBufferFragmentShader); if(!mYUVfboProgram->isProgramLinked()){ if(!mYUVfboProgram->linkProgram()){ // TODO 获取program连接日志` } } mYUVPositionAttribute = mYUVfboProgram->getAttributeIndex("aPosition"); mYUVTexCoordAttribute = mYUVfboProgram->getAttributeIndex("aTexCoord"); mYUVLuminanceTextureUniform = mYUVfboProgram->getuniformIndex("luminanceTexture"); mYUVCbTextureUniform = mYUVfboProgram->getuniformIndex("CbTexture"); mYUVCrTextureUniform = mYUVfboProgram->getuniformIndex("CrTexture"); mYUVMatrixUniform = mYUVfboProgram->getuniformIndex("colorConversionMatrix"); }); } GCVBase::YUVFrameBuffer::~YUVFrameBuffer() { delete fboBuffer; delete mYUVfboProgram; delete mTextureY; delete mTextureCb; delete mTextureCr; delete mYUVFramebuffer; } /** * 这个函数的作用主要是避免在频繁调用的函数中 new fbo 对象,这里需要用到四张fbo,非常占用内存 */ bool YUVFrameBuffer::checkUpdateFrameBuffer(MediaBuffer<uint8_t *> *videoBuffer) { int width = (int) (videoBuffer->metaData[WidthKey]); int height = (int) (videoBuffer->metaData[HeightKey]); if(mFrameWidth == width && mFrameHeight == height ){ return true; } /** * 否则说明FrameSize发生了改变,需要重建Fbo对象 */ delete mTextureY; delete mTextureCb; delete mTextureCr; delete mYUVFramebuffer; mFrameWidth = width; mFrameHeight = height; TextureOptions options; options.internalFormat = GL_LUMINANCE; options.format = GL_LUMINANCE; //Texture Y Size size(width, height); //这个size对象占用的是栈空间,方法块执行完自动释放 mTextureY = new FrameBuffer(size, options, Context::getShareContext()); //Texture U size = Size(size.width / 2, size.height / 2); mTextureCb = new FrameBuffer(size, options, Context::getShareContext()); //Texture V mTextureCr = new FrameBuffer(size, options, Context::getShareContext()); //YUV最终合成的 rgb Buffer mYUVFramebuffer = new FrameBuffer(size, TextureOptions(), Context::getShareContext()); // TODO 这个FrameBuffer对象也要重点关注!!! return false; } MediaBuffer<FrameBuffer *> *YUVFrameBuffer::decodeYUVBuffer(MediaBuffer<uint8_t *> *videoBuffer) { int width = (int) (videoBuffer->metaData[WidthKey]); int height = (int) (videoBuffer->metaData[HeightKey]); if(!checkUpdateFrameBuffer(videoBuffer)){ //检查FrameSize是否发生变化 __android_log_print(ANDROID_LOG_DEBUG, "checkUpdateFrameBuffer", "yuvFrameBuffer size has changed width == %d height == %d", width, height); } if(videoBuffer->mediaType == MediaType::Video){ int frameSize = width * height; //注意YUV信号是frameSize的3/2大小 char *frame = (char *) videoBuffer->mediaData; yBufferSize = static_cast<size_t>(frameSize); uvBufferSize = static_cast<size_t>(frameSize/4); //u、v各占y信号的1/4大小 yBuffer = (char *) malloc(yBufferSize); uBuffer = (char *) malloc(uvBufferSize); vBuffer = (char *) malloc(uvBufferSize); memset(yBuffer, 0, yBufferSize); memset(uBuffer, 0, uvBufferSize); memset(vBuffer, 0, uvBufferSize); memcpy(yBuffer, frame, yBufferSize); //复制y信号数据 int pixelFormat = (int) videoBuffer->metaData[PixelFormatKey]; int j = 0; switch (pixelFormat) { case 21: { //21代表420sp格式,也就是UV信号相间隔的传过来 for (int i = yBufferSize; i < (yBufferSize + 2 * uvBufferSize);) { uBuffer[j] = frame[i]; //u信号 vBuffer[j] = frame[i + 1]; //v信号 i += 2; j++; } }break; case 19: { //19代表420p格式,UV信号是在最后分两段整体传过来的 for (int i = yBufferSize; i < (yBufferSize + uvBufferSize); i++) { uBuffer[j] = frame[i]; //u信号 vBuffer[j] = frame[yBufferSize + 1]; //v信号 j++; } }break; default: return nullptr; } free(frame); glBindTexture(GL_TEXTURE_2D, mTextureY->texture()); glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, GL_LUMINANCE, GL_UNSIGNED_BYTE, yBuffer); free(yBuffer); yBuffer = nullptr; glBindTexture(GL_TEXTURE_2D, mTextureCb->texture()); glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width / 2, height / 2, GL_LUMINANCE, GL_UNSIGNED_BYTE, uBuffer); free(uBuffer); uBuffer = nullptr; glBindTexture(GL_TEXTURE_2D, mTextureCr->texture()); glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width / 2, height / 2, GL_LUMINANCE, GL_UNSIGNED_BYTE, vBuffer); free(vBuffer); vBuffer = nullptr; fboBuffer->mediaData = getyuv420Framebuffer(mTextureY->texture(), mTextureCb->texture(), mTextureCr->texture()); } if(!fboBuffer->mediaData){ return nullptr; } return fboBuffer; } FrameBuffer *YUVFrameBuffer::getyuv420Framebuffer(GLuint luma, GLuint cb, GLuint cr) { runSyncContextLooper(Context::getShareContext()->getContextLooper(), [&]{ Context::makeShareContextAsCurrent(); mYUVfboProgram -> useProgram(); glEnableVertexAttribArray(mYUVPositionAttribute); glEnableVertexAttribArray(mYUVTexCoordAttribute); glClearColor(0.0f, 1.0f, 0.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); static const GLfloat vertices[] = { -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 1.0f, }; static const GLfloat texCoord[] = { //这里先将纹理向左(逆时针)旋转90°,模仿相机硬件的角度,这样就可以兼容displayView中的旋转角度了 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, }; glVertexAttribPointer(mYUVPositionAttribute, 2, GL_FLOAT, 0, 0, vertices); glVertexAttribPointer(mYUVTexCoordAttribute, 2, GL_FLOAT, 0, 0, texCoord); glActiveTexture(GL_TEXTURE5); glBindTexture(GL_TEXTURE_2D, luma); glUniform1i(mYUVLuminanceTextureUniform, 5); glActiveTexture(GL_TEXTURE6); glBindTexture(GL_TEXTURE_2D, cb); glUniform1i(mYUVCbTextureUniform, 6); glActiveTexture(GL_TEXTURE7); glBindTexture(GL_TEXTURE_2D, cr); glUniform1i(mYUVCrTextureUniform, 7); static const GLfloat colorConversionMatrix[] = { 1.164, 1.164, 1.164, 0.0, -0.213, 2.112, 1.793, -0.533, 0.0, }; glUniformMatrix3fv(mYUVMatrixUniform, 1, GL_FALSE, colorConversionMatrix); mYUVFramebuffer->bindFramebuffer(); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); mYUVFramebuffer->unbindFramebuffer(); glDisableVertexAttribArray(mYUVPositionAttribute); glDisableVertexAttribArray(mYUVTexCoordAttribute); }); return mYUVFramebuffer; } <file_sep>// // Created by 刘轩 on 2018/12/18. // #ifndef GPUCAMERAVIDEO_GLCONTEXT_H #define GPUCAMERAVIDEO_GLCONTEXT_H #include <stdio.h> #include <string> class GLContext { public: std::string hello; void setString(); }; #endif //GPUCAMERAVIDEO_GLCONTEXT_H <file_sep>// // Created by 刘轩 on 2019/1/7. // #ifndef GPUCAMERAVIDEO_DISPLAYVIEW_H #define GPUCAMERAVIDEO_DISPLAYVIEW_H #include "NativeOutput.h" #include "GLProgram.h" namespace GCVBase { class DisplayView : NativeOutput { private: GLuint aPositionAttribute = 0; GLuint aTexCoordAttribute = 0; GLuint uTextureuniform = 0; int mDisplayWidth; int mDisplayHeight; Rotation rotationDisplayView = Rotation::defaultRotation(); GLProgram * mDisplayProgram; FrameBuffer *mOutputDisplayFramebuffer = NULL; public: DisplayView(int width, int height); ~DisplayView(); virtual void _newFrameReadyAtTime(); virtual void _setOutputRotation(const Rotation &rotation); virtual void _setOutputFramebuffer(FrameBuffer *framebuffer); }; } #endif //GPUCAMERAVIDEO_DISPLAYVIEW_H <file_sep>package com.example.mat.gpucameravideo import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.widget.Button import com.example.codeclibrary.MoviePlayer import com.example.codeclibrary.playerview.SurfacePlayerview import android.text.TextUtils import android.media.MediaMetadataRetriever import android.util.Log import android.view.SurfaceHolder /** * Created by liuxuan on 2019/2/7 */ class PlayerActivity : AppCompatActivity(), SurfacePlayerview.PreviewLifeListener { private var playerView: SurfacePlayerview? = null private var moviePlayer: MoviePlayer? = null private var btn: Button? = null private var moivePath : String = "/storage/emulated/0/test1550826781725.mp4" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_player) playerView = findViewById(R.id.surfacePlayerview) playerView?.addPreviewLifeListener(this) //设置PreView生命周期监听 btn = findViewById(R.id.playerbtn) btn?.setOnClickListener { val metadataRetriever = MediaMetadataRetriever() metadataRetriever.setDataSource(moivePath) val widthString = metadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH) if (!TextUtils.isEmpty(widthString)) { val width = Integer.valueOf(widthString) Log.e("width", width.toString()) } val heightString = metadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT) if (!TextUtils.isEmpty(heightString)) { val height = Integer.valueOf(heightString) Log.e("height", height.toString()) } val durationString = metadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION) if (!TextUtils.isEmpty(durationString)) { val duration = java.lang.Long.valueOf(durationString).toInt() Log.e("duration", duration.toString()) } val bitrateString = metadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_BITRATE) if (!TextUtils.isEmpty(bitrateString)) { val bitrate = Integer.valueOf(bitrateString) Log.e("bitrate", bitrate.toString()) } val degreeStr = metadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION) if (!TextUtils.isEmpty(degreeStr)) { val degree = Integer.valueOf(degreeStr) Log.e("degree", degree.toString()) } metadataRetriever.release() moviePlayer?.startPlayer() } } override fun onPreviewReady(holder: SurfaceHolder) { moviePlayer = MoviePlayer(moivePath) moviePlayer?.addTarget(playerView!!) } override fun onPreviewDestroyed(holder: SurfaceHolder) { moviePlayer?.surfaceDestroyed() } companion object { init { System.loadLibrary("codec-lib") } } }<file_sep>package com.example.cameralibrary.camera.api import android.graphics.SurfaceTexture import android.hardware.Camera import com.example.cameralibrary.camera.AspectRatio import com.example.cameralibrary.camera.CameraHandler import com.example.cameralibrary.camera.CameraSize import com.example.cameralibrary.preview.PreviewImpl import java.nio.ByteBuffer /** * Created by liuxuan on 2018/12/27 */ abstract class CameraImpl { private val cameraHandler : CameraHandler = CameraHandler() protected var mPreview: PreviewImpl? = null protected fun handler(runnable: (()->Unit)){ //()表示无参函数,->Unit表示返回类型为Unit(也就是没有返回值类型),整体(()->Unit)表示参数runnable cameraHandler.postRunnable(Runnable(runnable)) //这里构造了一个Runnable对象,Runnable()参数类型本身就要求为()->Unit } /** * 相机生命周期函数 */ abstract fun openCamera(mFacing: Int, callback: CameraOpenCallback) abstract fun closeCamera(callback: CameraCloseCallback) abstract fun startPreview(surfaceTexture: SurfaceTexture, callback: PreviewStartCallback) abstract fun stopPreview(callback: PreviewStopCallback) /** * 相机生命周期回调 */ interface CameraOpenCallback { fun onOpen(mCamera:Camera) fun onError() } interface CameraCloseCallback { fun onClose() fun onError() } interface PreviewStartCallback { fun onStart() fun onPreviewFrame(previewData:ByteBuffer) fun onError() } interface PreviewStopCallback { fun onStop() fun onError() } /** * 设置相机所在的预览界面的引用 */ abstract fun setPreviewImpl(mPreview: PreviewImpl) /** * 设置相机参数 */ abstract fun setFacing(facing: Int) abstract fun setFlash(flash: Int) abstract fun setAutoFocus(autoFocus: Boolean) abstract fun setAspectRatio(ratio: AspectRatio): Boolean abstract fun getSupportedAspectRatios(): Set<AspectRatio> abstract fun setDisplayOrientation(displayOrientation: Int) /** * 拍照 */ abstract fun takePicture(cameraTakePicture: PreviewImpl.CameraTakePictureListener) }<file_sep>package com.example.codeclibrary import android.view.Surface import com.example.baselib.GCVInput /** * Created by liuxuan on 2019/2/5 */ class MoviePlayer(readPath: String? = null, surface: Surface? = null) : GCVInput(){ init { inputObjectAdress = nativePlayerInit(readPath, surface) } fun setFilePath(readPath: String){ nativeSetFilePath(inputObjectAdress, readPath) } fun startPlayer(){ nativeStartPlayer(inputObjectAdress) } fun pausePlayer(){ nativePausePlayer(inputObjectAdress) } fun cancelPalyer(){ nativeCancelPalyer(inputObjectAdress) } fun setPlayerSurface(surface: Surface){ nativeSetPlayerSurface(inputObjectAdress, surface) } fun surfaceDestroyed(){ nativeSurfaceDestroyed(inputObjectAdress) } private external fun nativePlayerInit(readPath: String?, surface: Surface?): Long private external fun nativeStartPlayer(inputObjectAdress: Long) private external fun nativePausePlayer(inputObjectAdress: Long) private external fun nativeCancelPalyer(inputObjectAdress: Long) private external fun nativeSetFilePath(inputObjectAdress: Long, readPath: String) private external fun nativeSetPlayerSurface(inputObjectAdress: Long, surface: Surface) private external fun nativeSurfaceDestroyed(inputObjectAdress: Long) }<file_sep>// // Created by 刘轩 on 2018/12/25. // #include <thread> #include "EglCore.h" GCVBase::EglCore::EglCore(const void *sharedContext, ANativeWindow *window, int width, int height) { EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY); checkEglError("eglCreateEglDisplay"); if (display == EGL_NO_DISPLAY) { throw "eglGetDisplay failed"; } EGLint maxVersion, minVersion; EGLBoolean initResult = eglInitialize(display, &maxVersion, &minVersion); EGLConfig config = NULL; EGLint numConfigs = 0; EGLint confAttr[15] = { EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, EGL_SURFACE_TYPE, EGL_WINDOW_BIT, EGL_RED_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_BLUE_SIZE, 8, EGL_ALPHA_SIZE, 8, EGL_DEPTH_SIZE, 16, EGL_NONE }; if (!eglChooseConfig(display, confAttr, &config, 1, &numConfigs) || numConfigs != 1) { throw "eglChooseConfig failed"; } EGLint ctxAttr[3] = {EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE}; if(window){ // 创建可显示的surface int surfaceAttribs[] = {EGL_NONE}; EGLSurface surface = eglCreateWindowSurface(display, config, window, surfaceAttribs); checkEglError("eglCreateWindowSurface"); EGLContext context; if(sharedContext) { EGLContext sharedGLContext = (EGLContext) sharedContext; context = eglCreateContext(display, config, sharedGLContext, ctxAttr); } else{ context = eglCreateContext(display, config, EGL_NO_CONTEXT, ctxAttr); } if (context == EGL_NO_CONTEXT) { throw "eglCreateContext failed"; } mWindow = window; mEGLSurface = surface; mEGLContext = context; mEGLDisplay = display; mEGLConfig = config; } else{ //创建后台像素缓冲区 int surfaceAttribs[] = {EGL_WIDTH, width, EGL_HEIGHT, height, EGL_NONE}; EGLSurface surface = eglCreatePbufferSurface(display, config, surfaceAttribs); checkEglError("eglCreatePbufferSurface"); EGLContext context; if(sharedContext) { EGLContext sharedGLContext = (EGLContext) sharedContext; context = eglCreateContext(display, config, sharedGLContext, ctxAttr); } if (context == EGL_NO_CONTEXT) { throw "eglCreateContext failed"; } mEGLSurface = surface; mEGLContext = context; mEGLDisplay = display; mEGLConfig = config; } mSharedObject = sharedContext; } GCVBase::EglCore::~EglCore() { eglDestroySurface(mEGLDisplay, mEGLSurface); eglDestroyContext(mEGLDisplay, mEGLContext); eglTerminate(mEGLDisplay); eglReleaseThread(); if (mWindow) { ANativeWindow_release(mWindow); } } EGLContext GCVBase::EglCore::getEGLContext() const { return mEGLContext; } void GCVBase::EglCore::checkEglError(std::string msg) { int error; if ((error = eglGetError()) != EGL_SUCCESS) { throw msg + ": EGL error: 0x" + std::to_string(error); } } bool GCVBase::EglCore::isCurrentContext() { return eglGetCurrentContext() == mEGLContext; } /** * eglMakeCurrent函数(包括他的参数)是线程相关的,如果你在A线程中创建了mEGLDisplay、mEGLContext、mEGLSurface * 这些对象,却在B线程中调用了 eglMakeCurrent 方法,此时就会爆出 eglMakeCurrent:866 error 3002 (EGL_BAD_ACCESS)错误 * * 如果 eglMakeCurrent函数没有得到有效调用,那么opengl的各个函数都不会生效 !!! */ void GCVBase::EglCore::makeAsCurrent() { eglMakeCurrent(mEGLDisplay, mEGLSurface, mEGLSurface , mEGLContext); } /** * 如果一切都进展的顺利的话,在调用该函数后,我们就能在对应的屏幕上看到画面了 */ void GCVBase::EglCore::swapToScreen() { eglSwapBuffers(mEGLDisplay, mEGLSurface); } void GCVBase::EglCore::resetSurface(ANativeWindow *window) { if(!window){ return; } if(mEGLSurface){ if(!isCurrentContext()){ makeAsCurrent(); } int surfaceAttribs[] = {EGL_NONE}; mEGLSurface = eglCreateWindowSurface(mEGLDisplay, mEGLConfig, window, surfaceAttribs); makeAsCurrent(); } } const void * GCVBase::EglCore::getSharedObject() { return mSharedObject; } <file_sep>// // Created by 刘轩 on 2019/1/10. // #include <EglCore.h> #include "MediaRecorder.h" static const uint8_t MemoryAligned = 64; //默认64字节为一个读取单位进行内存对齐 std::string MediaRecordVertexShader = "attribute vec4 aPosition;\n" "attribute vec4 aTexCoord;\n" "varying vec2 vTexCoord;\n" "void main() {\n" " gl_Position = aPosition;\n" " vTexCoord = aTexCoord.xy;\n" "}\n"; std::string MediaRecordFragmentShader = "precision mediump float;\n" "varying vec2 vTexCoord;\n" "uniform sampler2D uTexture;\n" "void main() {\n" " gl_FragColor = texture2D(uTexture, vTexCoord);\n" "}\n"; GCVBase::MediaRecorder::MediaRecorder(const GCVBase::EncoderConfig &config, JNIEnv *env) { mVideoSize = config.outputSize; mediaEncoder = new MediaEncoder(config); mediaBuffer = new MediaBuffer<GLubyte *>(); auto size = (unsigned long) (mVideoSize.width * mVideoSize.height * 4); auto alignSize = alignment_up((size), MemoryAligned); mRGBADataSize = alignSize; EglCore * shareEglInstance = Context::getShareContext()->getEglInstance(); EglCore * recordEglInstance = new EglCore(shareEglInstance->getEGLContext(), nullptr, 1, 1); /* * 记录需要另起一个线程,在mainLooper中进行Camera预览界面的渲染绘制,在recordLooper中进行离屏渲染并保存, * 这样可以有效避免预览线程卡顿。同时由于recordLooper所在的线程需要进行离屏渲染,因此也要用到Egl对象,所以这里用到了 * ShareContext,与mainLooper所在的线程共享egl上下文,可以同时操作同一份纹理(当然此时要做好线程同步工作) */ recordContext = new Context(env, "recordLooper"); recordContext->setEglInstance(recordEglInstance); runSyncContextLooper(recordContext->getContextLooper(), [=]{ recordContext->useAsCurrentContext(); mRecordProgram = new GLProgram(MediaRecordVertexShader, MediaRecordFragmentShader); if(!mRecordProgram->isProgramLinked()){ if(!mRecordProgram->linkProgram()){ // TODO 获取program连接日志` } } aPositionAttribute = mRecordProgram->getAttributeIndex("aPosition"); aTexCoordAttribute = mRecordProgram->getAttributeIndex("aTexCoord"); uTextureuniform = mRecordProgram->getuniformIndex("uTexture"); }); } GCVBase::MediaRecorder::~MediaRecorder() { delete mediaEncoder; delete mediaBuffer; delete mRecordProgram; delete recordContext; } void GCVBase::MediaRecorder::startRecording(const std::function<void ()> &handler) { mIsRecording = true; mStartCallback = handler; runSyncContextLooper(recordContext->getContextLooper(), [=]{ mediaEncoder->startEncoder(mStartCallback); mStartCallback = nullptr; }); } void GCVBase::MediaRecorder::pauseRecording(const std::function<void ()> &handler) { mIsRecording = false; mPauseCallback = handler; runSyncContextLooper(recordContext->getContextLooper(), [=]{ mediaEncoder->pauseEncoder(mPauseCallback); mPauseCallback = nullptr; }); } void GCVBase::MediaRecorder::finishRecording(const std::function<void ()> &handler) { mIsRecording = false; mFinishCallback = handler; /** * finish的时候需要用异步添加的方式,因为同步的话recordLooper中积压的消息会卡预览线程 */ runAsyncContextLooper(recordContext->getContextLooper(), [=]{ if (!mEncoderIsFinished) { mEncoderIsFinished = true; mediaEncoder->finishEncoder(mFinishCallback); mFinishCallback = nullptr; } }); } void GCVBase::MediaRecorder::cancelRecording(const std::function<void ()> &handler) { mIsRecording = false; mCancelRecording = true; mCancelCallback = handler; runSyncContextLooper(recordContext->getContextLooper(), [=]{ mediaEncoder->cancelEncoder(mCancelCallback); mCancelCallback = nullptr; }); } void GCVBase::MediaRecorder::_setOutputFramebuffer(GCVBase::FrameBuffer *framebuffer) { mFinalFilterFramebuffer = framebuffer; } void GCVBase::MediaRecorder::_newFrameReadyAtTime() { if(!mIsRecording){ return; } glFlush(); runAsyncContextLooper(recordContext->getContextLooper(), [=]{ /** * 由于异步线程执行的record耗时任务,导致的recordLooper中Message堆积,我们点击了停止按钮之后 * recordLooper仍然在处理未执行完的 Fuction 函数,也就是本段所在的Lamada表达式。 * * 这本来无可厚非,我们应该等待这些 Fuction 函数执行完毕,但在本段中,我们执行的操作是: * 将 mFinalFilterFramebuffer(由Camera传给FilterGroup,再传给MediaRecorder和DisplayView)帧缓冲 * 渲染到 Recoder 所有的帧缓冲,然后通过 glReadPixels 读取像素保存,这个读取像素的过程是比较耗时的 * * 同时虽然Camera合成的每一帧都会调用到当前方法,也就是每一帧都会产生一个Fuction函数,用于读取 * mFinalFilterFramebuffer中的像素,但这个 Camera产生的唯一的FBO只能代表当前Camera实时合成的画面, * 这意味着并不是每一个Fuction函数能够取得它应取得的像素,也意味着并不是每一帧Camera的像素都能够保证被写入文件, * * 如此,当我们在击了停止按钮之后,recordLooper仍在处理堆积的Fuction函数,但此时这些Fuction函数中, * glReadPixels获取到的画面,是Camera当前实时合成的帧!!!也就是此时仍然在获取并写入点击停止之后的帧!!! * * 因此我们在这里加了这段 return 判断,用来在点击停止之后丢弃这些还在队列中积压的Fuction函数,确保点击停止 * 按钮之后确实停止录制。但这样,在整个录制的过程中我们就不可避免的产生了一些丢帧。 */ // TODO 解决上述丢帧问题得主要思路就是 fbo缓存,在写入的同时,把Camera实时产生的帧缓冲对象缓存起来,生成一个队列, // TODO recordLooper作为消费者去这个队列中去捞缓存起来的 fbo对象,尽可能使Camera产生的每一帧都写入到文件中去 if(!mIsRecording){ return; } renderRecorderFramebuffer(mFinalFilterFramebuffer); /** * glReadPixels(GLint x,GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLvoid*pixels) * * glReadPixels 是将GPU渲染完数据,从GPU回传到host端的唯一方式,由入参(x,y,w,h)指定一个从一帧图像中读取内存的矩形, * type和format指定格式,pixels是输出像素的buffer * * 注意:glReadPixels实际上是从缓冲区中读取数据,如果使用了双缓冲区,则默认是从正在显示的缓冲(即前缓冲)中读取, * 而绘制工作是默认绘制到后缓冲区的。因此,如果需要读取已经绘制好的像素,往往需要先交换前后缓冲 */ auto * mRGBAData = (GLubyte *)(malloc(mRGBADataSize)); memset(mRGBAData, 0, mRGBADataSize); // TODO 同时glReadPixels这个函数其实是效率相对比较低下的,可以考虑用openl es 3.0中的 GL_PIXEL_PACK_BUFFER 代替 glReadPixels(0,0, (int)mVideoSize.width, (int)mVideoSize.height, GL_RGBA, GL_UNSIGNED_BYTE, mRGBAData); mediaBuffer->mediaType = MediaType::Video; mediaBuffer->mediaData = mRGBAData; mediaBuffer->metaData[WidthKey] = (const void *)(long)mVideoSize.width; mediaBuffer->metaData[HeightKey] = (const void *)(long)mVideoSize.height; mediaEncoder->newFrameReadyAtTime(mediaBuffer); }); } /** * 这里是将外部的FrameBuffer中的texture上的内容渲染到 recordContext 中的 mRecorderFramebuffer上了 * @param framebuffer 外部的 FrameBuffer */ void GCVBase::MediaRecorder::renderRecorderFramebuffer(GCVBase::FrameBuffer *framebuffer) { recordContext->useAsCurrentContext(); mRecordProgram->useProgram(); creatRecorderFramebuffer(); glEnableVertexAttribArray(aPositionAttribute); glEnableVertexAttribArray(aTexCoordAttribute); glClearColor(1.0f, 0.0f, 0.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glActiveTexture(GL_TEXTURE4); glBindTexture(GL_TEXTURE_2D, framebuffer->texture()); static const GLfloat vertices[] = { -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 1.0f, }; const GLfloat * texCoord = CalculateRecoderRotation(rotationMediaRecorder); glUniform1i(uTextureuniform, 4); glVertexAttribPointer(aPositionAttribute, 2, GL_FLOAT, 0, 0, vertices); glVertexAttribPointer(aTexCoordAttribute, 2, GL_FLOAT, 0, 0, texCoord); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); glDisableVertexAttribArray(aPositionAttribute); glDisableVertexAttribArray(aTexCoordAttribute); } void GCVBase::MediaRecorder::creatRecorderFramebuffer() { if (mRecorderFramebuffer) { return; } glActiveTexture(GL_TEXTURE3); glGenFramebuffers(1, &mRecorderFramebuffer); glBindFramebuffer(GL_FRAMEBUFFER, mRecorderFramebuffer); glGenTextures(1, &mRecorderTexture); glBindTexture(GL_TEXTURE_2D, mRecorderTexture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, (int)mVideoSize.width, (int)mVideoSize.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, mRecorderTexture, 0); GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER); if(status != GL_FRAMEBUFFER_COMPLETE){ // TODO 打log,报错 } glBindFramebuffer(GL_FRAMEBUFFER, mRecorderFramebuffer); glViewport(0, 0, (int)mVideoSize.width, (int)mVideoSize.height); } void GCVBase::MediaRecorder::bindRecorderFramebuffer() { glBindFramebuffer(GL_FRAMEBUFFER, mRecorderFramebuffer); glViewport(0, 0, (int)mVideoSize.width, (int)mVideoSize.height); } void GCVBase::MediaRecorder::unBindRecorderFramebuffer() { glBindFramebuffer(GL_FRAMEBUFFER, 0); } void GCVBase::MediaRecorder::_setOutputRotation(const GCVBase::Rotation &rotation) { rotationMediaRecorder = rotation; } <file_sep>// // Created by 刘轩 on 2019/2/7. // #include <jni.h> #include <android/native_window.h> #include <android/native_window_jni.h> #include "DisplayView.h" using namespace GCVBase; extern "C" { jlong Java_com_example_codeclibrary_playerview_SurfacePlayerview_nativeSurfaceWindowInit(JNIEnv *env, jobject obj, jobject surface){ Context::initSharedContext(env); ANativeWindow * nativeWindow = ANativeWindow_fromSurface(env, surface); DisplayView * displayView = nullptr; runSyncContextLooper(Context::getShareContext()->getContextLooper(), [&displayView, &nativeWindow]{ Context::getShareContext()->setNativeWindow(nativeWindow); displayView = new DisplayView(ANativeWindow_getWidth(nativeWindow), ANativeWindow_getHeight(nativeWindow)); }); return (jlong)displayView; } void Java_com_example_codeclibrary_playerview_SurfacePlayerview_nativeSurfaceWindowDestroyed(JNIEnv *env, jobject obj, jlong nativeOutputSurfaceAddress){ auto * displayView = (DisplayView * )nativeOutputSurfaceAddress; delete displayView; } }<file_sep>package com.example.cameralibrary.effects import android.animation.Animator import android.animation.AnimatorListenerAdapter import android.content.Context import android.util.AttributeSet import android.view.LayoutInflater import android.widget.FrameLayout import android.widget.ImageView import com.example.cameralibrary.R /** * Created by liuxuan on 2019/1/5 */ class FocusMarkerView : FrameLayout { private val mFocusMarkerContainer: FrameLayout private val mFill: ImageView constructor(context: Context) : this(context, null) constructor(context: Context, attributeSet: AttributeSet?) : this(context, attributeSet, 0) constructor(context: Context, attributeSet: AttributeSet?, defStyleAttr :Int ):super(context, attributeSet, defStyleAttr) init { val view = LayoutInflater.from(context).inflate(R.layout.layout_focus_marker, this) mFocusMarkerContainer = view.findViewById(R.id.focusMarkerContainer) mFill = view.findViewById(R.id.fill) mFocusMarkerContainer.alpha = 0f } fun focus(mx: Float, my: Float) { val x = mx - mFocusMarkerContainer.width / 2 val y = my - mFocusMarkerContainer.width / 2 mFocusMarkerContainer.translationX = x mFocusMarkerContainer.translationY = y mFocusMarkerContainer.animate().setListener(null).cancel() mFill.animate().setListener(null).cancel() mFill.scaleX = 0f mFill.scaleY = 0f mFill.alpha = 1f mFocusMarkerContainer.scaleX = 1.36f mFocusMarkerContainer.scaleY = 1.36f mFocusMarkerContainer.alpha = 1f mFocusMarkerContainer.animate() .scaleX(1f).scaleY(1f) .setStartDelay(0).setDuration(330) .setListener(object : AnimatorListenerAdapter() { override fun onAnimationEnd(animation: Animator) { super.onAnimationEnd(animation) mFocusMarkerContainer.animate().alpha(0f).setStartDelay(750).setDuration(800).setListener(null).start() } }).start() mFill.animate() .scaleX(1f).scaleY(1f).setDuration(330) .setListener(object : AnimatorListenerAdapter() { override fun onAnimationEnd(animation: Animator) { super.onAnimationEnd(animation) mFill.animate().alpha(0f).setDuration(800).setListener(null).start() } }).start() } } <file_sep>// // Created by 刘轩 on 2018/12/17. // #include <jni.h> #include "EncoderConfig.hpp" #include "MediaRecorder.h" using namespace GCVBase; extern "C" { jlong Java_com_example_codeclibrary_MovieRecorder_nativeRecorderInit(JNIEnv * env, jobject obj, jstring savePath, jint width, jint height, jlong bitRate, jint outputOrientation, jint mediacodecColorFormat, jint bitRateMode){ EncoderConfig config; config.outputPath = env->GetStringUTFChars(savePath, nullptr); config.setOutputSize(Size(width, height)); config.videoBitRate = (unsigned long) bitRate; config.outputOrientation = outputOrientation; config.colorYUVFormat = mediacodecColorFormat; config.bitRateMode = bitRateMode; auto * mediaRecord = new MediaRecorder(config, env); return (jlong)mediaRecord; } void Java_com_example_codeclibrary_MovieRecorder_nativeStartRecorder(JNIEnv * env, jobject obj, jlong mMediaRecoderAddress){ if(!mMediaRecoderAddress){ return; } auto * mediaRecord = (MediaRecorder*) mMediaRecoderAddress; mediaRecord->startRecording([=]{ }); } void Java_com_example_codeclibrary_MovieRecorder_nativePauseRecorder(JNIEnv * env, jobject obj, jlong mMediaRecoderAddress){ if(!mMediaRecoderAddress){ return; } auto * mediaRecord = (MediaRecorder*) mMediaRecoderAddress; mediaRecord->pauseRecording([=]{ }); } void Java_com_example_codeclibrary_MovieRecorder_nativeFinishRecorder(JNIEnv * env, jobject obj, jlong mMediaRecoderAddress){ if(!mMediaRecoderAddress){ return; } auto * mediaRecord = (MediaRecorder*) mMediaRecoderAddress; mediaRecord->finishRecording([=]{ }); } void Java_com_example_codeclibrary_MovieRecorder_nativecancelRecording(JNIEnv * env, jobject obj, jlong mMediaRecoderAddress){ if(!mMediaRecoderAddress){ return; } auto * mediaRecord = (MediaRecorder*) mMediaRecoderAddress; mediaRecord->cancelRecording([=]{ }); } void Java_com_example_codeclibrary_MovieRecorder_nativeSurfaceDestory(JNIEnv * env, jobject obj, jlong mMediaRecoderAddress){ auto * mediaRecord = (MediaRecorder*) mMediaRecoderAddress; delete mediaRecord; } } <file_sep>package com.example.codeclibrary /** * Created by liuxuan on 2019/1/10 */ class AudioRecorder{ }<file_sep>// // Created by 刘轩 on 2019/1/27. // #include <Context.h> #include "Filter.h" std::string defaultFilterVertexShader = "attribute vec4 aPosition;\n" "attribute vec4 aTexCoord;\n" "varying vec2 vTexCoord;\n" "void main() {\n" " gl_Position = aPosition;\n" " vTexCoord = aTexCoord.xy;\n" "}\n"; std::string defaultFilterFragmentShader = "precision mediump float;\n" "varying vec2 vTexCoord;\n" "uniform sampler2D uTexture;\n" "void main() {\n" " gl_FragColor = texture2D(uTexture, vTexCoord);\n" "}\n"; GCVBase::Filter::Filter(int width, int height) { Filter(defaultFilterVertexShader, defaultFilterFragmentShader, width, height); } GCVBase::Filter::Filter(const std::string &vertexShader, const std::string &fragmentShader, int width, int height) { mFilterWidth = width; mFilterHeight = height; runSyncContextLooper(Context::getShareContext()->getContextLooper(), [=]{ Context::makeShareContextAsCurrent(); mFilterProgram = new GLProgram(vertexShader, fragmentShader); if(!mFilterProgram->isProgramLinked()){ if(!mFilterProgram->linkProgram()){ // TODO 获取program连接日志` } } aPositionAttribute = mFilterProgram->getAttributeIndex("aPosition"); aTexCoordAttribute = mFilterProgram->getAttributeIndex("aTexCoord"); uTextureuniform = mFilterProgram->getuniformIndex("uTexture"); }); } GCVBase::Filter::~Filter() { delete mFilterProgram; } void GCVBase::Filter::newFrameReadyAtTime() { if (!mFilterFramebuffer) { return; } runSyncContextLooper(Context::getShareContext()->getContextLooper(), [=]{ Context::makeShareContextAsCurrent(); mFilterProgram->useProgram(); glEnableVertexAttribArray(aPositionAttribute); glEnableVertexAttribArray(aTexCoordAttribute); glClearColor(0, 0, 0, 0); glClear(GL_COLOR_BUFFER_BIT); /** * 必须在这一步之前解绑 mOutputDisplayFramebuffer 的帧缓冲 */ glActiveTexture(GL_TEXTURE2); glBindTexture(GL_TEXTURE_2D, mFilterFramebuffer->texture()); static const GLfloat vertices[] = { -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 1.0f, }; static const GLfloat texCoord[] = { // Filter只负责对纹理的像素做采样处理,但对纹理坐标同样不做任何处理 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, }; glUniform1i(uTextureuniform, 2); glVertexAttribPointer(aPositionAttribute, 2, GL_FLOAT, 0, 0, vertices); glVertexAttribPointer(aTexCoordAttribute, 2, GL_FLOAT, 0, 0, texCoord); mFilterFramebuffer->bindFramebuffer(); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); mFilterFramebuffer->unbindFramebuffer(); glDisableVertexAttribArray(aPositionAttribute); glDisableVertexAttribArray(aTexCoordAttribute); }); } void GCVBase::Filter::setPreviousFramebuffer(GCVBase::FrameBuffer *framebuffer) { mFilterFramebuffer = framebuffer; } <file_sep>package com.example.cameralibrary.camera import android.support.v4.util.SparseArrayCompat /** * 摄像头的宽高比 * * Created by liuxuan on 2019/1/2 */ class AspectRatio(x: Int, y: Int) : Comparable<AspectRatio>{ private var mX: Int = x //宽 private var mY: Int = y //高 companion object { private val sCache = SparseArrayCompat<SparseArrayCompat<AspectRatio>>(16) fun of(x: Int, y: Int): AspectRatio { var x = x var y = y val gcd = gcd(x, y) x /= gcd y /= gcd var arrayX: SparseArrayCompat<AspectRatio>? = sCache.get(x) return if (arrayX == null) { val ratio = AspectRatio(x, y) arrayX = SparseArrayCompat() arrayX.put(y, ratio) sCache.put(x, arrayX) ratio } else { var ratio: AspectRatio? = arrayX.get(y) if (ratio == null) { ratio = AspectRatio(x, y) arrayX.put(y, ratio) } ratio } } fun parse(s: String): AspectRatio { val position = s.indexOf(':') if (position == -1) { throw IllegalArgumentException("Malformed aspect ratio: " + s) } try { val x = Integer.parseInt(s.substring(0, position)) val y = Integer.parseInt(s.substring(position + 1)) return AspectRatio.of(x, y) } catch (e: NumberFormatException) { throw IllegalArgumentException("Malformed aspect ratio: " + s, e) } } private fun gcd(a: Int, b: Int): Int { var a = a var b = b while (b != 0) { val c = b b = a % b a = c } return a } } fun getX(): Int { return mX } fun getY(): Int { return mY } fun matches(size: CameraSize): Boolean { val gcd = gcd(size.getWidth(), size.getHeight()) val x = size.getWidth() / gcd val y = size.getHeight() / gcd return mX == x && mY == y } override fun compareTo(other: AspectRatio): Int { if (equals(other)) { return 0 } else if (toFloat() - other.toFloat() > 0) { return 1 } return -1 } private fun toFloat(): Float { return mX.toFloat() / mY } fun inverse(): AspectRatio { return AspectRatio.of(mY, mX) } }<file_sep>// // Created by 刘轩 on 2018/12/22. // #include "MessageQueue.h" #include <utility> GCVBase::MessageQueue::MessageQueue(std::string looperName, std::string messageQueueName) { // TODO 在这里加断言,这两个东西都必须有值的 mLooperName = std::move(looperName); mMessageQueueName = std::move(messageQueueName); } void GCVBase::MessageQueue::addMessage(GCVBase::Message *message) { // TODO 这里应该加入message有效性的校验,比如说非空判断什么的 message->setMessageQueueName(mMessageQueueName); //给message设置所在队列的名称,方便回溯 if(queueHead != nullptr){ Message * temp = queueHead; while (temp->next != nullptr){ temp = temp->next; } temp->next = message; } else{ queueHead = message; } } GCVBase::Message *GCVBase::MessageQueue::getNextMessage() { if (queueHead == nullptr) { //等于NULL说明此时没有消息了 return nullptr; } Message *m = queueHead; queueHead = m->next; m->next = nullptr; return m; } void GCVBase::MessageQueue::recycleMessage(GCVBase::Message *message) { Message::recycle(message); } void GCVBase::MessageQueue::recycleAllMessage() { while(queueHead != nullptr){ Message *m = queueHead; queueHead = m->next; m->next = nullptr; //TODO 加一个提示,就说哪个哪个Message被回收了 Message::recycle(m); } } void GCVBase::MessageQueue::setMessageQueueName(std::string messageQueueName) { mMessageQueueName = std::move(messageQueueName); } std::string GCVBase::MessageQueue::getMessageQueueName() { return mMessageQueueName; } GCVBase::MessageQueue::~MessageQueue() { recycleAllMessage(); //此时消息队列中的消息还是没执行完,就不等了,直接回收 } bool GCVBase::MessageQueue::isMessageQueueEmpty() { return queueHead == nullptr; } <file_sep>package com.example.cameralibrary.camera.api import android.graphics.Rect import android.graphics.SurfaceTexture import android.hardware.Camera import android.os.Handler import android.os.Looper import android.support.v4.util.SparseArrayCompat import android.util.Log import android.view.MotionEvent import android.view.View import com.example.cameralibrary.camera.AspectRatio import com.example.cameralibrary.camera.CameraParam import com.example.cameralibrary.camera.CameraSize import com.example.cameralibrary.camera.CameraSizeMap import com.example.cameralibrary.preview.PreviewImpl import com.example.cameralibrary.preview.PreviewImpl.CameraTakePictureListener import java.nio.ByteBuffer import java.util.* import java.util.concurrent.atomic.AtomicBoolean /** * Created by liuxuan on 2018/12/27 */ class Camera1 : CameraImpl() { private val TAG = this::class.java.simpleName private var mCamera: Camera? = null private var mCameraParameters: Camera.Parameters? = null private val mCameraInfo = Camera.CameraInfo() private var mFacing: Int = 0 private var mFlash: Int = 0 private var mAutoFocus: Boolean = false private var mAspectRatio: AspectRatio? = null //当前相机preview的宽高比 private var mDisplayOrientation: Int = 0 private val mAutofocusCallback: Camera.AutoFocusCallback? = null private var mCameraTakePicture: CameraTakePictureListener? = null private var mShowingPreview: Boolean = false private var camera1state: Camera1State = Camera1State.RELEASED private val mPreviewSizes = CameraSizeMap() private val mPictureSizes = CameraSizeMap() private val FLASH_MODES = SparseArrayCompat<String>() private val isPictureCaptureInProgress = AtomicBoolean(false) private val isAutoFocusInProgress = AtomicBoolean(false) private val FOCUS_AREA_SIZE_DEFAULT = 300 private val FOCUS_METERING_AREA_WEIGHT_DEFAULT = 1000 private val MIN_TIME_FOR_AUTOFOCUS: Long = 2000 //拍照时最短的自动对焦时间限制 private val DELAY_MILLIS_BEFORE_RESETTING_FOCUS: Long = 3000 //重置焦距最短的自动对焦时间限制 override fun setPreviewImpl(preview: PreviewImpl) { mPreview = preview } init { FLASH_MODES.put(CameraParam.FLASH_OFF, Camera.Parameters.FLASH_MODE_OFF) FLASH_MODES.put(CameraParam.FLASH_ON, Camera.Parameters.FLASH_MODE_ON) FLASH_MODES.put(CameraParam.FLASH_TORCH, Camera.Parameters.FLASH_MODE_TORCH) FLASH_MODES.put(CameraParam.FLASH_AUTO, Camera.Parameters.FLASH_MODE_AUTO) FLASH_MODES.put(CameraParam.FLASH_RED_EYE, Camera.Parameters.FLASH_MODE_RED_EYE) } private enum class Camera1State { OPENED, STARTED, STOPPED, RELEASED; } private fun isCameraOpened(): Boolean { return camera1state == Camera1State.OPENED || camera1state == Camera1State.STARTED } /************************************** 相机生命周期函数 **********************************************/ override fun openCamera(mFacing: Int, callback: CameraOpenCallback) { handler { //handler函数只有一个runnable参数,因此直接用lamada表达式写在括号外面 val currentCamera = mCamera if (currentCamera != null) { callback.onError() return@handler } try { val cameraInfo = Camera.CameraInfo() val cameraId = (0 until Camera.getNumberOfCameras()).find { Camera.getCameraInfo(it, cameraInfo) if(mFacing == 0) { cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_BACK //相机朝向的方向 } else{ cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT //相机朝向的方向 } } if (cameraId == null) { callback.onError() return@handler } val camera = Camera.open(cameraId) camera.setErrorCallback { error, _ -> when (error) { Camera.CAMERA_ERROR_EVICTED -> RuntimeException("CAMERA_ERROR_EVICTED") Camera.CAMERA_ERROR_SERVER_DIED -> RuntimeException("CAMERA_ERROR_SERVER_DIED") Camera.CAMERA_ERROR_UNKNOWN -> RuntimeException("CAMERA_ERROR_UNKNOWN") else -> RuntimeException("Undefined camera error received, but assuming fatal.") } } this.mCamera = camera mCameraParameters = camera.parameters mPreviewSizes.clear() //将相机支持的PreciewSize保存到mPreviewSizes中 for (size in camera.parameters.supportedPreviewSizes) { mPreviewSizes.add(CameraSize(size.width, size.height)) } Log.i(TAG, "openCamera, supportedPreviewSizes: " + mPreviewSizes) mPictureSizes.clear() //将相机支持的PictureSize保存到mPreviewSizes中 for (size in camera.parameters.supportedPictureSizes) { mPictureSizes.add(CameraSize(size.width, size.height)) } Log.i(TAG, "openCamera, supportedPictureSizes: " + mPictureSizes) //删除在图片预览大小中那些没有必要的大小,因为这些大小在输出图片中不可能有这个宽高比,预览图片、输出图片和AspectRatio三个的比例值必须一样 val ratiosToDelete = mPreviewSizes.ratios().filterNot { mPictureSizes.ratios().contains(it) } for (ratio in ratiosToDelete) { mPreviewSizes.remove(ratio) } adjustCameraParameters() camera1state = Camera1State.OPENED callback.onOpen(camera) } catch (e: Exception) { callback.onError() } } } override fun startPreview(surfaceTexture: SurfaceTexture, callback: PreviewStartCallback) { handler { val currentCamera = mCamera if (currentCamera == null) { callback.onError() return@handler } try { currentCamera.setPreviewTexture(surfaceTexture) //一旦使用此方法注册预览回调接口,onPreviewFrame()方法会一直被调用,直到camera preview销毁 currentCamera.setPreviewCallback { bytes: ByteArray, _ -> callback.onPreviewFrame(ByteBuffer.wrap(bytes)) } currentCamera.startPreview() mShowingPreview = true camera1state = Camera1State.STARTED callback.onStart() } catch (e: Exception) { callback.onError() } } } override fun stopPreview(callback: PreviewStopCallback) { handler { val currentCamera = mCamera if (currentCamera == null) { callback.onError() return@handler } try { currentCamera.setPreviewCallback(null) currentCamera.stopPreview() mShowingPreview = false camera1state = Camera1State.STOPPED isPictureCaptureInProgress.set(false) isAutoFocusInProgress.set(false) } catch (e: Exception) { callback.onError() } finally { callback.onStop() } } } override fun closeCamera(callback: CameraCloseCallback) { handler { val currentCamera = mCamera if (currentCamera == null) { callback.onError() return@handler } try { currentCamera.release() } catch (e: Exception) { callback.onError() } finally { mCamera = null callback.onClose() } } } /****************************************** 拍照函数 *************************************************/ override fun takePicture(cameraTakePicture: CameraTakePictureListener) { mCameraTakePicture = cameraTakePicture if(!isCameraOpened()){ // TODO 打Log显示Camera生命周期有问题,拍照时还没有打开相机 return } if (getAutoFocus()) { // CameraLog.i(TAG, "takePicture => autofocus") mCamera?.cancelAutoFocus() //mCamera.autoFocus进行自动对焦,对焦好了之后再拍照,魅族MX6手机上对焦比较慢,导致这里可能需要等待好几秒才拍照成功 //这里为了更好的体验,限制2秒之内一定要进行拍照,也就是说3秒钟之内对焦还没有成功的话那就直接进行拍照 isAutoFocusInProgress.getAndSet(true) try {//从数据上报来看,部分相机自动对焦失败会发生crash,所以这里需要catch住,如果自动对焦失败了,那么就直接进行拍照 mCamera?.autoFocus({ _, _ -> if (isAutoFocusInProgress.get()) { // CameraLog.i(TAG, "takePicture, auto focus => takePictureInternal") isAutoFocusInProgress.set(false) takePictureInternal() } }) } catch (error: Exception) { if (isAutoFocusInProgress.get()) { // CameraLog.i(TAG, "takePicture, autofocus exception => takePictureInternal", error) isAutoFocusInProgress.set(false) takePictureInternal() } } val handler = Handler(Looper.getMainLooper()) handler.postDelayed({ if (isAutoFocusInProgress.get()) { // CameraLog.i(TAG, "takePicture, cancel focus => takePictureInternal") isAutoFocusInProgress.set(false) takePictureInternal() } }, MIN_TIME_FOR_AUTOFOCUS) } else { // CameraLog.i(TAG, "takePicture => takePictureInternal") takePictureInternal() } } private fun getAutoFocus(): Boolean { if (!isCameraOpened()) { return mAutoFocus } val focusMode = mCameraParameters?.focusMode return focusMode != null && focusMode.contains("continuous") } //上面的mCamera.autoFocus中的onAutoFocus这个回调会被调用两次,所以takePictureInternal方法中使用isPictureCaptureInProgress来控制takePicture的调用 private fun takePictureInternal() { if (isCameraOpened() && !isPictureCaptureInProgress.getAndSet(true)) { mCamera?.takePicture(null, null, null, Camera.PictureCallback { data, camera -> // CameraLog.i(TAG, "takePictureInternal, onPictureTaken") isPictureCaptureInProgress.set(false) mCameraTakePicture?.onPictureTaken(ByteBuffer.wrap(data)) camera.cancelAutoFocus() camera.startPreview() }) } } /************************************** 切换相机参数函数 **********************************************/ /** * 切换闪光灯模式 */ override fun setFlash(flash: Int) { if (flash == mFlash) { return } if (setFlashInternal(flash)) { mCamera?.parameters = mCameraParameters } } /** * 切换前后置镜头,考虑到有些手机上切换前后置镜头可能存在的闪退问题,因此这里将关闭再打开的过程放到了异步线程中, * 也就是在Camera类中调用stopPreview和openCamera,这里只是设置一下 mFacing 的值即可 */ override fun setFacing(facing: Int) { if (mFacing == facing) { return } mFacing = facing } override fun setAutoFocus(autoFocus: Boolean) { if (mAutoFocus == autoFocus) { return } if (setAutoFocusInternal(autoFocus)) { mCamera?.parameters = mCameraParameters } } /** * 设置预览界面的宽高比例 */ override fun setAspectRatio(ratio: AspectRatio): Boolean { if (mAspectRatio == null || !isCameraOpened()) { mAspectRatio = ratio //第一次在SurfaceViewPreview中初始化的时候走的这里,此时设置的是16:9比例的默认大小 return true } else if (mAspectRatio != ratio) { //这个对应我们切换preview界面比例时候的操作,此时相机已经打开 val sizes = mPreviewSizes.sizes(ratio) // 查询相机支不支持设置的比例 return if (sizes == null) { //说明previewSize并不支持这个比例,这个时候应该属于bug,不支持的比例就不应该展示出来 // TODO 打log,并提醒用户相机并不支持这个比例 false } else { mAspectRatio = ratio adjustCameraParameters() true } } return false } override fun getSupportedAspectRatios(): Set<AspectRatio> { //求出mPreviewSizes中那些在mPictureSizes中也存在的比例列表 val idealAspectRatios = mPreviewSizes val ratiosToDelete = idealAspectRatios.ratios().filter { mPictureSizes.sizes(it) == null } for (ratio in ratiosToDelete) { idealAspectRatios.remove(ratio) } return idealAspectRatios.ratios() } /** * 设置屏幕方向,用于在旋转屏幕的时候调整预览界面的方向,当然本项目中我们的预览界面直接是在native层用的 * OES纹理渲染的,所以需要根据这个 displayOrientation 的值 改变texture矩阵,比如右旋左旋等 */ override fun setDisplayOrientation(displayOrientation: Int) { if (mDisplayOrientation == displayOrientation) { // Log.i(TAG, "Camera1 setDisplayOrientation, displayOrientation = %d, not changed", displayOrientation) return } mDisplayOrientation = displayOrientation if (isCameraOpened()) { val rotation = calcCameraRotation(displayOrientation) mCameraParameters?.setRotation(rotation) mCamera?.parameters = mCameraParameters if (mShowingPreview) { mCamera?.stopPreview() } val orientation = calcDisplayOrientation(displayOrientation) mCamera?.setDisplayOrientation(orientation) if (mShowingPreview) { mCamera?.startPreview() } // CameraLog.i(TAG, "Camera1 setDisplayOrientation, new orientation = %d, camera rotation = %d, camera orientation = %d", displayOrientation, rotation, orientation) } } /** * 设置自动对焦 */ private fun setAutoFocusInternal(autoFocus: Boolean): Boolean { mAutoFocus = autoFocus if (isCameraOpened() && mCameraParameters != null) { val modes = mCameraParameters!!.supportedFocusModes if (autoFocus && modes.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE)) { attachFocusTapListener() mCameraParameters!!.focusMode = Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE // Log.i(TAG, "setAutoFocusInternal, FOCUS_MODE_CONTINUOUS_PICTURE, autoFocus = true") } else if (modes.contains(Camera.Parameters.FOCUS_MODE_FIXED)) { detachFocusTapListener() mCameraParameters!!.focusMode = Camera.Parameters.FOCUS_MODE_FIXED // Log.i(TAG, "setAutoFocusInternal, FOCUS_MODE_FIXED, autoFocus = %s", autoFocus) } else if (modes.contains(Camera.Parameters.FOCUS_MODE_INFINITY)) { detachFocusTapListener() mCameraParameters!!.focusMode = Camera.Parameters.FOCUS_MODE_INFINITY // Log.i(TAG, "setAutoFocusInternal, FOCUS_MODE_INFINITY, autoFocus = %s", autoFocus) } else { detachFocusTapListener() mCameraParameters!!.focusMode = modes[0] //getSupportedFocusModes方法返回的列表至少有一个元素 // Log.i(TAG, "setAutoFocusInternal, mode = %s, autoFocus = %s", modes[0], autoFocus) } return true } else { // Log.i(TAG, "setAutoFocusInternal, camera not open, autoFocus = %s", autoFocus) return false } } /** * 设置闪光灯 */ private fun setFlashInternal(flash: Int): Boolean { if (isCameraOpened() && mCameraParameters != null) { val modes = mCameraParameters!!.supportedFlashModes//如果不支持设置闪光灯的话,getSupportedFlashModes方法会返回null val mode = FLASH_MODES.get(flash) if (modes != null && modes.contains(mode)) { mCameraParameters!!.flashMode = mode mFlash = flash // Log.i(TAG, "setFlashInternal, flash = %d", flash) return true } val currentMode = FLASH_MODES.get(mFlash) if (modes == null || !modes.contains(currentMode)) { mCameraParameters!!.flashMode = Camera.Parameters.FLASH_MODE_OFF mFlash = CameraParam.FLASH_OFF Log.i(TAG, "setFlashInternal, flash is FLASH_OFF") return true } return false } else { mFlash = flash // Log.i(TAG, "setFlashInternal, camera not open, flash = %d", flash) return false } } /** * 手动对焦,参考方案: * https://github.com/lin18/cameraview/commit/47b8a4e493cdb5f1085333577d55b749443047e9 */ private fun attachFocusTapListener() { if (mPreview == null) { // TODO 打log报错 return } mPreview?.getView()?.setOnTouchListener(View.OnTouchListener { _, event -> if (event.action == MotionEvent.ACTION_UP) { if (mCamera != null) { val parameters = mCamera!!.parameters val focusMode = parameters.focusMode val rect = calculateFocusArea(event.x, event.y) val meteringAreas = ArrayList<Camera.Area>() meteringAreas.add(Camera.Area(rect, FOCUS_METERING_AREA_WEIGHT_DEFAULT)) if (parameters.maxNumFocusAreas != 0 && focusMode != null && (focusMode == Camera.Parameters.FOCUS_MODE_AUTO || focusMode == Camera.Parameters.FOCUS_MODE_MACRO || focusMode == Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE || focusMode == Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO)) { if (!parameters.supportedFocusModes.contains(Camera.Parameters.FOCUS_MODE_AUTO)) { return@OnTouchListener false //cannot autoFocus } parameters.focusMode = Camera.Parameters.FOCUS_MODE_AUTO parameters.focusAreas = meteringAreas if (parameters.maxNumMeteringAreas > 0) { parameters.meteringAreas = meteringAreas } mCamera!!.parameters = parameters try { mCamera!!.autoFocus({ success, camera -> resetFocus(success, camera) }) } catch (error: Exception) { //ignore this exception Log.e(TAG, "attachFocusTapListener, autofocus fail case 1", error) } } else if (parameters.maxNumMeteringAreas > 0) { if (!parameters.supportedFocusModes.contains(Camera.Parameters.FOCUS_MODE_AUTO)) { return@OnTouchListener false //cannot autoFocus } parameters.focusMode = Camera.Parameters.FOCUS_MODE_AUTO parameters.focusAreas = meteringAreas parameters.meteringAreas = meteringAreas mCamera!!.parameters = parameters try { mCamera!!.autoFocus({ success, camera -> resetFocus(success, camera) }) } catch (error: Exception) { //ignore this exception Log.e(TAG, "attachFocusTapListener, autofocus fail case 2", error) } } else { try { mCamera!!.autoFocus({ success, camera -> mAutofocusCallback?.onAutoFocus(success, camera) }) } catch (error: Exception) { //ignore this exception Log.e(TAG, "attachFocusTapListener, autofocus fail case 3", error) } } } } true }) } private fun detachFocusTapListener() { if (mPreview != null && mPreview!!.getView() != null) { mPreview!!.getView()?.setOnTouchListener(null) } } private val mHandler = Handler() private fun resetFocus(success: Boolean, camera: Camera?) { mHandler.removeCallbacksAndMessages(null) mHandler.postDelayed({ if (camera != null) { camera.cancelAutoFocus() try { val params = camera.parameters if (params != null && !params.focusMode.equals(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE, ignoreCase = true)) { if (params.supportedFocusModes.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE)) { params.focusMode = Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE params.focusAreas = null params.meteringAreas = null camera.parameters = params } } } catch (error: Exception) { //ignore this exception Log.e(TAG, "resetFocus, camera getParameters or setParameters fail", error) } mAutofocusCallback?.onAutoFocus(success, camera) } }, DELAY_MILLIS_BEFORE_RESETTING_FOCUS) } /************************************** 相机参数相关计算函数 *******************************************/ private fun adjustCameraParameters() { var sizes = mPreviewSizes.sizes(mAspectRatio) //这里size为空也可能表示mAspectRatio为空,也就是宽高比这个值还没有初始化 if (sizes == null) { // 不支持这个宽高比或者mAspectRatio还没有初始化 // Log.i(TAG, "adjustCameraParameters, ratio[%s] is not supported", mAspectRatio) mAspectRatio = chooseAspectRatio() //返回16:9或者4:3或者mPreviewSizes支持的第一个宽高比例 sizes = mPreviewSizes.sizes(mAspectRatio) //此时sizes肯定不为空了,除非mPreviewSizes为空 // Log.i(TAG, "adjustCameraParameters, change to ratio to %s", mAspectRatio) } val previewSize = choosePreviewSize(sizes) //选择预览帧的大小 if (previewSize == null) { Log.e("adjustCameraParameters", "previewSize is null") return } val pictureSize = choosePictureSize() //选择拍照图片的分辨率 if (pictureSize == null) { Log.e("adjustCameraParameters", "pictureSize is null") return } if (mShowingPreview) { mCamera?.stopPreview()//在重新设置CameraParameters之前需要停止预览 } mCameraParameters?.setPreviewSize(previewSize.getWidth(), previewSize.getHeight()) mCameraParameters?.setPictureSize(pictureSize.getWidth(), pictureSize.getHeight()) mCameraParameters?.setRotation(calcCameraRotation(mDisplayOrientation)) setAutoFocusInternal(mAutoFocus) setFlashInternal(mFlash) mCamera?.parameters = mCameraParameters // Log.i(TAG, "adjustCameraParameters, PreviewSize = %s, PictureSize = %s, AspectRatio = %s, AutoFocus = %s, Flash = %s", previewSize, pictureSize, mAspectRatio, mAutoFocus, mFlash) if (mShowingPreview) { mCamera?.startPreview() } } private fun choosePreviewSize(sizes: SortedSet<CameraSize>?): CameraSize? { if (mPreview == null) { // TODO 打log,报错,此时mPreview不应为null return null } if(sizes == null) { // TODO 打log,报错 return null } if (!mPreview!!.previewIsReady()) { // onSurfaceChanged执行完了之后就准备好了 // Log.i(TAG, "choosePreviewSize, preview is not ready, return size: %s", sizes.first()) return sizes.first() // 返回最小的值,因为我们用的SortedSet,且根据CameraSize中的campare,应该是从小到大排列 } val desiredWidth: Int val desiredHeight: Int val surfaceWidth = mPreview!!.getWidth() val surfaceHeight = mPreview!!.getHeight() if (isLandscape(mDisplayOrientation)) { desiredWidth = surfaceHeight desiredHeight = surfaceWidth } else { desiredWidth = surfaceWidth desiredHeight = surfaceHeight } /* * 从选定的长宽比支持的尺寸中,找到长和宽都大于或等于预览控件尺寸的,若是小于预览控件的宽高则会导致图像被拉伸了。 * 在宽高比一定的情况下,拍摄帧往往选择尺寸最大的,那样拍摄的图片更清楚 */ var result: CameraSize? = null for (size in sizes) { if (desiredWidth <= size.getWidth() && desiredHeight <= size.getHeight()) { return size } result = size } return result } private fun chooseAspectRatio(): AspectRatio { val aspectRatio: AspectRatio = when { mPreviewSizes.ratios().contains(CameraParam.DEFAULT_ASPECT_RATIO) -> //首先看16:9是否支持 CameraParam.DEFAULT_ASPECT_RATIO mPreviewSizes.ratios().contains(CameraParam.SECOND_ASPECT_RATIO) -> //再看4:3是否支持 CameraParam.SECOND_ASPECT_RATIO else -> //两个都不支持的话就取它支持的第一个作为当前的宽高比 mPreviewSizes.ratios().iterator().next() } Log.i(TAG, "chooseAspectRatio, aspect ratio changed to " + aspectRatio.toString()) return aspectRatio } /** * 这里针对具体需求调整最合适的宽高比和输出图片大小,对于不同的手机而言,大部分都支持16:9(4:3)的比例, * 同时大部分也都支持输出1920x1080(800x600)的图片大小 */ private fun choosePictureSize(): CameraSize? { if (mAspectRatio == null){ Log.e("choosePictureSize", "mAspectRatio is null") return null } val sizes = mPictureSizes.sizes(mAspectRatio) //图片支持的宽高比,用这个比例去选合适的分辨率 if (sizes == null){ Log.e("choosePictureSize", "sizes is null") return null } return when (mAspectRatio) { CameraParam.DEFAULT_ASPECT_RATIO -> { val preferedSizes = arrayOf(CameraSize(1920, 1080), CameraSize(1280, 720))//几个比较合适的输出大小 // for (size in preferedSizes) { // if (sizes.contains(size)) { // return size // } // } preferedSizes.firstOrNull { sizes.contains(it) } ?: getMiddleSize(sizes) //前面几个合适的大小都没有的话,那么就使用中间那个大小 } CameraParam.SECOND_ASPECT_RATIO -> { val preferedSizes = arrayOf(CameraSize(1440, 1080), CameraSize(1280, 960), CameraSize(1024, 768), CameraSize(800, 600))//几个比较合适的输出大小 preferedSizes.firstOrNull { sizes.contains(it) } ?: getMiddleSize(sizes) } else -> { getMiddleSize(sizes) } } } private fun calcDisplayOrientation(screenOrientationDegrees: Int): Int { return if (mCameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) { (360 - (mCameraInfo.orientation + screenOrientationDegrees) % 360) % 360 } else { (mCameraInfo.orientation - screenOrientationDegrees + 360) % 360 } } private fun calcCameraRotation(screenOrientationDegrees: Int): Int { return if (mCameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) { (mCameraInfo.orientation + screenOrientationDegrees) % 360 } else { val landscapeFlip = if (isLandscape(screenOrientationDegrees)) 180 else 0 (mCameraInfo.orientation + screenOrientationDegrees + landscapeFlip) % 360 } } /** * 根据屏幕旋转的度数来判断是否是横屏 */ private fun isLandscape(orientationDegrees: Int): Boolean { return orientationDegrees == CameraParam.LANDSCAPE_90 || orientationDegrees == CameraParam.LANDSCAPE_270 } //前面几个合适的大小都没有的话,那么就使用中间那个大小 (即使是中间这个大小也并不能保证它满足我们的需求,比如得到的图片还是很大,但是这种情况实在太少了) private fun getMiddleSize(sizes: SortedSet<CameraSize>): CameraSize { val length = sizes.size / 2 var i = 0 sizes.forEach { item -> if (i == length) { return item } i++ } return sizes.last() } private fun calculateFocusArea(x: Float, y: Float): Rect { val view = mPreview?.getView()!! val buffer = FOCUS_AREA_SIZE_DEFAULT / 2 val centerX = calculateCenter(x, view.width, buffer) val centerY = calculateCenter(y, view.height, buffer) return Rect( centerX - buffer, centerY - buffer, centerX + buffer, centerY + buffer ) } private fun calculateCenter(coord: Float, dimen: Int, buffer: Int): Int { val normalized = (coord / dimen * 2000 - 1000).toInt() return if (Math.abs(normalized) + buffer > 1000) { if (normalized > 0) { 1000 - buffer } else { -1000 + buffer } } else { normalized } } }<file_sep>package com.example.filterlibrary.effects import com.example.filterlibrary.Filter /** * Created by liuxuan on 2019/1/29 */ class BlackFilter constructor(with: Int = 0, height: Int = 0) : Filter(with, height) { companion object { private val kFilterVertex: String = "attribute vec4 aPosition;\n" + "attribute vec4 aTexCoord;\n" + "varying vec2 vTexCoord;\n" + "void main() {\n" + " gl_Position = aPosition;\n" + " vTexCoord = aTexCoord.xy;\n" + "}\n" private val kBlackFilterFragment: String = "varying highp vec2 vTexCoord;\n" + "uniform sampler2D uTexture;\n" + "void main() {\n" + " vec4 vCameraColor = texture2D(uTexture, vTexCoord);\n" + " float fGrayColor = (0.3*vCameraColor.r + 0.59*vCameraColor.g + 0.11*vCameraColor.b);\n" + " gl_FragColor = vec4(fGrayColor, fGrayColor, fGrayColor, 1.0);\n" + "}" } override fun getVertexShader(): String { return kFilterVertex } override fun getFragmentShader(): String { return kBlackFilterFragment } }<file_sep>// // Created by 刘轩 on 2018/12/18. // #include "FilterContext.hpp" void FilterContext::setString() { hello = "hello GLCameraContext"; } <file_sep>// // Created by 刘轩 on 2018/12/20. // #include "Message.h" #include <utility> int GCVBase::Message::maxSize = 20; int GCVBase::Message::nowSize = 0; GCVBase::Message * GCVBase::Message::poolHead = nullptr; /** * 所有的方法都在Looper中统一做加锁等多线程相关的处理 */ GCVBase::Message *GCVBase::Message::obtain() { Message *m = poolHead; if (poolHead != nullptr) { poolHead = m->next; m->next = nullptr; nowSize--; return m; } else { m = new Message(); } return m; } void GCVBase::Message::recycle(GCVBase::Message *message) { resetMessage(message); //回收时先重置Message对象中的各种信息 if(poolHead != nullptr){ if(!isNowMaxPool()) { Message *temp = poolHead; while (temp->next != nullptr) { temp = temp->next; } temp->next = message; } else{ // TODO 这里加一些删除操作的提示信息,用于判断缓存池容量大小是否合适,也可以在这里做一些逻辑用于决定缓存池是否扩容 delete(message); //如果此时缓存池已经是最大容量了,就不要再缓存了,直接删掉 } } else{ // TODO 检查 nowSize 的值,如果不为0那就有问题了 poolHead = message; } nowSize++; } void GCVBase::Message::resetMessage(Message * message) { message->next = nullptr; message->setMessageQueueName(""); //reset的时候主要把next和QueueName置空,Function对象不要动,可以重复利用 } void GCVBase::Message::clearMessagePool() { while(poolHead != nullptr){ //清空缓存池中的缓存消息 Message *m = poolHead; poolHead = m->next; m->next = nullptr; delete(m); } } GCVBase::Message::Message() { Message("", nullptr); } GCVBase::Message::Message(std::string messageQueueName, Function *messageFunction) { mMessageQueueName = std::move(messageQueueName); mMessageFunction = messageFunction; } GCVBase::Message::~Message() { delete(mMessageFunction); } void GCVBase::Message::setMessageQueueName(std::string messageQueueName) { mMessageQueueName = std::move(messageQueueName); } std::string GCVBase::Message::getMessageQueueName() { return mMessageQueueName; } void GCVBase::Message::setMessageFunction(GCVBase::Function *messageFunction) { mMessageFunction = messageFunction; } void GCVBase::Message::setMaxPoolSize(int max) { maxSize = max; } int GCVBase::Message::getNowPoolSize() { return nowSize; } bool GCVBase::Message::isNowMaxPool() { return nowSize >= maxSize; } <file_sep>package com.example.codeclibrary import android.media.MediaCodecInfo import android.media.MediaCodecList import android.media.MediaFormat import android.os.Build import android.util.Log import com.example.baselib.GCVOutput /** * Created by liuxuan on 2019/1/10 */ class MovieRecorder(savepath: String, width: Int, height: Int, bitRate: Long, outputOrientation: Int) : GCVOutput{ var movieRecorderAddress: Long = 0L init{ var colorFormat: Int = 0 var bitRateMode: Int = -1 val numCodecs = MediaCodecList.getCodecCount() // 获取所有支持编解码器数量 var codecInfo: MediaCodecInfo? = null var i = 0 while (i < numCodecs && codecInfo == null) { val info: MediaCodecInfo = MediaCodecList.getCodecInfoAt(i) // 编解码器相关性信息存储在MediaCodecInfo中 if (info.isEncoder) { // 判断是否为编码器 val types = info.supportedTypes // 获取编码器支持的MIME类型,并进行匹配 for (j in types.indices) { if (types[j] == "video/avc") { codecInfo = info break } } } if (codecInfo != null) { break } i++ } val capabilities: MediaCodecInfo.CodecCapabilities? = codecInfo?.getCapabilitiesForType("video/avc") if (Build.VERSION.SDK_INT > 21 && capabilities != null) { val encoderCapabilities = capabilities.encoderCapabilities when { encoderCapabilities.isBitrateModeSupported(MediaCodecInfo.EncoderCapabilities.BITRATE_MODE_CQ) -> bitRateMode = MediaCodecInfo.EncoderCapabilities.BITRATE_MODE_CQ encoderCapabilities.isBitrateModeSupported(MediaCodecInfo.EncoderCapabilities.BITRATE_MODE_CBR) -> bitRateMode = MediaCodecInfo.EncoderCapabilities.BITRATE_MODE_CBR encoderCapabilities.isBitrateModeSupported(MediaCodecInfo.EncoderCapabilities.BITRATE_MODE_VBR) -> bitRateMode = MediaCodecInfo.EncoderCapabilities.BITRATE_MODE_VBR } } if (capabilities != null) { for (i in capabilities.colorFormats.indices) { when (capabilities.colorFormats[i]) { MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420Planar, MediaCodecInfo.CodecCapabilities.COLOR_FormatYUV420SemiPlanar -> colorFormat = capabilities.colorFormats[i] else -> { } } if (colorFormat != 0) { break } } } movieRecorderAddress = nativeRecorderInit(savepath, width, height, bitRate, outputOrientation, colorFormat, bitRateMode) } override fun nativeOutput(): Long { return movieRecorderAddress } fun startRecorder(){ nativeStartRecorder(movieRecorderAddress) } fun finishRecorder(){ nativeFinishRecorder(movieRecorderAddress) } fun pauseRecorder(){ nativePauseRecorder(movieRecorderAddress) } fun cancelRecording(){ nativecancelRecording(movieRecorderAddress) } fun onSurfaceDestory(){ nativeSurfaceDestory(movieRecorderAddress) } /** * TODO 这里还要写几个生命周期函数供JNI层反射回调 */ private external fun nativeRecorderInit(savepath: String, width: Int, height: Int, bitRate: Long, outputOrientation: Int, mediacodecColorFormat: Int, bitRateMode:Int): Long private external fun nativeStartRecorder(movieRecorderAddress: Long) private external fun nativeFinishRecorder(movieRecorderAddress: Long) private external fun nativePauseRecorder(movieRecorderAddress: Long) private external fun nativecancelRecording(movieWriterAddress: Long) private external fun nativeSurfaceDestory(movieWriterAddress: Long) }<file_sep>package com.example.cameralibrary.camera.api import android.graphics.SurfaceTexture import com.example.cameralibrary.camera.AspectRatio import com.example.cameralibrary.preview.PreviewImpl /** * Created by liuxuan on 2018/12/27 */ class Camera2 : CameraImpl(){ override fun takePicture(cameraTakePicture: PreviewImpl.CameraTakePictureListener) { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun openCamera(mFacing: Int, callback: CameraOpenCallback) { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun closeCamera(callback: CameraCloseCallback) { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun startPreview(surfaceTexture: SurfaceTexture, callback: PreviewStartCallback) { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun stopPreview(callback: PreviewStopCallback) { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun setPreviewImpl(mPreview: PreviewImpl) { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun setFacing(facing: Int) { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun setFlash(flash: Int) { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun setAutoFocus(autoFocus: Boolean) { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun setAspectRatio(ratio: AspectRatio): Boolean { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun getSupportedAspectRatios(): Set<AspectRatio> { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun setDisplayOrientation(displayOrientation: Int) { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } }<file_sep>// // Created by 刘轩 on 2019/2/5. // #ifndef GPUCAMERAVIDEO_MEDIAPLAYER_H #define GPUCAMERAVIDEO_MEDIAPLAYER_H #include "Decode/MediaDecoder.h" #include "NativeInput.h" namespace GCVBase { class MediaPlayer : NativeInput { public: MediaPlayer(std::string readPath = nullptr, ANativeWindow * nativeWindow = nullptr); ~MediaPlayer(); void setFilePath( std::string readPath); void startPlayer(const std::function<void ()> &handler); void pausePlayer(const std::function<void ()> &handler); void cancelPlayer(const std::function<void ()> &handler); void setNativeSurface(ANativeWindow * nativeWindow); private: bool mIsPlaying = false; MediaDecoder * mediaDecoder = NULL; Rotation rotationPlayer = Rotation::defaultRotation(); std::function<void ()> startCallback = NULL; std::function<void ()> pauseCallback = NULL; std::function<void ()> cancelCallback = NULL; void readNextVideoFrame(); void readNextAudioFrame(); void newFrameReadyAtTime(const GCVBase::Rotation &mRotation,FrameBuffer *resultFbo, const MediaTime &time); }; } #endif //GPUCAMERAVIDEO_MEDIAPLAYER_H <file_sep>// // Created by 刘轩 on 2019/1/10. // #ifndef GPUCAMERAVIDEO_ENCODE_H #define GPUCAMERAVIDEO_ENCODE_H namespace GCVBase { class Encoder { }; } #endif //GPUCAMERAVIDEO_ENCODE_H <file_sep>// // Created by 刘轩 on 2019/1/10. // #ifndef GPUCAMERAVIDEO_TIME_H #define GPUCAMERAVIDEO_TIME_H #include <cstdio> #include <cmath> #include <chrono> namespace GCVBase{ union Time { struct { int64_t value; //从开始到当前帧经过的时间 int32_t fps; //帧率 }; public: Time(int64_t nValue , int32_t nfps){ value = nValue; fps = nfps; } static const Time &Zero() { static const Time zero(0, 1); return zero; } }; typedef Time MediaTime; static inline std::chrono::system_clock::duration periods() { return std::chrono::system_clock::now().time_since_epoch(); } static inline double currentTimeOfSeconds() { using namespace std::chrono; return duration_cast<seconds>(periods()).count(); } static inline double currentTimeOfMilliseconds(){ using namespace std::chrono; return duration_cast<milliseconds>(periods()).count(); } static inline double currentTimeOfNanoseconds(){ using namespace std::chrono; return duration_cast<nanoseconds>(periods()).count(); } } #endif //GPUCAMERAVIDEO_TIME_H <file_sep>package com.example.cameralibrary.preview.surfaceview import android.content.Context import android.graphics.SurfaceTexture import android.util.AttributeSet import android.view.* import com.example.baselib.GCVInput import com.example.baselib.GCVOutput import com.example.cameralibrary.R import com.example.cameralibrary.camera.AspectRatio import com.example.cameralibrary.camera.CameraParam import com.example.cameralibrary.preview.Preview import com.example.cameralibrary.preview.PreviewImpl import com.example.cameralibrary.preview.PreviewImpl.SurfaceListener import com.example.cameralibrary.preview.PreviewImpl.CameraOpenListener import com.example.cameralibrary.preview.PreviewImpl.CameraPreviewListener import com.example.cameralibrary.preview.PreviewImpl.CameraTakePictureListener import java.nio.ByteBuffer /** * Created by liuxuan on 2019/1/2 */ class SurfaceViewPreview(context: Context, parent: ViewGroup, attrs: AttributeSet?, defStyleAttr: Int) : PreviewImpl(context), GCVOutput, SurfaceListener, CameraOpenListener, CameraPreviewListener, CameraTakePictureListener { private var mSurfaceview: SurfaceView? = null private var mHolder: SurfaceHolder? = null private var mFilterGroup: GCVInput? = null private var mFacing: Int = 0 private var mContext: Context? = null private var mAttrs: AttributeSet? = null private var mDefStyleAttr: Int = 0 private var nativeOutputSurfaceViewAddress: Long = 0L private var mPreviewLifeListener: Preview.PreviewLifeListener? = null private var mPreviewDataListener: Preview.PreviewDataListener? = null init { /* * 设置本类引用,本来是不想让Camera持有View引用的,现在看来是不行(否则会非常麻烦),后面想办法重构吧 */ mCamera.setPreviewImpl(this) mAttrs = attrs mContext = context mDefStyleAttr = defStyleAttr val view = View.inflate(context, R.layout.surface_preview, parent) mSurfaceview = view.findViewById(R.id.surface_view) mHolder = mSurfaceview?.holder mHolder?.addCallback(SurfaceCallback(mCamera, this)) } override fun getView(): View? { return mSurfaceview } /** * 设置滤镜组 */ override fun setFilterGroup(filterGroup: GCVInput) { mFilterGroup = filterGroup mFilterGroup?.addTarget(this@SurfaceViewPreview) mCamera.addTarget(mFilterGroup as GCVOutput) } /** * 添加录像组件。注意如果需要有滤镜效果,则录像组件需要挂在滤镜组上 */ override fun setRecorder(movieRecorder: GCVOutput) { if(mFilterGroup != null){ mFilterGroup?.addTarget(movieRecorder) }else { mCamera.addTarget(this@SurfaceViewPreview) } } override fun setFacing(facing: Int){ mCamera.setFacing(facing) } override fun getFacing(): Int { return mCamera.getCameraFacing() } override fun previewIsReady(): Boolean { //onSurfaceChanged执行完了之后就准备好了 return getWidth() != 0 && getHeight() != 0 } override fun takePicture(){ mCamera.takePicture(this) } override fun nativeOutput(): Long { return if(nativeOutputSurfaceViewAddress != 0L ){ nativeOutputSurfaceViewAddress }else{ 0L } } /******************************** SurfaceCallback生命周期 ********************************************/ /** * 相机的生命周期应当由Surface来管理,不应当开放给顶层的View,但是我们可以通过 */ override fun onSurfaceCreated(nativeOutputAddress: Long) { nativeOutputSurfaceViewAddress = nativeOutputAddress mPreviewLifeListener?.onPreviewCreated() } override fun onSurfaceChanged(surfaceTexture: SurfaceTexture?, width: Int, height: Int) { setPreviewSize(width, height) if(surfaceTexture != null){ mCamera.openCamera(mFacing, surfaceTexture, this, this) } mPreviewLifeListener?.onPreviewChanged(width, height) } override fun onSurfaceDestory() { mCamera.stopPreview() mPreviewLifeListener?.onPreviewCreated() } /******************************** Camera 生命周期 ********************************************/ override fun onCameraOpen() { if(mAttrs != null && mContext != null) { initCamera(mContext!!, mAttrs!!, mDefStyleAttr) } } override fun onOpenError() { } override fun onPreviewStart() { mPreviewLifeListener?.onPreviewReady() } override fun onPreviewFrame(previewFrameData: ByteBuffer) { mPreviewDataListener?.onPreviewFrame(previewFrameData) } override fun onPreviewError() { } override fun onPictureTaken(cameraPictureData: ByteBuffer) { mPreviewDataListener?.onPictureTaken(cameraPictureData) } override fun onPictureError() { TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } /*********************************************************************************************/ override fun setPreviewLifeListener(previewLife: Preview.PreviewLifeListener) { mPreviewLifeListener = previewLife } override fun setPreviewDataListener(previewData: Preview.PreviewDataListener){ mPreviewDataListener = previewData } private fun initCamera(context: Context, attrs: AttributeSet, defStyleAttr: Int){ val typedArray = context.obtainStyledAttributes(attrs, R.styleable.CameraView, defStyleAttr, R.style.Widget_CameraView) mFacing = typedArray.getInt(R.styleable.CameraView_facing, CameraParam.FACING_BACK) val aspectRatio = typedArray.getString(R.styleable.CameraView_aspectRatio) if (aspectRatio != null) { mCamera.setAspectRatio(AspectRatio.parse(aspectRatio)) } else { mCamera.setAspectRatio(CameraParam.DEFAULT_ASPECT_RATIO)//默认宽高比是16:9 } mCamera.setFacing(mFacing) //默认后置摄像头 mCamera.setAutoFocus(typedArray.getBoolean(R.styleable.CameraView_autoFocus, true))//默认自动对焦模式 mCamera.setFlash(typedArray.getInt(R.styleable.CameraView_flash, CameraParam.FLASH_OFF))//默认关闭闪光灯 typedArray.recycle() } }<file_sep>package com.example.baselib /** * Created by liuxuan on 2019/1/7 */ interface GCVOutput { fun nativeOutput(): Long }<file_sep>// // Created by 刘轩 on 2019/1/11. // #include <Context.h> #include "libyuv.h" #include "MediaEncoder.hpp" const int COLOR_FormatYUV420Planar = 0x00000013; const int COLOR_FormatYUV420SemiPlanar = 0x00000015; const int BUFFER_FLAG_CODEC_CONFIG = 0x00000002; // 0x00000002 = BUFFER_FLAG_CODEC_CONFIG static inline uint64_t getCurrentTime() { return (uint64_t) (GCVBase::currentTimeOfNanoseconds() / 1000UL); } GCVBase::MediaEncoder::MediaEncoder(const GCVBase::EncoderConfig &config) { mEncoderConfig = config; encoderLooper = new Looper("encoderLooper"); initVideoCodec(); initAudioCodec(); } GCVBase::MediaEncoder::~MediaEncoder() { delete encoderLooper; } /****************************************** Encoder 类生命周期函数 *******************************************/ void GCVBase::MediaEncoder::startEncoder(std::function<void()> startHandler) { mStop = false; startMediaMuxer(); if (startHandler) { startHandler(); } } void GCVBase::MediaEncoder::pauseEncoder(std::function<void()> pauseHandler) { mStop = true; if (pauseHandler) { pauseHandler(); } } void GCVBase::MediaEncoder::cancelEncoder(std::function<void()> cancelHandler) { if (!mStop) { mStop = true; finishEncoder(nullptr); if (cancelHandler) { cancelHandler(); } } } void GCVBase::MediaEncoder::finishEncoder(std::function<void()> finishHandler) { if (mAudioMediaCodec) { stopMediaMuxer(mAudioMediaCodec); } if (mVideoMediaCodec) { stopMediaMuxer(mVideoMediaCodec); } if (!mStop) { mStop = true; if (finishHandler) { finishHandler(); } } } /*******************************************************************************************************/ /****************************************** Codec 生命周期函数 *******************************************/ void GCVBase::MediaEncoder::initVideoCodec() { if (!mEncoderConfig.colorYUVFormat) { //我们会在创建MediaRecoder时传入指定的纹理格式,这里我们设置解码的YUV数据格式缺省值为420p mEncoderConfig.colorYUVFormat = COLOR_FormatYUV420Planar; } mIsYUV420SP = mEncoderConfig.colorYUVFormat == COLOR_FormatYUV420SemiPlanar; AMediaFormat *videoEncoderFormat = AMediaFormat_new(); AMediaFormat_setInt32(videoEncoderFormat, AMEDIAFORMAT_KEY_BIT_RATE, (int32_t) mEncoderConfig.videoBitRate); AMediaFormat_setInt32(videoEncoderFormat, AMEDIAFORMAT_KEY_FRAME_RATE, mEncoderConfig.frameRate); AMediaFormat_setInt32(videoEncoderFormat, AMEDIAFORMAT_KEY_COLOR_FORMAT, mEncoderConfig.colorYUVFormat); AMediaFormat_setInt32(videoEncoderFormat, AMEDIAFORMAT_KEY_WIDTH, (int32_t) mEncoderConfig.outputSize.width); AMediaFormat_setInt32(videoEncoderFormat, AMEDIAFORMAT_KEY_HEIGHT, (int32_t) mEncoderConfig.outputSize.height); AMediaFormat_setInt32(videoEncoderFormat, AMEDIAFORMAT_KEY_I_FRAME_INTERVAL, 0); AMediaFormat_setInt32(videoEncoderFormat, "bitrate-mode", 0); //默认比特率模式为BITRATE_MODE_CQ: 表示完全不控制码率,尽最大可能保证图像质量 std::string videoMimeTypes[] = {"video/avc"}; int count = sizeof(videoMimeTypes) / sizeof(const std::string); for (int i = 0; i < count; ++i) { auto videoMimeType = videoMimeTypes[i]; mVideoMediaCodec = AMediaCodec_createEncoderByType(videoMimeType.c_str()); AMediaFormat_setString(videoEncoderFormat, AMEDIAFORMAT_KEY_MIME, videoMimeType.c_str()); if (mVideoMediaCodec) { break; } } int ret = AMediaCodec_configure(mVideoMediaCodec, videoEncoderFormat, NULL, NULL, AMEDIACODEC_CONFIGURE_FLAG_ENCODE); //最后一个参数表示这是个编码器,如果是解码器的话直接传个0就行了 if (ret != AMEDIA_OK) { //当 BITRATE_MODE_CQ为不支持的比特率模式时,重新用上层传下来的bitRateMode来配置,上层是经过 MediaCodecInfo.CodecCapabilities 查询之后选取的 AMediaFormat_setInt32(videoEncoderFormat, "bitrate-mode", mEncoderConfig.bitRateMode); ret = AMediaCodec_configure(mVideoMediaCodec, videoEncoderFormat, NULL, NULL, AMEDIACODEC_CONFIGURE_FLAG_ENCODE); } if (ret != AMEDIA_OK) { __android_log_print(ANDROID_LOG_ERROR, "VideoCodec", "configure video encoder failed == %d", ret); AMediaFormat_delete(videoEncoderFormat); } } void GCVBase::MediaEncoder::initAudioCodec() { AMediaFormat *audioEncoderFormat = AMediaFormat_new(); AMediaFormat_setInt32(audioEncoderFormat, AMEDIAFORMAT_KEY_SAMPLE_RATE, mEncoderConfig.sampleRate); AMediaFormat_setInt32(audioEncoderFormat, AMEDIAFORMAT_KEY_CHANNEL_COUNT, mEncoderConfig.getChannelCount()); AMediaFormat_setInt32(audioEncoderFormat, AMEDIAFORMAT_KEY_BIT_RATE, (int) mEncoderConfig.audioBitRate); __android_log_print(ANDROID_LOG_ERROR, "AudioCodec", "audio encode mime = %s", AMediaFormat_toString(audioEncoderFormat)); std::string audioMimeTypes[] = {"audio/mp4a-latm"}; int count = sizeof(audioMimeTypes) / sizeof(const std::string); for (int i = 0; i < count; ++i) { auto audioMimeType = audioMimeTypes[i]; __android_log_print(ANDROID_LOG_ERROR, "AudioCodec", "audio encode mime = %s", audioMimeType.c_str()); mAudioMediaCodec = AMediaCodec_createEncoderByType(audioMimeType.c_str()); AMediaFormat_setString(audioEncoderFormat, AMEDIAFORMAT_KEY_MIME, audioMimeType.c_str()); if (mAudioMediaCodec) { break; } } int ret = AMediaCodec_configure(mAudioMediaCodec, audioEncoderFormat, NULL, NULL, AMEDIACODEC_CONFIGURE_FLAG_ENCODE); if (ret != AMEDIA_OK) { __android_log_print(ANDROID_LOG_ERROR, "AudioCodec", "configure video encoder failed == %d", ret); AMediaFormat_delete(audioEncoderFormat); } } void GCVBase::MediaEncoder::newFrameEncodeVideo(GCVBase::MediaBuffer<uint8_t *> *videoBuffer) { if (!mVideoMediaCodec) { return; } auto inputBuffer = AMediaCodec_dequeueInputBuffer(mVideoMediaCodec, 2000); if (inputBuffer > AMEDIACODEC_INFO_TRY_AGAIN_LATER) { size_t outputSize = 0; //inputBuffer的长度 uint8_t *input = AMediaCodec_getInputBuffer(mVideoMediaCodec, (size_t) inputBuffer, &outputSize); //这玩意是送进编码器的空buffer,需要我们手动填充数据 memset(input, 0, outputSize); //初始化inputBuffer int width = (int) mEncoderConfig.outputSize.width; //图像宽度(像素) int height = (int) mEncoderConfig.outputSize.height; //图像高度(像素) auto y_size = width * height; auto yuv_size = y_size * 3 / 2; //如果是420p的数据,直接ABGRToI420即可;如果是420sp的数据,则先转成420p(I420),再转成420sp(NV21),因为libyuv不能直接将I420转到NV21 unsigned char *I420 = mIsYUV420SP ? (unsigned char *) malloc((size_t) yuv_size) : input; //这里的YUV代表的是起始地址,Y = I420表示的是从I420起始的地方开始读,同理易得U、V unsigned char *Y = I420; unsigned char *U = I420 + (unsigned long) (y_size); unsigned char *V = U + (unsigned long) (y_size / 4); /* BGRAToI420, 内存顺序是BGRA,但用libyuv转化的时候用得反过来用ARGB。 * * 跨距就是指图像中的一行图像数据所占的存储空间的长度,它是一个大于等于图像宽度的内存对齐的长度。 * 这样每次以行为基准读取数据的时候就能内存对齐,虽然可能会有一点内存浪费,但是在内存充裕的今天已经无所谓了。 */ libyuv::ABGRToI420(videoBuffer->mediaData, //一帧的数据 width * 4, //一帧数据的stride(跨距) Y, //Y数据的起始地址 width, //Y数据的 stride U, //U数据的起始地址 width / 2, //U数据的 stride V, //V数据的起始地址 width / 2, //V数据的 stride width, //宽 height); //高 if (mIsYUV420SP) { uint8_t *dst_y = input; int dst_stride_y = width; int dst_stride_uv = width; uint8_t *dst_uv = dst_y + width * height; libyuv::I420ToNV21(Y, width, V, width / 2, U, width / 2, dst_y, dst_stride_y, dst_uv, dst_stride_uv, width, height); free(I420); } free(videoBuffer->mediaData); uint64_t time = (uint64_t) getCurrentTime(); AMediaCodec_queueInputBuffer(mVideoMediaCodec, (size_t) inputBuffer, 0, (size_t) outputSize, time, 0); AMediaCodecBufferInfo bufferInfo; recordCodecBuffer(&bufferInfo, mVideoMediaCodec, mVideoTrackIndex); } } void GCVBase::MediaEncoder::newFrameEncodeAudio(GCVBase::MediaBuffer<uint8_t *> *audioBuffer) { if (!mAudioMediaCodec) { return; } auto buffer = audioBuffer; auto inputBuffer = AMediaCodec_dequeueInputBuffer(mAudioMediaCodec, 0); if (inputBuffer > AMEDIACODEC_INFO_TRY_AGAIN_LATER) { size_t outputSize = 0; uint8_t *input = AMediaCodec_getInputBuffer(mAudioMediaCodec, (size_t)inputBuffer, &outputSize); memset(input, 0, outputSize); memcpy(input, buffer->mediaData, (size_t) outputSize); uint64_t time = (uint64_t)getCurrentTime(); AMediaCodec_queueInputBuffer(mAudioMediaCodec, (size_t)inputBuffer, 0, (size_t) outputSize, time, 0); AMediaCodecBufferInfo bufferInfo; recordCodecBuffer(&bufferInfo, mAudioMediaCodec, mAudioTrackIndex); } } void GCVBase::MediaEncoder::recordCodecBuffer(AMediaCodecBufferInfo *bufferInfo, AMediaCodec *codec, int trackIndex) { auto outputBuffer = AMediaCodec_dequeueOutputBuffer(codec, bufferInfo, 2000); if (outputBuffer == AMEDIACODEC_INFO_OUTPUT_FORMAT_CHANGED) { auto outputFormat = AMediaCodec_getOutputFormat(codec); __android_log_print(ANDROID_LOG_INFO, "outputBuffer", "AMEDIACODEC_INFO_OUTPUT_FORMAT_CHANGED"); __android_log_print(ANDROID_LOG_INFO, "AMediaCodec_getOutputFormat", "output format === %s", AMediaFormat_toString(outputFormat)); ssize_t &index = codec == mVideoMediaCodec ? mVideoTrackIndex : mAudioTrackIndex; ssize_t track = AMediaMuxer_addTrack(mMuxer, outputFormat); if (track < 0) { index = mStartCount; } else { index = track; } mStartCount++; __android_log_print(ANDROID_LOG_INFO, "AMediaMuxer_addTrack", "add %s trackIndex: %d", mVideoMediaCodec == codec ? "video" : "Audio", index); if (mStartCount == 1) { //添加两次轨道之后就开始写入数据了(默认一条音轨一条视频轨道) int result = AMediaMuxer_start(mMuxer); if (result != AMEDIA_OK) { __android_log_print(ANDROID_LOG_ERROR, "AMediaMuxer_start", "AMediaMuxer start filed"); } mIsRunning = true; } else { AMediaCodecBufferInfo buffer; recordCodecBuffer(&buffer, codec == mVideoMediaCodec ? mAudioMediaCodec : mVideoMediaCodec, mStartCount); } } else if (outputBuffer == AMEDIACODEC_INFO_OUTPUT_BUFFERS_CHANGED) { __android_log_print(ANDROID_LOG_INFO, "outputBuffer", "AMEDIACODEC_INFO_OUTPUT_BUFFERS_CHANGED"); } else if (outputBuffer == AMEDIACODEC_INFO_TRY_AGAIN_LATER) { __android_log_print(ANDROID_LOG_INFO, "outputBuffer", "AMEDIACODEC_INFO_TRY_AGAIN_LATER"); } else { if (!mIsRunning || (!mVideoIsWritten && trackIndex == mAudioTrackIndex)) { //如果视频帧还没有写入(且这一帧为音频帧)就先丢弃这一帧 auto result = AMediaCodec_releaseOutputBuffer(codec, (size_t) outputBuffer, false); if (result != AMEDIA_OK) { __android_log_print(ANDROID_LOG_ERROR, "releaseOutputBuffer", "AMediaCodec_releaseOutputBuffer failed type:%s", trackIndex == 0 ? "audio" : "video"); } return; } size_t outputSize = 0; auto output = AMediaCodec_getOutputBuffer(codec, (size_t)outputBuffer, &outputSize); if ((bufferInfo->flags & BUFFER_FLAG_CODEC_CONFIG) != 0) { __android_log_print(ANDROID_LOG_INFO, "getOutputBuffer", "ignoring BUFFER_FLAG_CODEC_CONFIG"); bufferInfo->size = 0; } GCVBase::runSyncContextLooper(encoderLooper, [=]{ if (bufferInfo->size > 0) { media_status_t status = AMediaMuxer_writeSampleData(mMuxer, trackIndex, output, bufferInfo); //这里直接就把 outputbuffer传进去了,毕竟是同步写入文件,写完后才会释放buffer if (status != AMEDIA_OK) { __android_log_print(ANDROID_LOG_ERROR, "writeSampleData", "write sample data failed !!!type:%s", trackIndex == 0 ? "audio" : "video"); } mVideoIsWritten = true; } auto result = AMediaCodec_releaseOutputBuffer(codec, (size_t)outputBuffer, false); if (result != AMEDIA_OK) { __android_log_print(ANDROID_LOG_ERROR, "releaseOutputBuffer", "AMediaCodec_releaseOutputBuffer failed type:%s", trackIndex == 0 ? "audio" : "video"); } }); } } void GCVBase::MediaEncoder::startMediaMuxer() { FILE *file = fopen(mEncoderConfig.outputPath.c_str(), "wb+"); saveFile = file; int fd = fileno(file); mMuxer = AMediaMuxer_new(fd, AMEDIAMUXER_OUTPUT_FORMAT_MPEG_4); AMediaMuxer_setOrientationHint(mMuxer, mEncoderConfig.outputOrientation); int result = 0; if (mVideoMediaCodec) { result = AMediaCodec_start(mVideoMediaCodec); if (result != AMEDIA_OK) { __android_log_print(ANDROID_LOG_ERROR, "AMediaCodec_start", "VideoMediaCodec start filed"); } } if (mAudioMediaCodec) { result = AMediaCodec_start(mAudioMediaCodec); if (result != AMEDIA_OK) { __android_log_print(ANDROID_LOG_ERROR, "AMediaCodec_start", "AudioMediaCodec start filed"); } } } void GCVBase::MediaEncoder::stopMediaMuxer(AMediaCodec *codec) { if (!codec) { return; } std::string nowcodec = codec == mVideoMediaCodec ? "VideoMediaCodec" : "AudioMediaCodec"; __android_log_print(ANDROID_LOG_ERROR, "stopMediaMuxer", "now Codec is %s", nowcodec.c_str()); int result = AMediaCodec_flush(codec); if (result != AMEDIA_OK) { __android_log_print(ANDROID_LOG_ERROR, "Codec_flush", "MediaCodec flush filed"); return; } result = AMediaCodec_stop(codec); if (result != AMEDIA_OK) { __android_log_print(ANDROID_LOG_ERROR, "Codec_stop", "MediaCodec stop filed"); return; } result = AMediaCodec_delete(codec); if (result != AMEDIA_OK) { __android_log_print(ANDROID_LOG_ERROR, "Codec_delete", "MediaCodec delete filed"); return; } nowcodec == "VideoMediaCodec" ? mVideoMediaCodec = nullptr : mAudioMediaCodec = nullptr; if (mVideoMediaCodec || mAudioMediaCodec) { return; } if (mMuxer != nullptr) { int res = AMediaMuxer_stop(mMuxer); if (res != AMEDIA_OK) { __android_log_print(ANDROID_LOG_ERROR, "AMediaMuxer_stop", "AMediaMuxer_stop failed === %d", res); } res = AMediaMuxer_delete(mMuxer); if (res != AMEDIA_OK) { __android_log_print(ANDROID_LOG_ERROR, "AMediaMuxer_delet", "AMediaMuxer_delet failed === %d", res); } mMuxer = nullptr; } if (saveFile != nullptr) { fflush(saveFile); fclose(saveFile); saveFile = nullptr; } mIsRunning = false; mAudioTrackIndex = -1; mVideoTrackIndex = -1; }<file_sep>// // Created by 刘轩 on 2018/12/27. // #include <jni.h> #include <android/native_window_jni.h> #include "Context.h" #include "camera.h" #include "DisplayView.h" using namespace GCVBase; extern "C" { jlong Java_com_example_cameralibrary_preview_surfaceview_SurfaceCallback_nativeSurfaceWindowInit(JNIEnv *env, jobject obj, jobject surface){ Context::initSharedContext(env); ANativeWindow * nativeWindow = ANativeWindow_fromSurface(env, surface); DisplayView * displayView = NULL; runSyncContextLooper(Context::getShareContext()->getContextLooper(), [&displayView, &nativeWindow]{ Context::getShareContext()->setNativeWindow(nativeWindow); displayView = new DisplayView(ANativeWindow_getWidth(nativeWindow), ANativeWindow_getHeight(nativeWindow)); }); return (jlong)displayView; } jint Java_com_example_cameralibrary_preview_surfaceview_SurfaceCallback_nativeGenTexture(JNIEnv *env, jobject obj, jlong nativeCamera) { if(!nativeCamera){ return 0; } Camera * camera = (Camera *)nativeCamera; camera -> genSurfaceTexture(); return camera -> getSurfaceTexture(); } void Java_com_example_cameralibrary_preview_surfaceview_SurfaceCallback_onSurfaceTextureAvailable(JNIEnv *env, jobject obj, jlong nativeCamera) { if (!nativeCamera) { return; } Camera * camera = (Camera *)nativeCamera; if(!camera->getEglInstance()->isCurrentContext()){ camera->getEglInstance()->makeAsCurrent(); } } void Java_com_example_cameralibrary_preview_surfaceview_SurfaceCallback_surfaceTextureAvailable(JNIEnv *env, jobject obj, jlong nativeCamera) { if(!nativeCamera){ return ; } Camera * camera = (Camera *)nativeCamera; camera -> surfaceTextureAvailable(); } void Java_com_example_cameralibrary_preview_surfaceview_SurfaceCallback_nativeOnSurfaceChanged(JNIEnv *env, jobject obj, jlong nativeCamera, jint width, jint height) { if(!nativeCamera){ return ; } Camera * camera = (Camera *)nativeCamera; camera ->setPreviewWidth(width); camera ->setPreviewHeight(height); camera->onSurfaceChanged(); } } <file_sep>package com.example.codeclibrary.playerview import android.content.Context import android.util.AttributeSet import android.view.Surface import android.view.SurfaceHolder import android.view.SurfaceView import com.example.baselib.GCVOutput /** * Created by liuxuan on 2019/2/7 */ class SurfacePlayerview: SurfaceView, SurfaceHolder.Callback, GCVOutput { private var lifeListener:PreviewLifeListener? = null private var nativeOutputSurfaceAddress: Long = 0 constructor(context: Context) : this(context, null) constructor(context: Context, attributeSet: AttributeSet?) : this(context, attributeSet, 0) constructor(context: Context, attributeSet: AttributeSet?, defStyleAttr: Int) : super(context, attributeSet, defStyleAttr){ holder.addCallback(this) } override fun surfaceCreated(holder: SurfaceHolder?) { } override fun surfaceChanged(holder: SurfaceHolder?, format: Int, width: Int, height: Int) { if(holder != null) { nativeOutputSurfaceAddress = nativeSurfaceWindowInit(holder.surface) //初始化native层egl的surface表面 } if (holder != null) { lifeListener?.onPreviewReady(holder) } } override fun surfaceDestroyed(holder: SurfaceHolder?) { nativeSurfaceWindowDestroyed(nativeOutputSurfaceAddress) if (holder != null) { lifeListener?.onPreviewDestroyed(holder) } } fun addPreviewLifeListener(previewLife: PreviewLifeListener){ lifeListener = previewLife } fun getSurface(): Surface { return holder.surface } override fun nativeOutput(): Long { return nativeOutputSurfaceAddress } private external fun nativeSurfaceWindowInit(surface: Any): Long private external fun nativeSurfaceWindowDestroyed(nativeOutputSurfaceAddress: Long) interface PreviewLifeListener{ fun onPreviewReady(holder: SurfaceHolder) fun onPreviewDestroyed(holder: SurfaceHolder) } }<file_sep>// // Created by 刘轩 on 2019/1/7. // #include <Context.h> #include "NativeInput.h" GCVBase::FrameBuffer * GCVBase::NativeInput::getOutputFrameBuffer() { return mOutputFrameBuffer; } void GCVBase::NativeInput::removeOutputFrameBuffer() { mOutputFrameBuffer = NULL; } void GCVBase::NativeInput::addTarget(GCVBase::NativeOutput *newTarget) { runSyncContextLooper(Context::getShareContext()->getContextLooper(),[=]{ mTargets.push_back(newTarget); }); } const std::vector<const GCVBase::NativeOutput *> & GCVBase::NativeInput::getTargets() { return * (const std::vector<const GCVBase::NativeOutput *> * ) & mTargets; } void GCVBase::NativeInput::removeTarget(GCVBase::NativeOutput *target) { } void GCVBase::NativeInput::removeAllTargets() { } <file_sep>// // Created by 刘轩 on 2018/12/25. // #ifndef GPUCAMERAVIDEO_EGLCORE_H #define GPUCAMERAVIDEO_EGLCORE_H #include <string> #include <EGL/egl.h> #include <android/native_window.h> #include <GLES2/gl2.h> namespace GCVBase { class EglCore { private: EGLContext mEGLContext = 0; EGLDisplay mEGLDisplay = 0; EGLSurface mEGLSurface = 0; EGLConfig mEGLConfig = 0; ANativeWindow * mWindow = 0; const void *mSharedObject = NULL; void checkEglError(std::string msg); public: EglCore(const void * sharedContext = NULL, ANativeWindow * window = NULL, int width = 0, int height = 0); ~EglCore(); EGLContext getEGLContext() const; bool isCurrentContext(); void makeAsCurrent(); void swapToScreen(); void resetSurface(ANativeWindow * window); const void * getSharedObject(); }; } #endif //GPUCAMERAVIDEO_EGLCORE_H <file_sep>// // Created by 刘轩 on 2018/12/23. // #ifndef GPUCAMERAVIDEO_CONDITIONLOCK_H #define GPUCAMERAVIDEO_CONDITIONLOCK_H #include <mutex> #include <condition_variable> class ConditionLock { private: std::mutex mutex; std::condition_variable mConditionVariable; /* * 验证条件,不同的Condition锁有不同的完成条件: * 对于queueConditionLock,条件就是queue中的message执行完毕或者退出 * 对于functionConditionLock,条件就是该Function执行完毕 */ std::function<bool()> mVerificationCondition; public: ConditionLock(const std::function<bool()> &condition){ mVerificationCondition = condition; } void verificationCondition(){ if(!mVerificationCondition){ return; } std::unique_lock<decltype(mutex)> lock(mutex); while (!mVerificationCondition()){ mConditionVariable.wait(lock); } } void notifyOne(){ std::unique_lock<decltype(mutex)> lock(mutex); mConditionVariable.notify_one(); } void notifyAll(){ std::unique_lock<decltype(mutex)> lock(mutex); mConditionVariable.notify_all(); } }; #endif //GPUCAMERAVIDEO_CONDITIONLOCK_H <file_sep>package com.example.cameralibrary.camera import android.hardware.Camera /** * Created by liuxuan on 2018/12/27 * Email : <EMAIL> */ class CameraAttributes(cameraInfo: Camera.CameraInfo, cameraParameters: Camera.Parameters) { // val mPreviewSizes: CameraSizeMap = CameraSizeMap() /** * orientation 表示相机图像的方向。它的值是相机图像顺时针旋转到设备自然方向一致时的角度。 * * 对于竖屏应用来说,后置相机传感器是横屏安装的,当你面向屏幕时: * 如果后置相机传感器顶边和设备自然方向的右边是平行的,那么后置相机的 orientation 是 90。 * 如果是前置相机传感器顶边和设备自然方向的右边是平行的,则前置相机的 orientation 是 270。 * * 对于前置和后置相机传感器 orientation 是不同的,在不同的设备上也可能会有不同的值。 */ val sensorOrientation: Int = cameraInfo.orientation val previewSizes: Array<CameraSize> = cameraParameters.supportedPreviewSizes.map { CameraSize(it) }.toTypedArray() // init { // for (size in cameraParameters.supportedPreviewSizes) { // mPreviewSizes.add(CameraSize(size.width, size.height)) // } // } }<file_sep>// // Created by 刘轩 on 2019/2/3. // #ifndef GPUCAMERAVIDEO_ROTATION_H #define GPUCAMERAVIDEO_ROTATION_H #include <GLES2/gl2.h> namespace GCVBase { typedef enum { rotation0, rotation90, rotation270, }RotationMode; typedef enum { FacingBack, FacingFront, }FacingMode; union Rotation { struct{ RotationMode rotationMode; FacingMode facing; }; static const Rotation & defaultRotation(){ static const Rotation rotation(RotationMode::rotation90, FacingMode::FacingBack); return rotation; } Rotation(RotationMode mRotationMode, FacingMode mFacing){ rotationMode = mRotationMode; facing = mFacing; } }; typedef Rotation rotation; static const GLfloat * CalculateDisplayRotation(const Rotation &rotation){ if(rotation.facing == FacingMode::FacingBack){ switch(rotation.rotationMode){ case RotationMode::rotation0 : //注意这里的旋转0°是指屏幕竖直放置 static const GLfloat texCoord0[] = { //预览的纹理需要先倒置,再进行右旋90° 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, }; return texCoord0; case RotationMode::rotation90: //注意这里的旋转90°是指屏幕逆时针旋转90°,也就是向左旋转90° static const GLfloat texCoord90[] = { //预览的纹理不需要倒置,直接上下颠倒 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, }; return texCoord90; case RotationMode::rotation270: //注意这里的旋转270°是指屏幕逆时针旋转270°,也就是向右旋转90° static const GLfloat texCoord270[] = { //预览的纹理不需要倒置,直接左右反转 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, }; return texCoord270; } } } static const GLfloat * CalculateRecoderRotation(const Rotation &rotation){ if(rotation.facing == FacingMode::FacingBack){ switch(rotation.rotationMode){ case RotationMode::rotation0 : static const GLfloat texCoord0[] = { //录制的纹理不需要倒置,直接对原坐标进行右旋90°即可 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, }; return texCoord0; case RotationMode::rotation90: static const GLfloat texCoord90[] = { //录制的纹理不需要倒置,直接用原坐标即可 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, }; return texCoord90; case RotationMode::rotation270: static const GLfloat texCoord270[] = { //录制的纹理不需要倒置,直接对原坐标进行右旋180°即可 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, }; return texCoord270; } } } } #endif //GPUCAMERAVIDEO_ROTATION_H <file_sep>// // Created by 刘轩 on 2018/12/20. // #ifndef GPUCAMERAVIDEO_FUNCTION_H #define GPUCAMERAVIDEO_FUNCTION_H #include "ConditionLock.hpp" namespace GCVBase { class Function { private: std::function<void()> mFunction = NULL; ConditionLock * functionConditionLock = NULL; bool mAsync = false; bool mFinished = false; public: Function(const std::function<void()> &function, bool async){ mAsync = async; mFunction = function; functionConditionLock = new ConditionLock([&]()-> bool{ return mFinished; }); } ~Function(){ delete functionConditionLock; } void forceWaitFunctionFinish(){ functionConditionLock->verificationCondition(); } void run(){ if(mFunction){ mFunction(); } mFinished = true; } void notifyOne(){ functionConditionLock->notifyOne(); } void setFunction(const std::function<void()> &function, bool async){ mFunction = function; mAsync = async; mFinished = false; } bool isAsync(){ return mAsync; } }; } #endif //GPUCAMERAVIDEO_FUNCTION_H <file_sep>// // Created by 刘轩 on 2019/1/10. // #ifndef GPUCAMERAVIDEO_MEDIARECORD_H #define GPUCAMERAVIDEO_MEDIARECORD_H #include <jni.h> #include "Context.h" #include "GLProgram.h" #include "NativeOutput.h" #include "Encode/MediaEncoder.hpp" namespace GCVBase { class MediaRecorder : NativeOutput{ private: GLuint aPositionAttribute = 0; GLuint aTexCoordAttribute = 0; GLuint uTextureuniform = 0; Size mVideoSize = Size::zero(); size_t mRGBADataSize = 0; GLuint mRecorderTexture = 0; GLuint mRecorderFramebuffer = 0; MediaEncoder * mediaEncoder = nullptr; Context * recordContext = nullptr; GLProgram *mRecordProgram = nullptr; bool mIsRecording = false; bool mCancelRecording = false; bool mEncoderIsFinished = false; MediaBuffer<GLubyte *> *mediaBuffer = nullptr; Rotation rotationMediaRecorder = Rotation::defaultRotation(); FrameBuffer *mFinalFilterFramebuffer = nullptr; //滤镜链的最后一个滤镜持有的FrameBuffer std::function<void (void)> mStartCallback = nullptr; std::function<void (void)> mPauseCallback = nullptr; std::function<void (void)> mFinishCallback = nullptr; std::function<void (void)> mCancelCallback = nullptr; void renderRecorderFramebuffer(FrameBuffer *framebuffer); void creatRecorderFramebuffer(); void bindRecorderFramebuffer(); void unBindRecorderFramebuffer(); public: jobject jmediaObj = nullptr; MediaRecorder(const EncoderConfig &config, JNIEnv * env); ~MediaRecorder(); /* * 整个录制的每个生命周期都需要向Java层返回一个回调 */ void startRecording(const std::function<void ()> &handler); void pauseRecording(const std::function<void ()> &handler); void finishRecording(const std::function<void ()> &handler); void cancelRecording(const std::function<void ()> &handler); void _newFrameReadyAtTime() override; void _setOutputRotation(const Rotation &rotation) override; void _setOutputFramebuffer(FrameBuffer *framebuffer) override; }; } #endif //GPUCAMERAVIDEO_MEDIARECORD_H <file_sep>package com.example.cameralibrary.camera /** * Created by liuxuan on 2018/12/27 */ class CameraSize(val mWidth: Int, val mHeight: Int): Comparable<CameraSize> { companion object { operator fun invoke(size: android.hardware.Camera.Size): CameraSize{ return CameraSize(size.width, size.height) } } override fun equals(o: Any?): Boolean { if (o == null) { return false } if (this === o) { return true } if (o is CameraSize) { return mWidth == o.mWidth && mHeight == o.mHeight } return false } override fun hashCode(): Int { // assuming most sizes are <2^16, doing a rotate will give us perfect hashing return mHeight xor (mWidth shl Integer.SIZE / 2 or mWidth.ushr(Integer.SIZE / 2)) } fun getWidth(): Int{ return mWidth } fun getHeight(): Int{ return mHeight } fun getArea(): Int{ return mWidth * mHeight } override fun compareTo(other: CameraSize): Int { return when { getArea() > other.getArea() -> 1 getArea() < other.getArea() -> -1 else -> 0 } } }<file_sep>// // Created by 刘轩 on 2018/12/27. // #include <android/log.h> #include <Size.hpp> #include <FilterGroup.h> #include "Camera.h" std::string cameraVertexShader = "attribute vec4 aPosition;\n" "attribute vec4 aTexCoord;\n" "varying vec2 vTexCoord;\n" "void main() {\n" " gl_Position = aPosition;\n" " vTexCoord = aTexCoord.xy;\n" "}\n"; std::string cameraFragmentShader = "#extension GL_OES_EGL_image_external : require\n" "precision mediump float;\n" "varying vec2 vTexCoord;\n" "uniform samplerExternalOES uTexture;\n" "void main() {\n" " gl_FragColor = texture2D(uTexture, vTexCoord);\n" "}\n"; GCVBase::Camera::Camera(int mFacing) { mFacingMode = mFacing == 0 ? FacingMode::FacingBack : FacingMode::FacingFront; rotationCamera = Rotation(rotationMode, mFacingMode); runSyncContextLooper(Context::getShareContext()->getContextLooper(), [=] { Context::makeShareContextAsCurrent(); __android_log_print(ANDROID_LOG_ERROR, "Camera", "Camera Thread is %u", std::this_thread::get_id()); mCameraProgram = new GLProgram(cameraVertexShader, cameraFragmentShader); if(!mCameraProgram->isProgramLinked()){ if(!mCameraProgram->linkProgram()){ // TODO 获取program连接日志` } } aPositionAttribute = mCameraProgram->getAttributeIndex("aPosition"); aTexCoordAttribute = mCameraProgram->getAttributeIndex("aTexCoord"); uTextureuniform = mCameraProgram->getuniformIndex("uTexture"); }); } GCVBase::Camera::~Camera() { } std::string GCVBase::Camera::VertexShared() { return cameraVertexShader; } std::string GCVBase::Camera::FragmentShared() { return cameraFragmentShader; } GCVBase::EglCore *GCVBase::Camera::getEglInstance() { return mEglInstance; } /** * 这个函数是在Java层的 SurfaceHolder.Callback 线程中的,而我们的 sharedEglInstance 中的 eglInstance是在他自己的 * Looper 对应的线程中的,因此这里不能调sharedEglInstance(主Context)的eglMakeCurren函数,会出事情 * * 同时,这个函数中初始化了OES扩展纹理,这个纹理就是SurfaceTexture中绑定的纹理,后续系统的渲染函数都会到这个纹理上来,但是 * 同样因为这个纹理是在 SurfaceHolder.Callback 线程中,因此在 sharedEglInstance 对应的线程中是不能对这个纹理进行操作的 * * 因此我们这里用到了Egl的ShareContext(共享上下文),也就是重新new 一个 EglCore 对象,将上面的 sharedEglInstance 作为 * 共享上下文传入 eglCreateContext 函数中,这样的话两个线程就可以同时对 mOESTexture 进行操作了 * * 这样的话我们就可以在下面的 surfaceTextureAvailable 调用 sharedEglInstance的 eglSwapBuffers 函数,从而将渲染结果 * 交换到前台,显示到屏幕上了 * * 同时需要注意的是,我们新new 的 EglCore 对象中第二个参数(ANativeWindow * )是NULL,从对应的源码中我们可以看到,在这个 * 逻辑中我们创建EGLSurface 的是eglCreatePbufferSurface(),这个函数只是在后台创建一个数据缓冲区,用于缓存这一帧的像素 * 数据,之所以这么做是因为我们考虑后面在录制视频的时候要加一个写入线程,将缓冲区中的数据编码、写入本地,这样预览就不会卡了 */ void GCVBase::Camera::genSurfaceTexture() { __android_log_print(ANDROID_LOG_ERROR, "genSurfaceTexture", "genSurfaceTexture Thread is %u", std::this_thread::get_id()); if (!mEglInstance) { auto *sharedEglInstance = Context::getShareContext()->getEglInstance(); mEglInstance = new EglCore( (const void *)sharedEglInstance->getEGLContext(), nullptr, 1, 1); mEglInstance->makeAsCurrent(); glGenTextures(1, &mOESTexture); glBindTexture(GL_TEXTURE_EXTERNAL_OES, mOESTexture); glTexParameteri(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glBindTexture(GL_TEXTURE_EXTERNAL_OES, 0); } } GLuint GCVBase::Camera::getSurfaceTexture() { return mOESTexture; } void GCVBase::Camera::onSurfaceChanged() { runSyncContextLooper(Context::getShareContext()->getContextLooper(), [=] { if(mOutputFrameBuffer){ delete mOutputFrameBuffer; } Size framebufferSize = Size(mPreviewWidth, mPreviewHeight); mOutputFrameBuffer = new FrameBuffer(framebufferSize, mOutputTextureOptions, Context::getShareContext()); }); } void GCVBase::Camera::surfaceTextureAvailable() { glFlush(); runSyncContextLooper(Context::getShareContext()->getContextLooper(), [=]{ Context::makeShareContextAsCurrent(); mCameraProgram->useProgram(); glEnableVertexAttribArray(aPositionAttribute); glEnableVertexAttribArray(aTexCoordAttribute); glClearColor(0, 0, 0, 0); glClear(GL_COLOR_BUFFER_BIT); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_EXTERNAL_OES, mOESTexture); static const GLfloat vertices[] = { -1.0f, -1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 1.0f, }; static const GLfloat texCoord[] = { //这里对纹理坐标不进行任何处理,在输出部分(DisplayView、MediaRecorder处做最终的处理) 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, }; glUniform1i(uTextureuniform, 0); glVertexAttribPointer(aPositionAttribute, 2, GL_FLOAT, 0, 0, vertices); glVertexAttribPointer(aTexCoordAttribute, 2, GL_FLOAT, 0, 0, texCoord); mOutputFrameBuffer->bindFramebuffer(); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); //只需要在该步骤之前绑定帧缓冲即可,该步骤所有的绘制都会渲染到帧缓冲中的纹理上 mOutputFrameBuffer->unbindFramebuffer(); // DisplayView绘制之前必须解绑帧缓冲对象,否则系统自带的帧缓冲(0)渲染不出来!!!!!!! glDisableVertexAttribArray(aPositionAttribute); glDisableVertexAttribArray(aTexCoordAttribute); // MediaTime time = MediaTime((int64_t)currentTimeOfMilliseconds(), 30, TimeFlag_Init); newFrameReadyAtTime(); }); } void GCVBase::Camera::newFrameReadyAtTime() { for(auto i = mTargets.begin(); i < mTargets.end(); i++){ auto currentTarget = * i; FilterGroup * filterGroup = (FilterGroup *) (jlong)currentTarget; filterGroup->_setOutputRotation(rotationCamera); filterGroup->_setOutputFramebuffer(mOutputFrameBuffer); filterGroup->_newFrameReadyAtTime(); } } void GCVBase::Camera::orientationChanged(int orientation) { switch (orientation){ case 0: rotationMode = RotationMode::rotation0; break; case 90: rotationMode = RotationMode::rotation90; break; case 270: rotationMode = RotationMode::rotation270; break; default: break; } rotationCamera = Rotation(rotationMode, mFacingMode); } void GCVBase::Camera::facingChanged(int facing) { mFacingMode = facing == 0 ? FacingMode::FacingBack : FacingMode::FacingFront; rotationCamera = Rotation(rotationMode, mFacingMode); } <file_sep>// // Created by 刘轩 on 2018/12/30. // #ifndef GPUCAMERAVIDEO_FRAMEBUFFER_H #define GPUCAMERAVIDEO_FRAMEBUFFER_H #include <Size.hpp> #include <Context.h> #include "TextureOptions.h" namespace GCVBase { class FrameBuffer { private: GLuint mTexture = 0; GLuint mFrameBuffer = 0; Size mSize = Size::zero(); TextureOptions mTextureOptions; Context * mContext = NULL; public: FrameBuffer(const Size &size = Size::zero(), const TextureOptions &options = TextureOptions(), Context * context = NULL); void bindFramebuffer(); void unbindFramebuffer(); const TextureOptions &textureOptions() const; const Context *context() const; int framebuffer() const; GLuint texture() const; }; } #endif //GPUCAMERAVIDEO_FRAMEBUFFER_H
d93590e93362b7ad64a2388dcc8a43d2ee0e039a
[ "Markdown", "Gradle", "Kotlin", "C++" ]
88
Kotlin
youqibing/GPUCameraVideo
1935ea4bd468f61a03dbc22aaf198cb63b29eaf7
658e10499bfa3cb90d82df68aaf8adae1b8fdad1
refs/heads/master
<repo_name>deannvr/TODOListApp.sda<file_sep>/README.md # Welcome to my ToDoList Application This ToDoList Application provides sorting capabilities, creating projects, creating tasks within the project and even assing them a title and a date too. This project is part of my course program to teach myself Java. ### This Applications is allowing user to: <!-- UL --> * Create a new task * Assign them a title and a dueDate * Choose a project for the task to belong to * Edit the task * Mark the task as done * Remove the task * Sort the tasks according to date * Show all tasks * Show complete and incomplete tasks * Quit and save the current task list to file * Restart the Application with the former state restored ## This is my Application logo ![](https://www.myclientsplus.com/media/1007/task2fpractice-management.png) ### To test the Application: * Clone the repository using ```git clone``` * Open the project in Java, build and run #### When you run the Application the Main should look like: ``` Welcome to ToDoLy You have X tasks todo and X tasks are done! Please pick a project: Please select the project name in which this task belongs or create new project: ``` #### This is my UML diagram: [UML Diagram](https://github.com/deannvr/TODOListApp.sda/blob/feature/diagram/TodoListAppUmlDiagram.png) ## Licence: * [x] Open source :) ## Let me know! Mail me if you have any questions or suggestion regarding this project. <!-- Tables --> | Name | Email | | ---- | ------------------- | | Dean | <EMAIL> | <file_sep>/src/com/sda/todolistapp/Task.java package com.sda.todolistapp; import java.io.Serializable; import java.text.SimpleDateFormat; import java.util.Date; public class Task implements Serializable{ private String title; private String description; private String dueDate; private boolean done; public Task() { setDone(false); } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDueDate() { return dueDate; } public void setDueDate(String dueDate) { this.dueDate = dueDate; } public boolean isDone() { return done; } public void setDone(boolean done) { this.done = done; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Task task = (Task) o; if (done != task.done) return false; if (title != null ? !title.equals(task.title) : task.title != null) return false; if (description != null ? !description.equals(task.description) : task.description != null) return false; return dueDate != null ? dueDate.equals(task.dueDate) : task.dueDate == null; /** * if (done != task.done) return false; * if (!Objects.equals(title, task.title)) return false; * if (!Objects.equals(description, task.description)) return false; * return Objects.equals(dueDate, task.dueDate); */ } @Override public int hashCode() { int result = title != null ? title.hashCode() : 0; result = 31 * result + (description != null ? description.hashCode() : 0); result = 31 * result + (dueDate != null ? dueDate.hashCode() : 0); result = 31 * result + (done ? 1 : 0); return result; } @Override public String toString() { return String.format("Title: %s, Desciption: %s; Due date: %s, Done: %s;", title, description, dueDate, done); } }
a9a5a8d3ec12bf4781fe41b20497b252333c1da0
[ "Markdown", "Java" ]
2
Markdown
deannvr/TODOListApp.sda
e56a936ea016700e2f04d5e44dbfef40ec3d3d9e
836bd2fb37198cb3d363883b66b085d16ee1b21b
refs/heads/master
<repo_name>Zurich1994/Jsp-Template<file_sep>/chapter04/src/com/showmsg.java package com; import java.applet.Applet; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; public class showmsg extends Applet{ /** * */ private static final long serialVersionUID = 1978939073748554102L; String msg1,msg2,msg3; public void init() { msg1 = getParameter(msg1); msg2 = getParameter(msg2); msg3 = getParameter(msg3); } public void paint(Graphics g) { Font font = new Font("SansSerif",Font.BOLD,30); g.setFont(font); g.setColor(Color.blue); g.drawString(msg1, 20, 40); g.drawString(msg2, 20, 70); g.drawString(msg3, 20, 100); } } <file_sep>/README.md # Jsp-Template <file_sep>/SampleDesign/WebContent/JS/list_notes.js var OPER = "";//ADD增加,MOD修改,DEL删除 var bgcolor = "";//行背景色 var listId = 0;//要操作的信息的id var COL = 6; $(document).ready(function() { $(function(){ //$("#listTableDiv tbody tr:nth-child(odd)").addClass("odd"); $("#listTableDiv tbody tr:nth-child(even)").addClass("even"); }); //添加按钮,显示div $("#insertBtn").click(function() { $("#contentDiv input[type='text']").val(""); $(this).removeClass("mouseoverBtn");//鼠标离开,去掉样式 $(".clickBtn").removeClass("clickBtn");//上一个按钮去掉点击样式 $(this).addClass("clickBtn");//增加单击样式 $("#contentDiv h3").text("新增账户");//标题 $("#contentForm").attr("action","insert_do.jsp");//增加action $("#contentDiv").removeClass("hide");//显示div $("#operBtnDiv input,#queryFormDiv input").attr("disabled","disabled");//下层按钮不可用 }); //修改按钮,显示div $("#updateBtn").click(function() { if(listId != 0) { $(this).removeClass("mouseoverBtn"); $(".clickBtn").removeClass("clickBtn"); $(this).addClass("clickBtn"); $("#contentDiv h3").text("修改账户"); $("#contentForm").attr("action","update_do.jsp"); $("#operBtnDiv input,#queryFormDiv input").attr("disabled","disabled"); $("#contentDiv").removeClass("hide"); }else { alert("请选择一条信息进行修改!"); } }); //删除按钮 $("#deleteBtn").click(function() { if(listId != 0) { $(".clickBtn").removeClass("clickBtn"); $(this).addClass("clickBtn"); $("#contentForm").attr("action","delete_do.jsp"); if(confirm("是否删除'"+$("#new_name").val()+"'账户信息?")) { $("#contentForm").submit(); } }else { alert("请选择一条信息进行删除!"); } }); //取消按钮,隐藏div $("#cancel").click(function() { $("#contentDiv input[type='text'],#contentDiv textarea").val(""); $("#contentDiv").addClass("hide"); $("#operBtnDiv input,#queryFormDiv input").removeAttr("disabled"); }); //点击表中行,变色,获取当前行的信息id $("#listTableDiv table tbody tr").click(function() { if(bgcolor == "even") { $(".clickTr").addClass("even"); } $(".clickTr").removeClass("clickTr"); if($(this).hasClass("even")) { $(this).removeClass("even"); $(this).addClass("clickTr"); bgcolor = "even"; }else { $(this).addClass("clickTr"); bgcolor = "odd"; } $(this).find("td").each(function(i) { if(i%COL==0) { listId = $(this).text(); } }); //将要修改的内容写入div insertForUpdate(); //查询当前账户下的用户信息 $("#rec_users_iframe").attr("src","list_rec_users.jsp?rec_user_id="+listId); }); }); //插入要修改的信息 function insertForUpdate() { var clickTr = $(".clickTr"); clickTr.find("td").each(function(i) { if(i%COL==0) { $("#new_id").val($(this).text()); } if(i%COL==1) { $("#new_name").val($(this).text()); } if(i%COL==2) { $("#new_address").val($(this).text()); } if(i%COL==3) { $("#new_phone").val($(this).text()); } if(i%COL==4) { $("#new_datetime").val($(this).text()); } if(i%COL==5) { $("#new_money").val($(this).text()); } }); }
2ecf9d750f77d27f9e2959f74b53cb906dbb4da1
[ "Markdown", "Java", "JavaScript" ]
3
Java
Zurich1994/Jsp-Template
84c8eebaf7b289404ac432c7478b3b40edc4bdd1
ea4f1ddfdcdbf2cf2cf66b441e8ea7640c354446
refs/heads/master
<file_sep><?php define('WS_WSDL', 'http://localhost/ejercicio2/servidor.php?wsdl'); $client = new SoapClient(WS_WSDL); $metodosDisponibles = $client->__getFunctions(); foreach ($metodosDisponibles as $metodo) { echo "$metodo\n"; } $parametros = ["Ladrillo"=>[ "Tipo"=>"Maciso", "Tabla"=>182, "Canto"=>92, "Testa"=>34 ]]; $rsp = $client->__call("Stock.agregar", $parametros); echo "Resultado operacion: $rsp"; ?><file_sep><?php require_once "lib/nusoap.php"; $namespace = "http://educacionit.com/serviciosSoap"; class Operaciones { public function sumar($a, $b) { return $a + $b; } public function multiplicar($a, $b) { return $a * $b; } } $server = new soap_server(); $server->configureWSDL('OperacionesService', $namespace); $server->register("Operaciones.sumar", ["a"=>"xsd:integer", "b"=>"xsd:integer"], ["return"=>"xsd:integer"], $namespace, false, "rpc", "encoded", "Suma dos enteros" ); $server->register("Operaciones.multiplicar", ["a"=>"xsd:integer", "b"=>"xsd:integer"], ["return"=>"xsd:integer"], $namespace, false, "rpc", "encoded", "Multiplica dos enteros" ); if ( !isset($HTTP_RAW_POST_DATA)) $HTTP_RAW_POST_DATA = file_get_contents('php://input'); $server->service($HTTP_RAW_POST_DATA); ?><file_sep><?php require_once "lib/nusoap.php"; $namespace = "http://educacionit.com/serviciosSoap"; class Stock { public function agregar($ladrillo) { $path = "datos.txt"; file_put_contents($path, $ladrillo["Tipo"], FILE_APPEND); file_put_contents($path, $ladrillo["Tabla"], FILE_APPEND); file_put_contents($path, $ladrillo["Canto"], FILE_APPEND); file_put_contents($path, $ladrillo["Testa"], FILE_APPEND); file_put_contents($path, ";", FILE_APPEND); return strval($ladrillo["Tipo"]); } } $server = new soap_server(); $server->configureWSDL('StockService', $namespace); $tipoLadrillo = [ "Tipo" => ["name" => "TipoLadrillo", "type" => "xsd:string"], "Tabla" => ["name" => "Tabla", "type" => "xsd:int"], "Canto" => ["name" => "Canto", "type" => "xsd:int"], "Testa" => ["name" => "Testa", "type" => "xsd:int"] ]; $server->wsdl->addComplexType('Ladrillo', 'complexType', 'struct', 'all','', $tipoLadrillo); $server->register("Stock.agregar", ["Ladrillo" => "tns:Ladrillo"], ["return"=>"xsd:string"], $namespace, false, "rpc", "encoded", "Agrega un ladrillo al stock" ); if ( !isset($HTTP_RAW_POST_DATA)) $HTTP_RAW_POST_DATA = file_get_contents('php://input'); $server->service($HTTP_RAW_POST_DATA); ?><file_sep><?php define('WS_WSDL', 'http://localhost/ejercicio1/servidor.php?wsdl'); $client = new SoapClient(WS_WSDL); $metodosDisponibles = $client->__getFunctions(); foreach ($metodosDisponibles as $metodo) { echo "$metodo\n"; } $rsp = $client->__call("Operaciones.sumar", ["a"=>11, "b"=>55]); echo "Resultado operacion: $rsp"; ?>
1373b865a0cf6245c3640260bf2d073254dcc21f
[ "PHP" ]
4
PHP
almirjgg/apiwsclase2noche
ba229330f1f9b01abd8cf7a6a644d01473d8956a
635530a5ac8adef64eff67f445481dcb8c41b2fd
refs/heads/main
<repo_name>TomOtero1984/ArduinoLCDSensorMonitor<file_sep>/src/node/ArduinoLCDSensorMonitorNODE/client.js var ws_update_script = require("./d3_data") var ws_d = Array(100).fill(1) class Client { constructor(event_listener) { const URL = 'ws://localhost:3000' const PROTOCOL = 'echo-protocol' const client_socket = new WebSocket(URL, PROTOCOL); client_socket.onopen = () => { client_socket.send('Client connected'); }; client_socket.onmessage = (msg) => { // console.log(`[DEBUG][CLIENT]: ${msg.data}`) // for(var i in msg.data) // { // console.log(msg.data[i]) // } ws_d = JSON.parse(msg.data) console.log(`[DEBUG][CLIENT]: ${d3_data}`) event_listener.emit("d3_data",ws_d) }; } } module.exports = { Client: Client, }<file_sep>/src/arduino/LCDScreen/DistanceDisplay/DistanceDisplay.ino #include <Wire.h> #include <LiquidCrystal_I2C.h> #define LCD_WIDTH ((int)16) #define LCD_HEIGHT ((int)2) #define TRIG_PIN ((int)4) #define ECHO_PIN ((int)3) #define DISPLAY_OFFSET ((int) 5) LiquidCrystal_I2C lcd(0x27, LCD_WIDTH, 2); long data[2] = {0, 0}; // {in, cm} long prev_data[2] = {0, 0}; // {in, cm} void setup() { Serial.begin(9600); pinMode(TRIG_PIN, OUTPUT); pinMode(ECHO_PIN,INPUT_PULLUP); // initialize the lcd lcd.init(); lcd.backlight(); lcd.setCursor(1,0); lcd.print("in: "); lcd.setCursor(1,1); lcd.print("cm: "); } void loop() { getPingData(); printToLCD(); serialSendDataValues(); delay(500); } void getPingData() { // Gets data from the PING sensor // // Returns long waitStart = 0; long waitCur = 0; int errorFlag = 0; long duration; //////////////////////////////// // Trigger pin high for 10uS // // STEP: Set TRIG_PIN HIGH digitalWrite(TRIG_PIN, HIGH); // STEP: Wait for 10 uS waitStart = micros(); while(waitCur - waitStart < 10 || errorFlag == 1) { waitCur = micros(); if(waitCur < waitStart) { errorFlag = 1; } } // STEP: Set TRIG_PIN LOW digitalWrite(TRIG_PIN, LOW); // STEP: Read Echo pin, returns time in ms duration = pulseIn(ECHO_PIN, HIGH); // STEP: Save last data point prev_data[0] = data[0]; prev_data[1] = data[1]; // STEP: Convert the time into a distance data[0] = microsecondsToInches(duration); data[1] = microsecondsToCentimeters(duration); } long microsecondsToInches(long microseconds) { // According to Parallax's datasheet for the PING))), there are 73.746 // microseconds per inch (i.e. sound travels at 1130 feet per second). // This gives the distance travelled by the ping, outbound and return, // so we divide by 2 to get the distance of the obstacle. // See: http://www.parallax.com/dl/docs/prod/acc/28015-PING-v1.3.pdf return microseconds / 74 / 2; } long microsecondsToCentimeters(long microseconds) { // The speed of sound is 340 m/s or 29 microseconds per centimeter. // The ping travels out and back, so to find the distance of the object we // take half of the distance travelled. return microseconds / 29 / 2; } void printToLCD() { for(int row = 0; row<2; row++){ if(prev_data[row] > data[row]){ int prev_digits = countDigits(prev_data[row]); int cur_digits = countDigits(data[row]); clearLCD(DISPLAY_OFFSET + cur_digits, DISPLAY_OFFSET + prev_digits, row); } lcd.setCursor(DISPLAY_OFFSET,row); lcd.print(data[row]); } } void clearLCD(int col_start, int col_stop, int row){ for(int col=col_start; col<15; col++) { lcd.setCursor(col, row); lcd.print(" "); } } int countDigits(long num) { int count = 0; while(num != 0){ num = num/10; count++; } return count; } void serialSendDataValues(){ Serial.write("{"); Serial.write("\"in\" : "); Serial.print(data[0]); Serial.write(", \"cm\" : "); Serial.print(data[1]); Serial.write("}\n"); } <file_sep>/src/arduino/LCDScreen/test/test.ino /* * Tutorial https://create.arduino.cc/projecthub/Arnov_Sharma_makes/lcd-i2c-tutorial-664e5a#content */ #include <Wire.h> #include <LiquidCrystal_I2C.h> // initialize the library by associating any needed LCD interface pin // with the arduino pin number it is connected to LiquidCrystal_I2C lcd(0x27, 20, 4); void setup() { lcd.init(); // initialize the lcd // Print a message to the LCD. lcd.backlight(); lcd.setCursor(1,0); lcd.print("hello everyone"); lcd.setCursor(1,1); lcd.print("konichiwaa"); } void loop() { } <file_sep>/src/node/ArduinoLCDSensorMonitorNODE/server copy.js module.exports = { server: (data_handler) => { const express = require('express'); const ws = require('ws') const app = express(); const port = 3000; const wss = new ws.Server({ noServer: true }); wss.on('connection', (socket) => { socket.on('message', (message) => { console.log(message) }) }) // app.use('/d3_data.js', express.static(__dirname + 'd3_data.js')) app.use(express.static('public')) app.get('/', (req, res) => { res.sendFile('index.html') }); app.get('/api/data/', (req, res, next) => { data_handler.database_get_data() res.json(data_handler.d3_data) }) const server = app.listen(port, () => { console.log(`Example app listening at http://localhost:${port}`) }); server.on('upgrade', (req, socket, head) => { wss.handleUpgrade(req, socket, head, (socket) => { wss.emit('connection', socket, req); }) }) } }<file_sep>/src/node/ArduinoLCDSensorMonitorNODE/server.js const WebSocket = require('ws'); class Server { constructor(data_handler) { const express = require('express'); const app = express(); const port = 3000; this.wss = new WebSocket.Server({ clientTracking: true, noServer: true }); this.wss.on('connection', (ws) => { ws.on('message', (msg) => { console.log(`[INFO][SERVER] ${msg}`); }); }); // app.use('/d3_data.js', express.static(__dirname + 'd3_data.js')) app.use(express.static('public')); app.get('/', (req, res) => { res.sendFile('index.html'); }); app.get('/api/data/', (req, res, next) => { data_handler.database_get_data(); res.json(data_handler.d3_data); }); const server = app.listen(port, () => { console.log(`Example app listening at http://localhost:${port}`); }); server.on('upgrade', (req, socket, head) => { this.wss.handleUpgrade(req, socket, head, (socket) => { this.wss.emit('connection', socket, req); }); }); } send_msg(msg) { this.wss.clients.forEach(function each(client) { if (client.readyState === WebSocket.OPEN) { console.log(`[INFO][SERVER] Sending data to ${client}`) // console.log(JSON.stringify(msg)) client.send(JSON.stringify(msg)) } }) } } module.exports = { Server: Server, }<file_sep>/src/node/ArduinoLCDSensorMonitorNODE/event_listener.js const EventEmitter = require('events') class MyEmitter extends EventEmitter { } const myEmitter = new MyEmitter() myEmitter.once('newListener', (event, listener) => { console.log('EventEmitter initialized') } ) myEmitter.on('array_full', (data, data_handler) => { for(var i = 0; i < data.length; i++){ data_handler.database_insert_data(data[i]) } }) module.exports = { event_listener: myEmitter, }<file_sep>/src/node/ArduinoLCDSensorMonitorNODE/data_handler.js class DataHandler { constructor() { this.sqlite3 = require('sqlite3').verbose() this.db_filepath = `data/sensor_readings.db` this.db this.table_names = [] this.column_name = "data" this.datatype = "TEXT" this.date = new Date() this.sql_count = 0 this.data_readings = [] this.data_reading_limit = 5 this.d3_data = [] this.db_results = "" } generate_table_name() { var name = `sensor_readings_${this.date.getDate()}${this.date.getMonth() + 1}${this.date.getFullYear()}` return name } set_table_name() { var name = this.generate_table_name() this.table_name = name } set_column_name(name) { this.column_name = name } set_datatype(type) { this.datatype = "TEXT" } build() { return new Promise((resolve) => { this.db = new this.sqlite3.Database(this.db_filepath, (err) => { if (err) { return console.error(err.message) } console.log(`[INFO] Connected to the ${this.db_filepath} SQlite database.`) resolve(true) }) }) } // Database database_close() { this.db.close((err) => { if (err) { return console.error(err.message) } console.log('[INFO] Close the database connection.') }) } database_get_tables() { return new Promise((resolve) => { this.db.all(`SELECT name FROM sqlite_master;'`, (err, res) => { if (err) { return console.error(err.message) } for (let i = 0; i < res.length; i++) { this.table_names[i] = res[i]["name"] } resolve(true) }) }) } database_create_table(table_name) { return new Promise((resolve) => { if (!this.table_names.includes(table_name)) { console.log(`[INFO] Creating TABLE ${table_name}`) this.db.run(`CREATE TABLE ${table_name} (id INTEGER PRIMARY KEY AUTOINCREMENT, data TEXT);`, (err, res) => { if (err) { return console.error(`[ERROR][database_create_table]: ${err.message}`) } if (res) { return console.log(`[INFO][database_create_table]: ${res.message}`) } }) return } console.log(`[INFO] Table ${table_name} already exists`) resolve(true) }) } database_get_columns() { return new Promise((resolve) => { this.db.all(`PRAGMA table_info(${this.table_name});`, (err, res) => { if (err) { return console.error(`[ERROR][database_get_columns]: ${err.message}`) } for (let i = 0; i < res.length; i++) { this.column_names[i] = res[i]["name"] } resolve(true) }) }) } database_insert_data(data) { this.db.run(`INSERT INTO ${this.table_name}(${this.column_name}) VALUES('${data}');`) } database_reduce_table_by_range(table_name, column_name, range_start, range_end) { this.db.run(`DELETE from ${this.table_name} WHERE ${this.column_name} BETWEEN ${range_start} and ${range_end}`) } database_get_count() { this.db.get(`SELECT COUNT("id") FROM ${this.table_name};`, (err, res) => { this.sql_count = res console.log(res) }) } database_get_data() { return new Promise((resolve) => { this.db.all(`SELECT * FROM ${this.table_name} ORDER BY "id" DESC LIMIT 100;`, (err, res) => { if (err) { return console.error(`[INFO][database_get_data]: ${err.message}`); } this.db_results = res this.set_d3_data() resolve() }) }) } // Data Readings data_readings_push(data) { this.data_readings.push(data) } data_readings_pop(index) { this.data_readings.pop(index) } data_readings_clear() { this.data_readings = [] } data_readings_check_length() { return this.data_readings.length } // D3 Data set_d3_data() { for (var i in this.db_results) { console.log(this.db_results[i]["data"]) this.d3_data[i] = JSON.parse(this.db_results[i]["data"]) } } } module.exports = { DataHandler: DataHandler, }<file_sep>/src/node/ArduinoLCDSensorMonitorNODE/server_nope.js class Server { constructor(data_handler) { const express = require('express'); const app = express(); const port = 3000; // app.use('/d3_data.js', express.static(__dirname + 'd3_data.js')) app.use(express.static('public')); app.get('/', (req, res) => { res.sendFile('index.html'); }); app.get('/api/data/', (req, res, next) => { data_handler.database_get_data(); res.json(data_handler.d3_data); }); const server = app.listen(port, () => { console.log(`Example app listening at http://localhost:${port}`); }); server.on('upgrade', (req, socket, head) => { this.wss.handleUpgrade(req, socket, head, (socket) => { this.wss.emit('connection', socket, req); }); }); // WebSocket var WebSocketServer = require('websocket').server; this.wss = new WebSocketServer({ httpServer: server, autoAcceptConnections: true }); this.connection = null this.wss.on('request', (request) => { this.connection = request.accept('echo-protocol', request.origin) this.connection.on('message', (message) => { console.log(message) }) }); } } module.exports = { Server: Server, }<file_sep>/README.MD #README ## Description Arduino LCD Sensor Monitor is a project using an Arduino and LCD screen to monitor a sensor. <file_sep>/src/node/ArduinoLCDSensorMonitorNODE/index.js const { Arduino } = require("./arduino_monitor") const { Server } = require("./server") const { DataHandler } = require("./data_handler") // const { myEmitter } = require("./event_listener") // const { Client } = require("./client") async function data_handler_setup(data_handler) { await data_handler.build() await data_handler.set_table_name() // console.log(`[DEBUG] data_handler.table_name:${data_handler.table_name}`) await data_handler.database_get_tables() // console.log(`[DEBUG] data_handler.table_names: ${data_handler.table_names}`) await data_handler.database_create_table(data_handler.table_name) } async function init_d3_data(data_handler) { await data_handler.database_get_data() } async function main() { var data_handler = new DataHandler await data_handler_setup(data_handler) await init_d3_data(data_handler) var server = new Server(data_handler) // var client = new Client() var arduino = new Arduino(data_handler, server) } main() <file_sep>/src/node/ArduinoLCDSensorMonitorNODE/d3_test/d3_test.js const { DataHandler } = require("../data_handler") async function data_handler_setup(data_handler) { await data_handler.build() await data_handler.set_table_name() // console.log(`[DEBUG] data_handler.table_name:${data_handler.table_name}`) await data_handler.database_get_tables() // console.log(`[DEBUG] data_handler.table_names: ${data_handler.table_names}`) await data_handler.database_create_table(data_handler.table_name) } async function init_d3_data(data_handler) { await data_handler.database_get_data() data_handler.d3_data = data_handler.db_results for (var idx in data_handler.d3_data) { // console.log(`[DEBUG] d3 keys = ${Object.keys(data_handler.d3_data[idx])}`) data_handler.d3_data[idx] = JSON.parse(data_handler.d3_data[idx]["data"]) // console.log(`[DEBUG] d3 data = ${Object.keys(data_handler.d3_data[idx])}`) } } async function main() { var data_handler = new DataHandler await data_handler_setup(data_handler) await init_d3_data(data_handler) } main()<file_sep>/src/python/arduino_reader.py import serial def read_data(ser): start_flag = False end_flag = False data_found = False record = False data = "" error_flag = False while(not data_found or error_flag): # Get data s = ser.read(1).decode("utf-8") # Check for start or end if s == "}" and start_flag: end_flag = True elif s == "{" and not start_flag: start_flag = True record = True elif s == "{" and start_flag: error_flag = True # Record data if record: data = data + s # Check for end of loop if start_flag and end_flag: data_found = True return data def main(): ser = serial.Serial('COM6', 9600) try: while(True): print(read_data(ser)) except KeyboardInterrupt: print("EXIT") finally: ser.close() if __name__ == "__main__": main()<file_sep>/src/arduino/LCDScreen/PingTest/PingTest.ino int trigPin = 4; int echoPin = 3; long waitStart = 0; long waitCur = 0; int errorFlag = 0; int sample = 0; long duration, inches, cm; void setup() { Serial.begin(9600); pinMode(trigPin, OUTPUT); pinMode(echoPin, INPUT_PULLUP); } void loop() { /////////////////////////////// ///Trigger pin high for 10uS/// // STEP: Set trigPin HIGH digitalWrite(trigPin, HIGH); // STEP: Wait for 10 uS waitStart = micros(); while (((waitCur - waitStart) < 10) || errorFlag == 1) { // Serial.print("MICROS: "); // Serial.print(micros()); // Serial.println(); waitCur = micros(); if (waitCur < waitStart) { errorFlag = 1; } } waitCur = 0; errorFlag = 0; // STEP: Set trigPin LOW digitalWrite(trigPin, LOW); duration = pulseIn(echoPin, HIGH); // convert the time into a distance inches = microsecondsToInches(duration); cm = microsecondsToCentimeters(duration); Serial.print(inches); Serial.print("in, "); Serial.print(cm); Serial.print("cm"); Serial.println(); delay(100); } long microsecondsToInches(long microseconds) { // According to Parallax's datasheet for the PING))), there are 73.746 // microseconds per inch (i.e. sound travels at 1130 feet per second). // This gives the distance travelled by the ping, outbound and return, // so we divide by 2 to get the distance of the obstacle. // See: http://www.parallax.com/dl/docs/prod/acc/28015-PING-v1.3.pdf return microseconds / 74 / 2; } long microsecondsToCentimeters(long microseconds) { // The speed of sound is 340 m/s or 29 microseconds per centimeter. // The ping travels out and back, so to find the distance of the object we // take half of the distance travelled. return microseconds / 29 / 2; } <file_sep>/src/node/ArduinoLCDSensorMonitorNODE/test.js const ws = require('ws'); const client = new ws('ws://localhost:3000'); client.on('message', (res) => { // Causes the server to print "Hello" console.log(res); });<file_sep>/src/node/ArduinoLCDSensorMonitorNODE/d3_data.js const d3 = require("d3") const $ = require("jquery") const { event_listener } = require("./event_listener") // Event Listener event_listener.on('d3_data', (ws_d) => { d3_data = ws_d ws_update_script() }) // Global const const URL = 'ws://localhost:3000' const API = "/api/data" // Data array var d3_data = Array(100).fill(1) window.d3_data = d3_data // Web socket client const { Client } = require("./client") var client = new Client(event_listener) // D3 Graph var svgWidth = 800, svgHeight = 300, barPadding = 5; var barWidth = (svgWidth / d3_data.length); var svg = d3.select('svg') .attr("width", svgWidth) .attr("height", svgHeight) var barChart = svg.selectAll("rect") .data(d3_data) .enter() .append("rect") .attr("y", (d) => { return svgHeight - d }) .attr("height", (d) => { return d; }) .attr("width", barWidth - barPadding) .attr("transform", (d, i) => { var translate = [barWidth * i, 0]; return "translate(" + translate + ")"; }) // API function get_d3_data() { $.getJSON(URL+API, (res) => { d3_data = res console.log(d3_data) }) } window.get_d3_data = get_d3_data; function parse_d3_data() { for (var i in d3_data) { d3_data[i] = d3_data[i]["in"] } console.log(d3_data) } window.parse_d3_data = parse_d3_data; // Update function update_graph() { if (d3_data[0] === undefined) { console.error("[ERROR] d3_data is undefined") return } barWidth = (svgWidth / d3_data.length); d3.selectAll("rect") .data(d3_data) .attr("y", (d) => { return svgHeight - d }) .attr("height", (d) => { return d; }) .attr("width", barWidth - barPadding) .attr("transform", (d, i) => { var translate = [barWidth * i, 0]; return "translate(" + translate + ")"; }) } window.update_graph = update_graph; function update_script() { get_d3_data() parse_d3_data() update_graph() } window.update_script = update_script function ws_update_script() { // get_d3_data() parse_d3_data() update_graph() } window.update_script = ws_update_script // const interval_time = 120000 // setInterval(update_script, interval_time)
53b3381b154b3ce14660322a1a41ecda89684d86
[ "JavaScript", "Python", "C++", "Markdown" ]
15
JavaScript
TomOtero1984/ArduinoLCDSensorMonitor
02c566154609fd88ddcd706925a155b3d24f83fb
569941b7f469a628dd48b5031278045423ec3122
refs/heads/master
<file_sep>import {Component, OnInit } from '@angular/core'; import {PropositionService} from './proposition.service'; import {QuestionService} from '../../question-list/question/question.service'; import {Router} from '@angular/router'; import {Observable, Subject} from 'rxjs/Rx'; import {Question} from '../../question-list/question/question.model'; import {QuestionnaireService} from '../../questionnaire/questionnaire.service'; import {CheckDirective} from '../../../check.directive'; @Component({ selector: 'app-proposition', templateUrl: './proposition.component.html', styleUrls: ['./proposition.component.scss'] }) export class PropositionComponent implements OnInit { question: any; Page: Number =1; nbprop:Number ; Q: Question ; nbques: Number ; compteur: Number ; constructor(private propositionhttp: PropositionService ,private questionnairehttp: QuestionnaireService , private questionhttp: QuestionService, private router: Router) { } ngOnInit() { this.propositionhttp.getLastQuestion().subscribe(data => { console.log(data); this.question = data; }); } addProposition(proposition) { // .pipe // (map(this.extractData)); /* .subscribe(resp => { // access the body directly, which is typed as `Config`. this.questionnaire_id= { ... resp.body }; });*/ this.Page=this.questionhttp.getPage(); this.nbprop=this.questionhttp.GetNumber(); this.nbques=this.questionnairehttp.GetNumber(); /* this.question=this.propositionhttp.GetQuestionForProp(); this.question.subscribe(data => { this.Q = new Question(data.id,data.contenu,data.nbprop,data.reponse,data.type,data.questionnaire ); });*/ console.log(this.question); console.log(this.Page); const propositiona = { 'contenu': proposition['contenu'], 'question': this.question } ; this.compteur=this.questionhttp.getCompteur() ; this.propositionhttp.addProposition(propositiona).subscribe(res => { // console.log(this.questionnaire_id); console.log(res); console.log(propositiona['question']); }, (err) => { console.log(err); }); console.log('Compteur='+this.compteur) ; console.log('Nombre de question='+this.nbques) ; console.log('Page='+this.Page) ; console.log('Nombre de prop='+this.nbprop) ; if ((this.Page === this.nbprop)) { this.questionhttp.setPage(1); if(this.compteur<this.nbques) { this.router.navigate(['/questions']) ; } else { this.router.navigate(['/dashboard']); } } } } <file_sep>import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { HttpModule } from '@angular/http'; import { RouterModule } from '@angular/router'; import { NgbModule } from '@ng-bootstrap/ng-bootstrap'; import { AppRoutingModule } from './app.routing'; import { ComponentsModule } from './components/components.module'; import { AppComponent } from './app.component'; import { AdminLayoutComponent } from './layouts/admin-layout/admin-layout.component'; import { QuestionnaireListComponent } from './questionnaire-list/questionnaire-list.component'; import { QuestionnaireComponent } from './questionnaire-list/questionnaire/questionnaire.component'; import { QuestionComponent } from './questionnaire-list/question-list/question/question.component'; import { QuestionListComponent } from './questionnaire-list/question-list/question-list.component'; import { PropositionListComponent } from './questionnaire-list/proposition-list/proposition-list.component'; import { PropositionComponent } from './questionnaire-list/proposition-list/proposition/proposition.component'; import { TestComponent } from './test/test.component'; import { QuestionnaireDisplayComponent } from './test/questionnaire-display/questionnaire-display.component'; import { QuestionDisplayComponent } from './test/questionnaire-display/question-display/question-display.component'; import { OfferListComponent } from './offer-list/offer-list.component'; import { OfferComponent } from './offer-list/offer/offer.component'; import { ApplicationComponent } from './application-list/application/application.component'; import { ApplicationListComponent } from './application-list/application-list.component'; import { CheckDirective } from './check.directive'; import { LoginComponent } from './login/login.component'; import {LoginService} from './login/login.service'; import {HttpClient, HttpClientModule} from '@angular/common/http'; import {UserComponent} from './user/user.component'; import {User} from './user/user.model'; import {UserService} from './user/user.service'; @NgModule({ imports: [ BrowserAnimationsModule, FormsModule, HttpClientModule, ComponentsModule, RouterModule, AppRoutingModule, NgbModule.forRoot() ], declarations: [ AppComponent, AdminLayoutComponent, LoginComponent, UserComponent ], providers: [LoginService,UserService], bootstrap: [AppComponent] }) export class AppModule { } <file_sep>import { NgModule } from '@angular/core'; import { RouterModule } from '@angular/router'; import { CommonModule } from '@angular/common'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { AdminLayoutRoutes } from './admin-layout.routing'; import { DashboardComponent } from '../../dashboard/dashboard.component'; import { UserProfileComponent } from '../../user-profile/user-profile.component'; import { TableListComponent } from '../../table-list/table-list.component'; import { TypographyComponent } from '../../typography/typography.component'; import { IconsComponent } from '../../icons/icons.component'; import { MapsComponent } from '../../maps/maps.component'; import { NotificationsComponent } from '../../notifications/notifications.component'; import { ChartsModule } from 'ng2-charts'; import { NgbModule } from '@ng-bootstrap/ng-bootstrap'; import { ToastrModule } from 'ngx-toastr'; import {Questionnaire} from '../../questionnaire-list/questionnaire/questionnaire.model'; import {QuestionnaireComponent} from '../../questionnaire-list/questionnaire/questionnaire.component'; import {QuestionnaireListComponent} from '../../questionnaire-list/questionnaire-list.component'; import {QuestionnaireService} from '../../questionnaire-list/questionnaire/questionnaire.service'; import {HttpClientModule} from '@angular/common/http'; import {QuestionComponent} from '../../questionnaire-list/question-list/question/question.component'; import {NgxPaginationModule} from 'ngx-pagination'; import {QuestionService} from '../../questionnaire-list/question-list/question/question.service'; import {QuestionListComponent} from '../../questionnaire-list/question-list/question-list.component'; import {PropositionComponent} from '../../questionnaire-list/proposition-list/proposition/proposition.component'; import {PropositionListComponent} from '../../questionnaire-list/proposition-list/proposition-list.component'; import {PropositionService} from '../../questionnaire-list/proposition-list/proposition/proposition.service'; import {TestComponent} from '../../test/test.component'; import {TestService} from '../../test/test.service'; import {QuestionDisplayComponent} from '../../test/questionnaire-display/question-display/question-display.component'; import {QuestionnaireDisplayComponent} from '../../test/questionnaire-display/questionnaire-display.component'; import {OfferListComponent} from '../../offer-list/offer-list.component'; import {OfferComponent} from '../../offer-list/offer/offer.component'; import {OfferService} from '../../offer-list/offer/offer.service'; import {ApplicationComponent} from '../../application-list/application/application.component'; import {ApplicationListComponent} from '../../application-list/application-list.component'; import {ApplicationService} from '../../application-list/application/application.service'; import {CheckDirective} from '../../check.directive'; import {UserService} from '../../user/user.service'; import {UserComponent} from '../../user/user.component'; @NgModule({ imports: [ CommonModule, RouterModule.forChild(AdminLayoutRoutes), FormsModule, ChartsModule, NgbModule, ToastrModule.forRoot(), HttpClientModule, NgxPaginationModule], declarations: [ DashboardComponent, UserProfileComponent, TableListComponent, TypographyComponent, IconsComponent, MapsComponent, NotificationsComponent, QuestionnaireComponent, QuestionComponent, QuestionListComponent, PropositionComponent, PropositionListComponent, TestComponent, QuestionDisplayComponent, QuestionnaireDisplayComponent, OfferListComponent, OfferComponent, ApplicationComponent, ApplicationListComponent, CheckDirective, QuestionnaireListComponent ], exports: [ QuestionComponent ], providers: [QuestionnaireService, QuestionService, PropositionService, TestService, OfferService, ApplicationService] }) export class AdminLayoutModule {} <file_sep>import { Component, OnInit} from '@angular/core'; import {LoginService} from './login/login.service'; import {Router} from '@angular/router'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { constructor(private loginservice: LoginService, private router: Router) { } ngOnInit() { /* let token=this.loginservice.loadToken(); console.log('aaa'+token); if(!token) { this.router.navigate(['/login']); } */ } }<file_sep>import {Question} from '../../question-list/question/question.model'; export class Proposition { constructor( public id: number, public contenu: string, public question: Question) {} }<file_sep>import {Component, Input, OnInit} from '@angular/core'; import {QuestionnaireService} from '../../questionnaire/questionnaire.service'; import {QuestionService} from './question.service'; import {QuestionnaireComponent} from '../../questionnaire/questionnaire.component'; import {map} from 'rxjs/operators'; import {Router} from '@angular/router'; import {d} from '@angular/core/src/render3'; import {el} from '@angular/platform-browser/testing/src/browser_util'; @Component({ selector: 'app-question', templateUrl: './question.component.html', styleUrls: ['./question.component.scss'] }) export class QuestionComponent implements OnInit { nbprop: Number ; @Input() type: String; p: Number = 1; Page: Number = 1; nbques: Number; questionnaire_id: any; private extractData(res: Response) { const body = res; return body || {}; } constructor(private router: Router, private questionhttp: QuestionService, private questionnairehttp: QuestionnaireService) { } ngOnInit() { this.questionhttp.getLastId().subscribe(data => { // y console.log(data); this.questionnaire_id = data; }); } addQuestion(question) { // .pipe // (map(this.extractData)); /* .subscribe(resp => { // access the body directly, which is typed as `Config`. this.questionnaire_id= { ... resp.body }; });*/ if (question['type'] === 'texte') { this.questionhttp.SetNumber(0); this.nbprop = 0; } else if (question['type'] === 'checkbox') { // this.questionhttp.SetNumber(this.nbprop); this.questionhttp.SetNumber(question['nbprop']); this.nbprop = question['nbprop']; } this.Page = this.questionnairehttp.getPage(); this.nbques = this.questionnairehttp.GetNumber(); // y console.log(this.nbques) ; this.questionhttp.setCompteur(this.Page); /* const tab = { 'nbprop':question['nbprop'], 'id_quest': this.questionnaire_id['id'] }; this.questionhttp.serProp(tab,this.nbques); */ /* this.questionhttp.proposition_tab['nbques']=this.nbques; this.questionhttp.proposition_tab['tab']=tab ;*/ const questiona = { 'type': question['type'], 'contenu': question['contenu'], 'reponse': question['reponse'], 'nbprop': this.nbprop, 'questionnaire': this.questionnaire_id }; this.questionhttp.addQuestion(questiona).subscribe(res => { // console.log(this.questionnaire_id); // y console.log(res); // y console.log(questiona['questionnaire']); }, (err) => { console.log(err); }); console.log('Page de la question' + this.Page); console.log('nb prop' + this.nbprop); console.log('nb de question' + this.nbques); if (this.nbprop > 0) { this.router.navigate(['/propositions']); } if (this.nbprop === 0) { console.log(this.Page < this.nbques); if (this.Page<this.nbques) { // this.router.navigate(['/questionnaires']) ; this.router.navigateByUrl('/RefrshComponent', {skipLocationChange: true}).then(() => this.router.navigate(['/questions'])); } if (this.Page === this.nbques) { this.router.navigate(['/dashboard']); } } } } <file_sep>import {User} from '../../user/user.model'; import {Offer} from '../../offer-list/offer/offer.model'; export class Application { constructor( public id: number, public cv: string, public coveringletter: string, public user:User, public offer:Offer ) {} } <file_sep>import {Component, Input, OnInit} from '@angular/core'; import {QuestionnaireService} from '../questionnaire/questionnaire.service'; import {ActivatedRoute, Router} from '@angular/router'; import {QuestionService} from './question/question.service'; @Component({ selector: 'app-question-list', templateUrl: './question-list.component.html', styleUrls: ['./question-list.component.scss'] }) export class QuestionListComponent implements OnInit { nbques: Number ; p: number ; @Input() page: number ; constructor(private questionnairehttp: QuestionnaireService,private questionService:QuestionService) { /* private route: ActivatedRoute, private router: Router) { this.config= { currentPage: 1, itemsPerPage: 1 } this.route.queryParamMap .map(params => params.get('page')) .subscribe(page => this.config.currentPage = page);*/ } /*pageChange(newPage: number) { this.router.navigate([''], { queryParams: { page: newPage } }); }*/ ngOnInit() { this.nbques=this.questionnairehttp.GetNumber() ; this.p=this.questionService.getCompteur().valueOf()+1; this.questionnairehttp.setPage(this.p); // pourquoi ? console.log('page de la part question-list'+this.p); } array(n: number): any[] { return Array(n) ; } arrayTwo(n: number): number[] { return [...Array(n).keys()]; } setPage(p) { this.p=p; this.questionnairehttp.setPage(this.p); console.log(this.p); } } <file_sep>import { Injectable } from '@angular/core'; import {map} from 'rxjs/operators'; import {Observable} from 'rxjs/Rx'; import {HttpClient, HttpHeaders} from '@angular/common/http'; const httpOptions = { headers: new HttpHeaders({'Content-Type': 'application/json'}) }; const apiUrl = 'http://localhost:8080/api'; @Injectable() export class UserService { constructor(private httpclient: HttpClient) {} private extractData(res: Response) { const body = res; return body || {}; } getUser(id: string): Observable<any> { const url = `${apiUrl}/user/`; return this.httpclient.get(url +id, httpOptions).pipe( map(this.extractData)); } getLastId(): any { const url = `${apiUrl}/lastId`; return this.httpclient.get(url, httpOptions).pipe(map(this.extractData)) // .catch(this.handleError); // .pipe(map((res:Response) => res.json())); // ; // .subscribe(val => console.log(val)); } getUsers(): Observable<any> { const url = `${apiUrl}/users`; return this.httpclient.get(url, httpOptions) .pipe(map(this.extractData)); // convertir la reponse Observable vers un Array de session // .subscribe(); } addUser(user): Observable<any> { const url = `${apiUrl}/signUp`; return this.httpclient.post(url, user, httpOptions) .pipe(); } /* countFormateur(): Observable<any>{ const url = `${apiUrl}/nombreFormateur`; return this.httpclient.get(url, httpOptions) .pipe(map(this.extractData)); // convertir la reponse Observable vers un Array de session //.subscribe(); }*/ deleteUser(user): Observable<any> { const url = `${apiUrl}/user/`; return this.httpclient.delete(url + user.id, httpOptions) .pipe(map(this.extractData)); } updateUser(user): Observable<any> { const url = `${apiUrl}/update/`; return this.httpclient.put(url + user.id, user, httpOptions) .pipe(map(this.extractData)); } } <file_sep>import { Injectable } from '@angular/core'; import {HttpClient, HttpHeaders} from '@angular/common/http'; import {Observable} from 'rxjs/Rx'; import {map} from 'rxjs/operators'; const httpOptions = { headers: new HttpHeaders({'Content-Type': 'application/json'}) }; const apiUrl = 'http://localhost:8082/api'; @Injectable() export class QuestionService { nbprop:any; compteur:Number = 0; p:Number =1 ; nbques:Number ; proposition_tab = [ ] ; constructor(private httpclient: HttpClient) {} /* private extractData(res: Response) { let body = res.json(); // If response is a JSON use json() if (body) { return body.data || body; } else { return {}; } }*/ private extractData(res: Response) { const body = res; return body || {}; } serProp(prop,nbques) { this.proposition_tab.push(prop); this.nbques=nbques; } getProp(): {}[] { //y console.log(this.proposition_tab); return this.proposition_tab; } getnbques(): Number { return this.nbques ; } setCompteur(c){ this.compteur = c; // this.nbquestion=nbquestion; } getCompteur(){ return this.compteur ; // 'nbquestion':this.nbquestion} } setPage(p){ this.p = p; // this.nbquestion=nbquestion; } getPage():Number { return this.p ; // 'nbquestion':this.nbquestion} } private handleError(error: any) { // In a real world app, we might use a remote logging infrastructure // We'd also dig deeper into the error to get a better message let errMsg = (error.message) ? error.message : error.status ? `${error.status} - ${error.statusText}` : 'Server error'; console.error(errMsg); // log to console instead return Observable.throw(errMsg); } getQuestionnaire(id: string): Observable<any> { const url = `${apiUrl}/questionnaire/`; return this.httpclient.get(url +id, httpOptions).pipe( map(this.extractData)); } SetNumber(nbprop) { this.nbprop=nbprop; } GetNumber() { return this.nbprop ; } getLastId(): any { const url = `${apiUrl}/lastId`; return this.httpclient.get(url, httpOptions).pipe(map(this.extractData)) // .catch(this.handleError); // .pipe(map((res:Response) => res.json())); // ; // .subscribe(val => console.log(val)); } getQuestionnaires(): Observable<any> { const url = `${apiUrl}/questionnaires`; return this.httpclient.get(url, httpOptions) .pipe(map(this.extractData)); // convertir la reponse Observable vers un Array de session // .subscribe(); } addQuestion(question): Observable<any> { const url = `${apiUrl}/question`; return this.httpclient.post(url, question, httpOptions) .pipe(); } /* countFormateur(): Observable<any>{ const url = `${apiUrl}/nombreFormateur`; return this.httpclient.get(url, httpOptions) .pipe(map(this.extractData)); // convertir la reponse Observable vers un Array de session //.subscribe(); }*/ deleteQuestionnaire(questionnaire): Observable<any> { const url = `${apiUrl}/questionnaire/`; return this.httpclient.delete(url + questionnaire._id, httpOptions) .pipe(map(this.extractData)); } updateQuestionnaire(questionnaire): Observable<any> { const url = `${apiUrl}/update/`; return this.httpclient.put(url + questionnaire._id, questionnaire, httpOptions) .pipe(map(this.extractData)); } } <file_sep>import { Component, OnInit } from '@angular/core'; import {UserService} from './user.service'; @Component({ selector: 'app-user', templateUrl: './user.component.html', styleUrls: ['./user.component.scss'] }) export class UserComponent implements OnInit { constructor(private userhttp: UserService) { } ngOnInit() { } addUser(user) { const usera = { 'firstname': user['firstname'], 'lastname': user['lastname'], 'birthdate': user['birthdate'], 'cin': user['cin'], 'address': user['address'], 'phone': user['phone'], 'email': user['email'], 'login': user['login'], 'mdp': user['mdp'] }; this.userhttp.addUser(usera).subscribe(res => { // y console.log(res); }, (err) => { console.log(err); }); // this.router.navigate(['/users']); } } <file_sep>import { Injectable } from '@angular/core'; import {Observable} from 'rxjs/Rx'; import {HttpClient, HttpHeaders, HttpResponse} from '@angular/common/http'; import {Http} from '@angular/http'; import {map} from 'rxjs/operators'; const httpOptions = { headers: new HttpHeaders({'Content-Type': 'application/json'}) }; const apiUrl = 'http://localhost:8082/api'; @Injectable() export class QuestionnaireService { nbques: Number ; nbquestion : Number ; p: Number = 1 ; constructor(private httpclient: HttpClient) {} setPage(p) { this.p = p; // this.nbquestion=nbquestion; } getPage():Number { return this.p ; // 'nbquestion':this.nbquestion} } SetNumber(nbques) { this.nbques=nbques; } GetNumber() { return this.nbques ; } private extractData(res: Response) { const body = res; return body || {}; } getQuestionnaire(id: string): Observable<any> { const url = `${apiUrl}/questionnaire/`; return this.httpclient.get(url +id, httpOptions).pipe( map(this.extractData)); } getQuestionnaires(): Observable<any> { const url = `${apiUrl}/questionnaires`; return this.httpclient.get(url, httpOptions) .pipe(map(this.extractData)); // convertir la reponse Observable vers un Array de session // .subscribe(); } addQuestionnaire(questionnaire): Observable<any> { const url = `${apiUrl}/questionnaire`; return this.httpclient.post(url, questionnaire, httpOptions) .pipe(); } /* countFormateur(): Observable<any>{ const url = `${apiUrl}/nombreFormateur`; return this.httpclient.get(url, httpOptions) .pipe(map(this.extractData)); // convertir la reponse Observable vers un Array de session //.subscribe(); }*/ deleteQuestionnaire(questionnaire): Observable<any> { const url = `${apiUrl}/questionnaire/`; return this.httpclient.delete(url + questionnaire._id, httpOptions) .pipe(map(this.extractData)); } updateQuestionnaire(questionnaire): Observable<any> { const url = `${apiUrl}/update/`; return this.httpclient.put(url + questionnaire._id, questionnaire, httpOptions) .pipe(map(this.extractData)); } } <file_sep>import {Component, Input, OnInit} from '@angular/core'; import {BehaviorSubject, Observable, Subject} from 'rxjs/Rx'; import {Question} from '../../questionnaire-list/question-list/question/question.model'; import {Questionnaire} from '../../questionnaire-list/questionnaire/questionnaire.model'; import {TestService} from '../test.service'; @Component({ selector: 'app-questionnaire-display', templateUrl: './questionnaire-display.component.html', styleUrls: ['./questionnaire-display.component.scss'] }) export class QuestionnaireDisplayComponent implements OnInit { Q=new Subject<Questionnaire>(); ques= new Questionnaire(null,null,null) ; questions$: Observable<Question[]>; questions:Question[] ; id: number ; length: number; p: Number = 1 ; constructor(private testhttp:TestService) { } ngOnInit() { // this.Q=this.testhttp.GetQuest().getValue(); this.testhttp.GetQuest().subscribe(data => { this.Q.next(data) ; /*this.questions$ = this.testhttp.getQuestionstest(data.id); this.questions$.subscribe(data2 => { console.log(data2); })*/ }); /*.subscribe(data => { this.Q=new Questionnaire(data.id,data.sujet,data.nbques); });*/ // this.quest=new Questionnaire(Q['id'],Q['sujet'],Q['nbques']); this.Q.asObservable().subscribe(data => { this.ques = data; this.id= data.id ; console.log(this.id); const id = this.ques.id ; console.log(this.ques); this.questions$ = this.testhttp.getQuestionstest(id); this.questions$.subscribe(data2 => { console.log(data2); this.questions=data2 ; this.length=data2.length; }); }); /*.subscribe(data => { console.log(data); this.quest = data; });*/ } arrayTwo(n: number): number[] { return [...Array(n).keys()]; } } <file_sep>import { Component, OnInit } from '@angular/core'; import {TestService} from './test.service'; import {Questionnaire} from '../questionnaire-list/questionnaire/questionnaire.model'; import {Router} from '@angular/router'; import {BehaviorSubject, Subject} from 'rxjs/Rx'; import {Application} from '../application-list/application/application.model'; @Component({ selector: 'app-test', templateUrl: './test.component.html', styleUrls: ['./test.component.scss'] }) export class TestComponent implements OnInit { sujets: string[]; verif = false ; Q:Questionnaire; // = new BehaviorSubject<null> ; id:number; app = new Subject<Application>(); A : Application ; sujctrl:string ; constructor(private testhttp: TestService,private router: Router) { } ngOnInit() { this.testhttp.getsubjects().subscribe(data => { console.log(); this.sujets = data; console.log(this.sujets); }); this.testhttp.GetApp().subscribe(data => { console.log(); this.app.next(data) }); this.app.asObservable().subscribe(data => { this.sujctrl = data.offer.questionnaire ; /* new Application(data.id,data.cv,data.coveringletter,data.user,data.offer); console.log(this.A) ;*/ }); } verify(sujet):boolean { this.verif = false ; if (this.sujctrl === sujet) { console.log(this.sujctrl); this.verif= true ; } console.log(this.verif) ; return this.verif ; } questionnaire(sujet) { this.testhttp.getQuestionnaireBySujet(sujet).subscribe(data => { console.log(data); const quest=new Subject<Questionnaire>(); quest.next(data); // const quest = new Questionnaire() ; // quest.next(data); // this.quest=new Questionnaire(this.id; data['sujet']; data'nbques']); console.log(quest); this.testhttp.setQuest(data); }); // this.testhttp.setQuest(quest); // console.log(this.id); this.router.navigate(['/quest-disp']); } } <file_sep> export class User { constructor( public id: number, public firstname: String, public lastname: String, public birthdate: Date, public cin: number, public email: String, public address: String, public phone: number, public login:String, public mdp:String ) {} } <file_sep>import { Component, OnInit } from '@angular/core'; import {ApplicationService} from './application.service'; import {Application} from './application.model'; import {Offer} from '../../offer-list/offer/offer.model'; import {User} from '../../user/user.model'; import {Router} from '@angular/router'; @Component({ selector: 'app-application', templateUrl: './application.component.html', styleUrls: ['./application.component.scss'] }) export class ApplicationComponent implements OnInit { app: Application; offer: Offer; user: User; constructor(private applicationService: ApplicationService,private router:Router) { } ngOnInit() { } addApplication(application) { this.applicationService.GetOffer().subscribe(data => { this.offer = data; }); this.applicationService.GetUser().subscribe(data => { this.user = data; }); console.log(this.offer,this.user) ; this.app = new Application(null,application['cv'],application['lettre'],this.user,this.offer); console.log(this.app); this.applicationService.addApplication(this.app).subscribe(res => { // y console.log(res); }, (err) => { console.log(err); }); this.router.navigate(['/test']) ; } } <file_sep>import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { QuestionnaireDisplayComponent } from './questionnaire-display.component'; describe('QuestionnaireDisplayComponent', () => { let component: QuestionnaireDisplayComponent; let fixture: ComponentFixture<QuestionnaireDisplayComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ QuestionnaireDisplayComponent ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(QuestionnaireDisplayComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); }); <file_sep>import {Directive, ElementRef, HostListener, Renderer2} from '@angular/core'; @Directive({ selector: '[appCheck]' }) export class CheckDirective { constructor(private el: ElementRef, private renderer: Renderer2) { // this.renderer.setStyle(this.el,'class="btn btn-primary"',' type="submit" [disabled]="!propositionForm.form.valid"'); // renderer.setValue(el.nativeElement,'<i class="fal fa-check"></i>'); } @HostListener('click') onMouseEnter() { /* this.renderer.createElement('<i class="fal fa-check"></i>'); this.renderer.setValue(this.el.nativeElement,'<i class="fal fa-check"></i>'); this.renderer.setStyle(this.el,'color:green','<i class="fal fa-check"></i>');*/ console.log('mouseenter'); } } <file_sep>import { CheckDirective } from './check.directive'; describe('CheckDirective', () => { it('should create an instance', () => { const directive = new CheckDirective(); expect(directive).toBeTruthy(); }); }); <file_sep>import { Component, OnInit } from '@angular/core'; import {QuestionService} from '../question-list/question/question.service'; import {Question} from '../question-list/question/question.model'; import {TestService} from '../../test/test.service'; import {PropositionService} from './proposition/proposition.service'; import index from '@angular/cli/lib/cli'; @Component({ selector: 'app-proposition-list', templateUrl: './proposition-list.component.html', styleUrls: ['./proposition-list.component.scss'] }) export class PropositionListComponent implements OnInit { nbprop: Number ; p: Number = 1 ; tab: {}[] ; nbprop_tab=[ ] ; questions=[ ] ; nbques: Number ; length = 0 ; j =0 ; constructor(private questionhttp: QuestionService, private prophttp:PropositionService) { } private extractData(res: Response) { const body = res; return body || {}; } ngOnInit() { this.nbprop = this.questionhttp.GetNumber(); // y console.log(this.nbprop); // y console.log(this.questionhttp.getProp()); /* this.tab = this.questionhttp.getProp(); // y console.log(this.tab); this.nbques = this.tab.length; const array = this.questionhttp.getProp(); // let was ; // console.log(array.map(value => was = value['nbprop'])); // y console.log(array['0']); const vals = Object.keys(array).map(function (key) { return array[key]; }); /* document.write(array[0]['nbprop']); */ // y console.log(array[0]['nbprop']); // y console.log(vals[0]['nbprop']); /* vals.forEach((y) => {this.length=this.length+y['nbprop']; this.nbprop_tab.push(y['nbprop']); }); vals.forEach((value, index1) => {this.testhttp.getQuestionstest(value['id_quest']).subscribe(data => { // this.questions=data ; console.log(data); this.questions.push(data[index1]); })}); console.log(this.nbprop_tab); console.log(this.questions); /* for (let i = 0; i < this.nbques; i++) { this.length = this.length + vals[i]['nbprop']; console.log(i); console.log(this.length); } let s = 0 ; for(let i in vals){ s = s +vals[i]['nbprop'] ; } vals.forEach(function (value, index) { s = s +value['nbprop'] ; }) ; console.log(s); for (let i = 0; i < this.nbques; i++) { this.testhttp.getQuestionstest(vals[i]['id_quest']).subscribe(data => { this.questions = data; }); } console.log(this.questions) ;*/ } forProp() { let i = this.nbprop_tab[this.j]; if (this.p < i && this.j < this.questions.length) { this.prophttp.SeQuestionForProp(this.questions[this.j]); console.log(i); if (this.p === i) { this.j = this.j + 1; } } } arrayTwo(n: number): number[] { return [...Array(n).keys()]; } setPage(p) { this.questionhttp.setPage(p); // this.p=p; console.log(p); } } <file_sep>import { Injectable } from '@angular/core'; import {Observable, Subject} from 'rxjs/Rx'; import {map} from 'rxjs/operators'; import {HttpClient, HttpHeaders} from '@angular/common/http'; import {Question} from '../../question-list/question/question.model'; import {Questionnaire} from '../../questionnaire/questionnaire.model'; const httpOptions = { headers: new HttpHeaders({'Content-Type': 'application/json'}) }; const apiUrl = 'http://localhost:8082/api'; @Injectable() export class PropositionService { Q = new Subject<Question>(); constructor(private httpclient: HttpClient) { } private extractData(res: Response) { const body = res; return body || {}; } private handleError(error: any) { // In a real world app, we might use a remote logging infrastructure // We'd also dig deeper into the error to get a better message let errMsg = (error.message) ? error.message : error.status ? `${error.status} - ${error.statusText}` : 'Server error'; console.error(errMsg); // log to console instead return Observable.throw(errMsg); } getProposition(id: string): Observable<any> { const url = `${apiUrl}/proposition/`; return this.httpclient.get(url +id, httpOptions).pipe( map(this.extractData)); } SeQuestionForProp(Q:Question) { this.Q.next(Q) ; } GetQuestionForProp(): Observable<Question> { return this.Q.asObservable() ; } getLastQuestion(): any { const url = `${apiUrl}/lastQuestion`; return this.httpclient.get(url, httpOptions).pipe(map(this.extractData)) // .catch(this.handleError); // .pipe(map((res:Response) => res.json())); // ; // .subscribe(val => console.log(val)); } getPropositions(): Observable<any> { const url = `${apiUrl}/propositions`; return this.httpclient.get(url, httpOptions) .pipe(map(this.extractData)); // convertir la reponse Observable vers un Array de session // .subscribe(); } addProposition(proposition): Observable<any> { const url = `${apiUrl}/proposition`; return this.httpclient.post(url, proposition, httpOptions) .pipe(); } /* countFormateur(): Observable<any>{ const url = `${apiUrl}/nombreFormateur`; return this.httpclient.get(url, httpOptions) .pipe(map(this.extractData)); // convertir la reponse Observable vers un Array de session //.subscribe(); }*/ deleteProposition(proposition): Observable<any> { const url = `${apiUrl}/proposition/`; return this.httpclient.delete(url + proposition._id, httpOptions) .pipe(map(this.extractData)); } updateProposition(proposition): Observable<any> { const url = `${apiUrl}/update/`; return this.httpclient.put(url + proposition._id, proposition, httpOptions) .pipe(map(this.extractData)); } } <file_sep>import { Component, OnInit } from '@angular/core'; import {OfferService} from './offer/offer.service'; import {Offer} from './offer/offer.model'; import {BehaviorSubject} from 'rxjs/Rx'; import {UrlSerializer} from '@angular/router'; import {User} from '../user/user.model'; import {LoginService} from '../login/login.service'; import {ApplicationService} from '../application-list/application/application.service'; import {Application} from '../application-list/application/application.model'; @Component({ selector: 'app-offer-list', templateUrl: './offer-list.component.html', styleUrls: ['./offer-list.component.scss'] }) export class OfferListComponent implements OnInit { offers: Offer[] ; constructor(private offerhttp: OfferService,private loginservice:LoginService,private applicationService:ApplicationService) { } ngOnInit() { this.offerhttp.getOffers().subscribe(data => { this.offers=data ; }) } Postuler(offer) { this.applicationService.SetOffer(offer); // this.Offer.next(offer); this.loginservice.getconnectedUser().subscribe(data => { const user = data ; this.applicationService.SetUser(user); console.log(user); }); } } <file_sep> import { Injectable } from '@angular/core'; import {map} from 'rxjs/operators'; import {BehaviorSubject, Observable} from 'rxjs/Rx'; import {HttpClient, HttpHeaders} from '@angular/common/http'; import {Offer} from '../../offer-list/offer/offer.model'; import {User} from '../../user/user.model'; import {Application} from './application.model'; const httpOptions = { headers: new HttpHeaders({'Content-Type': 'application/json'}) }; const apiUrl = 'http://localhost:8080/api'; @Injectable() export class ApplicationService { private jwtToken = localStorage.getItem('token'); Offer = new BehaviorSubject<Offer>(null) ; User = new BehaviorSubject<User>(null) ; cle = false; constructor(private httpclient: HttpClient) {} /* private extractData(res: Response) { let body = res.json(); // If response is a JSON use json() if (body) { return body.data || body; } else { return {}; } }*/ SetUser(user){ this.User.next(user);} GetUser():Observable<User>{ return this.User.asObservable(); } SetOffer(offer) { this.Offer.next(offer); } GetOffer():Observable<Offer> { return this.Offer.asObservable() ; } private extractData(res: Response) { const body = res; return body || {}; } getOffer(id: string): Observable<any> { const url = `${apiUrl}/questionnaire/`; return this.httpclient.get(url +id, httpOptions).pipe( map(this.extractData)); } getLastId(): any { const url = `${apiUrl}/lastId`; return this.httpclient.get(url, httpOptions).pipe(map(this.extractData)) // .catch(this.handleError); // .pipe(map((res:Response) => res.json())); // ; // .subscribe(val => console.log(val)); } getApplications(): Observable<any> { const url = `${apiUrl}/applications`; return this.httpclient.get(url, httpOptions) .pipe(map(this.extractData)); // convertir la reponse Observable vers un Array de session // .subscribe(); } verify(application: Application){ let sujet: string ; if(application.offer.questionnaire===sujet) { this.cle=true; } } addApplication(application:Application): Observable<any> { console.log(application); const url = `${apiUrl}/application`; console.log(this.jwtToken); return this.httpclient.post(url,application, { headers: new HttpHeaders({'authorization': this.jwtToken}) }).pipe(); } /* countFormateur(): Observable<any>{ const url = `${apiUrl}/nombreFormateur`; return this.httpclient.get(url, httpOptions) .pipe(map(this.extractData)); // convertir la reponse Observable vers un Array de session //.subscribe(); }*/ deleteQuestionnaire(questionnaire): Observable<any> { const url = `${apiUrl}/questionnaire/`; return this.httpclient.delete(url + questionnaire._id, httpOptions) .pipe(map(this.extractData)); } updateQuestionnaire(questionnaire): Observable<any> { const url = `${apiUrl}/update/`; return this.httpclient.put(url + questionnaire._id, questionnaire, httpOptions) .pipe(map(this.extractData)); } } <file_sep>import {Questionnaire} from '../../questionnaire/questionnaire.model'; export class Question { constructor( public id: number, public contenu: string, public nbprop: number, public reponse: string, public type: string, public questionnaire: Questionnaire) {} } <file_sep>import {Component, Input, OnInit} from '@angular/core'; import {QuestionnaireService} from './questionnaire.service'; import {Router} from '@angular/router'; @Component({ selector: 'app-questionnaire', templateUrl: './questionnaire.component.html', styleUrls: ['./questionnaire.component.scss'] }) export class QuestionnaireComponent implements OnInit { @Input() nbques: Number ; constructor( private questionnairehttp: QuestionnaireService, private router: Router) { } ngOnInit() { } addQuestionnaire(questionnaire) { /* this.nbques=questionnaire['nbques']; console.log(this.nbques);*/ this.questionnairehttp.SetNumber(this.nbques) ; const questionnairea = { 'sujet': questionnaire['sujet'], 'nbques': questionnaire['nbques'] }; this.questionnairehttp.addQuestionnaire(questionnairea).subscribe(res => { // y console.log(res); }, (err) => { console.log(err); }); this.router.navigate(['/questions']); } } <file_sep>import {Component, Input, OnInit} from '@angular/core'; import {Question} from '../../../questionnaire-list/question-list/question/question.model'; import {TestService} from '../../test.service'; import {Proposition} from '../../../questionnaire-list/proposition-list/proposition/proposition.model'; // import {Proposition} from '../../../questionnaire-list/proposition-list/proposition/proposition.model'; @Component({ selector: 'app-question-display', templateUrl: './question-display.component.html', styleUrls: ['./question-display.component.scss'] }) export class QuestionDisplayComponent implements OnInit { @Input() question: Question; type: String; propositions: Proposition[]; value: String; proposition: { 'id':number, 'contenu':String }[]; score = 0; constructor(private testhttp: TestService) { } ngOnInit() { this.type = this.question.type; this.testhttp.getPropostionstest(this.question.id).subscribe(data => { this.propositions = data; console.log(this.propositions.length); }); console.log('Your score'+this.testhttp.getScore()); } OnCheckboxSelect(contenu, event) { if (event.target.checked === true) { this.value=contenu; console.log(this.value); } } Score(value) { if (this.value === this.question.reponse) { this.score = this.score + 1; this.testhttp.setScore(this.score); } console.log(this.value); console.log(this.score); } } <file_sep>import { Injectable } from '@angular/core'; import {map} from 'rxjs/operators'; import {Observable} from 'rxjs/Rx'; import {HttpClient, HttpHeaders} from '@angular/common/http'; const apiUrl = 'http://localhost:8080/api'; @Injectable() export class OfferService { private jwtToken = localStorage.getItem('token'); constructor(private httpclient: HttpClient) { /* let headers = new HttpHeaders(); headers.append('authorization', this.jwtToken);*/ /* let httpOptions = { headers: new HttpHeaders({'Content-Type': 'application/json','authorization': this.jwtToken}) };*/ } /* private extractData(res: Response) { let body = res.json(); // If response is a JSON use json() if (body) { return body.data || body; } else { return {}; } }*/ private extractData(res: Response) { const body = res; return body || {}; } getOffer(id: string): Observable<any> { const url = `${apiUrl}/questionnaire/`; return this.httpclient.get(url +id, {headers: new HttpHeaders({'authorization': this.jwtToken}) }).pipe( map(this.extractData)); } getLastId(): any { const url = `${apiUrl}/lastId`; return this.httpclient.get(url, {headers: new HttpHeaders({'authorization': this.jwtToken}) }).pipe(map(this.extractData)) // .catch(this.handleError); // .pipe(map((res:Response) => res.json())); // ; // .subscribe(val => console.log(val)); } getOffers(): Observable<any> { const url = `${apiUrl}/offers`; return this.httpclient.get(url, {headers: new HttpHeaders({'authorization': this.jwtToken}) }) .pipe(map(this.extractData)); // convertir la reponse Observable vers un Array de session // .subscribe(); } addQuestion(question): Observable<any> { const url = `${apiUrl}/question`; return this.httpclient.post(url, question, {headers: new HttpHeaders({'authorization': this.jwtToken}) }) .pipe(); } /* countFormateur(): Observable<any>{ const url = `${apiUrl}/nombreFormateur`; return this.httpclient.get(url, httpOptions) .pipe(map(this.extractData)); // convertir la reponse Observable vers un Array de session //.subscribe(); }*/ deleteQuestionnaire(questionnaire): Observable<any> { const url = `${apiUrl}/questionnaire/`; return this.httpclient.delete(url + questionnaire._id, {headers: new HttpHeaders({'authorization': this.jwtToken}) }) .pipe(map(this.extractData)); } updateQuestionnaire(questionnaire): Observable<any> { const url = `${apiUrl}/update/`; return this.httpclient.put(url + questionnaire._id, questionnaire, {headers: new HttpHeaders({'authorization': this.jwtToken}) }) .pipe(map(this.extractData)); } } <file_sep> export class Questionnaire { constructor( public id: number, public sujet: string, public nbques: number) {} static fromJson(json) { return new Questionnaire(json.id, json.sujet, json.nbques); } } <file_sep>import { Injectable } from '@angular/core'; import {BehaviorSubject, Observable, Subject} from 'rxjs/Rx'; import {map} from 'rxjs/operators'; import {HttpClient, HttpHeaders} from '@angular/common/http'; import {Questionnaire} from '../questionnaire-list/questionnaire/questionnaire.model'; const httpOptions = { headers: new HttpHeaders({'Content-Type': 'application/json'}) }; const apiUrl = 'http://localhost:8082/api'; @Injectable() export class TestService { private jwtToken = localStorage.getItem('token'); score:Number = 0 ; /* private dataSource = new BehaviorSubject<Questionnaire>(); data = this.dataSource.asObservable();*/ // quest: Observable<Questionnaire>; Q = new Subject<Questionnaire>(); constructor(private httpclient: HttpClient) { } private extractData(res: Response) { const body = res; return body || {}; } setQuest(ques:Questionnaire) { /* const quest = new BehaviorSubject<Questionnaire>(ques); console.log(quest.getValue()); this.Q=new BehaviorSubject<Questionnaire>(ques); // this.quest=new Questionnaire(quest.id,quest.sujet,quest.nbques); // console.log(this.quest.getValue()); // this.Q.next(this.quest.getValue());*/ console.log(ques); this.Q.next(ques); console.log(this.Q); } setScore(score) { this.score=this.score+score ; } getScore(){ return this.score ; } GetApp():Observable<any> { const url = `http://localhost:8080/api/lastapp`; return this.httpclient.get(url, { headers: new HttpHeaders({'authorization': this.jwtToken}) }).pipe(map(this.extractData)) ; } GetQuest():Observable<Questionnaire> { /* this.Q = new Questionnaire(this.quest.id,this.quest.sujet,this.quest.nbques); return this.Q ;*/ // console.log(this.Q.getValue()) ; return this.Q.asObservable() ; } getsubjects(): any { const url = `${apiUrl}/sujets`; return this.httpclient.get(url, httpOptions).pipe(map(this.extractData)) // .catch(this.handleError); // .pipe(map((res:Response) => res.json())); // ; // .subscribe(val => console.log(val)); } getQuestionnaireBySujet(sujet: string): Observable<any> { const url = `${apiUrl}/bysujet?sujet=`+sujet; console.log(url); return this.httpclient.get(url , httpOptions).pipe( map(this.extractData)); } getQuestionstest(id:number): Observable<any> { const url = `${apiUrl}/questiontest?id=`+id ; // +`&id=`+id; console.log(url); return this.httpclient.get(url , httpOptions).pipe( map(this.extractData)); } getPropostionstest(id:number): Observable<any> { const url = `${apiUrl}/propositiontest?id=`+id ; // +`&id=`+id; console.log(url); return this.httpclient.get(url , httpOptions).pipe( map(this.extractData)); } /* SetNumber(nbprop) { this.nbprop=nbprop; } GetNumber() { return this.nbprop ; }*/ getLastId(): any { const url = `${apiUrl}/lastId`; return this.httpclient.get(url, httpOptions).pipe(map(this.extractData)) // .catch(this.handleError); // .pipe(map((res:Response) => res.json())); // ; // .subscribe(val => console.log(val)); } getQuestionnaires(): Observable<any> { const url = `${apiUrl}/questionnaires`; return this.httpclient.get(url, httpOptions) .pipe(map(this.extractData)); // convertir la reponse Observable vers un Array de session // .subscribe(); } addQuestion(question): Observable<any> { const url = `${apiUrl}/question`; return this.httpclient.post(url, question, httpOptions) .pipe(); } private handleError(error: any) { // In a real world app, we might use a remote logging infrastructure // We'd also dig deeper into the error to get a better message let errMsg = (error.message) ? error.message : error.status ? `${error.status} - ${error.statusText}` : 'Server error'; console.error(errMsg); // log to console instead return Observable.throw(errMsg); } /* countFormateur(): Observable<any>{ const url = `${apiUrl}/nombreFormateur`; return this.httpclient.get(url, httpOptions) .pipe(map(this.extractData)); // convertir la reponse Observable vers un Array de session //.subscribe(); }*/ deleteQuestionnaire(questionnaire): Observable<any> { const url = `${apiUrl}/questionnaire/`; return this.httpclient.delete(url + questionnaire._id, httpOptions) .pipe(map(this.extractData)); } updateQuestionnaire(questionnaire): Observable<any> { const url = `${apiUrl}/update/`; return this.httpclient.put(url + questionnaire._id, questionnaire, httpOptions) .pipe(map(this.extractData)); } } <file_sep>import { Routes } from '@angular/router'; import { DashboardComponent } from '../../dashboard/dashboard.component'; import { UserProfileComponent } from '../../user-profile/user-profile.component'; import { TableListComponent } from '../../table-list/table-list.component'; import { TypographyComponent } from '../../typography/typography.component'; import { IconsComponent } from '../../icons/icons.component'; import { MapsComponent } from '../../maps/maps.component'; import { NotificationsComponent } from '../../notifications/notifications.component'; import {QuestionnaireComponent} from '../../questionnaire-list/questionnaire/questionnaire.component'; import {QuestionListComponent} from '../../questionnaire-list/question-list/question-list.component'; import {QuestionComponent} from '../../questionnaire-list/question-list/question/question.component'; import {PropositionListComponent} from '../../questionnaire-list/proposition-list/proposition-list.component'; import {PropositionComponent} from '../../questionnaire-list/proposition-list/proposition/proposition.component'; import {TestComponent} from '../../test/test.component'; import {QuestionDisplayComponent} from '../../test/questionnaire-display/question-display/question-display.component'; import {QuestionnaireDisplayComponent} from '../../test/questionnaire-display/questionnaire-display.component'; import {OfferComponent} from '../../offer-list/offer/offer.component'; import {OfferListComponent} from '../../offer-list/offer-list.component'; import {ApplicationComponent} from '../../application-list/application/application.component'; import {QuestionnaireListComponent} from '../../questionnaire-list/questionnaire-list.component'; import {UserComponent} from '../../user/user.component'; export const AdminLayoutRoutes: Routes = [ { path: 'dashboard', component: DashboardComponent }, { path: 'user-profile', component: UserProfileComponent }, { path: 'table-list', component: TableListComponent }, { path: 'typography', component: TypographyComponent }, { path: 'icons', component: IconsComponent }, { path: 'maps', component: QuestionnaireComponent }, { path: 'notifications', component: NotificationsComponent }, { path: 'questions', component: QuestionListComponent }, { path: 'question', component: QuestionComponent }, { path: 'propositions', component: PropositionListComponent }, { path: 'proposition', component: PropositionComponent }, { path: 'test', component: TestComponent }, { path: 'quest-disp', component: QuestionnaireDisplayComponent}, { path: 'question-disp', component: QuestionDisplayComponent }, { path: 'offers', component: OfferListComponent }, { path: 'application', component: ApplicationComponent }, { path: 'questionnaires', component: QuestionnaireListComponent } ];
2495febfe8455bcd56fabc5695884279c13dcd1f
[ "TypeScript" ]
30
TypeScript
wissal-mekki/gateway
8176c127fff81fe3482526595f79f659fcbe6698
50c7d8fd2a91f34eb87fc580592644f280225cd0
refs/heads/master
<repo_name>gulisashvili/react-todo<file_sep>/src/Index.js import React from 'react' import ReactDOM from 'react-dom' import { Router, Route } from 'react-router' import App from './components/App' import Tasks from './components/Tasks' import Auth from './components/Auth' import { parseInit } from './parse-helper/app' window.React = React; parseInit() ReactDOM.render( <Router> <Route path="/" component={App}> <Route path="/tasks" component={Tasks} /> <Route path="/auth" component={Auth} /> </Route> </Router> , document.getElementById('content') ); <file_sep>/README.md # React Todo List App Todo app developed on React.js <file_sep>/src/components/Auth.js import React from 'react'; export default React.createClass({ componentDidMount () { Parse.FacebookUtils.logIn("user_likes,email", { success: function(user) { console.log(user) }, error: function(user, error) { console.log('err : ', error) } }); }, logOut () { Parse.User.logOut(); }, render() { return ( <div> <h3> Auth </h3> <button onClick={this.logOut}> log out </button> </div> ) } }) <file_sep>/src/components/Task.js import React from 'react'; export default React.createClass({ render() { let task = this.props.task return ( <div className="task-card"> {task} </div> ) } }) <file_sep>/src/components/App.js import React from 'react'; import { Link } from 'react-router'; export default React.createClass({ componentDidMount () { if (this.getCurrentUser()) return this.setState({isUserAuthenticated: true}) return this.setState({isUserAuthenticated: false}) }, getInitialState () { return { isUserAuthenticated: false, tasks: [] } }, getCurrentUser () { return Parse.User.current() }, handleAuth () { console.log("Authenticating") Parse.FacebookUtils.logIn("user_likes,email", { success: function(user) { this.setState({isUserAuthenticated: true}) FB.api('/me', function(response) {}); }.bind(this), error: function(user, error) { console.log('err : ', error) }.bind(this) }); }, handleLogOut () { Parse.User.logOut(); this.setState({isUserAuthenticated: false}) console.log("cur user : ", Parse.User.current()) }, showContentIfUserIsAuthenticated (fbAuthLink) { if (fbAuthLink) return !this.state.isUserAuthenticated ? 'inline-block' : 'none' return this.state.isUserAuthenticated ? 'inline-block' : 'none' }, render() { let styles = { section : { display: this.showContentIfUserIsAuthenticated() }, fbAuthLink : { display: this.showContentIfUserIsAuthenticated(true) } } return ( <div> <header> <Link to="/"> React Todo App </Link> <Link style={styles.section} to="/tasks"> Tasks </Link> <a style={styles.fbAuthLink} href="#" onClick={this.handleAuth}> Login with Facebook </a> <a href="#" style={styles.section} onClick={this.handleLogOut}> Log out </a> </header> <section style={styles.section}> {this.props.children} </section> </div> ) } });
ee5a78db8cfed008d4f100c61de008ed5c31ae71
[ "JavaScript", "Markdown" ]
5
JavaScript
gulisashvili/react-todo
5c6dc4abbbf06f14d210b84ab26c87aa29cf46eb
b3bca82ee72a23c348ab4af9960f0f2edc61f7a9
refs/heads/master
<file_sep><?php namespace Common\Exception; class AppException extends \Exception { } <file_sep><?php /** * Description of PostService * * @author: <NAME> AwoyoToyin <<EMAIL>> */ namespace App\Service; use Common\Service\AbstractService; class PostService extends AbstractService { /** * Serves the index of all entity * * @param array $filters * @param array $orderBy * @param array $groupBy * @return EntityInterface */ public function index( array $filters = [], $orderBy = [], $groupBy = [] ) { return parent::index($filters, $orderBy, $groupBy); // return $this->provider->selectAllPaginate(0, 1, $filters, $orderBy, $groupBy, false); } } <file_sep><?php namespace Common; use Zend\ServiceManager\AbstractFactory\ConfigAbstractFactory; use Zend\ServiceManager\Factory\InvokableFactory; use Common\Factory\LoggingErrorListenerFactory; use Zend\Stratigility\Middleware\ErrorHandler; use Doctrine\Common\Cache\Cache; /** * The configuration provider for the Common module * * @see https://docs.zendframework.com/zend-component-installer/ */ class ConfigProvider { /** * Returns the configuration array * * To add a bit of a structure, each section is defined in a separate * method which returns an array with its configuration. * * @return array */ public function __invoke() { return [ 'dependencies' => $this->getDependencies(), 'templates' => $this->getTemplates(), ]; } /** * Returns the container dependencies * * @return array */ public function getDependencies() { return [ 'invokables' => [ ], 'factories' => [ ], 'delegators' => [ ErrorHandler::class => [ LoggingErrorListenerFactory::class, ], ], ]; } /** * Returns the templates configuration * * @return array */ public function getTemplates() { return [ 'paths' => [ 'common' => [__DIR__ . '/../templates/common'], 'error' => [__DIR__ . '/../templates/error'], 'layout' => [__DIR__ . '/../templates/layout'], ], ]; } } <file_sep><?php use Zend\Expressive\Router\FastRouteRouter; use Zend\Expressive\Router\RouterInterface; return [ 'dependencies' => [ 'invokables' => [ RouterInterface::class => FastRouteRouter::class, ], ], 'router' => [ 'fastroute' => [ // Enable caching support: 'cache_enabled' => true, // Optional (but recommended) cache file path: 'cache_file' => 'data/cache/fastroute.php.cache', ], ], ]; <file_sep><?php return [ 'templates' => [ 'paths' => [ 'app' => [__DIR__ . '/../templates/app'] ], ] ]; <file_sep><?php namespace Common\Entity; use Doctrine\ORM\Mapping as ORM; abstract class AbstractEntity implements EntityInterface { /** * @ORM\Id * @ORM\Column(name="id", type="integer", options={"unsigned"=true}) * @ORM\GeneratedValue(strategy="IDENTITY") * @var int */ protected $id; /** * @Column(name="created_at", type="string", length=255) */ private $createdAt; /** * @Column(name="updated_at", type="string", length=255) */ private $updatedAt; /** * Get the value of id * * @return int */ public function getId() { return $this->id; } /** * Set the value of id * * @param int $id * @return self */ public function setId(int $id) { $this->id = $id; return $this; } /** * Get the value of createdAt */ public function getCreatedAt() { return $this->createdAt; } /** * @ORM\PrePersist * Set the value of createdAt * * @return self */ public function setCreatedAt() { $this->createdAt = date('Y-m-d H:i:s'); return $this; } /** * Get the value of updatedAt */ public function getUpdatedAt() { return $this->updatedAt; } /** * @ORM\PreUpdate * Set the value of updatedAt * * @return self */ public function setUpdatedAt() { $this->updatedAt = date('Y-m-d H:i:s'); return $this; } /** * @param array $data */ public function exchangeArray(array $data) { foreach ($data as $key => $value) { $this->{$key} = (!empty($value)) ? $value : null; } } } <file_sep><?php namespace App; use Zend\ServiceManager\AbstractFactory\ConfigAbstractFactory; use Zend\ServiceManager\Factory\InvokableFactory; use Zend\Expressive\Template\TemplateRendererInterface; use Doctrine\Common\Cache\Cache; return [ 'dependencies' => [ 'invokables' => [ Action\PingAction::class => Action\PingAction::class, ], 'factories' => [ // Services Service\PostService::class => ConfigAbstractFactory::class, // Providers Provider\PostProvider::class => ConfigAbstractFactory::class, // Middleware Action\HomePageAction::class => ConfigAbstractFactory::class, ], ], ConfigAbstractFactory::class => [ // Services Service\PostService::class => [Provider\PostProvider::class], // Providers Provider\PostProvider::class => ['doctrine.entity_manager.orm_default'], // Middleware Action\HomePageAction::class => [Service\PostService::class, TemplateRendererInterface::class], ] ]; <file_sep><?php namespace App\Entity; use Doctrine\ORM\Mapping as ORM; use Common\Entity\AbstractEntity; /** * @ORM\Entity * @ORM\HasLifecycleCallbacks * @ORM\Table(name="blog_post") */ class Post extends AbstractEntity implements \JsonSerializable { /** * @ORM\Column(name="author", type="string", length=32) * @var string */ private $author; /** * @ORM\Column(name="title", type="string", length=32) * @var string */ private $title; /** * Get the value of author * * @return string */ public function getAuthor() { return $this->author; } /** * Set the value of author * * @param string $author * @return self */ public function setAuthor(string $author) { $this->author = $author; return $this; } /** * Get the value of title * * @return string */ public function getTitle() { return $this->title; } /** * Set the value of title * * @param string $title * @return self */ public function setTitle(string $title) { $this->title = $title; return $this; } public function jsonSerialize() { return [ 'id' => $this->id, 'author' => $this->author, 'title' => $this->title ]; } } <file_sep><?php /** * Description of ProviderInterface * * @author: <NAME> AwoyoToyin <<EMAIL>> */ namespace App\Provider; use Common\Provider\AbstractProvider; class PostProvider extends AbstractProvider { protected $entityClass = 'App\Entity\Post'; } <file_sep><?php namespace App\Action; use Interop\Http\ServerMiddleware\DelegateInterface; use Interop\Http\ServerMiddleware\MiddlewareInterface as ServerMiddlewareInterface; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Zend\Diactoros\Response\HtmlResponse; use Zend\Diactoros\Response\JsonResponse; use Zend\Expressive\Template; use Zend\Expressive\Plates\PlatesRenderer; use Common\Service\AbstractService; use Common\Exception\AppException; class HomePageAction implements ServerMiddlewareInterface { /** * @var \App\Service\PostService */ private $service; /** * @var Template\TemplateRendererInterface */ private $template; /** * @param \App\Service\PostService $service * @param Template\TemplateRendererInterface $template */ public function __construct(AbstractService $service, Template\TemplateRendererInterface $template = null) { $this->service = $service; $this->template = $template; } public function process(ServerRequestInterface $request, DelegateInterface $delegate) { $collection = $this->service->index(); if (!$this->template) { return new JsonResponse($collection); } $data = [ 'templateName' => 'Plates', 'templateDocs' => 'http://platesphp.com/', 'collection' => $collection ]; return new HtmlResponse($this->template->render('app::home-page', $data)); } }
2e5e90afa969a4a70758917804f51b3850c54de8
[ "PHP" ]
10
PHP
AwoyoToyin/expressive-doctrine-orm
c8a013989eb4ab91a2afbef19cd06ac953d885bd
cdca32648e162aa94daed09c3b683e0dc986ee6c
refs/heads/master
<file_sep>import React from "react"; import Avatar from "@material-ui/core/Avatar"; import "./Video.css"; function VideoCard({ title, image, channel, views, timestamp, channelImage }) { return ( <div className="videocard"> <img className="video_tumbnail" src={image} alt="" /> <div className="video_info"> <Avatar className="video_avatar" alt={channel} src={channelImage} /> <div className="video_text"> <h4>{title}</h4> <p>{channel}</p> <p> {views} . {timestamp} </p> </div> </div> </div> ); } export default VideoCard;
d53ab50ca08294fad24c700a7a5175c2ff6271f3
[ "JavaScript" ]
1
JavaScript
UzairNadeem580/Youtube-Clone
b4d3d6c25217d1000270c3a2fe7805420d7dad1f
3edcd0af48a14a6d0b8bff656f5ae9bd9da90b63
refs/heads/master
<file_sep><article class="post"> <?php echo View::factory('site/authorsidebar')->render(); ?> <h2 style="color: #C9C9C9;">Author Spotlight: <?php echo $authorName ?></h2> <br /> <p class="excerpt"><?php echo html_entity_decode(stripslashes($bio)); ?></p> </article><file_sep><?php foreach($usergroups as $usergroup){ $usergroupnames[] = $usergroup['groupName']; } ?> <?php echo Form::open(array('action' => '../../admin/authors/signup', 'class' => 'form author label-inline ', 'enctype' => 'multipart/form-data')); ?> <div style="float: left; position: absolute;" class="x6"> <div class="field"> <label for="uname">Username</label> <?php echo Form::input('uname', isset($fields['username']) ? $fields['username'] : '' , array('name' => 'uname', 'id' => 'uname', 'class' => 'medium')); ?> <div class="field_help">Not less than 3 or more than 20 characters</div> </div> <div class="field"> <label for="fname">First Name</label> <?php echo Form::input('fname', isset($fields['firstname']) ? $fields['firstname'] : '' ,array('name' => 'fname', 'id' => 'fname', 'class' => 'medium')); ?> <div class="field_help">Not less than 3 or more than 20 characters</div> </div> <div class="field"> <label for="lname">Last Name</label> <?php echo Form::input('lname', isset($fields['lastname']) ? $fields['lastname'] : '' ,array('name' => 'lname', 'id' => 'lname', 'class' => 'medium')); ?> <div class="field_help">Not less than 3 or more than 20 characters</div> </div> </div> <div style="float: right;" class="x6"> <div class="field"> <label for="pword">Password</label> <?php echo Form::input('pword', isset($fields['password']) ? $fields['password'] : '' ,array('name' => 'pword', 'id' => 'pword', 'class' => 'medium')); ?> <div class="field_help">Not less than 8 or more than 20 characters</div> </div> <div class="field"> <label for="email">Email</label> <?php echo Form::input('email', isset($fields['email']) ? $fields['email'] : '' ,array('name' => 'email', 'id' => 'email', 'class' => 'medium')); ?> <div class="field_help">Must be a valid email</div> </div> <div class="field"> <label for="ugroup">User Group</label> <?php echo Form::select("ugroup", array('name' => 'test', 'id' => 'type', 'class' => 'medium'), $usergroupnames) ?> </div> <div class="field buttonrow "> <?php echo Form::submit(array('class' => 'btn', 'value' => 'Create Author')); ?> </div> </div> <?php echo Form::close(); ?> <div style="clear:both;"></div><file_sep><?php // This PHP code developed by <NAME> of Avalux Web Development - AvaluxDev.com class Controller_Admin extends Controller_Template { public $template = 'template_login'; public function action_index() { $data = array(); $data['adminUserName'] = "Jeremy Buff"; $data['adminRole'] = "Lead Developer"; $data['user'] = Auth::instance()->get_user_array(); $this->template->title = 'Full Sail Times'; /* $this->template->content = View::factory('admin/login', $data); */ if(Auth::check()) { Response::redirect('../../admin/controlpanel'); } if($_POST) { $val = Validation::factory('users'); $val->add_field('username', 'Your username', 'required|min_length[3]|max_length[20]'); $val->add_field('password', '<PASSWORD>', 'required|min_length[3]|max_length[20]'); if($val->run()) { $auth = Auth::instance(); // check the credentials. This assumes that you have the previous table created if($auth->login($_POST['username'],$_POST['password'])) // if($auth->login(Input::post('username'), Input::post('password'))) { // credentials ok, go right in Response::redirect('../../admin/controlpanel'); } else { // Oops, no soup for you. try to login again. // Set some values to repopulate the username field and give some error text back to the view $data['username'] = $_POST['username']; $data['errors'] = 'Wrong username/password. Try again'; } } else { if($_POST) { $data['username'] = $val->validated('username'); $data['errors'] = 'Validation Failed; Please reenter credentials.'; } else { $data['errors'] = false; } } } $this->template->errors = @$data['errors']; $this->template->content = View::factory('admin/login', $data); echo View::factory('admin/login',$data); } public function action_logout() { $data = array(); try { $logoutSuccess = Auth::instance()->logout(); $e = "shit"; } catch(Exception $e) { $data['error'] = "We're sorry, we could not log you out due to an error. To fully logout, we suggest you clear your cookies and cache."; } echo View::factory('admin/login', $data); } public function action_recoverpassword() { $data = array(); // //$username = null //Auth::instance()->forgotten_password(); $data['error'] = "We're sorry, but at this time there is no way to recover a lost password. Please email <EMAIL>."; echo View::factory('admin/login', $data); } public function action_404() { $messages = array('Aw, crap!', 'Bloody Hell!', 'Uh Oh!', 'Nope, not here.', 'Huh?'); $data['title'] = $messages[array_rand($messages)]; // Set a HTTP 404 output header $this->response->status = 404; $this->response->body = View::factory('welcome/404', $data); } } ?><file_sep><div id="top"> <div class="content_pad"> <ul class="right"> <li><a href="<?php echo $base_path; ?>admin/profile" class="top_icon"><span class="ui-icon ui-icon-person"></span>Logged in as <?php echo $userName; ?></a></li> <li><a rel="facebox" href="#messages" class="new_messages top_alert">1 New Message</a></li> <li><a href="<?php echo $base_path; ?>admin/settings">Settings</a></li> <li><a href="<?php echo $base_path; ?>admin/logout">Logout</a></li> </ul> </div> <!-- .content_pad --> </div> <!-- #top --> <div id="header"> <div class="content_pad"> <h1><a href="<?php echo $base_path; ?>admin">Dashboard Admin</a></h1> <ul id="nav"> <li class="nav_icon"><a href="<?php echo $base_path; ?>admin"><span class="ui-icon ui-icon-home"></span>Home</a></li> <li class="nav_dropdown nav_icon"> <a href="<?php echo $base_path; ?>admin/posts"><span class="ui-icon ui-icon-gripsmall-diagonal-se"></span>Site Content</a> <div class="nav_menu"> <ul> <li><a href="<?php echo $base_path; ?>admin/new">Create a New Post</a></li> <li><a href="<?php echo $base_path; ?>admin/posts">Edit an Existing Post</a></li> <?php if($userRoleIsAdmin) { echo '<li><a href="' . $base_path . 'admin/authors">Create / Edit Authors</a></li>'; } ?> <li><a href="<?php echo $base_path; ?>admin/media">Manage Images</a></li> </ul> </div> </li> <li class="nav_icon"><a href="<?php echo $base_path; ?>admin/configuration"><span class="ui-icon ui-icon-gear"></span>Configuration</a></li> <li class="nav_icon"><a href="<?php echo $base_path; ?>admin/reports"><span class="ui-icon ui-icon-signal"></span>Reports</a></li> <li class="nav_dropdown nav_icon_only"> <a href="javascript:;">&nbsp;</a> <div class="nav_menu"> <ul> <li><a href="<?php echo $base_path; ?>admin/messages">Messages</a></li> <li><a href="<?php echo $base_path; ?>admin/comments">Comments</a></li> <li><a href="<?php echo $base_path; ?>admin/avalux">Contact Avalux</a></li> </ul> </div> <!-- .menu --> </li> </ul> </div> <!-- .content_pad --> </div> <!-- #header --> <div id="masthead"> <div class="content_pad"> <h1>Your Media</h1> <div id="bread_crumbs"> <a href="<?php echo $base_path; ?>admin">Home</a> / <a href="<?php echo $base_path; ?>admin/media" class="current_page">Manage Media</a> </div> <!-- #bread_crumbs --> <div id="search"> <?php echo Form::open(array('action' => $base_path .'admin/search', 'method' => 'GET')); ?> <?php echo Form::input(array('type' => 'text','value' => 'Search Posts', 'placeholder' => 'Search Posts', 'name' => 'search', 'id' => 'search_input', 'title' => 'Search')); ?> <?php echo Form::submit(array('name' => 'submit', 'class' => 'submit')); ?> <?php echo Form::close(); ?> </div> <!-- #search --> </div> <!-- .content_pad --> </div> <!-- #masthead --> <div id="content" class="xgrid"> <div class="x4"> <h3>Upload New Image</h3> <?php echo Form::open(array('class' => 'imgupload label-inline uniform', 'enctype' => 'multipart/form-data')); ?> <div style="margin:-15px 0 5px 0 !important; font-size: 11px;" class="field_help">To upload an avatar, <a href="<?php echo $base_path; ?>admin/settings">edit your profile</a>.</div> <div class="error"><strong> <?php if(isset($error)){ foreach($error as $e){ echo $e . "<br />"; } } ?> </strong></div> <div class="success"><strong> <?php if(isset($success)){ echo $success; } ?> </strong></div> <div class="field"> <label for="imgtitle">Image Title</label> <br /> <?php echo Form::input(array('name' => 'imgtitle', 'id' => 'imgtitle', 'class' => 'medium')); ?> </div> <div class="field"> <label for="imgalt">Image Alt</label> <br /> <?php echo Form::input(array('name' => 'imgalt', 'id' => 'imgalt', 'class' => 'medium')); ?> </div> <div class="field clearfix"> <label for="imagefile">Image</label> <br /> <?php echo Form::input(array('type' => 'file', 'name' => 'imagefile', 'id' => 'imagefile', 'class' => 'medium')); ?> </div> <div class="buttonrow"> <?php echo Form::submit(array('class' => 'btn', 'value' => 'Submit Post')); ?> </div> <?php echo Form::close(); ?> </div> <!-- .x4 --> <div class="x1"></div> <div class="x7"> <h3>Your Existing Images</h3> <ul id="imggallery"> <?php if(count($article_images) > 0) { foreach($article_images as $image){ echo '<li class="galleryImg">'; echo '<a rel="facebox" href="' . $base_path . 'public/assets/img/' . $image['imagePath'] . '"> '. Asset::img($image['imagePath'], array('class' => 'galleryImage', 'alt' => $image['alt'])) . '</a>'; echo '<div class="imgtitle">'. stripslashes($image['title']) .'</div>'; echo '</li>'; } } else { echo 'Uh oh! It looks like you don\'t have any images yet. Upload some to the right!'; } ?> </ul> <div style="clear:both;"></div> <br /><br /> <?php echo '<span style="float:left; margin: 12px 0 0 370px;" id="pagenumbers">' . Pagination::create_pagenum_links() . '</span>'; ?> <div class="dataTables_paginate paging_two_button" id="example_paginate" style="margin-right: 25px;"> <?php if($pageNum == 1){ echo '<div class="paginate_disabled_previous" title="Next" id="example_next"></div>'; }else { echo '<a href="' .$base_path. 'admin/media/' . ($pageNum -1) . '"><div class="paginate_enabled_previous" title="Previous" id="example_previous"></div></a>'; } if($totalPages == $pageNum ) { echo '<div class="paginate_disabled_next" title="Next" id="example_next"></div>'; } else { echo '<a href="' .$base_path. 'admin/media/' . ($pageNum +1) . '"><div class="paginate_enabled_next" title="Next" id="example_next"></div></a>'; } ?> </div> </div> <!-- .x3 --> </div> <!-- #content --> <div id="messages" style="display: none"> <h4 class="deletetitle">This Feature Arriving Soon</h4> <p>Before too long, you will be able to utilize the messaging and notification system.</p> </div> <div id="footer"> <div class="content_pad"> <p>&copy; 2011 Copyright <a href="http://www.avaluxdev.com">Avalux Web Development</a>. Powered by <a href="http://fuelphp.com/">Fuel PHP Framework</a>.</p> </div> <!-- .content_pad --> </div> <!-- #footer --><file_sep><?php // This PHP code developed by <NAME> of Avalux Web Development - AvaluxDev.com class Controller_Admin_Authors extends Controller_Template { public $template = 'template_backend'; public function action_index() { $data = array(); $data['adminRole'] = "Lead Developer"; $data['user'] = Auth::instance()->get_user_array(); $data['userID'] = $data['user']['id'][1]; $data['userGroup'] = $data['user']['usergroup'][0][1]; $data['articles'] = DB::select()->where('authorID', '=', $data['userID'])->from('articles')->execute()->as_array(); /* //$data['authorName'] = DB::select('fname', 'lname')->where('authorID', '=', $data['userID'])->from('authors')->execute()->as_array(); //$data['authorName'] = $data['authorName'][0]['fname'] . " " . $data['authorName'][0]['lname']; */ $data['authors'] = DB::select('authors.fname', 'authors.lname', 'authors.userID', 'authors.authorID','simpleauth.company', 'simpleauth.id', 'user_groups.groupName')->from('authors')->join('simpleauth','LEFT')->on('authors.userID', '=', 'simpleauth.id')->join('user_groups', 'LEFT')->on('simpleauth.group', '=', 'user_groups.groupID')->execute()->as_array(); $data['usergroups'] = DB::select('groupName')->from('user_groups')->execute()->as_array(); $userData = DB::select('authors.fname', 'authors.lname', 'authors.userID', 'simpleauth.id', 'simpleauth.group', 'user_groups.groupName', 'user_groups.groupNameArticle', 'images.imagePath')->from('authors')->join('simpleauth')->on('authors.userID', '=', 'simpleauth.id')->join('user_groups', 'LEFT')->on('simpleauth.group', '=', 'user_groups.groupID')->join('images', 'LEFT')->on('authors.userID', '=', 'images.authorID')->where('authors.userID', '=', $data['userID'])->and_where('images.imageType', '=', 1)->execute()->as_array(); $data['userName'] = $userData[0]['fname'] . " " . $userData[0]['lname']; /* $data['userRole'] = DB::select('groupName')->where('groupID', '=', ----simple auth id----)->from('user_groups')->execute()->as_array(); */ if(! Auth::check()) { Response::redirect('../../admin'); } else { if($data['userGroup'] > 2){ Response::redirect('../../admin'); $data['userRoleIsAdmin'] = false; } else { $data['userRoleIsAdmin'] = true; } } $this->template->title = 'Manage Authors'; $this->template->content = View::factory('admin/authors', $data); } public function action_authors_controlpanel() { Response::redirect('../../admin'); } public function action_signup() { if (! Auth::check()) { Response::redirect('../../admin'); } $data = array(); $data['adminUserName'] = "<NAME>"; $data['authorName'] = "<NAME>"; $data['adminRole'] = "Lead Developer"; $data['user'] = Auth::instance()->get_user_array(); $data['userID'] = $data['user']['id'][1]; $data['userGroup'] = $data['user']['usergroup'][0][1]; $data['articles'] = DB::select()->where('authorID', '=', $data['userID'])->from('articles')->execute()->as_array(); $data['authorName'] = DB::select('fname', 'lname')->where('authorID', '=', $data['userID'])->from('authors')->execute()->as_array(); $data['authorName'] = $data['authorName'][0]['fname'] . " " . $data['authorName'][0]['lname']; $data['authors'] = DB::select('authors.fname', 'authors.lname', 'authors.userID', 'simpleauth.company', 'simpleauth.id', 'user_groups.groupName')->from('authors')->join('simpleauth','LEFT')->on('authors.userID', '=', 'simpleauth.id')->join('user_groups', 'LEFT')->on('simpleauth.group', '=', 'user_groups.groupID')->execute()->as_array(); $data['usergroups'] = DB::select('groupName', 'groupNameArticle')->from('user_groups')->execute()->as_array(); $userData = DB::select('authors.fname', 'authors.lname', 'authors.userID', 'simpleauth.id', 'simpleauth.group', 'user_groups.groupName', 'user_groups.groupNameArticle', 'images.imagePath')->from('authors')->join('simpleauth')->on('authors.userID', '=', 'simpleauth.id')->join('user_groups', 'LEFT')->on('simpleauth.group', '=', 'user_groups.groupID')->join('images', 'LEFT')->on('authors.userID', '=', 'images.authorID')->where('authors.userID', '=', $data['userID'])->and_where('images.imageType', '=', 1)->execute()->as_array(); $data['userName'] = $userData[0]['fname'] . " " . $userData[0]['lname']; if (Input::method() == 'POST') { $username = Input::post('uname'); $firstname = Input::post('fname'); $lastname = Input::post('lname'); $password = Input::post('<PASSWORD>'); $group = Input::post('ugroup') + 1;; $email = Input::post('email'); $data['fields'] = array('username' => $username, 'firstname' => $firstname, 'lastname' => $lastname, 'password' => $password, 'email' => $email); $val = Validation::factory('user_signup'); $val->add_field('uname', 'Username', 'required|min_length[3]|max_length[20]|valid_string[alpha, numeric]'); $val->add_field('fname', 'First Name', 'required|min_length[3]|max_length[20]|valid_string[alpha]'); $val->add_field('lname', 'Last Name', 'required|min_length[3]|max_length[20]|valid_string[alpha]'); $val->add_field('pword', 'Password', 'required|min_length[8]|max_length[20]'); $val->add_field('email', 'Email', 'required|valid_email|min_length[3]|max_length[20]'); if ( $val->run() ) { $username = $val->validated('uname'); $firstname = $val->validated('fname'); $lastname = $val->validated('lname'); $password = Auth::instance()->hash_password($val->validated('pword')); $email = $val->validated('email'); try { $createuser = Model_Users::factory(array( 'username' => $username, 'password' => $<PASSWORD>, 'group' => $group, 'email' => $email, )); $createuser->save(); $newuserid = DB::select('username', 'email', 'id')->where('username', '=', $username)->and_where('email', '=', $email)->from('simpleauth')->execute()->as_array(); $createdauthor = Model_Author::factory(array( 'fname' => $firstname, 'lname' => $lastname, 'userID' => $newuserid[0]['id'], )); $createdauthor->save(); foreach($data['usergroups'] as $usergroup){ $usergroupnames[] = $usergroup['groupName']; $usergroupnamearticles[] = $usergroup['groupNameArticle']; } $dbUserGroup = $group - 1; $data['success'] = "You have successfully added " . $firstname . " as " . $usergroupnamearticles[$dbUserGroup] . " " . $usergroupnames[$dbUserGroup]; $createdavatar = Model_Images::factory(array( 'title' => $firstname . " " . $lastname ."'s Avatar", 'alt' => 'Avatar', 'authorID' => $newuserid[0]['id'], 'imageType' => 1, //Default image type id for AuthorPic/Avatar 'imagePath' => 'frontend/avatars/default.jpg', )); $createdavatar->save(); } catch (Exception $e) { $useradderror = 'There was an error. It seems that user "' . $username . '" already exists.'; $data['usererror'] = $useradderror; } } else { /* $notvalidated = "We're sorry, some of the information was not valid."; $data['usererror'] = $notvalidated; */ $val->set_message('required', 'The field ":label" is required.'); $val->set_message('min_length', 'The field ":label" must be at least :param:1 characters.'); $val->set_message('max_length', 'The field ":label" must be not more than :rule characters.'); $val->set_message('valid_email', 'The field ":label" must be a valid email.'); $val->set_message('valid_string', 'The field ":label" must be :param:1 characters only.'); $data['errorsArray'] = $val->errors(); /* $val->errors('uname')->get_message('The field :label must be filled out before auth is attempted.') $val->errors('fname')->get_message('The field :label must be filled out before auth is attempted.') */ ; $this->template->content = View::factory('admin/authors', $data); } } $this->template->title = 'Manage Authors'; $this->template->content = View::factory('admin/authors', $data); } public function action_404() { $messages = array('Aw, crap!', 'Bloody Hell!', 'Uh Oh!', 'Nope, not here.', 'Huh?'); $data['title'] = $messages[array_rand($messages)]; // Set a HTTP 404 output header $this->response->status = 404; $this->response->body = View::factory('welcome/404', $data); } } ?><file_sep><!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-type" content="text/html; charset=utf-8" /> <title>Login | Dashboard Admin</title> <?php echo Asset::css('backend/reset.css'); ?> <?php echo Asset::css('backend/text.css'); ?> <?php echo Asset::css('backend/form.css'); ?> <?php echo Asset::css('backend/buttons.css'); ?> <?php echo Asset::css('backend/login.css'); ?> </head> <body> <?php /* echo $content; */ ?> </body> </html> <!-- Localized --><file_sep><?php // This PHP code developed by <NAME> of Avalux Web Development - AvaluxDev.com class Controller_Common extends Controller_Template { public $template = 'template_frontend'; public function before() { $data['common'] = "This is common."; } public function action_404() { $messages = array('Aw, crap!', 'Bloody Hell!', 'Uh Oh!', 'Nope, not here.', 'Huh?'); $data['title'] = $messages[array_rand($messages)]; // Set a HTTP 404 output header $this->template->title = "404 - Page Not Found"; $this->response->status = 404; $this->template->content = View::factory('site/404', $data); } } ?><file_sep><div id="main"> <div id="admin"> <div class="infobar"> <h3>Thank you for logging in, <?php echo $adminName; ?></h3> <span><?php echo Date::factory()->format("%a, %b %d, %Y"); ?></span> <div id="breadcrumbs"> <a href="/asl1105/jbuff/cms/">homepage</a> &rarr; <a href="/asl1105/jbuff/cms/admin">admin</a> &rarr; <a class="current" href="/asl1105/jbuff/cms/admin/posts">edit</a> </div> </div> <form id="newpost" action="?" method="POST"> <ul> <li> <label for="title">Post Title</label> <input type="text" name="title" id="title" value="This is an Example Title" /> </li> <li> <label for="excerpt">Excerpt</label> <textarea name="excerpt" id="excerpt">This is an example excerpt.</textarea> </li> <li> <label for="postbody">Body</label> <textarea name="postbody" id="postbody">This is an example post body.</textarea> </li> <li> <input type="submit" value="Submit" /> <span><a href="#">or cancel</a></span> </li> </ul> </form> </div><!-- end /#admin --> </div><!-- end /#main --><file_sep><div id="main"> <div id="admin"> <div class="infobar"> <h3>Thank you for logging in, <?php echo $adminName; ?></h3> <span><?php echo Date::factory()->format("%a, %b %d, %Y"); ?></span> <div id="breadcrumbs"> <a href="/asl1105/jbuff/cms/">homepage</a> &rarr; <a class="current" href="/asl1105/jbuff/cms/admin">admin</a> </div> </div> <ul id="options"> <li><a href="admin/new/">Add Article</a></li> <li><a href="admin/posts/">Edit Articles</a></li> <li><a href="#">Upload Photos</a></li> <li><a href="#">Edit Authors</a></li> <li><a href="#">Edit Category</a></li> </ul> </div><!-- end /#admin --> </div><!-- end /#main --><file_sep><?php class Model_Category extends Orm\Model { protected static $_primary_key = array('catID'); } /* End of file article.php */<file_sep><div id="articles"> <div id="titlebar"> <h2><?php if($category) { echo 'Articles from "' . $category[0]['catName'] . '"'; } ?></h2> </div> <?php // This PHP code developed by <NAME> of Avalux Web Development - AvaluxDev.com if($articles){ foreach($articles as $article){ echo '<article class="reg">'; echo '<h2>' . stripslashes($article['articleTitle']) . '</h2>'; echo '<p class="excerpt-small">' . stripslashes($article['articleExcerpt']) . '</p>'; echo '<aside><a class="readmore" href="' .$base_path. 'article/?id=' . $article['articleID'] .'">Read More &raquo;</a></aside>'; echo '</article>'; } if($totalPages > 1){ echo '<div id="titlebar" class="pagination">' . Pagination::prev_link('&laquo; Previous'). '<span class="numlinks">' . Pagination::create_pagenum_links() . '</span>' . Pagination::next_link('Next &raquo;'). '</div>'; } } else { echo " There seems to be no articles in this category."; } // This PHP code developed by <NAME> of Avalux Web Development - AvaluxDev.com ?> </div> <?php echo View::factory('site/sidebar')->render(); ?><file_sep><?php // This PHP code developed by <NAME> of Avalux Web Development - AvaluxDev.com class Controller_Blog extends Controller_Template { public $template = 'template_frontend'; public function action_index() { $data = array(); $categories = Model_Category::find('all'); foreach ($categories as $c) { $cats[] = $c->catName; } $categories = $cats; View::set_global('categories', $categories); $articles = DB::select('*')->from('articles')->execute()->as_array(); $paginationConfig = array( 'pagination_url' => 'http://localhost:8888/asl1105/jbuff/cms', 'total_items' => count($articles), 'per_page' => 4, 'uri_segment' => 1, ); //Pagination::set_config($paginationConfig); NOTE: File bug report for this method. Config::set('pagination', $paginationConfig); $data['articles'] = DB::select('*')->from('articles') ->order_by('startDate', 'desc') ->limit(Pagination::$per_page) ->offset(Pagination::$offset) ->execute() ->as_array(); if($this->param('page') == 0){ $data['pageNum'] = 1; } else { $data['pageNum'] = $this->param('page'); } $data['totalPages'] = Pagination::total_pages(); $this->template->js = "$('#blog_page').addClass('active');"; $this->template->title = 'Full Sail Times Blog - Page ' . $data['pageNum']; $this->template->content = View::factory('site/blog', $data); } public function action_404() { $messages = array('Aw, crap!', 'Bloody Hell!', 'Uh Oh!', 'Nope, not here.', 'Huh?'); $data['title'] = $messages[array_rand($messages)]; // Set a HTTP 404 output header $this->template->title = "404 - Page Not Found"; $this->response->status = 404; $this->template->content = View::factory('site/404', $data); } } ?><file_sep>SimpleCMS ========= A simple CMS for fun. Coded in FuelPHP. Custom code in the public directory and in fuel > app > classes / views. <file_sep><?php namespace Fuel\Migrations; class Create_images { public function up() { \DBUtil::create_table('images', array( 'imageID' => array('constraint' => 11, 'type' => 'int', 'auto_increment' => true), 'title' => array('constraint' => 255, 'type' => 'varchar'), 'alt' => array('constraint' => 255, 'type' => 'varchar'), 'authorID' => array('constraint' => 11, 'type' => 'int'), 'imageType' => array('constraint' => 2, 'type' => 'int'), 'imagePath' => array('constraint' => 255, 'type' => 'varchar'), 'articleID' => array('constraint' => 11, 'type' => 'int'), ), array('imageID')); } public function down() { \DBUtil::drop_table('images'); } }<file_sep><div id="top"> <div class="content_pad"> <ul class="right"> <li><a href="<?php echo $base_path; ?>admin/profile" class="top_icon"><span class="ui-icon ui-icon-person"></span>Logged in as <?php echo $userName; ?></a></li> <li><a rel="facebox" href="#messages" class="new_messages top_alert">1 New Message</a></li> <li><a href="<?php echo $base_path; ?>admin/settings">Settings</a></li> <li><a href="<?php echo $base_path; ?>admin/logout">Logout</a></li> </ul> </div> <!-- .content_pad --> </div> <!-- #top --> <div id="header"> <div class="content_pad"> <h1><a href="<?php echo $base_path; ?>admin">Dashboard Admin</a></h1> <ul id="nav"> <li class="nav_icon"><a href="<?php echo $base_path; ?>admin"><span class="ui-icon ui-icon-home"></span>Home</a></li> <li class="nav_dropdown nav_icon"> <a href="<?php echo $base_path; ?>admin/posts"><span class="ui-icon ui-icon-gripsmall-diagonal-se"></span>Site Content</a> <div class="nav_menu"> <ul> <li><a href="<?php echo $base_path; ?>admin/new">Create a New Post</a></li> <li><a href="<?php echo $base_path; ?>admin/posts">Edit an Existing Post</a></li> <?php if($userRoleIsAdmin) { echo '<li><a href="' . $base_path . 'admin/authors">Create / Edit Authors</a></li>'; } ?> <li><a href="<?php echo $base_path; ?>admin/media">Manage Images</a></li> </ul> </div> </li> <li class="nav_icon"><a href="./configuration"><span class="ui-icon ui-icon-gear"></span>Configuration</a></li> <li class="nav_icon"><a href="./reports"><span class="ui-icon ui-icon-signal"></span>Reports</a></li> <li class="nav_dropdown nav_icon_only"> <a href="javascript:;">&nbsp;</a> <div class="nav_menu"> <ul> <li><a href="<?php echo $base_path; ?>admin/messages">Messages</a></li> <li><a href="<?php echo $base_path; ?>admin/comments">Comments</a></li> <li><a href="<?php echo $base_path; ?>admin/avalux">Contact Avalux</a></li> </ul> </div> <!-- .menu --> </li> </ul> </div> <!-- .content_pad --> </div> <!-- #header --> <div id="masthead"> <div class="content_pad"> <h1>Your Profile</h1> <div id="bread_crumbs"> <a href="<?php echo $base_path; ?>admin">Home</a> / <a href="<?php echo $base_path; ?>admin/profile" class="current_page">Profile</a> </div> <!-- #bread_crumbs --> <div id="search"> <?php echo Form::open(array('action' => $base_path. 'admin/search', 'method' => 'GET')); ?> <?php echo Form::input(array('type' => 'text','value' => 'Search Posts', 'placeholder' => 'Search Posts', 'name' => 'search', 'id' => 'search_input', 'title' => 'Search')); ?> <?php echo Form::submit(array('name' => 'submit', 'class' => 'submit')); ?> <?php echo Form::close(); ?> </div> <!-- #search --> </div> <!-- .content_pad --> </div> <!-- #masthead --> <div id="content" class="xgrid"> <div class="x12"> <h2><?php echo $userName; ?></h2> <div id="profile"> <div id="profileavatar"> <?php echo Asset::img($authorPic, array('height' => '75', 'alt' => 'Avatar', 'class' => 'avatar profile')); ?> <br /><br /><br /><br /> <a class="edit" href="<?php echo $base_path; ?>admin/settings">Edit Profile</a> </div> <div id="profilefields" class="form"> <div class="field"> <label>Bio:</label> <div class="biotxt"><?php echo $authorBio; ?></div> </div> </div> </div> </div> <!-- .x12 --> </div> <!-- #content --> <div id="messages" style="display: none"> <h4 class="deletetitle">This Feature Arriving Soon</h4> <p>Before too long, you will be able to utilize the messaging and notification system.</p> </div> <div id="footer"> <div class="content_pad"> <p>&copy; 2011 Copyright <a href="http://www.avaluxdev.com">Avalux Web Development</a>. Powered by <a href="http://fuelphp.com/">Fuel PHP Framework</a>.</p> </div> <!-- .content_pad --> </div> <!-- #footer --> <file_sep><h2 class="nudgecatname">Overview of all Full Sail Times Categories</h2> <div id="categories"> <?php // This PHP code developed by <NAME> of Avalux Web Development - AvaluxDev.com foreach($categories as $key => $category) { $catKey = $key; echo '<section>'; echo '<h2>' . $category['catName'] . '</h2>'; echo '<ul>'; foreach($articles as $key => $article){ if(isset($articles[($catKey)][$key])){ $articleTitle = $articles[($catKey)][$key]['articleTitle']; $articleID = $articles[($catKey)][$key]['articleID']; echo '<li><a href="' .$base_path. 'article?id=' . $articleID . '">' . html_entity_decode(stripslashes($articleTitle)) . "</a></li>"; } } echo '</ul>'; echo '<a href="' .$base_path. 'category/' . $category['catID'] . '" class="viewcat">View All Articles</a>'; echo '</section>'; } ?> </div><file_sep><div id="top"> <div class="content_pad"> <ul class="right"> <li><a href="<?php echo $base_path; ?>admin/profile" class="top_icon"><span class="ui-icon ui-icon-person"></span>Logged in as <?php echo $userName; ?></a></li> <li><a rel="facebox" href="#messages" class="new_messages top_alert">1 New Message</a></li> <li><a href="<?php echo $base_path; ?>admin/settings">Settings</a></li> <li><a href="<?php echo $base_path; ?>admin/logout">Logout</a></li> </ul> </div> <!-- .content_pad --> </div> <!-- #top --> <div id="header"> <div class="content_pad"> <h1><a href="<?php echo $base_path; ?>admin">Dashboard Admin</a></h1> <ul id="nav"> <li class="nav_icon"><a href="<?php echo $base_path; ?>admin"><span class="ui-icon ui-icon-home"></span>Home</a></li> <li class="nav_current nav_dropdown nav_icon"> <a href="<?php echo $base_path; ?>admin/posts"><span class="ui-icon ui-icon-gripsmall-diagonal-se"></span>Site Content</a> <div class="nav_menu"> <ul> <li><a href="<?php echo $base_path; ?>admin/new">Create a New Post</a></li> <li><a href="<?php echo $base_path; ?>admin/posts">Edit an Existing Post</a></li> <li><a href="<?php echo $base_path; ?>admin/authors">Create / Edit Authors</a></li> <li><a href="<?php echo $base_path; ?>admin/media">Manage Images</a></li> </ul> </div> </li> <li class="nav_icon"><a href="<?php echo $base_path; ?>admin/configuration"><span class="ui-icon ui-icon-gear"></span>Configuration</a></li> <li class="nav_icon"><a href="<?php echo $base_path; ?>admin/reports"><span class="ui-icon ui-icon-signal"></span>Reports</a></li> <li class="nav_dropdown nav_icon_only"> <a href="javascript:;">&nbsp;</a> <div class="nav_menu"> <ul> <li><a href="<?php echo $base_path; ?>admin/messages">Messages</a></li> <li><a href="<?php echo $base_path; ?>admin/comments">Comments</a></li> <li><a href="<?php echo $base_path; ?>admin/avalux">Contact Avalux</a></li> </ul> </div> <!-- .menu --> </li> </ul> </div> <!-- .content_pad --> </div> <!-- #header --> <div id="masthead"> <div class="content_pad"> <h1>Manage Authors</h1> <div id="bread_crumbs"> <a href="<?php echo $base_path; ?>admin">Home</a> / <a href="<?php echo $base_path; ?>admin/authors" class="current_page">Manage Authors</a> </div> <!-- #bread_crumbs --> <div id="search"> <?php echo Form::open(array('action' => $base_path .'admin/search', 'method' => 'GET')); ?> <?php echo Form::input(array('type' => 'text','value' => 'Search Posts', 'placeholder' => 'Search Posts', 'name' => 'search', 'id' => 'search_input', 'title' => 'Search')); ?> <?php echo Form::submit(array('name' => 'submit', 'class' => 'submit')); ?> <?php echo Form::close(); ?> </div> <!-- #search --> </div> <!-- .content_pad --> </div> <!-- #masthead --> <div id="content" class="xgrid"> <div class="x12"> <h2>Create a New Author</h2> <div class="error"><strong> <?php if(isset($errorsArray)){ foreach($errorsArray as $error) { echo $error . "<br />"; } echo "<br />"; } if(isset($usererror)){ echo $usererror . "<br /><br />"; } ?> </strong></div> <div class="success"><strong><?php if(isset($success)) { echo $success . "<br /><br />"; } ?></strong></div> <?php /* echo render('admin/_newauthorform', $fields); */?> <?php if(isset($fields)) { $data['fields'] = $fields; } else { $data['fields'] = array(); } $data['usergroups'] = $usergroups; echo View::factory('admin/_newauthorform', $data)->render(); ?> <h2>Listing of Authors</h2> <table class="data display" id="example"> <thead> <tr> <th>Author Name</th> <th>Author Role</th> <th>Manage Author</th> </tr> </thead> <tbody> <?php foreach($authors as $author): ?> <tr class="odd gradeX"> <td><?php echo $author['fname']; ?> <?php echo $author['lname'] ?></td> <td><?php echo $author['groupName'] . " - " . $author['company']; ?></td> <td> <a rel="facebox" href="#edit_user"><button class="btn btn-grey">Edit</button></a> <a rel="facebox" id="<?php echo $userID; ?>" href="#delete_user"><button class="btn btn-red">Delete</button></a> </td> </tr> <?php endforeach; ?> </tbody> </table> <div id="edit_user" style="display: none"> <h4>Edit User <?php echo $author['fname']; ?> <?php echo $author['lname'] ?></h4> <form action="#" method="post" class="label-inline uniform"> <div class="field"> <label for="fname">First Name</label> <input id="fname" name="fname" size="50" type="text" class="xlarge" /> </div> <div class="field"> <label for="lname">Last Name</label> <input id="lname" name="lname" size="50" type="text" class="xlarge" /> </div> <div class="field"> <label for="type">Author Role</label> <select id="type" class="medium"> <optgroup label="Please Pick a Role"> <option>Developer</option> <option selected="selected">Author</option> <option>Editor</option> </optgroup> </select> </div> <div class="field buttonrow" style="margin-top: 20px;"> <button class="btn btn-small">Save Changes</button> </div> </form> </div> <div id="delete_user" style="display: none"> <h4>Delete User This User?</h4> <?php echo Form::open(); ?> <div class="artid"></div> <?php echo Form::submit(array('class' => 'btn btn-small btn-red', 'value' => 'Delete Post')); ?> <?php echo Form::close(); ?> </div> </div> <!-- .x12 --> </div> <!-- #content --> <div id="messages" style="display: none"> <h4 class="deletetitle">This Feature Arriving Soon</h4> <p>Before too long, you will be able to utilize the messaging and notification system.</p> </div> <div id="footer"> <div class="content_pad"> <p>&copy; 2011 Copyright <a href="http://www.avaluxdev.com">Avalux Web Development</a>. Powered by <a href="http://fuelphp.com/">Fuel PHP Framework</a>.</p> </div> <!-- .content_pad --> </div> <!-- #footer --> <file_sep><?php // This PHP code developed by <NAME> of Avalux Web Development - AvaluxDev.com class Controller_admin_dbtest extends Controller_Template { public $template = 'template_backend'; public function action_index() { $data = array(); $data['articles'] = Model_Article::find('all'); $this->template->content = View::factory('articles/view', $data); } public function action_view($id = null) { $data['articles'] = Model_Article::find($id); $this->template->title = "Monkey"; $this->template->content = View::factory('articles/view', $data); } public function action_404() { $messages = array('Aw, crap!', 'Bloody Hell!', 'Uh Oh!', 'Nope, not here.', 'Huh?'); $data['title'] = $messages[array_rand($messages)]; // Set a HTTP 404 output header $this->response->status = 404; $this->response->body = View::factory('welcome/404', $data); } } ?><file_sep><?php namespace Fuel\Migrations; class Create_authors { public function up() { \DBUtil::create_table('authors', array( 'authorID' => array('constraint' => 11, 'type' => 'int', 'auto_increment' => true), 'fname' => array('constraint' => 25, 'type' => 'varchar'), 'lname' => array('constraint' => 40, 'type' => 'varchar'), 'bio' => array('constraint' => 1000, 'type' => 'varchar'), 'authorPhone' => array('constraint' => 20, 'type' => 'varchar'), 'bioImageID' => array('constraint' => 11, 'type' => 'int'), 'userID' => array('constraint' => 11, 'type' => 'int'), ), array('authorID')); } public function down() { \DBUtil::drop_table('authors'); } }<file_sep><?php // This PHP code developed by <NAME> of Avalux Web Development - AvaluxDev.com class Controller_Admin extends Controller_Template { public function action_index() { $data = array(); $data['adminName'] = '<NAME>'; $this->template->title = 'Example Page'; $this->template->content = View::factory('admin/index', $data); } } ?><file_sep><!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title><?php echo $title; ?></title> <?php echo Asset::css('frontend/newstyle.css'); ?> </head> <body> <div id="container"> <header> <a href="<?php echo $base_path; ?>"><h1 class="logo">Full Sail Times <span>Curated by WDDBS Students</span></h1></a> <nav> <a id="home_page" href="<?php echo $base_path; ?>">Home</a> <a id="blog_page" href="<?php echo $base_path; ?>blog">Blog</a> <a id="categories_page" href="<?php echo $base_path; ?>categories/">Categories</a> <a id="contact_page" href="<?php echo $base_path; ?>contact/">Contact</a> </nav> </header> <div id="main" style="position:relative; overflow: auto;"> <?php echo $content; ?> </div> <!-- end main --> <footer> Copyright &copy; 2011 Avalux Web Development. All rights reserved. </footer> </div><!-- end container --> <?php echo Asset::js('frontend/jquery.js'); ?> <?php echo Asset::js('frontend/cufon.js'); ?> <?php echo Asset::js('frontend/font.js'); ?> <script type="text/javascript"> jQuery(document).ready(function() { Cufon.replace('h1, h2, h3'); }); </script> <script type="text/javascript"> Cufon.now(); <?php if(isset($js)){ echo html_entity_decode($js); } ?> </script> </body> </html><file_sep><?php defined('COREPATH') or exit('No direct script access allowed'); ?> Error - 2011-05-22 05:08:49 --> 8 - Undefined index: errors in /Applications/MAMP/htdocs/asl1105/jbuff/cms/fuel/app/classes/controller/admin.php on line 62 <file_sep><!-- <span style="color: #fff;"><?php print_r(Auth::instance()); ?></span> --> <div id="login"> <h1>Dashboard</h1> <div id="login_panel"> <?php echo Form::open(array('action' => $base_path .'admin', 'enctype' => 'multipart/form-data')); ?> <div class="login_fields"> <div class="field"> <span class="error"><?php if(isset($error)){ echo $error; } ?></span> <label for="username">Username</label> <?php echo Form::input(array('name' => 'username', 'id' => 'username')); ?> </div> <div class="field"> <label for="password">Password <small><a href="<?php echo $base_path; ?>admin/recoverpassword">Forgot Password?</a></small></label> <?php echo Form::input(array('name' => 'password', 'id' => 'password', 'type' => 'password')); ?> </div> </div> <div class="login_actions"> <button type="submit" class="btn btn-orange" tabindex="3">Login</button> <span class="error"> <?php if(isset($errors)) { echo $errors; }; ?> </span> </div> <?php echo Form::close(); ?> <file_sep><!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title><?php echo $title; ?> - ASL Content Management System</title> <?php echo Asset::css('style.css'); ?> <?php echo Asset::css('admin.css'); ?> </head> <body> <div id="container"> <div id="header"> <a id="logo" href="/asl1105/jbuff/cms/">ASL Content Management System</a> <div id="signin"> <form action="?" method="POST"> <input type="text" id="username" value="username" /> <input type="<PASSWORD>" id="password" value="<PASSWORD>" /> <input type="submit" id="submitbtn" value="" /> </form> </div> </div> <div id="main"> <?php echo $content; ?> </div> </div><!-- end container --> <div id="footer"> Copyright &copy; 2011 Avalux Web Development. All rights reserved. </div> </body> </html><file_sep><?php // This PHP code developed by <NAME> of Avalux Web Development - AvaluxDev.com class Controller_Admin_Media extends Controller_Template { public $template = 'template_backend'; public function action_index() { $data = array(); /* this is how to delete a file; but remember, it must also be removed from the database. \Fuel::add_path('/Applications/MAMP/htdocs/asl1105/jbuff/cms/public/assets/img/frontend/'); $path = \Fuel::find_file('content', 'Screen shot 2011-05-09 at 2.50.50 AM_1', '.png'); \File::delete($path); */ $data['user'] = Auth::instance()->get_user_array(); $data['userGroup'] = $data['user']['usergroup'][0][1]; $data['userID'] = $data['user']['id'][1]; $userData = DB::select('authors.fname', 'authors.lname', 'authors.userID', 'authors.authorID', 'simpleauth.id', 'simpleauth.group', 'user_groups.groupName', 'user_groups.groupNameArticle', 'images.imagePath')->from('authors')->join('simpleauth')->on('authors.userID', '=', 'simpleauth.id')->join('user_groups', 'LEFT')->on('simpleauth.group', '=', 'user_groups.groupID')->join('images', 'LEFT')->on('authors.userID', '=', 'images.authorID')->where('authors.userID', '=', $data['userID'])->and_where('images.imageType', '=', 1)->execute()->as_array(); $data['userName'] = $userData[0]['fname'] . " " . $userData[0]['lname']; //Authentication check if(! Auth::check()) { Response::redirect('../../admin'); } else { if($data['userGroup'] > 2){ $data['userRoleIsAdmin'] = false; } else { $data['userRoleIsAdmin'] = true; } } $authorID = $userData[0]['authorID']; $articleImages = DB::select('*')->from('images')->where('imageType', '=', 2)->and_where('authorID', '=', $authorID)->execute()->as_array(); if (Input::method() == 'POST') { if ( Upload::is_valid() ){ Upload::save(); foreach( Upload::get_files() as $file ) { $uploadedFile = "frontend/content/" . $file['saved_as']; } } $val = Validation::factory('upload_image'); $val->add_field('imgtitle', 'Image Title', 'required|min_length[2]|max_length[25]'); $val->add_field('imgalt', 'Image Alt Tag', 'required|min_length[2]|max_length[25]'); if ($val->run()) { try { $uploadedImage = Model_Images::factory(array( 'title' => $val->validated('imgtitle'), 'alt' => $val->validated('imgalt'), 'authorID' => $authorID, 'imageType' => 2, 'imagePath' => $uploadedFile, )); $uploadedImage->save(); $data['success'] = "Images added successfully."; } catch(Exception $e){ //throw image upload error $data['error'] = "There was an error."; } } else { $data['error'] = $val->errors(); } } $paginationConfig = array( 'pagination_url' => 'admin/media', 'total_items' => count($articleImages), 'per_page' => 6, 'uri_segment' => 3, ); //Pagination::set_config($paginationConfig); NOTE: File bug report for this method. Config::set('pagination', $paginationConfig); $data['article_images'] = DB::select('*')->from('images')->where('imageType', '=', 2)->and_where('authorID', '=', $authorID) ->limit(Pagination::$per_page) ->offset(Pagination::$offset) ->execute() ->as_array(); if($this->param('pagenumber') == 0){ $data['pageNum'] = 1; } else { $data['pageNum'] = $this->param('pagenumber'); } $data['totalPages'] = Pagination::total_pages(); $this->template->galleryJS = ""; $this->template->title = 'Media Manager'; $this->template->content = View::factory('admin/media', $data); } public function action_404() { $messages = array('Aw, crap!', 'Bloody Hell!', 'Uh Oh!', 'Nope, not here.', 'Huh?'); $data['title'] = $messages[array_rand($messages)]; // Set a HTTP 404 output header $this->response->status = 404; $this->response->body = View::factory('welcome/404', $data); } } ?><file_sep><div id="top"> <div class="content_pad"> <ul class="right"> <li><a href="<?php echo $base_path; ?>admin/profile" class="top_icon"><span class="ui-icon ui-icon-person"></span>Logged in as <?php echo $userName; ?></a></li> <li><a rel="facebox" href="#messages" class="new_messages top_alert">1 New Message</a></li> <li><a href="<?php echo $base_path; ?>admin/settings">Settings</a></li> <li><a href="<?php echo $base_path; ?>admin/logout">Logout</a></li> </ul> </div> <!-- .content_pad --> </div> <!-- #top --> <div id="header"> <div class="content_pad"> <h1><a href="<?php echo $base_path; ?>admin">Dashboard Admin</a></h1> <ul id="nav"> <li class="nav_icon"><a href="<?php echo $base_path; ?>admin"><span class="ui-icon ui-icon-home"></span>Home</a></li> <li class="nav_dropdown nav_icon"> <a href="<?php echo $base_path; ?>admin/posts"><span class="ui-icon ui-icon-gripsmall-diagonal-se"></span>Site Content</a> <div class="nav_menu"> <ul> <li><a href="<?php echo $base_path; ?>admin/new">Create a New Post</a></li> <li><a href="<?php echo $base_path; ?>admin/posts">Edit an Existing Post</a></li> <?php if($userRoleIsAdmin) { echo '<li><a href="' . $base_path . 'admin/authors">Create / Edit Authors</a></li>'; } ?> <li><a href="<?php echo $base_path; ?>admin/media">Manage Images</a></li> </ul> </div> </li> <li class="nav_icon"><a href="<?php echo $base_path; ?>admin/configuration"><span class="ui-icon ui-icon-gear"></span>Configuration</a></li> <li class="nav_icon nav_current"><a href="./reports"><span class="ui-icon ui-icon-signal"></span>Reports</a></li> <li class="nav_dropdown nav_icon_only"> <a href="javascript:;">&nbsp;</a> <div class="nav_menu"> <ul> <li><a href="<?php echo $base_path; ?>admin/messages">Messages</a></li> <li><a href="<?php echo $base_path; ?>admin/comments">Comments</a></li> <li><a href="<?php echo $base_path; ?>admin/avalux">Contact Avalux</a></li> </ul> </div> <!-- .menu --> </li> </ul> </div> <!-- .content_pad --> </div> <!-- #header --> <div id="masthead"> <div class="content_pad"> <h1>Site Configuration</h1> <div id="bread_crumbs"> <a href="<?php echo $base_path; ?>admin">Home</a> / <a href="<?php echo $base_path; ?>admin/configuration" class="current_page">Site Configuration</a> </div> <!-- #bread_crumbs --> <div id="search"> <?php echo Form::open(array('action' => $base_path. 'admin/search', 'method' => 'GET')); ?> <?php echo Form::input(array('type' => 'text','value' => 'Search Posts', 'placeholder' => 'Search Posts', 'name' => 'search', 'id' => 'search_input', 'title' => 'Search')); ?> <?php echo Form::submit(array('name' => 'submit', 'class' => 'submit')); ?> <?php echo Form::close(); ?> </div> <!-- #search --> </div> <!-- .content_pad --> </div> <!-- #masthead --> <div id="content" class="xgrid"> <div class="x12"> <h2>This Feature Coming Soon</h2> <p>As of right now, we are hard at work developing this feature. Soon, you will be able to view performance reports and analytics right from your admin panel. You will be able to edit frontend details, such as the website's title, widgets, and featured post(s). We'll keep you notified of any new details via the messaging system. </p> </div> <!-- .x12 --> </div> <!-- #content --> <div id="messages" style="display: none"> <h4 class="deletetitle">This Feature Arriving Soon</h4> <p>Before too long, you will be able to utilize the messaging and notification system.</p> </div> <div id="footer"> <div class="content_pad"> <p>&copy; 2011 Copyright <a href="http://www.avaluxdev.com">Avalux Web Development</a>. Powered by <a href="http://fuelphp.com/">Fuel PHP Framework</a>.</p> </div> <!-- .content_pad --> </div> <!-- #footer --> <file_sep><?php echo Form::open(array('class' => 'form label-inline uniform', 'enctype' => 'multipart/form-data')); ?> <div class="field"> <label for="ptitle">Post Title</label> <?php echo Form::input(array('name' => 'ptitle', 'id' => 'ptitle', 'class' => 'full'), Input::post('ptitle', isset($article) ? $article->articleTitle : '')); ?> </div> <div class="field"> <label for="pexcerpt">Post Excerpt</label> <?php echo Form::textarea(array('name' => 'pexcerpt', 'id' => 'pexcerpt', 'rows' => 3, 'class' => 'full'), Input::post('pexcerpt', isset($article) ? $article->articleExcerpt : '')); ?> <p class="field_help" id="charlimitinfo">You have 350 characters left.</p> </div> <div class="field"> <label for="pbody">Post Body</label> <?php echo Form::textarea(array('name' => 'pbody', 'id' => 'pbody', 'rows' => 10, 'class' => 'full'), Input::post('pbody', isset($article) ? $article->articleBody : '')); ?> </div> <div class="field clearfix"> <label for="pimage">Post Image</label> <?php echo Form::input(array('type' => 'file', 'name' => 'pimage', 'id' => 'pimage'), Input::post('pimage', isset($article) ? $article->articleImage : '')); ?> <p class="field_help nudge_down"> &nbsp; &nbsp; or <a href="javascript:;">select a file</a> from your library.</p> </div> <div class="field"> <label for="pcat">Post Category </label> <?php echo Form::select('pcat', array('name' => 'test', 'id' => 'type', 'class' => 'medium'), array( 'gen' => 'General News', 'op' => 'Opportunities' )); ?> </div> <div class="buttonrow"> <?php echo Form::submit(array('class' => 'btn', 'value' => 'Submit Post')); ?> </div> <?php echo Form::close(); ?><file_sep><?php // This PHP code developed by <NAME> of Avalux Web Development - AvaluxDev.com class Controller_Author extends Controller_Template { public $template = 'template_frontend'; public function action_index() { $data = array(); $authors = DB::select('*')->from('authors')->execute()->as_array(); View::set_global('authors', $authors); $authorData = DB::select('*')->from('authors')->where('authorID', '=', Input::get('id'))->execute()->as_array(); $data['authorName'] = $authorData[0]['fname'] . " " . $authorData[0]['lname']; View::set_global('authorName', $data['authorName']); $data['bio'] = $authorData[0]['bio']; $userid = $authorData[0]['userID']; $authorImg = DB::select('imagePath', 'imageID')->from('images')->where('authorID', '=', $userid)->and_where('imageType', '=', 1)->order_by('imageID', 'desc')->execute()->as_array(); if($authorImg != null) { $authorImg = $authorImg[0]['imagePath']; View::set_global('authorImage', $authorImg); } $authorID = Input::get('id'); $this->template->js = '$("#' .$authorID. '").css("color", "#fff");'; $this->template->title = 'Full Sail Times'; $this->template->content = View::factory('site/author', $data); } public function action_404() { $messages = array('Aw, crap!', 'Bloody Hell!', 'Uh Oh!', 'Nope, not here.', 'Huh?'); $data['title'] = $messages[array_rand($messages)]; // Set a HTTP 404 output header $this->template->title = "404 - Page Not Found"; $this->response->status = 404; $this->template->content = View::factory('site/404', $data); } } ?><file_sep><div id="main"> <div id="admin"> <div class="infobar"> <h3>Thank you for logging in, <?php echo $adminName; ?></h3> <span><?php echo Date::factory()->format("%a, %b %d, %Y"); ?></span> <div id="breadcrumbs"> <a href="/asl1105/jbuff/cms/">homepage</a> &rarr; <a href="/asl1105/jbuff/cms/admin">admin</a> &rarr; <a class="current" href="/asl1105/jbuff/cms/admin/posts">posts</a> </div> </div> <div id="postlist"> <h2>List of Your Articles</h2> <span class="pagedesc">Edit or delete posts</span> <ol> <li> <span class="posttitle">This is an Example Title</span> <a class="btn delete" href="#">Delete</a> <a class="btn edit" href="../edit/">Edit</a> </li> <li> <span class="posttitle">This is an Example Title of an Article</span> <a class="btn delete" href="#">Delete</a> <a class="btn edit" href="../edit/">Edit</a> </li> <li> <span class="posttitle">This is an Example Title about Bees that is really, really, really, really, really, really, really, really, really, really, and cut off...</span> <a class="btn delete" href="#">Delete</a> <a class="btn edit" href="../edit/">Edit</a> </li> <li> <span class="posttitle">This is an Example Title</span> <a class="btn delete" href="#">Delete</a> <a class="btn edit" href="../edit/">Edit</a> </li> <li> <span class="posttitle">This is an Example Title of an Article</span> <a class="btn delete" href="#">Delete</a> <a class="btn edit" href="../edit/">Edit</a> </li> <li> <span class="posttitle">This is an Example Title about Bees that is really, really, really, really, really, really, really, really, really, really, and cut off...</span> <a class="btn delete" href="#">Delete</a> <a class="btn edit" href="../edit/">Edit</a> </li> <li> <span class="posttitle">This is an Example Title</span> <a class="btn delete" href="#">Delete</a> <a class="btn edit" href="../edit/">Edit</a> </li> <li> <span class="posttitle">This is an Example Title of an Article</span> <a class="btn delete" href="#">Delete</a> <a class="btn edit" href="../edit/">Edit</a> </li> <li> <span class="posttitle">This is an Example Title about Bees that is really, really, really, really, really, really, really, really, really, really, and cut off...</span> <a class="btn delete" href="#">Delete</a> <a class="btn edit" href="../edit/">Edit</a> </li> </ol> </div> </div><!-- end /#admin --> </div><!-- end /#main --><file_sep><?php // This PHP code developed by <NAME> of Avalux Web Development - AvaluxDev.com class Controller_Admin_Settings extends Controller_Template { public $template = 'template_backend'; public function action_index() { $data = array(); $data['user'] = Auth::instance()->get_user_array(); $data['userID'] = $data['user']['id'][1]; $data['userGroup'] = $data['user']['usergroup'][0][1]; $userData = DB::select('authors.fname', 'authors.lname', 'authors.userID', 'authors.bio', 'authors.authorPhone', 'authors.authorID', 'simpleauth.id', 'simpleauth.group', 'user_groups.groupName', 'user_groups.groupNameArticle', 'images.imagePath', 'images.imageType', 'images.imageID', 'simpleauth.password')->from('authors')->join('simpleauth')->on('authors.userID', '=', 'simpleauth.id')->join('user_groups', 'LEFT')->on('simpleauth.group', '=', 'user_groups.groupID')->join('images', 'LEFT')->on('authors.userID', '=', 'images.authorID')->where('authors.userID', '=', $data['userID'])->and_where('images.imageType', '=', 1)->order_by('images.imageID', 'desc')->execute()->as_array(); $data['userName'] = $userData[0]['fname'] . " " . $userData[0]['lname']; $data['userRole'] = $userData[0]['groupNameArticle'] . " " .$userData[0]['groupName']; $data['authorPic'] = $userData[0]['imagePath']; //for form editing profile fields $data['firstName'] = $userData[0]['fname']; $data['lastName'] = $userData[0]['lname']; $data['bio'] = $userData[0]['bio']; $data['temp'] = $userData; $fullPhone = $userData[0]['authorPhone']; $phoneChunks = explode("-", $fullPhone); if(count($phoneChunks) == 3) { $data['phone1'] = $phoneChunks[0]; $data['phone2'] = $phoneChunks[1]; $data['phone3'] = $phoneChunks[2]; } else { $data['phone1'] = null; $data['phone2'] = null; $data['phone3'] = null; } //Authentication check if(! Auth::check()) { Response::redirect('../../admin'); } else { if($data['userGroup'] > 2){ $data['userRoleIsAdmin'] = false; } else { $data['userRoleIsAdmin'] = true; } } $authorID = $userData[0]['authorID']; if (Input::method() == 'POST') { switch(Input::post('formname')) { case 'password' : $originalPassword = Input::post('<PASSWORD>'); $newPassword1 = Input::post('<PASSWORD>'); $newPassword2 = Input::post('<PASSWORD>'); $val = Validation::factory('user_password_change'); $val->add_field('opword', 'Original Password', 'required|min_length[8]|max_length[20]'); $val->add_field('npword1', 'New Password', 'required|min_length[8]|max_length[20]'); $val->add_field('npword2', 'Confirm Password', 'required|min_length[8]|max_length[20]|match_field[npword1]'); if ( $val->run() ) { $newpass = $val->validated('np<PASSWORD>2'); if ( Auth::instance()->hash_password($originalPassword) == $userData[0]['password']){ Auth::instance()->change_password($originalPassword, $newpass, $data['user']['screen_name']); $data['successpassword'] = "Your password was changed. Great success!"; } } else { $val->set_message('match_field', 'Your new passwords do not match. Please try again.'); $data['errorsArrayPassword'] = $val->errors(); } break; case 'profile' : if(Upload::is_valid()){ $avatarPath = DOCROOT. 'assets/img/frontend/avatars'; Upload::process(array( 'path' => $avatarPath, 'normalize' => true, 'change_case' => 'lower' )); Upload::save(); foreach( Upload::get_files() as $file ) { $uploadedFile = "frontend/avatars/" . $file['saved_as']; } } else { /* $data['errorsArrayProfile'] = "This file could not be uploaded"; */ $uploadedFile = null; } $firstName = Input::post('fname'); $lastName = Input::post('lname'); $phoneNumber = Input::post('phone') . "-" . Input::post('phone2') . "-" . Input::post('phone3'); $bio = Input::post('bio'); $avatar = Input::post('avatar'); $val = Validation::factory('user_info_change'); $val->add_field('fname', 'First Name', 'required|min_length[2]|max_length[25]|valid_string[alpha]'); $val->add_field('lname', 'Last Name', 'required|min_length[2]|max_length[25]|valid_string[alpha]'); $val->add_field('bio', 'Biography', 'max_length[1000]'); $val->add_field('phone', 'Area Code', 'exact_length[3]'); $val->add_field('phone2', 'Phone Number', 'exact_length[3]'); $val->add_field('phone3', 'Phone Number', 'exact_length[4]'); if ( $val->run() ) { try { $updateAuthor = Model_Author::find($authorID); $updateAuthor->fname = $val->validated('fname'); $updateAuthor->lname = $val->validated('lname'); $updateAuthor->bio = $val->validated('bio'); $updateAuthor->authorPhone = $val->validated('phone') . "-" . $val->validated('phone2') . "-" . $val->validated('phone3'); $updateAuthor->save(); //I NEED TO INCLUDE THE FUNCTIONS TO UPDATE THE IMAGE TABLE IF A NEW IMAGE WAS SUCCESSFULLY UPLOADED. $data['firstName'] = $val->validated('fname'); $data['lastName'] = $val->validated('lname'); $data['bio'] = $val->validated('bio'); $fullPhone = $val->validated('phone') . "-" . $val->validated('phone2') . "-" . $val->validated('phone3'); $phoneChunks = explode("-", $fullPhone); $data['phone1'] = $phoneChunks[0]; $data['phone2'] = $phoneChunks[1]; $data['phone3'] = $phoneChunks[2]; // I need to update the avatar here if($uploadedFile != null){ $uploadedImage = Model_Images::factory(array( 'title' => $data['firstName'] ."'s Avatar", 'alt' => "Avatar", 'authorID' => $data['userID'], 'imageType' => 1, 'imagePath' => $uploadedFile, )); $uploadedImage->save(); } } catch(Exception $e) { //I need to throw an error here that will inform the user that their data cannot be updated. } } else { $data['errorsArrayProfile'] = $val->errors(); } $this->template->js = " $('#profileform').trigger('click', function(){ $.scrollTo('#profileform'); }); "; $data['profilesuccess'] = "You have successfully updated your profile."; break; } } /* $data['oldpwd'] = $originalPassword; */ $this->template->title = 'Your Settings'; $this->template->content = View::factory('admin/settings', $data); } public function action_404() { $messages = array('Aw, crap!', '<NAME>!', 'Uh Oh!', 'Nope, not here.', 'Huh?'); $data['title'] = $messages[array_rand($messages)]; // Set a HTTP 404 output header $this->response->status = 404; $this->response->body = View::factory('welcome/404', $data); } } ?><file_sep><?php // This PHP code developed by <NAME> of Avalux Web Development - AvaluxDev.com class Controller_Contact extends Controller_Template { public $template = 'template_frontend'; public function action_index() { $data = array(); $categories = Model_Category::find('all'); foreach ($categories as $c) { $cats[] = $c->catName; } $categories = $cats; View::set_global('categories', $categories); $this->template->js = "$('#contact_page').addClass('active');"; $this->template->title = 'Full Sail Times'; $this->template->content = View::factory('site/contact', $data); } public function action_404() { $messages = array('Aw, crap!', 'Bloody Hell!', 'Uh Oh!', 'Nope, not here.', 'Huh?'); $data['title'] = $messages[array_rand($messages)]; // Set a HTTP 404 output header $this->template->title = "404 - Page Not Found"; $this->response->status = 404; $this->template->content = View::factory('site/404', $data); } } ?><file_sep><?php echo View::factory('site/articlesidebar')->render(); ?> <article class="post"> <?php // This PHP code developed by <NAME> of Avalux Web Development - AvaluxDev.com echo '<h2 class="articletitle"><a href="'.$base_path . 'article/?id=' . $article[0]['articleID'] .'">' . html_entity_decode(stripslashes($article[0]['articleTitle'])) . '</a></h2>'; echo '<p class="excerpt" style="font-style: italic;">' . stripslashes($article[0]['articleExcerpt']) . '</p>'; if(isset($postImage)){ echo Asset::img($postImage, array('class' => 'postImg')); } echo '<p class="text">' . html_entity_decode(stripslashes(nl2br($article[0]['articleBody']))) . '</p>'; echo '<div style="clear:both;"></div>'; echo '<aside class="meta"> Posted in <a href=" ' .$base_path. 'category/'. $postCategory['catID'] . '">' . $postCategory['catName'] . '</a> &nbsp;&nbsp;|&nbsp;&nbsp; Written by <a href="' .$base_path. 'author/?id=' .$authorID. '">' .$authorName. '</a> &nbsp;&nbsp;|&nbsp;&nbsp; Published on ' . date("F j, Y", strtotime($article[0]['startDate'])) . ' </aside>'; ?> </article><file_sep><?php // This PHP code developed by <NAME> of Avalux Web Development - AvaluxDev.com class View_Admin_New extends ViewModel { public function view() { $this->title = 'Testing this ViewModel thing'; $this->articles = Model_Category::find('all'); } } ?><file_sep><div id="articles"> <div id="titlebar"><h2>Welcome to the Blog - Page <?php echo $pageNum; ?></h2></div> <?php // This PHP code developed by <NAME> of Avalux Web Development - AvaluxDev.com foreach($articles as $article){ echo '<article class="reg">'; echo stripslashes('<h2>' . $article['articleTitle'] . '</h2>'); echo stripslashes('<p class="excerpt-small">' . $article['articleExcerpt'] . '</p>'); echo '<aside><a class="readmore" href="./article/?id=' . $article['articleID'] .'">Read More &raquo;</a></aside>'; echo '</article>'; } echo '<div id="titlebar" class="pagination">' . Pagination::prev_link('&laquo; Previous'). '<span class="numlinks">' . Pagination::create_pagenum_links() . '</span>' . Pagination::next_link('Next &raquo;'). '</div>'; ?> </div> <!-- end #articles --> <?php echo View::factory('site/sidebar')->render(); ?> <file_sep><?php // This PHP code developed by <NAME> of Avalux Web Development - AvaluxDev.com class Controller_Categories extends Controller_Template { public $template = 'template_frontend'; public function action_index() { $data = array(); $data['categories'] = DB::select('*')->from('categories')->execute()->as_array(); foreach($data['categories'] as $key => $category) { $data['articles'][] = DB::select('articleTitle', 'articleID')->from('articles')->where('articleCat', '=', ($key +1))->limit(5)->execute()->as_array(); } $this->template->js = "$('#categories_page').addClass('active');"; $this->template->title = 'Full Sail Times'; $this->template->content = View::factory('site/categories', $data); } private function truncateTextbyWords($phrase, $max_words) { $phrase_array = explode(' ',$phrase); if(count($phrase_array) > $max_words && $max_words > 0) $phrase = implode(' ',array_slice($phrase_array, 0, $max_words)).'...'; return $phrase; } public function action_404() { $messages = array('Aw, crap!', 'Bloody Hell!', 'Uh Oh!', 'Nope, not here.', 'Huh?'); $data['title'] = $messages[array_rand($messages)]; // Set a HTTP 404 output header $this->response->status = 404; $this->template->content = View::factory('site/404', $data); } } ?><file_sep><?php // This PHP code developed by <NAME> of Avalux Web Development - AvaluxDev.com class Controller_Admin_ControlPanel extends Controller_Template { public $template = 'template_backend'; public function action_index() { $data = array(); $data['adminUserName'] = "Jeremy Buff"; $data['categories'] = Model_Category::find('all'); $data['user'] = Auth::instance()->get_user_array(); $data['userID'] = $data['user']['id'][1]; $data['userGroup'] = $data['user']['usergroup'][0][1]; // $data['authorName'] = DB::select('fname', 'lname')->where('authorID', '=', $data['userID'])->from('authors')->execute()->as_array(); // $data['authorName'] = $data['authorName'][0]['fname'] . " " . $data['authorName'][0]['lname']; $userData = DB::select('authors.fname', 'authors.lname', 'authors.userID', 'simpleauth.id', 'simpleauth.group', 'user_groups.groupName', 'user_groups.groupNameArticle', 'images.imagePath', 'images.imageID')->from('authors')->join('simpleauth')->on('authors.userID', '=', 'simpleauth.id')->join('user_groups', 'LEFT')->on('simpleauth.group', '=', 'user_groups.groupID')->join('images', 'LEFT')->on('authors.userID', '=', 'images.authorID')->where('authors.userID', '=', $data['userID'])->and_where('images.imageType', '=', 1)->order_by('images.imageID', 'desc')->execute()->as_array(); $data['userName'] = $userData[0]['fname'] . " " . $userData[0]['lname']; $data['userRole'] = $userData[0]['groupNameArticle'] . " " .$userData[0]['groupName']; $data['authorPic'] = $userData[0]['imagePath']; if($data['authorPic'] == null) { $data['authorPic'] = "frontend/avatars/default.jpg"; } //Authentication check if(! Auth::check()) { Response::redirect('../../admin'); } else { if($data['userGroup'] > 2){ $data['userRoleIsAdmin'] = false; } else { $data['userRoleIsAdmin'] = true; } } //Preping the variable $cats to display the category name instead of the cateogry id. foreach ($data['categories'] as $c) { $cats[] = $c->catName; } $data['cats'] = $cats; // Converting the result of the select field to a value that the database will accept since database IDs are not base index zero. $cat = Input::post('cparent'); $newcat = $cat; // Checking to see if the first option, "None", is selected. If so, then null is passed into the database; a.k.a. new category doesn't have a parent. if($cat == 0){ $newcat = null; } if (Input::method() == 'POST') { $category = Model_Category::factory(array( 'catName' => Input::post('cname'), 'catParent' => $newcat, )); $category->save(); } $this->template->title = 'Control Panel'; $this->template->content = View::factory('admin/index', $data); } public function action_404() { $messages = array('Aw, crap!', 'Bloody Hell!', 'Uh Oh!', 'Nope, not here.', 'Huh?'); $data['title'] = $messages[array_rand($messages)]; // Set a HTTP 404 output header $this->response->status = 404; $this->response->body = View::factory('welcome/404', $data); } } ?><file_sep><?php // This PHP code developed by <NAME> of Avalux Web Development - AvaluxDev.com class Controller_Article extends Controller_Template { public $template = 'template_frontend'; public function action_index() { $categories = Model_Category::find('all'); foreach ($categories as $c) { $cats[] = $c->catName; } $categories = $cats; View::set_global('categories', $categories); $data = array(); $data['article'] = DB::select('*')->from('articles')->where('articleID', '=', Input::get('id'))->execute()->as_array(); $authorData = DB::select('*')->from('authors')->where('authorID', '=', $data['article'][0]['authorID'])->execute()->as_array(); $author = $authorData[0]['fname'] . " " . $authorData[0]['lname']; $authorID = $authorData[0]['authorID']; $bio = $authorData[0]['bio']; $articleID = $data['article'][0]['articleID']; View::set_global('authorName', $author); View::set_global('authorID', $authorID); View::set_global('bio', $this->truncateTextbyWords($bio, 35)); $postImageArray = DB::select('imagePath')->from('images')->where('articleID', '=', $articleID)->order_by('imageID', 'desc')->limit(1)->order_by('imagePath', 'desc')->execute()->as_array(); $data['imgs'] = $postImageArray; if($postImageArray){ $data['postImage'] = $postImageArray[0]['imagePath']; } else { $data['postImage'] = null; } $articleCat = DB::select('catName', 'catID')->from('categories')->where('catID', '=', $data['article'][0]['articleCat'])->limit(1)->order_by('catName', 'desc')->execute()->as_array(); if($articleCat){ $data['postCategory'] = $articleCat[0]; } else { $data['postCategory'] = null; } $this->template->js = "$('#blog_page').addClass('active');"; $this->template->title = html_entity_decode(stripslashes($data['article'][0]['articleTitle']. ' - ' .'Full Sail Times')); $this->template->content = View::factory('site/article', $data); } private function truncateTextbyWords($phrase, $max_words) { $phrase_array = explode(' ',$phrase); if(count($phrase_array) > $max_words && $max_words > 0) $phrase = implode(' ',array_slice($phrase_array, 0, $max_words)).'...'; return $phrase; } public function action_404() { $messages = array('Aw, crap!', 'Bloody Hell!', 'Uh Oh!', 'Nope, not here.', 'Huh?'); $data['title'] = $messages[array_rand($messages)]; // Set a HTTP 404 output header $this->response->status = 404; $this->template->content = View::factory('site/404', $data); } } ?><file_sep><?php // This PHP code developed by <NAME> of Avalux Web Development - AvaluxDev.com foreach($categories as $category) { $cats[] = $category->catName; } ?> <div id="top"> <div class="content_pad"> <ul class="right"> <li><a href="<?php echo $base_path; ?>admin/profile" class="top_icon"><span class="ui-icon ui-icon-person"></span>Logged in as <?php echo $userName; ?></a></li> <li><a rel="facebox" href="#messages" class="new_messages top_alert">1 New Message</a></li> <li><a href="<?php echo $base_path; ?>admin/settings">Settings</a></li> <li><a href="<?php echo $base_path; ?>admin/logout">Logout</a></li> </ul> </div> <!-- .content_pad --> </div> <!-- #top --> <div id="header"> <div class="content_pad"> <h1><a href="<?php echo $base_path; ?>admin">Dashboard Admin</a></h1> <ul id="nav"> <li class="nav_icon"><a href="<?php echo $base_path; ?>admin"><span class="ui-icon ui-icon-home"></span>Home</a></li> <li class="nav_current nav_dropdown nav_icon"> <a href="<?php echo $base_path; ?>admin/posts"><span class="ui-icon ui-icon-gripsmall-diagonal-se"></span>Site Content</a> <div class="nav_menu"> <ul> <li><a href="<?php echo $base_path; ?>admin/new">Create a New Post</a></li> <li><a href="<?php echo $base_path; ?>admin/edit">Edit an Existing Post</a></li> <?php if($userRoleIsAdmin) { echo '<li><a href="' . $base_path . 'admin/authors">Create / Edit Authors</a></li>'; } ?> <li><a href="<?php echo $base_path; ?>admin/media">Manage Images</a></li> </ul> </div> </li> <li class="nav_icon"><a href="<?php echo $base_path; ?>admin/configuration"><span class="ui-icon ui-icon-gear"></span>Configuration</a></li> <li class="nav_icon"><a href="<?php echo $base_path; ?>admin/reports"><span class="ui-icon ui-icon-signal"></span>Reports</a></li> <li class="nav_dropdown nav_icon_only"> <a href="javascript:;">&nbsp;</a> <div class="nav_menu"> <ul> <li><a href="<?php echo $base_path; ?>admin/messages">Messages</a></li> <li><a href="<?php echo $base_path; ?>admin/comments">Comments</a></li> <li><a href="<?php echo $base_path; ?>admin/avalux">Contact Avalux</a></li> </ul> </div> <!-- .menu --> </li> </ul> </div> <!-- .content_pad --> </div> <!-- #header --> <div id="masthead"> <div class="content_pad"> <h1>Your Posts</h1> <div id="bread_crumbs"> <a href="../controlpanel">Home</a> / <a href="./posts" class="current_page">View Posts</a> </div> <!-- #bread_crumbs --> <div id="search"> <?php echo Form::open(array('action' => $base_path .'admin/search', 'method' => 'GET')); ?> <?php echo Form::input(array('type' => 'text','value' => 'Search Posts', 'placeholder' => 'Search Posts', 'name' => 'search', 'id' => 'search_input', 'title' => 'Search')); ?> <?php echo Form::submit(array('name' => 'submit', 'class' => 'submit')); ?> <?php echo Form::close(); ?> </div> <!-- #search --> </div> <!-- .content_pad --> </div> <!-- #masthead --> <div id="content" class="xgrid"> <div class="x12"> <h2>Search Results for keyword "<?php echo Input::get('search'); ?>"</h2> <table class="data display datatable" id="example"> <thead> <tr> <th>Post Title</th> <th width="450">Post Excerpt</th> <th>Post Category</th> <th>Publish Date</th> </tr> </thead> <tbody> <?php foreach($articles as $article): ?> <tr class="odd gradeX row" style="height: 50px;"> <td> <a href="#"><?php echo html_entity_decode(stripslashes($article['articleTitle'])); ?></a> </td> <td><?php echo html_entity_decode(stripslashes($article['articleExcerpt'])); ?></td> <td><?php $catID = $article['articleCat']; $catArrayIndex = $catID - 1; echo $cats[$catArrayIndex]; ?> </td> <td><?php echo $article['startDate']; ?></td> </tr> <?php endforeach; ?> </tbody> </table> <!-- <div class="field buttonrow" style="margin-top: 20px;"> <button class="btn btn-small btn-red">Delete User</button> <button class="btn btn-small btn-grey">Cancel</button> </div> --> </div> </div> <!-- .x12 --> </div> <!-- #content --> <div id="messages" style="display: none"> <h4 class="deletetitle">This Feature Arriving Soon</h4> <p>Before too long, you will be able to utilize the messaging and notification system.</p> </div> <div id="footer"> <div class="content_pad"> <p>&copy; 2011 Copyright <a href="http://www.avaluxdev.com">Avalux Web Development</a>. Powered by <a href="http://fuelphp.com/">Fuel PHP Framework</a>.</p> </div> <!-- .content_pad --> </div> <!-- #footer --> <file_sep><?php class Model_Images extends Orm\Model { protected static $_primary_key = array('imageID'); } /* End of file images.php */<file_sep><div id="articles"> <div id="featured"> <article> <h2><a href="<?php echo $base_path .'article/?id='. $featArticle[0]['articleID'] ?>"><?php echo $featArticle[0]['articleTitle']; ?></a></h2> <div class="homepage_featimg"></div> <?php if(!empty($featImg)){ echo '<a href="' . $base_path . 'article/?id='. $featArticle[0]['articleID'] .'">' .Asset::img($featImg[0]['imagePath'], array('width' => '866', 'height' => '146', 'alt' => 'Feature Image')) . '</a>'; } ?> <p class="excerpt"><?php echo html_entity_decode(stripslashes($featArticle[0]['articleExcerpt'])); ?></p> <a class="readmore" href="<?php echo $base_path .'article/?id='. $featArticle[0]['articleID'] ?>">Read More &raquo;</a> </article> </div><!-- end #featured --> <?php // This PHP code developed by <NAME> of Avalux Web Development - AvaluxDev.com foreach($articles as $article){ echo '<article class="reg">'; echo '<a href="' .$base_path. 'article/?id=' . $article['articleID'] .'">' .stripslashes('<h2>' . html_entity_decode(stripslashes($article['articleTitle'])) . '</h2></a>'); echo stripslashes('<p class="excerpt-small">' . html_entity_decode(stripslashes($article['articleExcerpt'])) . '</p>'); echo '<aside><a class="readmore" href="' .$base_path. 'article/?id=' . $article['articleID'] .'">Read More &raquo;</a></aside>'; echo '</article>'; } echo '<div id="titlebar" class="pagination">' . Pagination::prev_link('&laquo; Previous'). '<span class="numlinks">' . Pagination::create_pagenum_links() . '</span>' . Pagination::next_link('Next &raquo;'). '</div>'; ?> </div> <!-- end #articles --> <?php echo View::factory('site/sidebar')->render(); ?><file_sep><?php class Model_Users extends Orm\Model { protected static $_table_name = 'simpleauth'; } /* End of file users.php */<file_sep><aside id="sidebar"> <h3><?php echo $authorName; ?></h3> <?php if(isset($authorImage)){ echo Asset::img($authorImage, array('class' => 'biopic', 'width' => 75, 'height' => 75)); } ?> <h3>Site Authors</h3> <ul> <?php // This PHP code developed by <NAME> of Avalux Web Development - AvaluxDev.com if(isset($authors)){ foreach($authors as $key => $author) { echo '<li><a id="' .$author['authorID']. '" href="' . $base_path. 'author/?id=' . $author['authorID'] .'">' . $author['fname'] . " " . $author['lname'] . '</a></li>'; } } ?> </ul> <div class="fullsail"></div> </aside><file_sep><aside id="sidebar"> <h3>Author: <?php echo $authorName; ?></h3> <p class="welcome"><?php echo html_entity_decode(stripslashes($bio)) ;?></p> <p class="welcome" style="float: right;margin-top: 5px;"><a href="<?php echo $base_path . 'author/?id=' . $authorID ?>">View My Profile</a></p> <h3 class="title">Topics</h3> <ul> <?php // This PHP code developed by <NAME> of Avalux Web Development - AvaluxDev.com if(isset($categories)){ foreach($categories as $key => $cat) { echo '<li><a href="' . $base_path. 'category/' . ($key +1) .'">' . $cat . '</a></li>'; } } ?> </ul> <div class="fullsail"></div> </aside><file_sep><div id="top"> <div class="content_pad"> <ul class="right"> <li><a href="<?php echo $base_path; ?>admin/profile" class="top_icon"><span class="ui-icon ui-icon-person"></span>Logged in as <?php echo $userName; ?></a></li> <li><a rel="facebox" href="#messages" class="new_messages top_alert">1 New Message</a></li> <li><a href="<?php echo $base_path; ?>admin/settings">Settings</a></li> <li><a href="<?php echo $base_path; ?>admin/logout">Logout</a></li> </ul> </div> <!-- .content_pad --> </div> <!-- #top --> <div id="header"> <div class="content_pad"> <h1><a href="<?php echo $base_path; ?>admin">Dashboard Admin</a></h1> <ul id="nav"> <li class="nav_icon"><a href="controlpanel"><span class="ui-icon ui-icon-home"></span>Home</a></li> <li class="nav_dropdown nav_icon"> <a href="<?php echo $base_path; ?>admin/posts"><span class="ui-icon ui-icon-gripsmall-diagonal-se"></span>Site Content</a> <div class="nav_menu"> <ul> <li><a href="<?php echo $base_path; ?>admin/new">Create a New Post</a></li> <li><a href="<?php echo $base_path; ?>admin/edit">Edit an Existing Post</a></li> <?php if($userRoleIsAdmin) { echo '<li><a href="' . $base_path . 'admin/authors">Create / Edit Authors</a></li>'; } ?> <li><a href="<?php echo $base_path; ?>admin/media">Manage Images</a></li> </ul> </div> </li> <li class="nav_icon"><a href="<?php echo $base_path; ?>admin/configuration"><span class="ui-icon ui-icon-gear"></span>Configuration</a></li> <li class="nav_icon"><a href="<?php echo $base_path; ?>admin/reports"><span class="ui-icon ui-icon-signal"></span>Reports</a></li> <li class="nav_dropdown nav_icon_only"> <a href="javascript:;">&nbsp;</a> <div class="nav_menu"> <ul> <li><a href="<?php echo $base_path; ?>admin/messages">Messages</a></li> <li><a href="<?php echo $base_path; ?>admin/comments">Comments</a></li> <li><a href="<?php echo $base_path; ?>admin/avalux">Contact Avalux</a></li> </ul> </div> <!-- .menu --> </li> </ul> </div> <!-- .content_pad --> </div> <!-- #header --> <div id="masthead"> <div class="content_pad"> <h1>Your Settings</h1> <div id="bread_crumbs"> <a href="<?php echo $base_path; ?>admin">Home</a> / <a href="<?php echo $base_path; ?>admin/settings" class="current_page">Settings</a> </div> <!-- #bread_crumbs --> <div id="search"> <?php echo Form::open(array('action' => $base_path . 'admin/search', 'method' => 'GET')); ?> <?php echo Form::input(array('type' => 'text','value' => 'Search Posts', 'placeholder' => 'Search Posts', 'name' => 'search', 'id' => 'search_input', 'title' => 'Search')); ?> <?php echo Form::submit(array('name' => 'submit', 'class' => 'submit')); ?> <?php echo Form::close(); ?> </div> <!-- #search --> </div> <!-- .content_pad --> </div> <!-- #masthead --> <div id="content" class="xgrid"> <div class="x9"> <div class="accordion_container"> <h2 class="accordion_panel"><a class="passwordform" href="#">Change Password</a></h2> <div class="accordion_content"> <div class="block"> <div class="error"><strong> <?php if(isset($errorsArrayPassword)){ foreach($errorsArrayPassword as $error) { echo $error . "<br />"; } echo "<br />"; } ?> </strong></div> <div class="success"><strong> <?php if(isset($successpassword)){ echo $successpassword . "<br /><br />"; } ?> </strong></div> <?php echo Form::open(array('class' => 'form label-inline')); ?> <div class="field"> <label for="opword">Old Password: </label> <?php echo Form::input(array('type' => 'password','name' => 'opword', 'id' => 'opword', 'class' => 'medium')); ?> </div> <div class="field"> <label for="npword1">New Password: </label> <?php echo Form::input(array('type' => 'password','name' => 'npword1', 'id' => 'npword1', 'class' => 'medium')); ?> </div> <div class="field"> <label for="npword2">Retype Password: </label> <?php echo Form::input(array('type' => 'password','name' => 'npword2', 'id' => 'npword2', 'class' => 'medium')); ?> </div> <?php echo Form::hidden(array('name' => 'formname', 'id' => 'formname', 'value' => 'password')); ?> <br /> <div class="buttonrow"> <?php echo Form::submit(array('name' => 'submit', 'class' => 'btn btn-orange', 'value' => 'Change Password')); ?> </div> <?php echo Form::close(); ?> </div> </div> <h2 class="accordion_panel"><a id="profileform" href="#">Personal Information</a></h2> <div class="accordion_content"> <div class="block"> <div class="error"><strong> <?php if(isset($errorsArrayProfile)){ if($errorsArrayProfile == array()){ foreach($errorsArrayProfile as $error) { echo $error . "<br />"; } } else { echo $errorsArrayProfile; } echo "<br />"; } ?> </strong></div> <div class="success"><strong> <?php if(isset($profilesuccess)){ echo $profilesuccess . "<br /><br />"; } ?> </strong></div> <?php echo Form::open(array('class' => 'form label-inline uniform', 'enctype' => 'multipart/form-data')); ?> <div class="field"> <label for="fname">First Name </label> <?php echo Form::input(array('type' => 'text','name' => 'fname', 'id' => 'fname', 'class' => 'medium', 'value' => $firstName)); ?> </div> <div class="field"> <label for="lname">Last Name </label> <?php echo Form::input(array('type' => 'text','name' => 'lname', 'id' => 'lname', 'class' => 'medium', 'value' => $lastName)); ?> </div> <div class="field phone_field"> <label for="phone">Telephone</label> <?php echo Form::input(array('type' => 'text','name' => 'phone', 'id' => 'phone', 'class' => 'xsmall', 'value' => $phone1, 'maxlength' => '3')); ?> - <?php echo Form::input(array('type' => 'text','name' => 'phone2', 'id' => 'phone2', 'class' => 'xsmall', 'value' => $phone2, 'maxlength' => '3')); ?> - <?php echo Form::input(array('type' => 'text','name' => 'phone3', 'id' => 'phone3', 'class' => 'xsmall', 'value' => $phone3, 'maxlength' => '4')); ?> </div> <div class="field"> <label for="bio">Bio</label> <?php echo Form::textarea(array('cols' => '50', 'rows' => '7', 'type' => 'password','name' => 'bio', 'id' => 'bio', 'class' => 'xlarge', 'value' => html_entity_decode(stripslashes($bio)))); ?> </div> <div class="field"> <label for="avatar">Avatar</label> <div class="avatar"><?php echo Asset::img($authorPic, array('height' => '75')); ?></div> <?php echo Form::input(array('type' => 'file', 'name' => 'avatar', 'id' => 'avatar')); ?> <p class="field_help nudge_down"> &nbsp; &nbsp; or <a href="javascript:;">select an avatar</a> from your collection. <br /><br />Note: Avatar must be 75x75px.</p> </div> <?php echo Form::hidden(array('name' => 'formname', 'id' => 'formname', 'value' => 'profile')); ?> <br /> <div class="buttonrow"> <?php echo Form::submit(array('name' => 'submit', 'class' => 'btn btn-orange', 'value' => 'Update Information')); ?> </div> <?php echo Form::close(); ?> </div> </div> <h2 class="accordion_panel"><a href="#">Your Role</a></h2> <div class="accordion_content"> <div class="block"> <p>You're role is <strong><?php echo $userRole; ?></strong>. As a member of the development team, this means that you have full access to all facets of the site. With this role, you have full access to the frontend and backend of <i>Full Sail Times</i>. If you are unsure of the risks of any change which you are considering making, please consult the development team: <a href="#">Avalux Web Development</a>. Your role contains permissions that could result in a significant change to the website- possibly one resulting in downtime. Please be alert and aware of the ramifications of any change you may make. </div> </div> </div> <!-- .accordion_container --> </div> <!-- .x9 --> <div class="x3"> <h3>Adjust Your Settings</h3> <p><strong>Your Role: </strong><?php echo $userRole; ?><br /> To adjust your settings, utilize the fields to the left. Please remember that this information is considered confidential, and should not be shared with other people.</p> <p>If your role should need to be changed, please contact the <a href="javascript:;">site administrator</a>.</p> </div> <!-- .x3 --> </div> <!-- #content --> <div id="messages" style="display: none"> <h4 class="deletetitle">This Feature Arriving Soon</h4> <p>Before too long, you will be able to utilize the messaging and notification system.</p> </div> <div id="footer"> <div class="content_pad"> <p>&copy; 2011 Copyright <a href="http://www.avaluxdev.com">Avalux Web Development</a>. Powered by <a href="http://fuelphp.com/">Fuel PHP Framework</a>.</p> </div> <!-- .content_pad --> </div> <!-- #footer --><file_sep><?php echo View::factory('site/sidebar')->render(); ?> <h2 style="color: #C9C9C9;">Get In Touch With Us!</h2> <p class="excerpt">Feel free to get in touch with us! Fill out the form below to ask us a question, suggest an article, or report a bug.</p> <form action="" method="post" id="contact"> <div class="field"> <label>Your Name:</label> <input type="text" /> </div> <div class="field"> <label>Your Email:</label> <input type="text" /> </div> <div class="field"> <label>Message:</label> <textarea></textarea> </div> <br /><br /> <input type="submit" value="Send Message" /> </form><file_sep><?php namespace Fuel\Migrations; class Create_articles { public function up() { \DBUtil::create_table('articles', array( 'articleID' => array('constraint' => 11, 'type' => 'int', 'auto_increment' => true), 'articleTitle' => array('constraint' => 65, 'type' => 'varchar'), 'articleExcerpt' => array('constraint' => 350, 'type' => 'varchar'), 'articleBody' => array('type' => 'longtext'), 'startDate' => array('type' => 'datetime'), 'endDate' => array('type' => 'datetime'), 'modDate' => array('type' => 'datetime'), 'authorID' => array('constraint' => 11, 'type' => 'int'), 'articleCat' => array('constraint' => 11, 'type' => 'int'), 'articleImage' => array('constraint' => 65, 'type' => 'varchar'), 'featured' => array('constraint' => 1, 'type' => 'int'), ), array('articleID')); } public function down() { \DBUtil::drop_table('articles'); } }<file_sep><div id="top"> <div class="content_pad"> <ul class="right"> <li><a href="<?php echo $base_path; ?>admin/profile" class="top_icon"><span class="ui-icon ui-icon-person"></span>Logged in as <?php echo $userName; ?></a></li> <li><a rel="facebox" href="#messages" class="new_messages top_alert">1 New Message</a></li> <li><a href="<?php echo $base_path; ?>admin/settings">Settings</a></li> <li><a href="<?php echo $base_path; ?>admin/logout">Logout</a></li> </ul> </div> <!-- .content_pad --> </div> <!-- #top --> <div id="header"> <div class="content_pad"> <h1><a href="<?php echo $base_path; ?>admin/">Dashboard Admin</a></h1> <ul id="nav"> <li class="nav_current nav_icon"><a href="<?php echo $base_path; ?>admin/"><span class="ui-icon ui-icon-home"></span>Home</a></li> <li class="nav_dropdown nav_icon"> <a href="<?php echo $base_path; ?>admin/posts"><span class="ui-icon ui-icon-gripsmall-diagonal-se"></span>Site Content</a> <div class="nav_menu"> <ul> <li><a href="<?php echo $base_path; ?>admin/new">Create a New Post</a></li> <li><a href="<?php echo $base_path; ?>admin/posts">Edit an Existing Post</a></li> <?php if($userRoleIsAdmin) { echo '<li><a href="' . $base_path . 'admin/authors">Create / Edit Authors</a></li>'; } ?> <li><a href="<?php echo $base_path; ?>admin/media">Manage Images</a></li> </ul> </div> </li> <li class="nav_icon"><a href="<?php echo $base_path; ?>admin/configuration"><span class="ui-icon ui-icon-gear"></span>Configuration</a></li> <li class="nav_icon"><a href="<?php echo $base_path; ?>admin/reports"><span class="ui-icon ui-icon-signal"></span>Reports</a></li> <li class="nav_dropdown nav_icon_only"> <a href="javascript:;">&nbsp;</a> <div class="nav_menu"> <ul> <li><a href="<?php echo $base_path; ?>admin/messages">Messages</a></li> <li><a href="<?php echo $base_path; ?>admin/comments">Comments</a></li> <li><a href="<?php echo $base_path; ?>admin/avalux">Contact Avalux</a></li> </ul> </div> <!-- .menu --> </li> </ul> </div> <!-- .content_pad --> </div> <!-- #header --> <div id="masthead"> <div class="content_pad"> <h1 class="no_breadcrumbs">Home</h1> <div id="search"> <?php echo Form::open(array('action' => './admin/search', 'method' => 'GET')); ?> <?php echo Form::input(array('type' => 'text','value' => 'Search Posts', 'placeholder' => 'Search Posts', 'name' => 'search', 'id' => 'search_input', 'title' => 'Search')); ?> <?php echo Form::submit(array('name' => 'submit', 'class' => 'submit')); ?> <?php echo Form::close(); ?> </div> <!-- #search --> </div> <!-- .content_pad --> </div> <!-- #masthead --> <div id="content" class="xgrid"> <div id="welcome" class="x4"> <h3>Welcome back, <?php echo $userName; ?></h3> <div class="avatar"><?php echo Asset::img($authorPic, array('height' => '75', 'alt' => 'Avatar')); ?></div> You are currently signed in as <?php echo $userRole; ?> <br /><a target="_new" href="<?php echo $base_path; ?>">View your site.</a> </p> <h3 class="top_space">Latest News from the Dev Team</h3> <ul> <li><a href="#">Your site is now updated to v1.5!</a></li> <li><a href="#">UPGRADE: Planned Upgrade Downtime</a></li> <li><a href="#">ANALYTICS: Your April Analytics are available</a></li> <li><a href="#">UPGRADE: Planned Homepage Redesign</a></li> <li><a href="#">ANALYTICS: Your March Analytics are available</a></li> <li><a href="#">BILLING: Your Q1 2011 Bill is now available</a></li> </ul> <a href="<?php echo $base_path; ?>admin/messages"> View All Messages</a> </p> <h3>Year-Over-Year Pageviews</h3> <table class="stats" data-chart="pie"> <caption>2008/2009/2010 Views by Year (Million)</caption> <thead> <tr> <td>&nbsp;</td> <th>2008</th> <th>2009</th> <th>2010</th> </tr> </thead> <tbody> <tr> <th>2008</th> <td>25</td> </tr> <tr> <th>2009</th> <td>40</td> </tr> <tr> <th>2010</th> <td>35</td> </tr> </tbody> </table> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p> </div> <!-- .x4 --> <div class="x8" style="border-left: 2px solid #DFDFDF; padding-left: 20px; width: 590px"> <h2>Manage Your Site</h2> <a href="./new" class="admin_action"> <h4 class="action">Create a Post</h4> <span>Add a new article to your website</span> </a> <a href="./posts" class="admin_action"> <h4 class="action">Edit a Post</h4> <span>Edit an existing post on your website</span> </a> <a href="./media" class="admin_action"> <h4 class="action">Upload Images</h4> <span>Upload a new image to your website gallery</span> </a> <?php if($userRoleIsAdmin) { echo ' <a href="./authors" class="admin_action"> <h4 class="action">Create an Author</h4> <span>Add a new author role to your website</span> </a> '; } else { echo ' <a href="./categories" class="admin_action"> <h4 class="action">Edit Categories</h4> <span>Add or edit your website categories</span> </a> '; } ?> <br /><br /><br /><br /><br /><br /> <div style="clear:both; margin-top: 10px !important;"></div> <h2>Manage Your Categories</h2> <p>Add a new category or edit your <a href="<?php echo $base_path; ?>admin/categories">existing categories</a>.</p> <?php echo Form::open(array('class' => 'form label-inline uniform', 'enctype' => 'multipart/form-data')); ?> <div class="field"> <label for="cname">Category Name</label> <?php echo Form::input(array('name' => 'cname', 'id' => 'cname', 'class' => 'medium')); ?> </div> <div class="field"> <label for="cparent">Category Parent</label> <?php array_unshift($cats, 'None'); echo Form::select('cparent', array('name' => 'test', 'id' => 'type', 'class' => 'medium'), $cats) ?> </div> <div class="field buttonrow" style="margin-top: -20px;"> <?php echo Form::submit(array('class' => 'btn btn-small', 'value' => 'Submit Post')); ?> </div> <?php echo Form::close(); ?> <h2>Recent Comments</h2> <table class="data support_table"> <tbody> <tr> <td><span class="ticket open">Open</span></td> <td class="full"><a href="#">Lorem ipsum dolor sit amet</a></td> <td class="who">Posted by Bill</td> </tr> <tr> <td><span class="ticket open">Open</span></td> <td class="full"><a href="#">Consectetur adipiscing</a></td> <td class="who">Posted by Pam</td> </tr> <tr> <td><span class="ticket open">Open</span></td> <td class="full"><a href="#">Sed in porta lectus maecenas</a></td> <td class="who">Posted by Curtis</td> </tr> <tr> <td><span class="ticket closed">Closed</span></td> <td class="full"><a href="#">Dignissim enim</a></td> <td class="who">Posted by John</td> </tr> <tr> <td><span class="ticket responded">Responded</span></td> <td class="full"><a href="#">Duis nec rutrum lorem</a></td> <td class="who">Posted by James</td> </tr> <tr> <td><span class="ticket closed">Closed</span></td> <td class="full"><a href="#">Maecenas id velit et elit</a></td> <td class="who">Posted by Sam</td> </tr> <tr> <td><span class="ticket responded">Responded</span></td> <td class="full"><a href="#">Duis nec rutrum lorem</a></td> <td class="who">Posted by Carlos</td> </tr> </tbody> </table> </div> <!-- .x8 --> <div class="xbreak "></div> <!-- .xbreak --> <div id="messages" style="display: none"> <h4 class="deletetitle">This Feature Arriving Soon</h4> <p>Before too long, you will be able to utilize the messaging and notification system.</p> </div> </div> <!-- #content --> <div id="footer"> <div class="content_pad"> <p>&copy; 2011 Copyright <a href="http://www.avaluxdev.com">Avalux Web Development</a>. Powered by <a href="http://fuelphp.com/">Fuel PHP Framework</a>.</p> </div> <!-- .content_pad --> </div> <!-- #footer --> <file_sep><div id="main"> <div id="admin"> <div class="infobar"> <h3>Thank you for logging in, <?php echo $adminName; ?></h3> <span><?php echo Date::factory()->format("%a, %b %d, %Y"); ?></span> <div id="breadcrumbs"> <a href="/asl1105/jbuff/cms/">homepage</a> &rarr; <a href="/asl1105/jbuff/cms/admin">admin</a> &rarr; <a class="current" href="/asl1105/jbuff/cms/admin/new">new post</a> </div> </div> <form id="newpost" action="?" method="POST"> <ul> <li> <label for="title">Post Title</label> <input type="text" name="title" id="title" /> </li> <li> <label for="excerpt">Excerpt</label> <textarea name="excerpt" id="excerpt"></textarea> </li> <li> <label for="postbody">Body</label> <textarea name="postbody" id="postbody"></textarea> </li> <fieldset class="abc"> <legend>Post Options</legend> <li> <label for="image">Post Image</label> <input type="file" name="image" id="image" /> </li> </fieldset> <li> <input type="submit" value="Submit" /> <span><a href="#">or cancel</a></span> </li> </ul> </form> </div><!-- end /#admin --> </div><!-- end /#main --><file_sep><?php class Model_Article extends Orm\Model { protected static $_primary_key = array('articleID'); } /* End of file article.php */<file_sep><?php class Controller_Admin_New extends Controller_Template { public $template = 'template_backend'; public function action_index() { $data['user'] = Auth::instance()->get_user_array(); $data['userID'] = $data['user']['id'][1]; $data['userGroup'] = $data['user']['usergroup'][0][1]; $data['articles'] = Model_Article::find('all'); $data['categories'] = Model_Category::find('all'); $categories = $data['categories']; $userData = DB::select('authors.fname', 'authors.lname', 'authors.userID', 'authors.authorID', 'simpleauth.id', 'simpleauth.group', 'user_groups.groupName', 'user_groups.groupNameArticle', 'images.imagePath')->from('authors')->join('simpleauth')->on('authors.userID', '=', 'simpleauth.id')->join('user_groups', 'LEFT')->on('simpleauth.group', '=', 'user_groups.groupID')->join('images', 'LEFT')->on('authors.userID', '=', 'images.authorID')->where('authors.userID', '=', $data['userID'])->and_where('images.imageType', '=', 1)->execute()->as_array(); $data['userName'] = $userData[0]['fname'] . " " . $userData[0]['lname']; $authorID = $userData[0]['authorID']; $lastPostArray = DB::select('articleID')->from('articles')->where('authorID', '=', $authorID)->limit(1)->order_by('articleID', 'desc')->execute()->as_array(); // This if statement covers the chance that an author may not previously have an article ID, thus we can not grab it. if($lastPostArray != null) { $lastpost = $lastPostArray[0]['articleID']; } //Authentication check if(! Auth::check()) { Response::redirect('../../admin'); } else { if($data['userGroup'] > 2){ $data['userRoleIsAdmin'] = false; } else { $data['userRoleIsAdmin'] = true; } } if (Input::method() == 'POST') { if ( Upload::is_valid() ) { Upload::save(); foreach( Upload::get_files() as $file ) { $uploadedFile = "frontend/content/" .$file['saved_as']; } } else { $uploadedFile = NULL; } foreach ($categories as $c) { $cats[] = $c->catName; } $featured = Input::post('pfeature'); $cat = Input::post('pcat'); $newcat = $cat + 1; $catName = $cats[$cat]; $val = Validation::factory('new_article'); $val->add_field('ptitle', 'Article Title', 'required|min_length[2]|max_length[65]'); $val->add_field('pexcerpt', 'Article Excerpt', 'required|min_length[2]|max_length[350]'); $val->add_field('pbody', 'Article Body', 'required|min_length[2]'); if ($val->run()) { try { $article = Model_Article::factory(array( 'articleTitle' => $val->validated('ptitle'), 'articleExcerpt' => $val->validated('pexcerpt'), 'articleBody' => $val->validated('pbody'), 'authorID' => $authorID, 'articleCat' => $newcat, 'startDate' => date('Y-m-d H:i:s'), 'featured' => $featured, )); $article->save(); $data['success'] = "Your post was successfully saved."; $lastPostArray = DB::select('articleID')->from('articles')->where('authorID', '=', $authorID)->limit(1)->order_by('articleID', 'desc')->execute()->as_array(); $lastpost = $lastPostArray[0]['articleID']; if($uploadedFile != null){ $image = Model_Images::factory(array( 'title' => $val->validated('ptitle'), 'alt' => $catName . ' Image', 'authorID' => $authorID, 'imageType' => 2, 'imagePath' => $uploadedFile, 'articleID' => $lastpost, )); $image->save(); } } catch(Exception $e){ $data['addErrors'] = "There was an error connecting to the database."; } } else{ $data['addErrors'] = $val->errors(); } } $this->template->title = 'Full Sail Times'; $this->template->excerptJS = " initText = $('#pexcerpt').val().length; excerptLimit = 350; $('#charlimitinfo').html('You have ' + (excerptLimit -initText) + ' characters left'); $('#pexcerpt').keyup(function(){ limitChars('pexcerpt', excerptLimit, 'charlimitinfo'); }); "; $this->template->content = View::factory('admin/new', $data); } public function action_404() { $messages = array('Aw, crap!', 'Bloody Hell!', 'Uh Oh!', 'Nope, not here.', 'Huh?'); $data['title'] = $messages[array_rand($messages)]; // Set a HTTP 404 output header $this->response->status = 404; $this->response->body = View::factory('welcome/404', $data); } } ?><file_sep><aside id="sidebar"> <h3>Welcome to Full Sail Times</h3> <p class="welcome">Welcome to the official online newspaper of Full Sail University. Here, you will find many topics; from campus news to GPS point events. We look forward to serving you!</p> <h3 class="title">Topics</h3> <ul> <?php // This PHP code developed by <NAME> of Avalux Web Development - AvaluxDev.com if(isset($categories)){ foreach($categories as $key => $cat) { echo '<li><a href="' .$base_path. 'category/' . ($key +1) .'">' . $cat . '</a></li>'; } } ?> </ul> <div class="fullsail"></div> <!-- Placeholder for the fullsail logo loaded by css --> </aside><file_sep><?php class Model_Author extends Orm\Model { protected static $_primary_key = array('authorID'); } /* End of file author.php */<file_sep><div id="categories"> <h1>Categories</h1> <ul> <li>&raquo; National League News</li> <li>&raquo; American League News</li> <li>&raquo; Minor League News</li> <li>&raquo; Injuries</li> <li>&raquo; Baseball Opinion</li> <li>&raquo; Major League Events</li> <li>&raquo; Photographs</li> <li>&raquo; Video Updates</li> <li>&raquo; Press Releases</li> </ul> </div> <div id="articles"> <div class="entry"> <?php echo Asset::img('content/office.jpg', array('class' => 'featimg')); ?> <div class="meta"> <h1>This is a Fake Title</h1> <span>May 3, 2011</span> </div> <div class="text"> <p>Etiam at risus et justo dignissim congue. Donec congue lacinia dui, a porttitor lectus condimentum laoreet. Nunc eu ullamcorper orci. Quisque eget odio ac lectus vestibulum faucibus eget in metus. In pellentesque faucibus vestibulum. Nulla at nulla justo, eget luctus tortor. Nulla facilisi. Duis aliquet egestas purus in blandit. Curabitur vulputate.Etiam at risus et justo dignissim congue. Donec congue lacinia dui, a porttitor lectus condimentum laoreet. Nunc eu ullamcorper orci. Quisque eget odio ac lectus vestibulum faucibus eget in metus. In pellentesque faucibus vestibulum. Nulla at nulla justo, eget luctus tortor. Nulla facilisi. Duis aliquet egestas purus in blandit. Curabitur vulputate.</p> <p>Etiam at risus et justo dignissim congue. Donec congue lacinia dui, a porttitor lectus condimentum laoreet. Nunc eu ullamcorper orci. Quisque eget odio ac lectus vestibulum faucibus eget in metus. In pellentesque faucibus vestibulum. Nulla at nulla justo, eget luctus tortor. Nulla facilisi. Duis aliquet egestas purus in blandit. Curabitur vulputate.Etiam at risus et justo dignissim congue. Donec congue lacinia dui, a porttitor lectus condimentum laoreet. Nunc eu ullamcorper orci. Quisque eget odio ac lectus vestibulum faucibus eget in metus. In pellentesque faucibus vestibulum. Nulla at nulla justo, eget luctus tortor. Nulla facilisi. Duis aliquet egestas purus in blandit. Curabitur vulputate.</p> <p>Etiam at risus et justo dignissim congue. Donec congue lacinia dui, a porttitor lectus condimentum laoreet. Nunc eu ullamcorper orci. Quisque eget odio ac lectus vestibulum faucibus eget in metus. In pellentesque faucibus vestibulum. Nulla at nulla justo, eget luctus tortor. Nulla facilisi. Duis aliquet egestas purus in blandit. Curabitur vulputate.Etiam at risus et justo dignissim congue. Donec congue lacinia dui, a porttitor lectus condimentum laoreet. Nunc eu ullamcorper orci. Quisque eget odio ac lectus vestibulum faucibus eget in metus. In pellentesque faucibus vestibulum. Nulla at nulla justo, eget luctus tortor. Nulla facilisi. Duis aliquet egestas purus in blandit. Curabitur vulputate.</p> </div> </div> </div> <file_sep><!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-type" content="text/html; charset=utf-8" /> <title><?php echo $title; ?> | Avalux Admin</title> <?php echo Asset::css('backend/reset.css'); ?> <?php echo Asset::css('backend/text.css'); ?> <?php echo Asset::css('backend/form.css'); ?> <?php echo Asset::css('backend/buttons.css'); ?> <?php echo Asset::css('backend/grid.css'); ?> <?php echo Asset::css('backend/layout.css'); ?> <?php echo Asset::css('backend/ui-darkness/jquery-ui-1.8.12.custom.css'); ?> <?php echo Asset::css('backend/plugin/jquery.visualize.css'); ?> <?php echo Asset::css('backend/plugin/facebox.css'); ?> <?php echo Asset::css('backend/plugin/uniform.default.css'); ?> <?php echo Asset::css('backend/plugin/dataTables.css'); ?> <?php echo Asset::css('backend/custom.css'); ?> </head> <body> <div id="wrapper"> <?php echo $content; ?> </div> <!-- #wrapper --> <?php echo Asset::js('backend/jquery/jquery-1.5.2.min.js'); ?> <?php echo Asset::js('backend/jquery/jquery-ui-1.8.12.custom.min.js'); ?> <?php echo Asset::js('backend/misc/excanvas.min.js'); ?> <?php echo Asset::js('backend/jquery/facebox.js'); ?> <?php echo Asset::js('backend/jquery/jquery.visualize.js'); ?> <?php echo Asset::js('backend/jquery/jquery.dataTables.min.js'); ?> <?php echo Asset::js('backend/jquery/jquery.tablesorter.min.js'); ?> <?php echo Asset::js('backend/jquery/jquery.uniform.min.js'); ?> <?php echo Asset::js('backend/jquery/jquery.placeholder.min.js'); ?> <?php echo Asset::js('backend/jquery/jquery.scrollTo-min.js'); ?> <?php echo Asset::js('backend/widgets.js'); ?> <?php echo Asset::js('backend/dashboard.js'); ?> <script type="text/javascript"> function limitChars(textid, limit, infodiv) { var text = $('#'+textid).val(); var textlength = text.length; if(textlength >= (limit - 10)) { $('#' + infodiv).addClass('warning'); } if(textlength <= (limit - 11)) { $('#' + infodiv).removeClass('warning'); } if(textlength > limit) { $('#' + infodiv).removeClass('warning').addClass('error').html('You cannot write more then '+limit+' characters!'); $('#'+textid).val(text.substr(0,limit)); return false; } else { $('#' + infodiv).removeClass('error').html('You have '+ (limit - textlength) +' characters left.'); return true; } } </script> <script type="text/javascript"> $(document).ready ( function () { $deleteid = ""; Dashboard.init (); //For jQuery $.extend({ getUrlVars: function(){ var vars = [], hash; var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&'); for(var i = 0; i < hashes.length; i++) { hash = hashes[i].split('='); vars.push(hash[0]); vars[hash[0]] = hash[1]; } return vars; }, getUrlVar: function(name){ return $.getUrlVars()[name]; } }); var search = $.getUrlVar('search'); /* $('#example_filter').find('input').val(search); */ $('#example_filter').find('input').val(search).end().trigger('keyup'); $('.searchinput').trigger('keyup'); $('.accordion_container').accordion (); $('.tab_container').tabs (); $('.row').mouseenter(function() { $('.options').removeClass('hidden').addClass('shown'); }); $('.row').mouseleave(function() { $('.options').removeClass('shown').addClass('hidden'); }); $('a.delete').mouseover(function(){ /* console.log(this.id); */ }); $('a.delete').click(function(){ $deleteid = this.id; console.log($deleteid); /* $('.deletetitle').html($deleteid); */ $('.artid').html( " " + "<input type='hidden' name='articleid' value='" + $deleteid + "' />" ); }); $('#search_input').focus(function(){ if(this.value == 'Search Posts'){ this.value = ''; } }); $('#search_input').blur(function(){ if(this.value == ''){ this.value = 'Search Posts'; } }); $(function(){ <?php if(isset($excerptJS)){ echo $excerptJS; } ?> }); }); </script> <script type="text/javascript"> $(document).ready ( function () { <?php if(isset($js)){ echo $js; } if(isset($galleryJS)){ echo $galleryJS; } ?> }); </script> </body> </html> <!-- Localized --><file_sep><?php namespace Fuel\Migrations; class View_categories { public function up() { \DBUtil::create_table('categories', array( 'catID' => array('constraint' => 11, 'type' => 'int', 'auto_increment' => true), 'catName' => array('constraint' => 30, 'type' => 'varchar'), ), array('catID')); } public function down() { \DBUtil::drop_table('categories'); } }<file_sep><div id="top"> <div class="content_pad"> <ul class="right"> <li><a href="<?php echo $base_path; ?>admin/profile" class="top_icon"><span class="ui-icon ui-icon-person"></span>Logged in as <?php echo $userName; ?></a></li> <li><a rel="facebox" href="#messages" class="new_messages top_alert">1 New Message</a></li> <li><a href="<?php echo $base_path; ?>admin/settings">Settings</a></li> <li><a href="<?php echo $base_path; ?>admin/logout">Logout</a></li> </ul> </div> <!-- .content_pad --> </div> <!-- #top --> <div id="header"> <div class="content_pad"> <h1><a href="<?php echo $base_path; ?>admin">Dashboard Admin</a></h1> <ul id="nav"> <li class="nav_icon"><a href="<?php echo $base_path; ?>admin"><span class="ui-icon ui-icon-home"></span>Home</a></li> <li class="nav_current nav_dropdown nav_icon"> <a href="<?php echo $base_path; ?>admin/posts"><span class="ui-icon ui-icon-gripsmall-diagonal-se"></span>Site Content</a> <div class="nav_menu"> <ul> <li><a href="<?php echo $base_path; ?>admin/new">Create a New Post</a></li> <li><a href="<?php echo $base_path; ?>admin/edit">Edit an Existing Post</a></li> <?php if($userRoleIsAdmin) { echo '<li><a href="' . $base_path . 'admin/authors">Create / Edit Authors</a></li>'; } ?> <li><a href="<?php echo $base_path; ?>admin/media">Manage Images</a></li> </ul> </div> </li> <li class="nav_icon"><a href="<?php echo $base_path; ?>admin/configuration"><span class="ui-icon ui-icon-gear"></span>Configuration</a></li> <li class="nav_icon"><a href="<?php echo $base_path; ?>admin/reports"><span class="ui-icon ui-icon-signal"></span>Reports</a></li> <li class="nav_dropdown nav_icon_only"> <a href="javascript:;">&nbsp;</a> <div class="nav_menu"> <ul> <li><a href="<?php echo $base_path; ?>admin/messages">Messages</a></li> <li><a href="<?php echo $base_path; ?>admin/comments">Comments</a></li> <li><a href="<?php echo $base_path; ?>admin/avalux">Contact Avalux</a></li> </ul> </div> <!-- .menu --> </li> </ul> </div> <!-- .content_pad --> </div> <!-- #header --> <div id="masthead"> <div class="content_pad"> <h1>Editing "<?php echo stripslashes($entry->articleTitle) ?>"</h1> <div id="bread_crumbs"> <a href="<?php echo $base_path; ?>admin">Home</a> / <a href="<?php echo $base_path; ?>admin/edit?id=<?php echo $articleID; ?>" class="current_page">Edit Post</a> </div> <!-- #bread_crumbs --> <div id="search"> <?php echo Form::open(array('action' => $base_path .'admin/search', 'method' => 'GET')); ?> <?php echo Form::input(array('type' => 'text','value' => 'Search Posts', 'placeholder' => 'Search Posts', 'name' => 'search', 'id' => 'search_input', 'title' => 'Search')); ?> <?php echo Form::submit(array('name' => 'submit', 'class' => 'submit')); ?> <?php echo Form::close(); ?> </div> <!-- #search --> </div> <!-- .content_pad --> </div> <!-- #masthead --> <!-- html_entity_decode(stripslashes()) --> <div id="content" class="xgrid"> <div class="x12"> <?php if(isset($editErrors)) { echo '<div class="error"><strong>'; foreach($editErrors as $e) { echo $e . "<br />"; } echo '</strong></div><br />'; } ?> <?php if(isset($savemsgs)) { echo '<div class="success"><strong>'; echo $savemsgs . "<br /><br />"; echo '</strong></div>'; } ?> <?php echo Form::open(array('action' => $base_path .'admin/edit?id=' . $articleID .'', 'class' => 'form label-inline uniform', 'enctype' => 'multipart/form-data')); ?> <div class="field"> <label for="ptitle">Post Title</label> <?php echo Form::input(array('name' => 'ptitle', 'id' => 'ptitle', 'class' => 'full', 'value' => html_entity_decode(stripslashes($entry->articleTitle)))); ?> </div> <div class="field"> <label for="pexcerpt">Post Excerpt</label> <?php echo Form::textarea(array('name' => 'pexcerpt', 'id' => 'pexcerpt', 'rows' => 3, 'class' => 'full', 'value' => stripslashes($entry->articleExcerpt))); ?> <p class="field_help" id="charlimitinfo">You have 350 characters left.</p> </div> <div class="field"> <label for="pbody">Post Body</label> <?php echo Form::textarea(array('name' => 'pbody', 'id' => 'pbody', 'rows' => 10, 'class' => 'full', 'value' => stripslashes($entry->articleBody))); ?> </div> <div class="field clearfix"> <label for="pimage">Post Image</label> <?php echo Form::input(array('type' => 'file', 'name' => 'pimage', 'id' => 'pimage'), Input::post('pimage', isset($article) ? $article->articleImage : '')); ?> <p class="field_help nudge_down"> &nbsp; &nbsp; or <a href="javascript:;">select a file</a> from your library.</p> </div> <label>Current Image:</label> <div class="editpostimg"> <?php if($postImage != null){ echo Asset::img($postImage, array('height' => '100', 'alt' => 'Post Image')); } ?> </div> <div class="field"> <label for="pcat">Post Category </label> <?php echo Form::select('pcat', array('name' => 'pcat', 'id' => 'pcat', 'class' => 'medium', 'selected' => ($entry->articleCat -1)), $cats) ?> </div> <div class="field clearfix"> <label for="pfeature">Feature Post?</label> <?php echo Form::select('pfeature', array('name' => 'test', 'id' => 'type', 'class' => 'medium', 'selected' => ($entry->featured)), array(1 => 'No', 2 =>'Yes')) ?> </div> <div class="buttonrow"> <?php echo Form::submit(array('class' => 'btn', 'value' => 'Update Post')); ?> </div> <?php echo Form::close(); ?> </div> <!-- .x12 --> </div> <!-- #content --> <div id="messages" style="display: none"> <h4 class="deletetitle">This Feature Arriving Soon</h4> <p>Before too long, you will be able to utilize the messaging and notification system.</p> </div> <div id="footer"> <div class="content_pad"> <p>&copy; 2011 Copyright <a href="http://www.avaluxdev.com">Avalux Web Development</a>. Powered by <a href="http://fuelphp.com/">Fuel PHP Framework</a>.</p> </div> <!-- .content_pad --> </div> <!-- #footer --> <file_sep><?php // This PHP code developed by <NAME> of Avalux Web Development - AvaluxDev.com class Controller_Admin_Profile extends Controller_Template { public $template = 'template_backend'; public function action_index() { $data = array(); $data['categories'] = Model_Category::find('all'); $data['user'] = Auth::instance()->get_user_array(); $data['userID'] = $data['user']['id'][1]; $data['userGroup'] = $data['user']['usergroup'][0][1]; $data['articles'] = DB::select()->where('authorID', '=', $data['userID'])->from('articles')->execute()->as_array(); $data['authorName'] = DB::select('fname', 'lname')->where('authorID', '=', $data['userID'])->from('authors')->execute()->as_array(); $userData = DB::select('authors.fname', 'authors.lname', 'authors.userID', 'authors.bio', 'simpleauth.id', 'simpleauth.group', 'user_groups.groupName', 'user_groups.groupNameArticle', 'images.imagePath')->from('authors')->join('simpleauth')->on('authors.userID', '=', 'simpleauth.id')->join('user_groups', 'LEFT')->on('simpleauth.group', '=', 'user_groups.groupID')->join('images', 'LEFT')->on('authors.userID', '=', 'images.authorID')->where('authors.userID', '=', $data['userID'])->and_where('images.imageType', '=', 1)->execute()->as_array(); $data['userName'] = $userData[0]['fname'] . " " . $userData[0]['lname']; $data['userRole'] = $userData[0]['groupNameArticle'] . " " .$userData[0]['groupName']; $data['authorPic'] = $userData[0]['imagePath']; $data['authorBio'] = $userData[0]['bio']; //Authentication check if(! Auth::check()) { Response::redirect('../../admin'); } else { if($data['userGroup'] > 2){ $data['userRoleIsAdmin'] = false; } else { $data['userRoleIsAdmin'] = true; } } $this->template->title = 'Reports'; $this->template->content = View::factory('admin/profile', $data); } public function action_404() { $messages = array('Aw, crap!', 'Bloody Hell!', 'Uh Oh!', 'Nope, not here.', 'Huh?'); $data['title'] = $messages[array_rand($messages)]; // Set a HTTP 404 output header $this->response->status = 404; $this->response->body = View::factory('admin/404', $data); } } ?><file_sep><?php // This PHP code developed by <NAME> of Avalux Web Development - AvaluxDev.com class Controller_Category extends Controller_Template { public $template = 'template_frontend'; public function action_index() { $data = array(); $categories = Model_Category::find('all'); foreach ($categories as $c) { $cats[] = $c->catName; } $categories = $cats; View::set_global('categories', $categories); $catURISegment = Uri::segment(2); $data['articles'] = DB::select('*')->from('articles')->where('articleCat', '=', $catURISegment)->execute()->as_array(); $data['category'] = DB::select('*')->from('categories')->where('catID', '=', $catURISegment)->execute()->as_array(); $articles = DB::select('*')->from('articles')->where('articleCat', '=', $catURISegment)->execute()->as_array(); $pconf = array( 'pagination_url' => 'http://localhost:8888/asl1105/jbuff/cms/category/'. ($this->param('page') + 0), 'total_items' => count($articles), 'per_page' => 4, 'uri_segment' => 3, ); //Pagination::set_config($paginationConfig); Config::set('pagination', $pconf); $data['articles'] = DB::select('*')->from('articles') ->where('articleCat', '=', $catURISegment) ->order_by('startDate', 'desc') ->limit(Pagination::$per_page) ->offset(Pagination::$offset) ->execute() ->as_array(); if($this->param('page') == 0){ $data['pageNum'] = 1; } else { $data['pageNum'] = $this->param('page'); } $data['totalPages'] = Pagination::total_pages(); $this->template->js = "$('#categories_page').addClass('active');"; $this->template->title = 'Full Sail Times'; $this->template->content = View::factory('site/category', $data); } public function action_404() { $messages = array('Aw, crap!', 'Bloody Hell!', 'Uh Oh!', 'Nope, not here.', 'Huh?'); $data['title'] = $messages[array_rand($messages)]; // Set a HTTP 404 output header $this->response->status = 404; $this->template->content = View::factory('site/404', $data); } } ?><file_sep><?php // This PHP code developed by <NAME> of Avalux Web Development - AvaluxDev.com class Controller_Admin_Edit extends Controller_Template { public function action_index() { $data = array(); $data['adminName'] = '<NAME>'; $this->template->title = 'Full Sail Times'; $this->template->content = View::factory('admin/editpost', $data); } public function action_404() { $messages = array('Aw, crap!', 'Bloody Hell!', 'Uh Oh!', 'Nope, not here.', 'Huh?'); $data['title'] = $messages[array_rand($messages)]; // Set a HTTP 404 output header $this->response->status = 404; $this->response->body = View::factory('admin/404', $data); } } ?><file_sep><?php defined('COREPATH') or exit('No direct script access allowed'); ?> Error - 2012-09-03 01:30:24 --> 8 - Undefined index: errors in /Applications/MAMP/htdocs/fullsail/jbuff/cms/fuel/app/classes/controller/admin.php on line 62 <file_sep><?php return array( '_root_' => 'welcome/index', // The default route '_404_' => 'welcome/404', // The main 404 route 'admin/media/:pagenumber' => '/admin/media/', 'admin' => 'admin', 'admin/(:any)' => 'admin/$1', 'categories' => 'categories', 'category' => 'categories', 'category/(:page)' => 'category', 'contact' => 'contact', 'article' => 'article', 'author' => 'author', ':page' => 'blog', /** * This is an example of a BASIC named route (used in reverse routing). * The translated route MUST come first, and the 'name' element must come * after it. */ // 'foo/bar' => array('welcome/foo', 'name' => 'foo'), /// NOTE: The above works like url => 'controller/function' );
3c09b5bc9cf69c01db6de82d5603cd893def23c8
[ "Markdown", "PHP" ]
61
PHP
cuongleqng/SimpleCMS
0481efe65d3459ee8f51c004e7ea865d4faabc8f
2a48f6f3708785939ad70d53ae04813850a72d3c
refs/heads/main
<file_sep># Final-project-reactJs
78409a8628d6593e9d3adec58fcb3cb752fc865e
[ "Markdown" ]
1
Markdown
Ahlem-fahem/Final-project-reactJs
1091c1be5c2c734fc2f7c36f1eeaa5bff0268181
8b26b6ddba29323cc8ac44331918729a47829a95
refs/heads/master
<file_sep>import pandas as pd from strategy.base_strategy import BaseStrategy from jqdemo.offline_stock_action import OfflineStockAction from config.config import * from strategy.error import StrategyError class IndexCalculatorStategy(BaseStrategy): def __init__(self): self.offline_stock_action = OfflineStockAction() BaseStrategy.__init__(self) def calculate_concept_index(self, concept_code): concept_stocks = self.offline_stock_action.query_stocks_by_concept(concept_code) stock_code_list = list(concept_stocks['stock_code']) stock_valuations = self.offline_stock_action.query_valuations(stock_code_list) stock_last_prices = self.offline_stock_action.query_last_prices(stock_code_list) stock_first_prices = self.offline_stock_action.query_first_prices(stock_code_list) stock_valuations.sort_values(by='code') stock_last_prices.sort_values(by='stock_code') temp = pd.merge(stock_last_prices, stock_valuations, left_on='stock_code', right_on='code') total_cap = 0 market_capital = 0 for index, item in temp.iterrows(): market_capital += item['market_cap'] #*10000*item['close'] total_cap += item['capitalization'] log.info('%s指数 -> %.2f',concept_stocks['concept_name'][0] ,market_capital*100000000/(total_cap*10000)) pass <file_sep>import datetime import unittest import pandas as pd from strategy.strategy_indicator import IndicatorStrategy from jqdemo.offline_stock_action import OfflineStockAction from jqdemo.stock_action import StockAction from strategy.strategy_bull_up import BullUpStrategy import threading from config.config import * class TestMACDStrategy(unittest.TestCase): def __init__(self, method_name): unittest.TestCase.__init__(self, method_name) self.indicator_strategy = IndicatorStrategy() self.offline_stock_action = OfflineStockAction() self.bull_up_strategy = BullUpStrategy() # def test_dmi(self): # stocks = self.offline_stock_action.get_all_stock() # i = 1 # for index, stock in stocks.iterrows(): # price = self.offline_stock_action.query_all_history_prices(stock['stock_code']) # m_di, p_di, adx = self.indicator_strategy.calculate_dmi(price['high'], price['low'], price['close']) # if float(p_di.tail(1)) > float(m_di.tail(2).head(1)) \ # and float(adx.tail(1)) > 30: # log.info("NOTICE => %s", stock['stock_code']) # view_bar(i, len(stocks.index)) # i += 1 # def test_list_macd_gold(self): # stocks = self.offline_stock_action.get_all_stock() # log.info("======================================") # for index, stock in stocks.iterrows(): # price = self.offline_stock_action.query_all_history_prices(stock['stock_code']) # real = self.indicator_strategy.calculate_rsi(price['close']) # cci = self.indicator_strategy.calculate_cci(price['high'], price['low'], price['close']) # if float(price['paused'].tail(1)) <= 0: # if int(cci.tail(1)) > 100 > int(cci.tail(2).head(1)): # log.info("NOTICE ==> %s CCI今日超过100", stock['stock_code']) # macd, macdsignal, macdhist = self.indicator_strategy.calculate_macd(price['close']) # if float(macdhist.tail(1)) > 0 > float(macdhist.tail(2).head(1)) and float(macd.tail(1)) > 0: # log.info("\t\tNOTICE ==> %s MACD金叉行情",stock['stock_code']) # if float(macd.tail(1)) > 0 > float(macd.tail(2).head(1)): # log.info("\t\tNOTICE ==> %s DIF>0行情", stock['stock_code']) # def test_valuations(self): # print(self.stock_action.refresh_valuations()) # def test_concept(self): stock_action = StockAction() print(stock_action.refresh_concepts()) def test_refresh_concept_stock(self): stock_action = StockAction() stock_action.refresh_concept_stocks() # def test_concept_stocks(self): # # print(self.stock_action.refresh_concept_stocks()) # print(self.offline_stock_action.query_stock_concept('000027.XSHE')) def test_all_stock_history_price(self): stocks = self.offline_stock_action.query_all_stock() stocks_0 = stocks[0:600] stocks_1 = stocks[600:1200] stocks_2 = stocks[1200:1800] stocks_3 = stocks[1800:2400] stocks_4 = stocks[2400:3000] stocks_5 = stocks[3000:len(stocks)] thread_0 = threading.Thread(target=self.append_stock_price, args=(stocks_0,)) thread_1 = threading.Thread(target=self.append_stock_price, args=(stocks_1,)) thread_2 = threading.Thread(target=self.append_stock_price, args=(stocks_2,)) thread_3 = threading.Thread(target=self.append_stock_price1, args=(stocks_3,)) thread_4 = threading.Thread(target=self.append_stock_price1, args=(stocks_4,)) thread_5 = threading.Thread(target=self.append_stock_price1, args=(stocks_5,)) thread_0.setDaemon(True) thread_1.setDaemon(True) thread_2.setDaemon(True) thread_3.setDaemon(True) thread_4.setDaemon(True) thread_5.setDaemon(True) thread_0.start() thread_1.start() thread_2.start() thread_3.start() thread_4.start() thread_5.start() thread_0.join() thread_1.join() thread_2.join() thread_3.join() thread_4.join() thread_5.join() def append_stock_price(self, stocks): log.info("%s running", threading.get_ident()) stock_codes = list(stocks['stock_code']) for i in range(len(stock_codes)): #view_bar(i+1, len(stock_codes), '(' + str(threading.get_ident())+')') stock_action = StockAction() stock_action.append_stock_price(stock_codes[i]) log.info("%s done", threading.get_ident()) def append_stock_price1(self, stocks): log.info("%s running", threading.get_ident()) stock_codes = list(stocks['stock_code']) for i in range(len(stock_codes)): #view_bar(i+1, len(stock_codes), '(' + str(threading.get_ident())+')') stock_action = StockAction(user_name= '****', pwd='****') stock_action.append_stock_price(stock_codes[i]) log.info("%s done", threading.get_ident()) # def test_swing_backtesting(self): # start_date = datetime.datetime(2019, 1, 1) # stock_code = '000027.XSHE' # price = self.offline_stock_action.query_all_history_prices(stock_code) # # self.bull_up_strategy. # pass if __name__ == '__main__': unittest.main() <file_sep>import talib from strategy.base_strategy import BaseStrategy class IndicatorStrategy(BaseStrategy): def __init__(self): BaseStrategy.__init__(self) @staticmethod def calculate_macd(stock_prices): return talib.MACD(stock_prices, fastperiod=12, slowperiod=26, signalperiod=9) @staticmethod def calculate_rsi(stock_close_prices): return talib.RSI(stock_close_prices, timeperiod=14) @staticmethod def calculate_cci(high, low, close): return talib.CCI(high, low, close, timeperiod=14) @staticmethod def calculate_dmi(high, low, close): return [talib.MINUS_DI(high, low, close, timeperiod=14), talib.PLUS_DI(high, low, close, timeperiod=14), talib.ADX(high, low, close, timeperiod=14)] @staticmethod def is_good_dmi(m_di, p_di, adx): if float(p_di) > float(m_di) and float(adx) > 30: return True return False @staticmethod def calculate_boll(close): upperband, middleband, lowerband = talib.BBANDS(close, timeperiod=20, nbdevup=2, nbdevdn=2, matype=0) return upperband, middleband, lowerband <file_sep>from jqdemo import stock_action from jqdemo import tick_action from jqdemo import offline_stock_action <file_sep>import unittest import jqdemo class TestStockAction(unittest.TestCase): def __init__(self, method_name): unittest.TestCase.__init__(self, method_name) self.stock_action = jqdemo.stock_action.StockAction() # def test_get_all_stock(self): # self.stock_action.refresh_base_stock_info() # # def test_fresh_trade_day(self): # self.stock_action.refresh_trade_days() # # def test_locked_share(self): # self.stock_action.refresh_locked_share() # # def test_refresh_all_stock_price(self): # self.stock_action.refresh_all_stock_price() # def test_refresh_all_stock_price(self): if __name__ == "__main__": unittest.main() <file_sep>from backtesting.base_backtesting import BaseBackTesing from jqdemo.offline_stock_action import OfflineStockAction from strategy.strategy_indicator import IndicatorStrategy from strategy.strategy_bull_up import BullUpStrategy from config.config import * import datetime import pandas as pd class SimpleBackTesting(BaseBackTesing): def __init__(self): BaseBackTesing.__init__(self) self.stock_code = None self.offline_stock_action = OfflineStockAction() self.bull_up_strategy = BullUpStrategy() self.indicator_strategy = IndicatorStrategy() self.total_dmi = None self.stock = None self.pressure_level = self.MAX_VALUE self.stop_loss_level = 0 pass def set_stock_code(self, stock_code): self.stock_code = stock_code def is_buy_position(self, history_prices, current_price): history_prices = history_prices.append(current_price) # 判断是否是反弹时间点 bull_up_list = self.bull_up_strategy\ .list_bull_up_stock(count=4, up_thread_hold=0.03, stock_list=self.stock, end_day=current_price['trade_day'], prices=history_prices[history_prices['trade_day'] <= current_price['trade_day']], safe_flag=True) if bull_up_list[0].empty is False: self.stock = bull_up_list[0] self.pressure_level = self.stock['pressure_price'] self.stop_loss_level = self.stock['stop_loss_price'] current_dmi = self.total_dmi[self.total_dmi['trade_day'] == current_price['trade_day']] if float(current_dmi['pdi'].tail(1)) > float(current_dmi['mdi'].tail(1)) \ and float(current_dmi['adx'].tail(1)) > 30: return True return False def buy_action(self, history_prices, current_price): self.buy_position_percent_value(current_price=current_price, percent=0.8) def is_sell_position(self, history_prices, current_price): return super().is_sell_position(history_prices, current_price) def sell_action(self, history_prices, current_price): super().sell_action(history_prices, current_price) def is_add_position(self, history_prices, current_price): if float(current_price['close']) > float(self.pressure_level) \ and current_price['volume'] > history_prices.tail(5)['volume'].mean(): return True return super().is_add_position(history_prices, current_price) #放量突破压力位,加仓20% def add_position_action(self, history_prices, current_price): self.stop_loss_level = self.pressure_level self.pressure_level = self.pressure_level * 1.05 self.buy_position_percent_value(current_price=current_price, percent=0.6) def is_reduce_position(self, history_prices, current_price): if int(self.position) > 0 and float(current_price['close']) < float(self.pressure_level)\ < float(current_price['high']): return True return super().is_reduce_position(history_prices, current_price) #遇到压力位如果当天最高价超过,但是收盘没有超过则减仓50% def reduce_position_action(self, history_prices, current_price): self.sell_position_percent_value(current_price=current_price, percent=0.5) def is_clear_position(self, history_prices, current_price): if int(self.position) > 0 and float(current_price['close']) < float(self.stop_loss_level): return True return super().is_clear_position(history_prices, current_price) # 到达止损位,清仓出局 def clear_position_action(self, history_prices, current_price): self.sell_position_percent_value(current_price=current_price, percent=1) def buy_fee(self): return 5 #TODO 暂时固定按5元 def sell_fee(self): return 5 #TODO 暂时固定按5元 def end_backtesting(self, history_prices, current_price): if self.position > 0: self.sell_position_percent_value(current_price=current_price, percent=1) def run(self): if self.stock_code is None: raise Exception("stock code can not be None") self.stock = pd.DataFrame(self.offline_stock_action.query_by_stock_code(self.stock_code)) total_history_prices = self.offline_stock_action.query_all_history_prices( self.stock_code) mdi, pdi, adx = self.indicator_strategy.calculate_dmi(total_history_prices['high'], total_history_prices['low'], total_history_prices['close']) dmis = { 'mdi': mdi, 'pdi': pdi, 'adx': adx, 'trade_day': total_history_prices['trade_day'] } self.total_dmi = pd.DataFrame(dmis) super().run_backtesting(total_history_prices=total_history_prices, start_date=datetime.datetime(2019, 1, 1)) return float(round((self.balance - self.INIT_BALANCE)/self.INIT_BALANCE*100, 2)) <file_sep>import unittest from strategy.strategy_bull_up import BullUpStrategy from strategy.strategy_indicator import IndicatorStrategy from jqdemo.offline_stock_action import OfflineStockAction from config.config import * class TestStrategy(unittest.TestCase): def __init__(self, method_name): unittest.TestCase.__init__(self, method_name) self.strategy_bull_up = BullUpStrategy() self.indicator_strategy = IndicatorStrategy() self.offline_stock_action = OfflineStockAction() # def test_bull_up(self): # # log.info("===============================================") # result = self.strategy_bull_up.list_bull_up_stock(count=4, up_thread_hold=0.03)[0] # log.info("===============================================") # result = self.strategy_bull_up.list_bull_up_stock(7, 0.03, result)[0] # log.info("===============================================") # result = self.strategy_bull_up.list_bull_up_stock(8, 0.03, result)[0] # log.info("===============================================") # def test_stock_concept(self): # self # def test_dmi_indicator(self): # 找出放量突破布林线中轴 # 高于昨日最高价3%以上 # 当日K线实体部分至少占80%的 # 认为有企稳信号 def test_bollinger_band(self): stocks = self.offline_stock_action.query_all_stock() for index, stock in stocks.iterrows(): all_prices = self.offline_stock_action.query_all_history_prices(stock['stock_code']) avg_vol = all_prices.tail(5)['volume'].mean() #5日均量 newest_price = all_prices.tail(1) close_price = newest_price['close'] newest_vol = newest_price['volume'] newest_high = newest_price['high'] newest_low = newest_price['low'] newest_open = newest_price['open'] last_high_price = all_prices.tail(2).head(1)['high'] last_close_price = all_prices.tail(2).head(1)['close'] if newest_high.item() > last_high_price.item()*1.03\ and (close_price.item() - newest_open.item()) > 0.8*(newest_high.item() - newest_low.item())\ and (newest_vol.item() > avg_vol.item()): upperband, middleband, lowerband = self.indicator_strategy.calculate_boll(all_prices['close']) if close_price.item() > middleband[len(middleband)-1] \ and last_close_price.item() < middleband[len(middleband)-2]: log.info("stock_info: %s(%s) close_price:%.2f, +%.2f%%", stock['display_name'],stock['stock_code'], close_price.item(), (close_price.item()-last_close_price.item())/last_close_price.item()*100) log.info("upper :%.2f; middle: %.2f; lower: %.2f", upperband[len(upperband)-1], middleband[len(middleband)-1], lowerband[len(lowerband)-1]) log.info("======================================================") pass if __name__ == "__main__": unittest.main() <file_sep>import logging import sys import datetime logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') logging.basicConfig(level=logging.ERROR, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') log = logging.getLogger(__name__) def get_user_name(): return input('name') def get_pwd(): return input('pwd') def view_bar(num, total, desc=''): r = '\r%d/%d%s' % (num, total, desc) sys.stdout.write(r) sys.stdout.flush() def view(content): r = '\r%s' % content sys.stdout.write(r) sys.stdout.flush() def get_today(): return datetime.datetime.utcnow() def get_yesterday(today): today = today + datetime.timedelta(-1) return today def add_day(day, delta): return day + datetime.timedelta(delta)<file_sep>import pymongo as mongo from config.config import * class BaseMongo: def __init__(self): self.db_client = mongo.MongoClient("mongodb://localhost:27017/") self.db = self.db_client.jqdata def close(self): self.db_client.close() def __del__(self): log.debug("close connection") self.close() <file_sep>### jqdatasdk demo ## 一个获取聚宽数据的demo。 使用mongodb持久化数据 技术指标使用TA-Lib ## 测试 test目录下是单元测试目录 <file_sep> class StrategyError(Exception): pass<file_sep>import datetime def convert_date_to_datetime(dates): res = [] for date in dates: res.append(datetime.datetime(date.year, date.month, date.day)) return res <file_sep>from backtesting.cci_backtesting import CCIBacktesing from backtesting.boll_backtesting import BollBacktesting from jqdemo.offline_stock_action import OfflineStockAction import pandas as pd import datetime import unittest class TestBacktesing(unittest.TestCase): def __init__(self, method_name): unittest.TestCase.__init__(self, method_name) self.offline_stock_action = OfflineStockAction() # def test_simple_backtesting(self): # stocks = self.offline_stock_action.get_all_stock() # sample_stocks = stocks.sample(100) # stock_codes = [] # profits = [] # for index, stock in sample_stocks.iterrows(): # simple_backtesting = SimpleBackTesting() # simple_backtesting.set_stock_code(stock['stock_code']) # profit = simple_backtesting.run() # stock_codes.append(stock['stock_code']) # profits.append(profit) # sample = { # 'stock_code': stock_codes, # 'profit': profits # } # sample_result = pd.DataFrame(sample) # sample_result.to_excel('./result/simple_backtesting-' + # str(datetime.datetime.strftime( # datetime.datetime.now(), '%Y%m%d%H%M%S' # )) +'.xlsx') # def test_cci_backtesting(self): # stocks = self.offline_stock_action.query_all_stock() # sample_stocks = stocks.sample(20) # stock_codes = [] # profits = [] # for index, stock in sample_stocks.iterrows(): # cci_backtesting = CCIBacktesing() # cci_backtesting.set_stock_code(stock['stock_code']) # profit = cci_backtesting.run() # stock_codes.append(stock['stock_code']) # profits.append(profit) # sample = { # 'stock_code': stock_codes, # 'profit': profits # } # sample_result = pd.DataFrame(sample) # sample_result.to_excel('./result/cci_backtesting-' + # str(datetime.datetime.strftime( # datetime.datetime.now(), '%Y%m%d%H%M%S' # )) +'.xlsx') def test_boll_backtesting(self): stocks = self.offline_stock_action.query_all_stock() sample_stocks = stocks.sample(100) stock_codes = [] profits = [] for index, stock in sample_stocks.iterrows(): boll_backtesting = BollBacktesting() stock_code = stock['stock_code'] boll_backtesting.set_stock_code(stock_code) profit = boll_backtesting.run() stock_codes.append(stock['stock_code']) profits.append(profit) sample = { 'stock_code': stock_codes, 'profit': profits } sample_result = pd.DataFrame(sample) sample_result.to_excel('./result/boll_backtesting-' + str(datetime.datetime.strftime( datetime.datetime.now(), '%Y%m%d%H%M%S' )) + '.xlsx') if __name__ == '__main__': unittest.main() <file_sep>from jqdemo.base_mongo import BaseMongo from jqdemo.base_jqdatasdk import BaseJQData class TickAction(BaseMongo, BaseJQData): pass<file_sep>from strategy import strategy_bull_up <file_sep>from jqdemo.base_mongo import BaseMongo import datetime import pandas as pd from config.config import * class OfflineStockAction(BaseMongo): def __init__(self): BaseMongo.__init__(self) def query_prices_by_stock_code_time(self, stock_code, count, end_date=get_today()): return pd.DataFrame(list(self.db.total_stock_price.find({"stock_code": stock_code, "trade_day": {"$lte": end_date}}) .sort([("trade_day", -1)]).limit(count))) def query_all_stock(self): return pd.DataFrame(list(self.db.base_stock.find({"type": "stock"}))) def query_by_stock_code(self, stock_code): return pd.DataFrame(list(self.db.base_stock.find( {"$and":[{"stock_code": {"$regex": stock_code + ".*"}}, {"type":"stock"}] }) .limit(1))) def query_price_by_stock_code(self, stock_code): return self.db.price.find({"stock_code": {"$regex": stock_code+".*"}}) def query_n_trade_days_before_today(self, count): today = datetime.datetime.today() result = self.db.trade_days.find({"trade_day": {"$lte": today}}) \ .sort([("trade_day", -1)]).limit(count) return result def query_all_history_prices(self, stock_code): return pd.DataFrame(list(self.db.total_stock_price.find({"stock_code": stock_code}))) def query_all_concepts(self): return pd.DataFrame(list(self.db.concepts.find({}))) def query_stock_concept(self, stock_code): return list(self.db.concept_stock_code.find({'stock_code': stock_code})) def query_stocks_by_concept(self, concept_code): return pd.DataFrame(list(self.db.concept_stock_code.find({'concept_code': concept_code}))) def query_valuations(self, stock_code_list): return pd.DataFrame(list(self.db.stock_valuations.find({'code' : {'$in': stock_code_list}}))) def query_last_prices(self, stock_list): trade_day = pd.DataFrame(list(self.query_n_trade_days_before_today(1)))['trade_day'][0] return pd.DataFrame(list(self.db.total_stock_price .find({'$and': [{'stock_code': {'$in': stock_list}}, {'trade_day': trade_day}]}))) def query_first_prices(self, stock_code_list): result = pd.DataFrame() for stock_code in stock_code_list: result.append(pd.DataFrame(list(self.db.total_stock_price.find({'stock_code': stock_code}).sort([('stock_code', 1)])\ .limit(1)))) return result def get_last_updated_time_of_stock(self): return self.db.stock_config.find_one()['updated_time'] def get_last_updated_time_of_trade_day(self): return self.db.trade_day_config.find_one()['updated_time'] def get_last_updated_time_of_locked_share(self): return self.db.locked_share_config.find_one()['updated_time'] <file_sep>from backtesting.base_backtesting import BaseBackTesing from jqdemo.offline_stock_action import OfflineStockAction from strategy.strategy_indicator import IndicatorStrategy from strategy.strategy_bull_up import BullUpStrategy from config.config import * import datetime import pandas as pd class CCIBacktesing(BaseBackTesing): def __init__(self): BaseBackTesing.__init__(self) self.stock_code = None self.offline_stock_action = OfflineStockAction() self.indicator_strategy = IndicatorStrategy() self.cci = None self.stock = None def set_stock_code(self, stock_code): self.stock_code = stock_code def is_buy_position(self, history_prices, current_price): pre_price = history_prices.tail(1) pre_price = pre_price.reset_index(drop=True) try: pre_cci = self.cci[self.cci['trade_day'] == pre_price['trade_day'][0] ] except IndexError: print(pre_price['trade_day'][0]) raise Exception("ERROR") cur_cci = self.cci[self.cci['trade_day'] == current_price['trade_day']] if float(pre_cci['cci']) < 100 < float(cur_cci['cci']): return True return False def buy_action(self, history_prices, current_price): cur_cci = self.cci[self.cci['trade_day'] == current_price['trade_day']] self.buy_position_percent_value(current_price=current_price, percent=round(float(cur_cci['cci'])/100, 1) - 0.5) def is_sell_position(self, history_prices, current_price): pre_price = history_prices.tail(1) pre_price = pre_price.reset_index(drop=True) pre_cci = self.cci[self.cci['trade_day'] == pre_price['trade_day'][0]] cur_cci = self.cci[self.cci['trade_day'] == current_price['trade_day']] if float(pre_cci['cci']) > 100 > float(cur_cci['cci']): return True return False def sell_action(self, history_prices, current_price): if self.position > 0: self.sell_position_percent_value(current_price=current_price, percent=1) def is_add_position(self, history_prices, current_price): super().is_add_position(history_prices=history_prices, current_price=current_price) def add_position_action(self, history_prices, current_price): super().add_position_action(history_prices=history_prices, current_price=current_price) def is_reduce_position(self, history_prices, current_price): super().is_reduce_position(history_prices=history_prices, current_price=current_price) def reduce_position_action(self, history_prices, current_price): super().reduce_position_action(history_prices=history_prices, current_price=current_price) def is_clear_position(self, history_prices, current_price): if self.position > 0: profit = self.balance - self.INIT_BALANCE if profit < 0 and (-profit)/self.INIT_BALANCE > 0.08: return True return False def clear_position_action(self, history_prices, current_price): super().sell_position_percent_value(current_price=current_price, percent=1) def buy_fee(self): return 5 def sell_fee(self): return 5 def end_backtesting(self, history_prices, current_price): if self.position > 0: self.sell_position_percent_value(current_price=current_price, percent=1) def buy_position_percent_value(self, current_price, percent): super().buy_position_percent_value(current_price, percent) def sell_position_percent_value(self, current_price, percent): super().sell_position_percent_value(current_price, percent) def run(self): if self.stock_code is None: raise Exception("stock code can not be None") self.stock = pd.DataFrame(self.offline_stock_action.query_by_stock_code(self.stock_code)) total_history_prices = self.offline_stock_action.query_all_history_prices( self.stock_code) ccis = self.indicator_strategy.calculate_cci(total_history_prices['high'], total_history_prices['low'], total_history_prices['close']) cci = { 'cci': ccis, 'trade_day': total_history_prices['trade_day'] } self.cci = pd.DataFrame(cci) super().run_backtesting(total_history_prices=total_history_prices, start_date=datetime.datetime(2018, 1, 1)) return float(round((self.balance - self.INIT_BALANCE)/self.INIT_BALANCE*100, 2)) <file_sep>import pandas as pd from jqdatasdk import * import jqdatasdk from config.config import * from jqdemo.util import * class BaseJQData: def __init__(self, user_name, pwd): log.debug("init jqdata") auth(user_name, pwd) @staticmethod def get_all_stocks(): today = datetime.datetime.today() all_stocks = get_all_securities(types=['stock', 'index', 'etf'], date=today) all_stocks['stock_code'] = all_stocks.index return all_stocks @staticmethod def get_all_trade_days(): all_trade_days = get_all_trade_days() all_trade_days = convert_date_to_datetime(all_trade_days) all_trade_days = pd.DataFrame(all_trade_days, columns=['trade_day']) return all_trade_days @staticmethod def get_locked_share(stock_list, start_day, count=500): locked_shares = get_locked_shares(stock_list=stock_list, start_date=start_day, forward_count=count) return locked_shares @staticmethod def get_price(stock_list, end_day, start_day): return get_price(stock_list, start_date=start_day, end_date=end_day, frequency='daily', fq='pre', fields=['open', 'close', 'low', 'high', 'volume', 'money', 'factor', 'high_limit', 'low_limit', 'avg', 'pre_close', 'paused']) @staticmethod def get_concepts(): return get_concepts() @staticmethod def get_concept_stocks(concept_code, date=None): return get_concept_stocks(concept_code=concept_code, date=date) @staticmethod def get_industry(stock_code, date): return get_industry(stock_code, date) @staticmethod def get_industries(name): return get_industries(name=name) @staticmethod def get_industry_stocks(industry_code, date=datetime.datetime.today()): return get_industry_stocks(industry_code, date) @staticmethod def get_valuations(date, stock_list): return get_fundamentals(date=date, query_object=query(valuation) .filter(valuation.code.in_(stock_list))) <file_sep>import pandas as pd import datetime import math from jqdemo.base_mongo import BaseMongo from jqdemo.base_jqdatasdk import BaseJQData from jqdemo.offline_stock_action import OfflineStockAction import config.config class StockAction(OfflineStockAction, BaseJQData): def __init__(self, user_name=config.get_user_name(), pwd=config.get_pwd()): OfflineStockAction.__init__(self) BaseJQData.__init__(self, user_name, pwd) def refresh_base_stock_info(self): self.db.base_stock.delete_many({}) self.db.base_stock.insert_many(self.get_all_stocks().to_dict('record')) self.db.stock_config.delete_many({}) self.db.stock_config.insert_one({"updated_time": config.get_today()}) def refresh_trade_days(self): self.db.trade_days.delete_many({}) self.db.trade_days.insert_many(self.get_all_trade_days().to_dict('record')) self.db.trade_day_config.delete_many({}) self.db.trade_day_config.insert_one({"updated_time": config.get_today()}) def refresh_locked_share(self): stocks = pd.DataFrame(list(self.db.base_stock.find({"type": "stock"}))) locked_share = self.get_locked_share(list(stocks["stock_code"]), start_day=config.get_today()) self.db.locked_share.delete_many({}) self.db.locked_share.insert_many(locked_share.to_dict('record')) self.db.locked_share_config.delete_many({}) self.db.locked_share_config.insert_one({"updated_time": config.get_today()}) def refresh_all_stock_price(self): stock_codes = list(self.get_all_stocks()['stock_code']) start_day = self.db.price_config.find_one() if start_day is None: self.db.price.delete_many({}) start_day = datetime.datetime(2019, 1, 1) else: start_day = start_day['updated_time'] print('last updated time: ', start_day) for i in range(len(stock_codes)): config.config.view_bar(i + 1, len(stock_codes)) prices = self.get_price(stock_codes[i], start_day=start_day, end_day=datetime.datetime.today()) prices['stock_code'] = stock_codes[i] prices['time'] = prices.index self.db.price.insert_many(prices.to_dict('record')) self.db.price_config.delete_many({}) self.db.price_config.insert_one({"updated_time": config.get_today()}) # 由于数据量巨大,需要单个获取,每次更新 def refresh_total_price(self, stock_code, start_day): all_price = self.get_price(stock_code, start_day=start_day, end_day=datetime.datetime.utcnow()) self.db.all_price.insert_many(all_price.to_dict('record')) return all_price # def refresh_total_stock_price(self, stocks): # self.db.total_stock_price.delete_many({}) # for i in range(len(stocks)): # all_price = self.get_price(stocks[i]['stock_code'], start_day=stocks[i]['start_date'], # end_day=datetime.datetime.utcnow()) # all_price['stock_code'] = stocks[i]['stock_code'] # all_price['trade_day'] = all_price.index # all_price['created_time'] = datetime.datetime.utcnow() # all_price['updated_time'] = datetime.datetime.utcnow() # self.db.total_stock_price.insert_many(all_price.to_dict('record')) # config.view_bar(i+1, len(stocks)) def append_stock_price(self, stock_code): newest_record = pd.DataFrame(list(self.db.total_stock_price.find({"stock_code": stock_code}) .sort([("trade_day", -1)]).limit(1))) end_day = config.add_day(datetime.datetime.today(), 1) end_day = end_day.strftime('%Y-%m-%d') if newest_record.count().size == 0: stock = pd.DataFrame(self.db.base_stock.find_one({"stock_code": stock_code}), index=[0]) start_day = stock['start_date'][0].strftime('%Y-%m-%d') else: start_day = config.add_day(newest_record['trade_day'], 1) start_day = start_day[0].strftime('%Y-%m-%d') config.log.debug('start_date : %s', str(start_day)) prices = self.get_price(stock_code, end_day=end_day, start_day=start_day) prices['stock_code'] = stock_code prices['trade_day'] = prices.index prices['created_time'] = datetime.datetime.today() prices['updated_time'] = datetime.datetime.today() indexes = [] for index, price in prices.iterrows(): if math.isnan(price['open']) and (math.isnan(price['paused']) or math.isnan(price['paused'])): config.log.debug('%s[%s] 未获取到新数据, drop此行', stock_code, index) indexes.append(index) pass else: pass prices.drop(indexes, axis=0, inplace=True) if prices.size > 0: self.db.total_stock_price.insert_many(prices.to_dict('record')) def refresh_valuations(self): self.db.stock_valuations.delete_many({}) stock_list = list(self.query_all_stock()['stock_code']) self.db.stock_valuations.insert_many(self.get_valuations(date=datetime.datetime.today(), stock_list=stock_list).to_dict('record')) def refresh_concepts(self): concepts = self.get_concepts() concepts['concept_code'] = concepts.index self.db.concepts.delete_many({}) self.db.concepts.insert_many(concepts.to_dict('record')) return concepts def refresh_concept_stocks(self): self.db.concept_stock_code.delete_many({}) result = pd.DataFrame() concepts = self.query_all_concepts() i = 1 for index, concept in concepts.iterrows(): config.view_bar(i, len(concepts.index)) stock_codes = self.get_concept_stocks(concept['concept_code']) temp = pd.DataFrame({'concept_code': concept['concept_code'], 'start_date': concept['start_date'], 'concept_name': concept['name'], 'stock_code': stock_codes, 'updated_time': datetime.datetime.today().strftime('%Y-%m-%d')}) result = result.append(temp) i = i + 1 self.db.concept_stock_code.insert_many(result.to_dict('record')) return result def __del__(self): BaseMongo.__del__(self) <file_sep>import unittest import datetime import unittest from strategy.strategy_index_calculator import IndexCalculatorStategy from jqdemo.offline_stock_action import OfflineStockAction from jqdemo.stock_action import StockAction from config.config import * class TestConceptIndex(unittest.TestCase): def __init__(self, method_name): unittest.TestCase.__init__(self, method_name) self.index_strategy = IndexCalculatorStategy() self.offline_stock_action = OfflineStockAction() def test_concept_index(self): self.index_strategy.calculate_concept_index('GN086') pass if __name__ == '__main__': unittest.main()<file_sep>import pandas as pd from strategy.base_strategy import BaseStrategy from jqdemo.offline_stock_action import OfflineStockAction from config.config import * from strategy.error import StrategyError from strategy.strategy_indicator import IndicatorStrategy class BullUpStrategy(BaseStrategy): def __init__(self): self.stock_action = OfflineStockAction() self.indicator_strategy = IndicatorStrategy() BaseStrategy.__init__(self) def list_bull_up_stock(self, count, up_thread_hold, stock_list=None, end_day=get_today(), prices=None, safe_flag=False): log.debug("当前条件为, %s日下跌之后进行放量反弹,并且超过前日最高价%s%%", str(count - 1), str(up_thread_hold * 100)) if stock_list is None: stock_list = self.stock_action.query_all_stock() # stock_code_list = stocks['stock_code'] result = pd.DataFrame() result_price = pd.DataFrame() i = 1 for index, stock in stock_list.iterrows(): i = i+1 if prices is None: prices = self.stock_action.query_prices_by_stock_code_time(stock['stock_code'], count=count, end_date=end_day) else: pass if prices is None: raise StrategyError(str(count) + "日价格为空") ratio = self.is_bull_up(prices, up_thread_hold, count) if ratio is not None: is_clash_the_top = False str_f = "NOTICE ==> %s\n[%s 当前收盘 %s(最高价 %s) 涨幅 %.2f%%(最高涨幅 %.2f%%) " \ "建议止损位 %s 压力位 %s" if ratio[3]*100 > 9.6 and ratio[1]*100 < ratio[3]*100: is_clash_the_top = True if safe_flag is False: # 忽略掉开板股票 log.info(str_f + " 警惕开板风险]", str(stock['stock_code']), str(stock['display_name']), str(ratio[0]), str(ratio[2]), ratio[1] * 100, ratio[3] * 100, ratio[4], ratio[5]) elif ratio[0] == ratio[2]: log.info(str_f + " 强势光头阳,值得关注]", str(stock['stock_code']), str(stock['display_name']), str(ratio[0]), str(ratio[2]), ratio[1] * 100, ratio[3] * 100, ratio[4], ratio[5]) else: log.info(str_f + "]", str(stock['stock_code']), str(stock['display_name']), str(ratio[0]), str(ratio[2]), ratio[1] * 100, ratio[3] * 100, ratio[4], ratio[5]) stock['stop_loss_price'] = ratio[4] stock['pressure_price'] = ratio[5] if safe_flag is False or is_clash_the_top is False: result = result.append(stock) result_price = result_price.append(prices) return [result, result_price] def is_bull_up(self, prices, thread_hold, count): if len(prices) < 4: log.warning("%s时间太短", str(prices['stock_code'][0])) return None prices.sort_values(by="trade_day", ascending=False, inplace=True) prices = prices.reset_index(drop=True) close_price = prices['close'][0] high_price = prices['high'][0] last_high = prices['high'][1] last_close = prices['close'][1] take_profit_price = 0 i = 1 while i < len(prices)-1: i = i + 1 if last_high < prices['high'][i]: last_high = prices['high'][i] else: take_profit_price = last_high break if i > (count - 1) and prices['volume'][0] > self.calculate_avg_vol(prices) \ and close_price > prices['high'][1] * (1+thread_hold): # TODO 找出来近期高位 return [close_price, close_price/prices['close'][1]-1, high_price, high_price/prices['close'][1]-1, last_close, take_profit_price] return None @staticmethod def calculate_avg_vol(prices): avg_volume = prices['volume'].mean() return avg_volume <file_sep>from abc import ABCMeta, abstractmethod from config.config import * class BaseBackTesing: def __init__(self): self.INIT_BALANCE = 30 * 1000 self.MAX_VALUE = 9999 self.position = 0 self.profit_times = 0 self.loss_time = 0 self.profit_money = 0 self.loss_money = 0 self.cost_price = 0 self.balance = self.INIT_BALANCE #默认30,000 self.buy_fees = 0 self.sell_fees = 0 self.sell_times = 0 self.buy_times = 0 @abstractmethod def is_buy_position(self, history_prices, current_price): return True @abstractmethod def buy_action(self, history_prices, current_price): pass @abstractmethod def is_sell_position(self, history_prices, current_price): return False @abstractmethod def sell_action(self, history_prices, current_price): pass @abstractmethod def is_add_position(self, history_prices, current_price): return False @abstractmethod def add_position_action(self, history_prices, current_price): pass @abstractmethod def is_reduce_position(self, history_prices, current_price): return False @abstractmethod def reduce_position_action(self, history_prices, current_price): pass @abstractmethod def is_clear_position(self, history_prices, current_price): return False @abstractmethod def clear_position_action(self, history_prices, current_price): pass @abstractmethod def buy_fee(self): return 5 @abstractmethod def sell_fee(self): return 5 @abstractmethod def end_backtesting(self, history_prices, current_price): pass # 计算买入 percent仓位之后的账户属性 def buy_position_percent_value(self, current_price, percent): if float(percent) < 0: raise Exception("can not buy below 0") if float(percent) > 1: log.warning("percent is set 1") percent = 1 # 以close价格买入percent 仓 close_price = current_price['close'] # 计算余额可以买入的最大数量 max_stock_num = (self.balance - self.buy_fee()) // (close_price * 100) * 100 buy_num = max_stock_num * percent // 100 * 100 if buy_num <= 0: log.warning("[%s]无法买入,余额不足,当前余额 : %.2f, 当前close:%.2f", current_price['trade_day'], self.balance, close_price) log.warning("最大可买%.2f, 买入 %.2f, percent %.2f", max_stock_num, buy_num, percent) else: current_spend = close_price * buy_num + self.buy_fee() log.info("[%s]当前余额:%.2f\t买入后余额:%.2f\t能够买入最大数量 %d\t买入数量 %d\t买入单价%.2f", current_price['trade_day'], self.balance, self.balance - current_spend, max_stock_num, buy_num, close_price) self.balance -= current_spend self.position += buy_num self.buy_fees += self.buy_fee() # TODO self.buy_times += 1 self.cost_price = (self.INIT_BALANCE - self.balance) / self.position log.info("[%s]买入成功,当前余额:%.2f\t持仓 %d\t成本价: %.2f", current_price['trade_day'], self.balance, self.position, self.cost_price) def sell_position_percent_value(self, current_price, percent): if percent < 0: raise Exception("can not sell below 0") if percent > 1: log.warning("percent is set 1") percent = 1 close_price = current_price['close'] # 计算卖出数量 sell_position = self.position * percent if sell_position == 0: log.warning("[%s]无法卖出,持仓为 0 ", current_price['trade_day']) else: added_balance = close_price * sell_position - self.sell_fee() self.balance += added_balance self.position = self.position - sell_position if self.position == 0: self.cost_price = 0 else: self.cost_price = (self.INIT_BALANCE - self.balance) / self.position self.sell_times += 1 self.sell_fees += self.sell_fee() log.info("[%s]卖出(%.2f)成功, 当前余额: %.2f\t仓位 %d\t成本价 %.2f", current_price['trade_day'], current_price['close'], self.balance, self.position, self.cost_price) def run_backtesting(self, total_history_prices, start_date): trade_prices = total_history_prices[total_history_prices['trade_day'] >= start_date]\ .sort_values(by='trade_day', ascending=True) his_prices = total_history_prices[total_history_prices['trade_day'] < start_date]\ .sort_values(by='trade_day', ascending=True) for index, day in trade_prices.iterrows(): if self.is_clear_position(his_prices, day): self.clear_position_action(his_prices, day) elif self.position <= 0 and self.is_buy_position(his_prices, day): self.buy_action(his_prices, day) if self.position > 0 and self.is_add_position(his_prices, day): self.add_position_action(his_prices, day) if self.position > 0 and self.is_reduce_position(his_prices, day): self.reduce_position_action(his_prices, day) if self.position > 0 and self.is_sell_position(his_prices, day): self.sell_action(his_prices, day) his_prices = his_prices.append(day) # view(str(his_prices['trade_day'].tail(1))) # print(day['trade_day']) # last_day = trade_prices.tail(1) self.end_backtesting(history_prices=his_prices, current_price=trade_prices.tail(1)) # 如果当前持仓全部尾盘卖掉,计算盈利 # log.info("回测结束,尾盘%.2f卖掉全部持仓,实现盈利为 %.2f", last_day['close'], # (last_day['close']-self.cost_price)*self.position) log.info("回测结束,收益%.2f(%.2f%%),买入%d次,卖出%d次", self.balance-self.INIT_BALANCE, (self.balance-self.INIT_BALANCE)/self.INIT_BALANCE*100, self.buy_times, self.sell_times) <file_sep>from backtesting.base_backtesting import BaseBackTesing from jqdemo.offline_stock_action import OfflineStockAction from strategy.strategy_indicator import IndicatorStrategy from strategy.strategy_bull_up import BullUpStrategy from config.config import * import datetime import pandas as pd class BollBacktesting(BaseBackTesing): def __init__(self): super().__init__() self.stock_code = None self.offline_stock_action = OfflineStockAction() self.indicator_strategy = IndicatorStrategy() self.boll = None self.stock = None self.buy_date = None def set_stock_code(self, stock_code): self.stock_code = stock_code def is_buy_position(self, history_prices, current_price): all_prices = history_prices avg_vol = all_prices.tail(5)['volume'].mean() # 5日均量 newest_price = all_prices.tail(1) close_price = newest_price['close'] newest_vol = newest_price['volume'] newest_high = newest_price['high'] newest_low = newest_price['low'] newest_open = newest_price['open'] last_high_price = all_prices.tail(2).head(1)['high'] last_close_price = all_prices.tail(2).head(1)['close'] try: if newest_high.item() > last_high_price.item() * 1.03 \ and (close_price.item() - newest_open.item()) > 0.8 * (newest_high.item() - newest_low.item()) \ and (newest_vol.item() > avg_vol.item()): upperband = self.boll['upperband'] middleband = self.boll['middleband'] lowerband = self.boll['lowerband'] if close_price.item() > middleband[len(middleband) - 1] \ and last_close_price.item() < middleband[len(middleband) - 2]: log.info("stock_info: %s(%s) close_price:%.2f, +%.2f%%", self.stock['display_name'], self.stock['stock_code'], close_price.item(), (close_price.item() - last_close_price.item()) / last_close_price.item() * 100) log.info("upper :%.2f; middle: %.2f; lower: %.2f", upperband[len(upperband) - 1], middleband[len(middleband) - 1], lowerband[len(lowerband) - 1]) log.info("======================================================") self.buy_date = datetime.datetime.strptime(str(current_price['trade_day']).split(" ")[0], '%Y-%m-%d') return True except ValueError: print(newest_high) return False return False def buy_action(self, history_prices, current_price): self.buy_position_percent_value(current_price, 1) def is_sell_position(self, history_prices, current_price): if self.buy_date is not None \ and self.position > 0: cur_date = datetime.datetime.strptime(str(current_price['trade_day']).split(" ")[0], '%Y-%m-%d') print((cur_date - self.buy_date).days) if (cur_date - self.buy_date).days > 3: self.buy_date = None log.info("持有超过2天,卖出") return True return False def sell_action(self, history_prices, current_price): self.sell_position_percent_value(current_price, 1) def is_add_position(self, history_prices, current_price): super().is_add_position(history_prices, current_price) def add_position_action(self, history_prices, current_price): super().add_position_action(history_prices, current_price) def is_reduce_position(self, history_prices, current_price): super().is_reduce_position(history_prices, current_price) def reduce_position_action(self, history_prices, current_price): super().reduce_position_action(history_prices, current_price) def is_clear_position(self, history_prices, current_price): if self.position > 0: profit = self.position*current_price['open'] - self.INIT_BALANCE print(profit) if profit < 0 and (-profit)/self.INIT_BALANCE > 0.08: log.info("触及止损,清仓") return True return False def clear_position_action(self, history_prices, current_price): super().sell_position_percent_value(current_price=current_price, percent=1) def buy_fee(self): return super().buy_fee() def sell_fee(self): return super().sell_fee() def end_backtesting(self, history_prices, current_price): if self.position > 0: self.sell_position_percent_value(current_price, 1) def buy_position_percent_value(self, current_price, percent): # 早盘就卖 current_price['close'] = current_price['open'] return super().buy_position_percent_value(current_price, percent) def sell_position_percent_value(self, current_price, percent): return super().sell_position_percent_value(current_price, percent) def run(self): if self.stock_code is None: raise Exception("stock code can not be None") self.stock = pd.DataFrame(self.offline_stock_action.query_by_stock_code(self.stock_code)) total_history_prices = self.offline_stock_action.query_all_history_prices( self.stock_code) upperband, middleband, lowerband = self.indicator_strategy.calculate_boll(total_history_prices['close']) bollinger = { 'upperband' : upperband, 'middleband': middleband, 'lowerband': lowerband, 'trade_day': total_history_prices['trade_day'] } self.boll = pd.DataFrame(bollinger) super().run_backtesting(total_history_prices=total_history_prices, start_date=datetime.datetime(2018, 1, 1)) return float(round((self.balance - self.INIT_BALANCE)/self.INIT_BALANCE*100, 2))<file_sep>import talib class BaseStrategy: n5 = 5 n10 = 10 def __init__(self): pass def macd(self): pass<file_sep>import datetime import unittest from strategy.strategy_indicator import IndicatorStrategy from jqdemo.offline_stock_action import OfflineStockAction from jqdemo.stock_action import StockAction from config.config import * class TestDrawPic(unittest.TestCase): def __init__(self, method_name): unittest.TestCase.__init__(self, method_name) def test_draw_wave_buy_and_sell_point(self): print(datetime.datetime.today().strftime('%Y-%m-%d')) pass if __name__ == '__main__': unittest.main()
7eac43b1d41b9ea1210ff764d4cd2c25c5baace5
[ "Markdown", "Python" ]
25
Python
msmpy2002/jqdatasdk_demo
0b71d0e78e3d2a1b7fee6bf3c1d17fe13c3c420b
ac9f13ee7fe046e01a379739d0830fccd57ba3c5
refs/heads/master
<repo_name>LinDDL/jumeiyouping<file_sep>/script/res.js var pass; var pass1; var pass2; $("#username").on("blur",function(){ var oUsername=$("#username").val(); var regName=/^1[3|4|5|8][0-9]\d{4,8}$/; if(regName.test(oUsername)){ $(".the_one").css({ "display":"inline", }) $("#number").removeClass("failline"); $("#number .invalid").css({ "display":"none" }) pass=true; }else{ $("#number").addClass("failline"); $("#number .invalid").css({ "display":"block" }) pass=false; } }) $("#password").on("blur",function(){ var oPassword=$("#password").val(); var regPdw=/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$/; if(regPdw.test(oPassword)){ $(".the_two").css({ "display":"inline", }) $("#pword").removeClass("failline"); $("#pword .invalid").css({ "display":"none" }) pass1=true; }else{ $("#pword").addClass("failline"); $("#pword .invalid").css({ "display":"block" }) pass1=false; } }) $("#password2").on("blur",function(){ var oPassword2=$("#password2").val(); var oPassword=$("#password").val(); if(oPassword2==oPassword){ $(".the_three").css({ "display":"inline", }) $("#pword2").removeClass("failline"); $("#pword2 .invalid").css({ "display":"none" }) pass2=true; }else{ $("#pword2").addClass("failline"); $("#pword2 .invalid").css({ "display":"block" }) pass2=false; } }) var oBtn = document.getElementById("btn"); var oUser = document.getElementById("username"); var oPwd = document.getElementById("password"); $("#btn").on("click",function(){ console.log(pass) if(pass&&pass1&&pass2){ $.ajax({ url:"http://localhost:8001/proxy/localhost/php/res.php", type:"GET", data:`username=${oUser.value}&password=${oPwd.value}`, datatype:"html", success:function(res){ alert(res); $("#username").val(""); $("#password").val(""); $("#password2").val(""); $(".the_one").css({ "display":"none", }) $(".the_two").css({ "display":"none", }) $(".the_three").css({ "display":"none", }) setTimeout(function(){ location.href="jumei_login.html" },3000) } }) } })<file_sep>/script/jumei_login_success.js (function(window, document, undefined) { var dog = {//声明一个命名空间,或者称为对象 $ : function(id) { return document.querySelector(id); }, on : function(el, type, handler) { el.addEventListener(type, handler, false); }, off : function(el, type, handler) { el.removeEventListener(type, handler, false); } }; //封装一个滑块类 function Slider() { var args = arguments[0]; for ( var i in args) { this[i] = args[i]; //一种快捷的初始化配置 } //直接进行函数初始化,表示生成实例对象就会执行初始化 this.init(); } Slider.prototype = { constructor : Slider, init : function() { this.getDom(); this.dragBar(this.handler); }, getDom : function() { this.slider = dog.$('#' + this.id); this.handler = dog.$('.handler'); this.bg = dog.$('.drag_bg'); // console.log(this.slider); }, dragBar : function(handler) { var that = this, startX = 0, lastX = 0, doc = document, width =261, max = width- handler.offsetWidth, drag = { down : function(e) { var e = e || window.event; that.slider.classList.add('unselect'); //console.log(this.slider,width); startX = e.clientX - handler.offsetLeft; //console.log('startX: ' + startX + ' px'); dog.on(doc, 'mousemove', drag.move); dog.on(doc, 'mouseup', drag.up); return false; }, move : function(e) { var e = e || window.event; lastX = e.clientX - startX; lastX = Math.max(0, Math.min(max, lastX)); //这一步表示距离大于0小于max,巧妙写法 //console.log('lastX: ' + lastX + ' px'); if (lastX >= max) { handler.classList.add('handler_ok_bg'); that.slider.classList.add('slide_ok'); dog.off(handler, 'mousedown', drag.down); drag.up(); } that.bg.style.width = lastX + 'px'; handler.style.left = lastX + 'px'; }, up : function(e) { var e = e || window.event; that.slider.classList.remove('unselect'); if (lastX < width) { that.bg.classList.add('ani'); handler.classList.add('ani'); that.bg.style.width = 0; handler.style.left = 0; setTimeout(function() { that.bg.classList.remove('ani'); handler.classList.remove('ani'); }, 300); } dog.off(doc, 'mousemove', drag.move); dog.off(doc, 'mouseup', drag.up); } }; dog.on(handler, 'mousedown', drag.down); } }; window.S = window.Slider = Slider; })(window, document); var defaults = { id : 'slider' }; new S(defaults);<file_sep>/script/jumei_login_more.js $(function(){ //登录选项卡 $(".radiobox span").click(function(){ $(".radiobox span") .eq($(this).index()) $(".logo_box .in_box").hide() .eq($(this).index()) .show() }); //更多部分的特效,点击出现更多模块。并改变图标背景图的位置 var index=0; $(".more").on("click",function(){ index++; $(".icon-p").slideToggle(); if(index%2==0){ $('.more i').css({ "background-position": "-274px -23px" }) }else{ $('.more i').css({ "background-position": "-274px 0" }) } }) var str=window.location.hash; var list = str.split("http://localhost:8001/jumei_login.html?"); if(list.indexOf("bylogin")==1){ $("#logins").css({"display":"block;"}) $("#ress").css({"display":"none;"}) }else if(list.indexOf("byres")==1){ $("#logins").css({"display":"none;"}) $("#ress").css({"display":"block;"}) } }) <file_sep>/dist/script/right_nav.js $(function(){ //鼠标划入btn_login显示login_box,划出隐藏 //这里涉及延时器,当划入login_box,使其显示 $(".btn_login").on("mouseenter",function(){ $(".login_box").css({ "display":"block", }) }) var timer=null; $(".btn_login").on("mouseleave",function(){ timer=setTimeout(function(){ $(".login_box").css({ "display":"none", }) },500) }) $(".login_box").on("mouseenter",function(){ clearTimeout(timer); }) $(".login_box").on("mouseleave",function(){ $(".login_box").css({ "display":"none", }) }) $(".close_btn").on("click",function(){ $(".login_box").css({ "display":"none", }) }) //显示元素 //特效为1.显示 // 2.从左向右滑动 $(".main_panel .btn_li").on("mouseenter",function(){ $(".panel_top .btn_li") .eq($(this).index()) $(this).children(".tool_text").css({ "visibility":"visible", "left":"-92px", "opacity":"1" }) }) $(".main_panel .btn_li").on("mouseleave",function(){ $(".panel_top .btn_li") .eq($(this).index()) $(this).children(".tool_text").css({ "visibility":"hidden", "left":"-122px", "opacity":"0" }) }) //鼠标划入btn_code显示np_code,划出隐藏 //这里涉及延时器,当划入login_box,使其显示 $(".btn_code").on("mouseenter",function(){ $(".np_code").css({ "display":"block", }) }) var timer=null; $(".btn_code").on("mouseleave",function(){ timer=setTimeout(function(){ $(".np_code").css({ "display":"none", }) },500) }) $(".np_code").on("mouseenter",function(){ clearTimeout(timer); }) $(".np_code").on("mouseleave",function(){ $(".np_code").css({ "display":"none", }) }) $(".np_code").on("click",function(){ $(".np_code").css({ "display":"none", }) }) //返回顶部效果 $(window).on('scroll',function(){ //console.log($("html,body").scrollTop()); if($("html,body").scrollTop()>200){ $(".btn_gotop").css({ 'visibility': 'visible', }) }else{ $(".btn_gotop").css({ 'visibility': 'hidden', }); } }) $(".btn_gotop").on("click",function(){ $("html,body").scrollTop(0); }) //详情页的 $(".nav_store_name").on("mouseenter",function(){ $(".dec").css({ "display":"block", }) }) var timer=null; $(".nav_store_name").on("mouseleave",function(){ timer=setTimeout(function(){ $(".dec").css({ "display":"none", }) },500) }) $(".dec").on("mouseenter",function(){ clearTimeout(timer); }) $(".dec").on("mouseleave",function(){ $(".dec").css({ "display":"none", }) }) }) <file_sep>/dist/script/gouwuche.js function ShopCar(){} $.extend(ShopCar.prototype,{ init:function(){ this.main = $("#today_now_goods") this.loadJson() .done(function(res){ this.addData(res);; }) this.bindEvent(); this.listSum(); // console.log($(".car_box>div")); }, loadJson:function(){ var opt = { url:"https://list.mogujie.com/search", dataType:"jsonp", data:{page:this.page}, context:this } return $.ajax(opt); }, bindEvent:function(){ //增加购物车商品 $("#today_now_goods").on("click","button",this.addCar.bind(this)); //鼠标移入显示在购物车的商品 $(".car_box>div").on("mouseenter",this.showList.bind(this)); //移除影藏 $(".car_box>div").on("mouseleave",function(){ $(".goods_list").children().remove(); }); $(".car_box>div").on("click",function(event){ var target = event.target ; if(target != $(".car_box>div")[0]) return 0; $.removeCookie("shopCar"); // 执行鼠标移出事件; $(".car_box>div").triggerHandler("mouseleave"); this.listSum(); }.bind(this)); //点击进入购物车页面 $(".car_box>div").on("click",function(){ location.href = "gouwuche.html"; }) //点击侧边购物车,显示侧边购物车 $(".btn_cart").on("click",function(){ $("#iBarCart").css({ "display":"block", }) }) //点击关闭侧边购物车 $(".close_btn").on("click",function(){ $("#iBarCart").css({ "display":"none", }) }) }, addData:function(json1){ this.json=json1.result.wall.list; //console.log(this.json) }, addCar:function(event){ var target = event.target ; var goodsId = $(target).attr("rel-id"); //console.log(goodsId) var cookie; var hasGoods = false; //console.log($.cookie("shopCar")) if((cookie = $.cookie("shopCar"))){ var cookieArray = JSON.parse(cookie); // console.log(cookieArray,cookieArray.length); for(var i = 0 ; i < cookieArray.length ; i ++){ if(cookieArray[i].iid == goodsId ) { hasGoods = true; cookieArray[i].num ++; break; } } if(hasGoods == false){ var goods = { iid : goodsId, num : "1" } cookieArray.push(goods); } $.cookie("shopCar",JSON.stringify(cookieArray)); }else{ $.cookie("shopCar",`[{"iid":"${goodsId}","num":"1"}]`); } //console.log($.cookie("shopCar")); this.listSum(); } , showList:function(event){ var target = event.target; if(target != $(".car_box>div")[0]) return 0; //console.log($(".car_box>div")); var cookie; if(!(cookie = $.cookie("shopCar"))){ return 0; }; var cookieArray = JSON.parse(cookie); //console.log(cookieArray); var html = ""; var html2=""; for(var i = 0 ; i < cookieArray.length ; i ++){ //console.log(this.json) for(var j = 0 ; j < this.json.length ; j ++){ if(cookieArray[i].iid == this.json[j].iid){ html += ` <li class="btn_cart"> <div class="cart_con_over cart_con_single"> <div class="single_pic"> <a href="javascript:void(0)"> <img src="${this.json[j].show.img}"> </a> </div> <div class="single_info"> <a href="javascript:void(0)" class="name">${this.json[j].title}</a> <span class="price">${this.json[j].price}</span> <span class="price_plus"> x </span> <span class="price_num">${cookieArray[i].num}</span> </div> </div> `; html2+=`<li class="ibar_cart_item clearfix"> <div class="ibar_cart_item_pic"> <a target="_blank" title="${this.json[j].title}" href="javascript:void(0)"> <img src="${this.json[j].show.img}"> <span class="ibar_cart_item_tag png"></span> </a> </div> <div class="ibar_cart_item_desc"> <span class="ibar_cart_item_name_wrapper"> <span class="ibar_cart_item_global">[极速免税]</span> <a class="ibar_cart_item_name" title="${this.json[j].title}>${this.json[j].title}</a> </span> <div class="ibar_cart_item_sku ibar_text_ellipsis"> <span title=" 100g">型号: 100g</span> </div> <div class="ibar_cart_item_price ibar_pink"> <span class="unit_price">${this.json[j].price}</span> <span class="unit_plus"> x </span> <span class="ibar_cart_item_count">${cookieArray[i].num}</span> </div> </div> </li> ` break; } } } // $("#car_wrap")[0].style.cssText = 'display:block; z-index:4 ' $(".goods_list").html(html); $(".ibar_cart_group_items").html(html2); }, listSum:function(){ var cookie; if(!(cookie = $.cookie("shopCar"))){ $(".totle").html(0); return 0; }; var cookieArray = JSON.parse(cookie); var sum = 0; for(var i = 0 ; i < cookieArray.length ; i ++){ sum += Number(cookieArray[i].num); } $(".totle").html(sum); $(".car_count").html(sum); $(".ibar_cart_total_quantity").html(sum); } }) var car = new ShopCar(); car.init();<file_sep>/script/movein.js $(function(){ $('.img_box_href').on("mouseenter",function(){ $('.commit_new').css({ "display":"block", }) $('.add_cart_box').css({ "display":"block", }); }) $('.img_box_href').on("mouseleave",function(){ timer=setTimeout(function(){ $('.commit_new').css({ "display":"none", }); $('.add_cart_box').css({ "display":"none", }); },100) }) $(".commit_new").on("mouseenter",function(){ clearTimeout(timer); }) $(".add_cart_box").on("mouseenter",function(){ clearTimeout(timer); }) }) <file_sep>/dist/script/particulars_page.js function WaterFall(){} $.extend(WaterFall.prototype,{ //初始化 init:function(){ //当前页数 this.page=1; this.main = $(".model_right"); //判断是否在加载中 this.loading = false; //和promise .then相似 this.loadJson() //返回值是deferred对象(promise前身) .done(function(res){ // deferred 的 done 回调 this指向的都是 jquery 对象本身 //console.log(res.list); this.renderPage(res.datalist); console.log(res.datalist) }) this.bindEvent(); }, //加载数据 loadJson:function(){ var opt = { // url:"http://www.wookmark.com/api/json/popular", url:"http://lancome.jumei.com/Ajax/GetModuleByMId?arrModuleId%5B%5D=47586&arrModuleId%5B%5D=47587&storeid=101&is_review=0", dataType:"jsonp", // data:{page:this.page}, // //this ===>指向实例化对象 context:this } return $.ajax(opt); }, //渲染页面 renderPage:function(json1){ //console.log(json1); var json=json1; //console.log(json) var html=""; for( var i=0; i<json.length; i++){ // var height = json[i].height/(json[i].width/220); // if(isNaN(height)) continue; // html +=` // <div class="box" style="height:${height}px"> // <img src="${json[i].show.img}" alt=""> // </div> // ` // console.log(json[i].price) // } //var height = json[i].height; // if(isNaN(height)) continue; html +=` <div id="model_彩妆系列" mid="47585" productnum="15" sidebar_img="0" shelf_img="0" moduletypeid="6" style="background: none; height: auto; opacity: 1;" loaded="true"> <div class="series_title"> <h2> <a target="_blank" class="title_text" style="color:#ffffff;" href="javascript:void(0)">彩妆系列</a> <a target="_blank" class="title_more" style="color:#ffffff;" href="http://lancome.jumei.com/search.html?series=1948&amp;from=store_lancome_index_804_47585_1">更多》</a> </h2> </div> <div id="search_list_wrap"> <div class="products_wrap"> <ul> <li class="formall item left" pid="13051" bid="3660" cid="23" search_product_type="mall" product_type="mall_product"> <div class="item_wrap clearfix"> <div class="item_wrap_right deal_item_wrap"> <div class="s_l_pic"> <a href="http://mall.jumei.com/product_13051.html?from=store_lancome_index_804_47585_1&amp;site=bj" target="_blank"> <div class="qiang_guang"></div> <img original="http://p0.jmstatic.com/product/000/013/13051_std/13051_350_350.jpg" width="255" height="255" src="http://p0.jmstatic.com/product/000/013/13051_std/13051_350_350.jpg" style="display:inline;"> </a> </div> <div class="s_l_name"> <a href="http://mall.jumei.com/product_13051.html?from=store_lancome_index_804_47585_1" target="_blank"> <span class="disc"> </span> Lancome <em class="pink"></em> 法国•兰蔻 (Lancome)速洁眼部卸妆水 30ml </a> </div> <div class="s_l_view_bg"> <div class="icon_wrap_bot clearfix"> </div> <div class="search_list_price"> <label>¥</label> <span>49.9</span> <div class="saleinfos"> </div> </div> </div> <div class="search_deal_buttom_bg clearfix"> <div class="search_pl"> 2861篇评价| </div> <div class="rating"> <div style="width:94" class="value"></div> </div> </div> <div class="search_list_button"> <a target="_blank" class="btn_notice" href="http://www.jumei.com/i/deal/mobile_subscribe/?id=13051" data-sku="" data-from="store_lancome_index_804_47585_1" title="到货通知"> </a> <a href="javascript:;" class="btn_fav" pid="13051" title="收藏商品"></a> </div> <p class="search_list_tags"> <span>清洁</span> <span>滋润</span> <span>温和</span> </p> </div> </div> </li> <li class="formall item left" pid="193895" bid="3660" cid="23" search_product_type="mall" product_type="mall_product"> <div class="item_wrap clearfix"> <div class="item_wrap_right deal_item_wrap"> <div class="s_l_pic"> <a href="http://mall.jumei.com/product_193895.html?from=store_lancome_index_804_47585_1" target="_blank"> <img original="http://p0.jmstatic.com/product/000/193/193895_std/193895_350_350.jpg" width="255" height="255" src="http://p0.jmstatic.com/product/000/193/193895_std/193895_350_350.jpg" style="display:inline;"> </a> </div> <div class="s_l_name"> <a href="http://mall.jumei.com/product_193895.html?from=store_lancome_index_804_47585_1" target="_blank"> <span class="disc"> </span> Lancome <em class="pink"></em> 法国•兰蔻 (Lancome)梦魅睛灵防水睫毛膏01# 6.5g/6.5ml </a> </div> <div class="s_l_view_bg"> <div class="icon_wrap_bot clearfix"> </div> <div class="search_list_price"> <label>¥</label> <span>269</span> <div class="saleinfos"> </div> </div> </div> <div class="search_deal_buttom_bg clearfix"> <div class="search_pl"> 110篇评价| </div> <div class="rating"> <div style="width:100" class="value"></div> </div> </div> <div class="search_list_button"> <a target="_blank" class="track_click btn_addcart" track_click="b2c/product_193895/buy_list" data-sku="" data-from="store_lancome_list__list_items_index_" title="加入购物车"> </a> <a href="javascript:;" class="btn_fav" pid="193895" title="收藏商品"></a> </div> <p class="search_list_tags"> <span>睫毛增长</span> </p> </div> </div> </li> <li class="formall item left" pid="362169" bid="3660" cid="23" search_product_type="mall" product_type="mall_product"> <div class="item_wrap clearfix"> <div class="item_wrap_right deal_item_wrap"> <div class="s_l_pic"> <a href="http://mall.jumei.com/product_362169.html?from=store_lancome_index_804_47585_1" target="_blank"> <img original="http://p0.jmstatic.com/product/000/362/362169_std/362169_350_350.jpg" width="255" height="255" src="http://p0.jmstatic.com/product/000/362/362169_std/362169_350_350.jpg" style="display:inline;"> </a> </div> <div class="s_l_name"> <a href="http://mall.jumei.com/product_362169.html?from=store_lancome_index_804_47585_1" target="_blank"> <span class="disc"> <em>包邮</em> / </span> Lancome <em class="pink"></em> 法国•兰蔻 (Lancome)梦魅巨星璀璨睫毛膏01# 6.5g/ml </a> </div> <div class="s_l_view_bg"> <div class="icon_wrap_bot clearfix"> </div> <div class="search_list_price"> <label>¥</label> <span>340</span> <div class="saleinfos"> </div> </div> </div> <div class="search_deal_buttom_bg clearfix"> <div class="search_pl"> 97篇评价| </div> <div class="rating"> <div style="width:100" class="value"></div> </div> </div> <div class="search_list_button"> <a target="_blank" class="track_click btn_addcart" track_click="b2c/product_362169/buy_list" data-sku="" data-from="store_lancome_list__list_items_index_" title="加入购物车"> </a> <a href="javascript:;" class="btn_fav" pid="362169" title="收藏商品"></a> </div> <p class="search_list_tags"> <span>眼部造型</span> <span>装扮</span> </p> </div> </div> </li> </ul> <div class="clear"></div> </div> </div> </div> ` //console.log(json[i].price) } this.main.html(this.main.html() + html); // this.sortPage(); }, // sortPage:function(){ // var obox = this.main.children(); // // console.log(obox); // var heightArray = []; // for(var i=0 ;i<obox.length; i++){ // //第一排设置基准 // if(i<5){ // heightArray.push(obox.eq(i).height()); // }else{ // // Math.min.apply => 可以获取数组中的最小值 // var min = Math.min.apply(false,heightArray); // var minindex = heightArray.indexOf(min); // obox.eq(i).css({ // position:"absolute", // top:min, // left:obox.eq(minindex).offset().left // }) // heightArray[minindex] += obox.eq(i).height(); // } // } // this.loading = false; // }, bindEvent:function(){ $(window).on("scroll",this.ifLoad.bind(this)); }, //是否加载 滚动就会触发此事件 ifLoad:function(){ var scrollTop = $("html,body").scrollTop(); var clientHeight = $("html")[0].clientHeight; var lastBox = this.main.children(":last"); //加载到最后一张图片再次加载数据 if(scrollTop + clientHeight > lastBox.offset().top){ //如果已经加载,就return 0关闭,如果为false关闭就变为true if(this.loading){ return 0 } this.loading = true; // console.log("加载"); this.page ++; this.loadJson() .done(function(res){ this.renderPage(res); }) } } }) var waterfall = new WaterFall(); waterfall.init(); // //面向对象编程 // function WaterFall(){} // $.extend(WaterFall.prototype,{ // //初始化 // init:function(){ // //当前页数 // this.page=1; // this.main = $("#today_now_goods"); // //判断是否在加载中 // this.loading = false; // //和promise .then相似 // this.loadJson() //返回值是deferred对象(promise前身) // .done(function(res){ // // deferred 的 done 回调 this指向的都是 jquery 对象本身 // this.renderPage(res); // }) // this.bindEvent(); // }, // //加载数据 // loadJson:function(){ // var opt = { // // url:"http://www.wookmark.com/api/json/popular", // url:"https://list.mogujie.com/search", // dataType:"jsonp", // data:{page:this.page}, // //this ===>指向实例化对象 // context:this // } // return $.ajax(opt); // }, // //渲染页面 // renderPage:function(json1){ // //console.log(json1.result.wall.list); // var json=json1.result.wall.list; // console.log(json) // var html=""; // for( var i=0; i<json.length; i++){ // html +=` // <li class="deal_box"> // <div class="img_box"> // <a href="#" class="img_box_href"> // <img src="${json[i].show.img}" alt=""> // </a> // <i class="deal_tags teg_list fangwei"></i> // <div class="commit_new"> // <div class="commit_new_box"> // <b class="link"> // <i class="num">1855</i> // 条评论 // </b> // <div class="service_rating"> // <i class="rating_num">4.7/5</i> // <div class="rating"> // <div class="value" style="width:94%"></div> // </div> // </div> // </div> // </div> // </div> // <div class="add_cart_box all_cart_wrap"><a href="javascript:void(0)" class="add_cart all_cart">加入购物车</a></div> // <a href="#" class="clearfix"> // <div class="deal_detail"> // <p class="title"><span class="pink">${json[i].title}</p> // <div class="in_box"> // <div class="price_box"> // <span class="pnum">${json[i].price}</span> // <span class="mnum">${json[i].orgPrice}</span> // </div> // <div class="timer_box"> // <div class="time_box" id="time_box"></div> // <div class="num_box">销量: <span class="buy_num">${json[i].sale}}</span> |</div> // </div> // </div> // </div> // </a> // </li> // ` // // console.log(json[i].price) // //<div class="box" > // // <img src="${json[i].show.img}" alt=""> // // <div class="describe"> // // <p>${json[i].title}</p> // // <span>${json[i].price}</span> // // <del>${json[i].orgPrice}</del> // // <i class="sales">${json[i].sale}</i> // // </div> // // </div> // } // this.main.html(this.main.html() + html); // this.loading = false; // }, // bindEvent:function(){ // $(window).on("scroll",this.ifLoad.bind(this)); // }, // //是否加载 滚动就会触发此事件 // ifLoad:function(){ // var scrollTop = $("html,body").scrollTop(); // var clientHeight = $("html")[0].clientHeight; // var lastBox = this.main.children(":last"); // //加载到最后一张图片再次加载数据 // if(scrollTop + clientHeight > lastBox.offset().top){ // //如果已经加载,就return 0关闭,如果为false关闭就变为true // if(this.loading){ // return 0 // } // if(this.page>3){ // return 0; // } // this.loading = true; // // console.log("加载"); // this.page ++; // this.loadJson() // .done(function(res){ // this.renderPage(res); // }) // } // } // }) // var waterfall = new WaterFall(); // waterfall.init(); <file_sep>/script/jumei_login_focus.js //表单验证,当聚焦时显示下面的div $(function(){ $(".num").focus(function(){ $(".num").siblings(".focus_text").css({"display":"block"}) }) $(".num").focusout(function(){ $(".num").siblings(".focus_text").css({"display":"none"}) }) $(".password").focus(function(){ $(".password").siblings(".focus_text").css({"display":"block"}) }) $(".password").focusout(function(){ $(".password").siblings(".focus_text").css({"display":"none"}) }) $(".dynamic_password").focus(function(){ $(".dynamic_password").siblings(".focus_text").css({"display":"block"}) }) $(".dynamic_password").focusout(function(){ $(".dynamic_password").siblings(".focus_text").css({"display":"none"}) }) $(".myname").focus(function(){ $(".myname").siblings(".focus_text").css({"display":"block"}) }) $(".myname").focusout(function(){ $(".myname").siblings(".focus_text").css({"display":"none"}) }) $("#mobile").focus(function(){ $("#mobile").siblings(".focus_text").css({"display":"block"}) }) $("#mobile").focusout(function(){ $("#mobile").siblings(".focus_text").css({"display":"none"}) }) $("#mobile_verify").focus(function(){ $("#mobile_verify").siblings(".focus_text").css({"display":"block"}) }) $("#mobile_verify").focusout(function(){ $("#mobile_verify").siblings(".focus_text").css({"display":"none"}) }) $("#password").focus(function(){ $("#password").siblings(".focus_text").css({"display":"block"}) }) $("#password").focusout(function(){ $("#password").siblings(".focus_text").css({"display":"none"}) }) $("#password2").focus(function(){ $("#password2").siblings(".focus_text").css({"display":"block"}) }) $("#password2").focusout(function(){ $("#password2").siblings(".focus_text").css({"display":"none"}) }) }) <file_sep>/script/tab_box.js var data1=[{ img:"images/bk1.jpg", class:"today_top_1", title:"【香港直邮】什么?你还没用过SK-II护肤面膜(10片)?女人一生中至少也要经历一次SK-II护肤面膜的亲密接触!敷一次肌肤就嫩到你的前男友悔不当初!现男友爱你到死心塌地!富含30ml的精华液,让你皮肤满足的吃饱营养,每一个细胞都变得活力充盈!", now_price:"659", old_price:"1060", total:"0" },{ img:"images/bk2.jpg", class:"today_top_2", title:" DHC橄榄护唇膏1.5g——橄榄精华油与双唇自然融合!功效不吹嘘,有口皆碑,持久水润保湿,深层滋润呵护,有效防止双唇粗糙干裂,令双唇娇嫩欲滴!真的一点也不油腻哦!口红前打底,不仅护唇,更易上色更持久!", now_price:"55", old_price:"69.9", total:"0" }] window.onload=function(){ var aBox=document.querySelector(".today_main .tab_content"); var html=""; for(var i=0;i<data1.length;i++){ html+=` <div class="tab_box"> <div class="today_tab_content"> <a href="#" class="today_tab_link"> <img src="${data1[i].img}" alt="" class="cart_img"> <span class="${data1[i].class}"></span> </a> <span class="tags_list haitao">海淘</span> <div class="produce_detail"> <div class="the_time"> <span class="end_time"> <span class="end_text">距特卖结束</span> <span class="today_time"></span> </span> </div> <a href="#" class="product_title"> ${data1[i].title} </a> <div class="product_price"> <span class="now_price"> <em>¥</em> ${data1[i].now_price} </span> <div class="old_price">¥${data1[i].old_price}</div> <div class="goto_cart_wrap all_cart_wrap"> <a class="goto_btn goto_cart all_cart" href="javascript:;">加入购物车</a> </div> </div> <div class="tag"> <span class="tag_a"> <img src="images/tag.jpg" alt=""> </span> <span class="tag_like"> <em>${data1[i].total}</em> 人已购买 </span> </div> </div> </div> </div>`; } aBox.innerHTML=html; } <file_sep>/script/left_list_go.js //点击li元素到相应的楼层的方法 var flag = true //设置标识。防止出现跑马灯 $(".left_list li").click(function(){ //flag = false $(this).addClass("act").siblings().removeClass("act") var index = $(this).index()//获取当前点击元素的索引 var top = $(".ban").eq(index).offset().top;//获取每个banner到顶部的距离 $("html,body").stop(true).scrollTop(top) }) // 滚轮滑动切换楼层 $(window).scroll(function(){ if(flag){ //浏览器可视窗口的一半,也可以根据自己需求设定 var winH = $(window).innerHeight()/2; var scrollT = $(window).scrollTop() var len = 3; for(var i=0;i<len;i++){ //注意这里banner对象加了i之后变成了js对象,所以用offsetTop var bannerGap = $(".ban")[i].offsetTop - scrollT if(bannerGap < winH){ $(".left_list li").eq(i).addClass("act").siblings().removeClass("act") } } } }) <file_sep>/dist/script/tab_box.js var data1=[{ img:"images/bk1.jpg", class:"today_top_1", title:"【香港直邮】什么?你还没用过SK-II护肤面膜(10片)?女人一生中至少也要经历一次SK-II护肤面膜的亲密接触!敷一次肌肤就嫩到你的前男友悔不当初!现男友爱你到死心塌地!富含30ml的精华液,让你皮肤满足的吃饱营养,每一个细胞都变得活力充盈!", now_price:"659", old_price:"1060", total:"0" },{ img:"images/bk2.jpg", class:"today_top_2", title:" DHC橄榄护唇膏1.5g——橄榄精华油与双唇自然融合!功效不吹嘘,有口皆碑,持久水润保湿,深层滋润呵护,有效防止双唇粗糙干裂,令双唇娇嫩欲滴!真的一点也不油腻哦!口红前打底,不仅护唇,更易上色更持久!", now_price:"55", old_price:"69.9", total:"0" },{ img:"images/bk3.jpg", class:"today_top_3", title:" <em>【官方授权】</em>敷了会“上瘾”的RAY银色金色蚕丝面膜10片+安娜贝拉Annabella海藻面膜10片!缔造泰国补水亮白经典!满满的蜗牛精华变身“锁水大补丸”给肌肤“吃饱”水分。敷上一片变素颜女神!去泰国不囤一盒都觉得“亏”!拯救干涸肌,痘印暗沉全不见!", now_price:"99", old_price:"139", total:"53" },{ img:"images/bk4.jpg", class:"", title:" <em>【官方授权】</em>肌肤干燥起皮,天天敷面膜好冰脸,怎么办?美迪惠尔第三代涂抹式【玻尿酸水光针精华】一支浓缩10盒水库面膜精华,一次使用相当于敷了5片面膜,【比敷面膜更补水】!【小分子玻尿酸】填充丰盈缺水细胞,增加肌肤持久保湿能力,打造韩国女星水光肌!", now_price:"89", old_price:"299", total:"5" },{ img:"images/bk5.jpg", class:"", title:" <em>【官方授权】</em>韩国•【祛痘不安全=慢性毁容】,乱用祛痘产品,痘没去,美迪惠尔(MEDIHEAL)温和祛痘修复套组,“急救祛痘精华” 隔离分层萃取技术,保证有效成分活性,点对点快、准、狠、安全战痘!+“祛痘霜”控痕+溶痘+消印,加赠棉签30+,再见“痘花妹”,边,变脸做女神!", now_price:"89", old_price:"199", total:"0" },{ img:"images/bk6.jpg", class:"", title:" <em>【官方授权】</em>肌肤清洁,就是要彻底。肌肤之钥(Cle De Peau BEAUTE)奢华泡沫洁面乳(清爽型)125g,迅速产生丰盈细腻的泡沫,无微不至清洁肌理,为您带来亮采美肌。清爽型泡沫洁面乳,洁面后肌肤光滑亮采。", now_price:"388", old_price:"500", total:"0" },{ img:"images/bk7.jpg", class:"", title:" <em>【官方授权】</em>露华浓(Revlon)不脱色粉底液30ml,露华浓明星产品!粉底界开山鼻祖。轻轻一抹,轻松打造不脱色瞬间。质地细腻,提亮肤色,遮瑕痘印,隔离防晒。多色号可选。​控油、遮瑕、提亮、保湿 ,匀净无瑕,妆容精致一整天!", now_price:"65", old_price:"79", total:"386" },{ img:"images/bk8.jpg", class:"", title:" <em>【官方授权】</em>可莱丝经典再次升级,美迪惠尔(MEDIHEAL)胶原蛋白面膜贴10片/盒,精华升级,深海水溶胶原蛋白,有效补充营养,抗皱紧致肌肤。面膜布升级,服帖效果*3,吸附精华快速推送。肌肤拒绝被老化,重塑紧致细嫩童颜肌!", now_price:"55", old_price:"116", total:"137" },{ img:"images/bk9.jpg", class:"", title:" <em>【官方授权】</em>肤色暗黄要用化妆品来层层遮盖?日本ULUKA红石榴葡萄籽换肤水光精华水,【高山红石榴】从此告别暗沉泛黄,黄脸婆变身白雪公主~【葡萄籽多酚】帮你阻挡变黑因素,轻松抵抗氧化!滴滴植物精华,深层美肌,一瓶撕掉你的暗黄皮,让你素颜也是亮白“女神”肌!", now_price:"69", old_price:"199", total:"8" },{ img:"images/bk10.jpg", class:"", title:" <em>【官方授权】</em>澳洲女性生理健康都靠它,Swisse蔓越莓胶囊30粒,选用被誉为红宝石的北美高端蔓越莓,接近5年才能结一次果,原材料十分稀少,从内而外的调养,让你的肌肤透出蔓越莓的红!", now_price:"85", old_price:"219", total:"14" },{ img:"images/bk11.jpg", class:"", title:"3度登COSME美容液大赏的【百搭小魔瓶】。日本3000个玻尿酸护肤品牌无法脱离的核心原料。深层补水,长效保湿,有效控油。100次大用量,从头到脚都适用。1滴,让你的所有护肤品都+1。让补水不再是刻意的事。", now_price:"69.9", old_price:"79", total:"68" },{ img:"images/bk12.jpg", class:"", title:"三养 辣火鸡炒面 140g*5包,超辣,挑战舌尖,好辣的亲们不妨感受一下哦。劲道的面,搭配劲辣,再加上白芝麻与紫菜的调味,香喷喷美味,岂能错过?脆脆的芝麻和烤海苔的香味让辣鸡味炒面更加特别更加美味!", now_price:"21.9", old_price:"39", total:"1314" },{ img:"images/bk13.jpg", class:"", title:"理肤泉(LA ROCHE-POSAY)B5多效修护霜40ml,含有维他命B5、积雪草萃取物,滋养保湿,修复舒缓肌肤不适问题、肌肤印痕,减少各种肌肤问题导致的印迹产生,敏感肌可用。舒缓肌肤,多效修护。一支解决多种肌肤问题。", now_price:"65", old_price:"75", total:"50" },{ img:"images/bk14.jpg", class:"", title:"【香港直邮】从深海到手心,从诺言到现实。她的所有使用者都是美丽的信徒,他们锲而不舍,将美丽看作热爱生命的态度,即使奢贵,也在所不惜,因为青春美颜,才是他们的无价瑰宝。海蓝之谜(LA MER)浓缩修护精华露30ml,珍稀成就奢华。赋活肌肤的过程,肌肤柔嫩平滑,光泽透亮!", now_price:"1859", old_price:"2019", total:"0" },{ img:"images/bk15.jpg", class:"", title:"来自法国的贝德玛(Bioderma)净妍控油洁肤液500ml*2,告别繁复卸妆步骤,轻松一抹,卸妆快速,无残留;无需水洗,懒人优选!卸妆、洁面、控油、补水四效合一,能够净化皮脂,混合、油性痘肌的选择!多款包装随机发货。", now_price:"179", old_price:"199", total:"44" }] window.onload=function(){ var aBox=document.querySelector(".today_main .tab_content"); var html=""; for(var i=0;i<data1.length;i++){ html+=` <div class="tab_box"> <div class="today_tab_content"> <a href="#" class="today_tab_link"> <img src="${data1[i].img}" alt="" class="cart_img"> <span class="${data1[i].class}"></span> </a> <span class="tags_list haitao">海淘</span> <div class="produce_detail"> <div class="the_time"> <span class="end_time"> <span class="end_text">距特卖结束</span> <span class="today_time"></span> </span> </div> <a href="#" class="product_title"> ${data1[i].title} </a> <div class="product_price"> <span class="now_price"> <em>¥</em> ${data1[i].now_price} </span> <div class="old_price">¥ ${data1[i].old_price}</div> <div class="goto_cart_wrap all_cart_wrap"> <a class="goto_btn goto_cart all_cart" href="javascript:;">加入购物车</a> </div> </div> <div class="tag"> <span class="tag_a"> <img src="images/tag.jpg" alt=""> </span> <span class="tag_like"> <em> ${data1[i].total}</em> 人已购买 </span> </div> </div> </div> </div>`; } aBox.innerHTML=html; } <file_sep>/script/select.js $(function(){ $(".tab_menu span").click(function(){ $(".tab_menu span") .eq($(this).index()) .addClass("tab_menu_active") .siblings().removeClass("tab_menu_active"); $(".tab_content .tab_box").hide() .eq($(this).index()) .show() }); })
d46525244774041702c4f6198f7daaf5977a3831
[ "JavaScript" ]
12
JavaScript
LinDDL/jumeiyouping
32818ff6f297b1fbfe541bc88e92a9504ece92f3
1887ad88d01341854c33339cdaf774327a0d2565
refs/heads/master
<repo_name>Hudhaifa/ros-stereo-vision-tuner<file_sep>/src/bmvariables.h #ifndef BMVARIABLES_H #define BMVARIABLES_H class BMVariables { public: BMVariables(); int preFilterCap; int SADWindowSize; int minimumDisparity; int numberofDisparities; int textureThreshold; int uniquenessRatio; int speckleWindowSize; int speckleRange; int maximumDisparityDifference; }; #endif // BMVARIABLES_H <file_sep>/README.md ros-stereo-vision-tuner ======================= This package provides an interface for ROS users to test out any stereo correspondence algorithm on a pair of images and then tune its parameters to get the most optimum result. Its purpose is to find out the algorithm that will work best for the condition that is being tested. So far, it allows the user to test the algorithms that are available in OpenCV library. Future version will allow the user to add more algorithms(even custom algorithm) in this package. *Recommended ROS version*: ROS Fuerte The package requires *OpenCV2, rqt, image_transport* to be installed. <file_sep>/src/imagedepthprocessor.cpp #include "imagedepthprocessor.h" #include <image_transport/image_transport.h> #include <QThread> #include <QString> #include <QDebug> using namespace cv; ImageDepthProcessor::ImageDepthProcessor(QObject *parent) : QObject(parent), it_(nh_) { valuesInitialized = false; imageLeftUpdated = false; imageStereoPublish = it_.advertise("disparity_output", 1); imageLeftSubscribe = it_.subscribe("left", 1, &ImageDepthProcessor::imageLeftGetData, this); imageRightSubscribe = it_.subscribe("right", 1, &ImageDepthProcessor::imageRightGetDataAndProcess, this); cv::namedWindow(WINDOW); } ImageDepthProcessor::~ImageDepthProcessor() { cv::destroyWindow(WINDOW); } void ImageDepthProcessor::process() { } void ImageDepthProcessor::updateValues(const BMVariables &bm, const SGBMVariables &sgbm, const VarVariables &var, const int algo) { bmVariables = bm; sgbmVariables = sgbm; varVariables = var; algorithm = algo; valuesInitialized = true; ros::spinOnce(); } void ImageDepthProcessor::deleteLater() { } void ImageDepthProcessor::killProcess() { emit finished(); } void ImageDepthProcessor::imageLeftGetData(const sensor_msgs::ImageConstPtr& msg) { imageLeftUpdated = false; cv_bridge::CvImagePtr cv_ptr; try { cv_ptr = cv_bridge::toCvCopy(msg, enc::BGR8); } catch (cv_bridge::Exception& e) { ROS_ERROR("cv_bridge exception: %s", e.what()); return; } imageLeft = cv_ptr->image; imageLeftUpdated = true; } void ImageDepthProcessor::imageRightGetDataAndProcess(const sensor_msgs::ImageConstPtr& msg) { cv_bridge::CvImagePtr cv_ptr; try { cv_ptr = cv_bridge::toCvCopy(msg, enc::BGR8); } catch (cv_bridge::Exception& e) { ROS_ERROR("cv_bridge exception: %s", e.what()); return; } imageRight = cv_ptr->image; if(imageLeft.data && imageLeftUpdated && valuesInitialized) //now to verify if the left image has been successfully extracted and parameters are ready { enum { STEREO_BM=0, STEREO_SGBM=1, STEREO_VAR=2 }; int alg = algorithm; int SADWindowSize = 0, numberOfDisparities = 0; StereoBM bm; StereoSGBM sgbm; StereoVar var; Size img_size = imageLeft.size(); Rect roi1, roi2; numberOfDisparities = numberOfDisparities > 0 ? numberOfDisparities : ((img_size.width/8) + 15) & -16; bm.state->roi1 = roi1; bm.state->roi2 = roi2; bm.state->preFilterCap = bmVariables.preFilterCap; bm.state->SADWindowSize = bmVariables.SADWindowSize; bm.state->minDisparity = bmVariables.minimumDisparity; bm.state->numberOfDisparities = bmVariables.numberofDisparities; bm.state->textureThreshold = bmVariables.textureThreshold; bm.state->uniquenessRatio = bmVariables.uniquenessRatio; bm.state->speckleWindowSize = bmVariables.speckleWindowSize; bm.state->speckleRange = bmVariables.speckleRange; bm.state->disp12MaxDiff = bmVariables.maximumDisparityDifference; sgbm.preFilterCap = sgbmVariables.preFilterCap; sgbm.SADWindowSize = sgbmVariables.SADWindowSize; int cn = imageLeft.channels(); sgbm.P1 = 8*cn*sgbm.SADWindowSize*sgbm.SADWindowSize; sgbm.P2 = 32*cn*sgbm.SADWindowSize*sgbm.SADWindowSize; sgbm.minDisparity = sgbmVariables.minimumDisparity; sgbm.numberOfDisparities = sgbmVariables.numberOfDisparities; sgbm.uniquenessRatio = sgbmVariables.uniquenessRatio; sgbm.speckleWindowSize = sgbmVariables.speckleWindowSize; sgbm.speckleRange = sgbmVariables.speckleRange; sgbm.disp12MaxDiff = sgbmVariables.maximumDisparityDifference; sgbm.fullDP = sgbmVariables.fullScale2xPass; var.levels = 3; // ignored with USE_AUTO_PARAMS var.pyrScale = 0.5; // ignored with USE_AUTO_PARAMS var.nIt = varVariables.iterations; var.minDisp = -varVariables.maximumDisparity; var.maxDisp = varVariables.minimumDisparity; var.poly_n = varVariables.orderOfPolynomial; var.poly_sigma = varVariables.standardDeviation; var.fi = (float)varVariables.smoothness; var.lambda = (float)varVariables.threshold; var.penalization = var.PENALIZATION_TICHONOV; // ignored with USE_AUTO_PARAMS var.cycle = var.CYCLE_V; // ignored with USE_AUTO_PARAMS var.flags = var.USE_SMART_ID | var.USE_AUTO_PARAMS | var.USE_INITIAL_DISPARITY | var.USE_MEDIAN_FILTERING ; Mat disp, disp8; if( alg == STEREO_BM ) { Mat imgLeft, imgRight; cvtColor(imageLeft, imgLeft, CV_BGR2GRAY); cvtColor(imageRight, imgRight, CV_BGR2GRAY); bm(imgLeft, imgRight, disp); imgLeft.release(); imgRight.release(); } else if( alg == STEREO_VAR ) var(imageLeft, imageRight, disp); else sgbm(imageLeft, imageRight, disp); if( alg != STEREO_VAR ) disp.convertTo(disp8, CV_8U, 255/(numberOfDisparities*16.)); else disp.convertTo(disp8, CV_8U); imshow(WINDOW, disp8); cv_ptr->image = disp; imageStereoPublish.publish(cv_ptr->toImageMsg()); } } <file_sep>/src/imagedepth.h #ifndef IMAGEDEPTH_H #define IMAGEDEPTH_H #include <QMainWindow> #include "bmvariables.h" #include "sgbmvariables.h" #include "varvariables.h" namespace Ui { class ImageDepth; } class ImageDepth : public QMainWindow { Q_OBJECT public: explicit ImageDepth(QWidget *parent = 0); BMVariables *bmVariables; SGBMVariables *sgbmVariables; VarVariables *varVariables; ~ImageDepth(); public slots: void recalculate(); signals: void valuesChanged(const BMVariables&, const SGBMVariables&, const VarVariables&, const int); private: Ui::ImageDepth *ui; enum { ALG_BM=0, ALG_SGBM=1, ALG_VAR=2 }; void mapValues(); }; #endif // IMAGEDEPTH_H <file_sep>/src/sgbmvariables.h #include <QString> #ifndef SGBMVARIABLES_H #define SGBMVARIABLES_H class SGBMVariables { public: SGBMVariables(); int preFilterCap; int SADWindowSize; int minimumDisparity; int numberOfDisparities; int uniquenessRatio; int speckleWindowSize; int speckleRange; int maximumDisparityDifference; bool fullScale2xPass; void setFullScale2xPass(const QString value); }; #endif // SGBMVARIABLES_H <file_sep>/src/varvariables.cpp #include "varvariables.h" #include <QString> VarVariables::VarVariables() { } void VarVariables::setThreshold(const QString value) { threshold = value.toFloat(); } <file_sep>/src/ui_imagedepth.h /******************************************************************************** ** Form generated from reading UI file 'imagedepth.ui' ** ** Created: Tue Dec 25 23:10:05 2012 ** by: Qt User Interface Compiler version 4.8.1 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_IMAGEDEPTH_H #define UI_IMAGEDEPTH_H #include <QtCore/QVariant> #include <QtGui/QAction> #include <QtGui/QApplication> #include <QtGui/QButtonGroup> #include <QtGui/QComboBox> #include <QtGui/QFormLayout> #include <QtGui/QHeaderView> #include <QtGui/QLabel> #include <QtGui/QLineEdit> #include <QtGui/QMainWindow> #include <QtGui/QStatusBar> #include <QtGui/QTabWidget> #include <QtGui/QWidget> #include "myqslider.h" QT_BEGIN_NAMESPACE class Ui_ImageDepth { public: QWidget *centralWidget; QWidget *formLayoutWidget; QFormLayout *formLayout; QLabel *algorithmLabel; QComboBox *algorithmComboBox; QTabWidget *tabWidget; QWidget *tab; QWidget *formLayoutWidget_5; QFormLayout *formLayout_6; QLabel *BMPreFilterCapLabel; MyQSlider *BMPreFilterCapSlider; QLabel *BMSADWindowSizeLabel; MyQSlider *BMSADWindowSizeSlider; QLabel *BMMinimumDisparityLabel; MyQSlider *BMMinimumDisparitySlider; QLabel *BMNumberOfDisparitiesLabel; MyQSlider *BMNumberOfDisparitiesSlider; QLabel *BMTextureThresholdLabel; MyQSlider *BMTextureThresholdSlider; QLabel *BMUniquenessRatioLabel; MyQSlider *BMUniquenessRatioSlider; QLabel *BMSpeckleWindowSizeLabel; MyQSlider *BMSpeckleWindowSizeSlider; QLabel *BMSpeckleRangeLabel; MyQSlider *BMSpeckleRangeSlider; QLabel *BMMaximumDisparityDifferenceLabel; MyQSlider *BMMaximumDisparityDifferenceSlider; QWidget *tab_3; QWidget *formLayoutWidget_6; QFormLayout *formLayout_7; QLabel *SGBMPreFilterCapLabel; MyQSlider *SGBMPreFilterCapSlider; QLabel *SGBMSADWindowSizeLabel; MyQSlider *SGBMSADWindowSizeSlider; QLabel *SGBMMinimumDisparityLabel; MyQSlider *SGBMMinimumDisparitySlider; QLabel *SGBMNumberOfDisparitiesLabel; MyQSlider *SGBMNumberOfDisparitiesSlider; QLabel *SGBMUniquenessRatioLabel; MyQSlider *SGBMUniquenessRatioSlider; QLabel *SGBMSpeckleWindowSizeLabel; MyQSlider *SGBMSpeckleWindowSizeSlider; QLabel *SGBMSpeckleRangeLabel; MyQSlider *SGBMSpeckleRangeSlider; QLabel *SGBMMaximumDisparityDifferenceLabel; MyQSlider *SGBMMaximumDisparityDifferenceSlider; QLabel *SGBMFullScale2xPassLabel; QComboBox *SGBMFullScale2xPassComboBox; QWidget *tab_2; QWidget *formLayoutWidget_2; QFormLayout *formLayout_2; QLabel *VarIterationsLabel; MyQSlider *VarIterationsSlider; QLabel *VarMinimumDisparityLabel; MyQSlider *VarMinimumDisparitySlider; QLabel *VarMaximumDisparityLabel; MyQSlider *VarMaximumDisparitySlider; QLabel *VarOrderOfPolynomialLabel; MyQSlider *VarOrderOfPolynomialSlider; QLabel *VarStandardDeviationLabel; MyQSlider *VarStandardDeviationSlider; QLabel *VarSmoothnessLabel; MyQSlider *VarSmoothnessSlider; QLabel *VarThresholdLabel; QLineEdit *VarThresholdLineEdit; QStatusBar *statusBar; void setupUi(QMainWindow *ImageDepth) { if (ImageDepth->objectName().isEmpty()) ImageDepth->setObjectName(QString::fromUtf8("ImageDepth")); ImageDepth->resize(702, 452); QSizePolicy sizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); sizePolicy.setHorizontalStretch(0); sizePolicy.setVerticalStretch(0); sizePolicy.setHeightForWidth(ImageDepth->sizePolicy().hasHeightForWidth()); ImageDepth->setSizePolicy(sizePolicy); ImageDepth->setMinimumSize(QSize(702, 452)); ImageDepth->setMaximumSize(QSize(702, 452)); centralWidget = new QWidget(ImageDepth); centralWidget->setObjectName(QString::fromUtf8("centralWidget")); formLayoutWidget = new QWidget(centralWidget); formLayoutWidget->setObjectName(QString::fromUtf8("formLayoutWidget")); formLayoutWidget->setGeometry(QRect(20, 10, 661, 31)); formLayout = new QFormLayout(formLayoutWidget); formLayout->setSpacing(6); formLayout->setContentsMargins(11, 11, 11, 11); formLayout->setObjectName(QString::fromUtf8("formLayout")); formLayout->setFieldGrowthPolicy(QFormLayout::AllNonFixedFieldsGrow); formLayout->setContentsMargins(0, 0, 0, 0); algorithmLabel = new QLabel(formLayoutWidget); algorithmLabel->setObjectName(QString::fromUtf8("algorithmLabel")); formLayout->setWidget(0, QFormLayout::LabelRole, algorithmLabel); algorithmComboBox = new QComboBox(formLayoutWidget); algorithmComboBox->setObjectName(QString::fromUtf8("algorithmComboBox")); formLayout->setWidget(0, QFormLayout::FieldRole, algorithmComboBox); tabWidget = new QTabWidget(centralWidget); tabWidget->setObjectName(QString::fromUtf8("tabWidget")); tabWidget->setGeometry(QRect(20, 50, 661, 370)); tab = new QWidget(); tab->setObjectName(QString::fromUtf8("tab")); formLayoutWidget_5 = new QWidget(tab); formLayoutWidget_5->setObjectName(QString::fromUtf8("formLayoutWidget_5")); formLayoutWidget_5->setGeometry(QRect(21, 20, 632, 284)); formLayout_6 = new QFormLayout(formLayoutWidget_5); formLayout_6->setSpacing(6); formLayout_6->setContentsMargins(11, 11, 11, 11); formLayout_6->setObjectName(QString::fromUtf8("formLayout_6")); formLayout_6->setFieldGrowthPolicy(QFormLayout::AllNonFixedFieldsGrow); formLayout_6->setContentsMargins(0, 0, 0, 0); BMPreFilterCapLabel = new QLabel(formLayoutWidget_5); BMPreFilterCapLabel->setObjectName(QString::fromUtf8("BMPreFilterCapLabel")); formLayout_6->setWidget(0, QFormLayout::LabelRole, BMPreFilterCapLabel); BMPreFilterCapSlider = new MyQSlider(formLayoutWidget_5); BMPreFilterCapSlider->setObjectName(QString::fromUtf8("BMPreFilterCapSlider")); BMPreFilterCapSlider->setMinimumSize(QSize(420, 26)); formLayout_6->setWidget(0, QFormLayout::FieldRole, BMPreFilterCapSlider); BMSADWindowSizeLabel = new QLabel(formLayoutWidget_5); BMSADWindowSizeLabel->setObjectName(QString::fromUtf8("BMSADWindowSizeLabel")); formLayout_6->setWidget(1, QFormLayout::LabelRole, BMSADWindowSizeLabel); BMSADWindowSizeSlider = new MyQSlider(formLayoutWidget_5); BMSADWindowSizeSlider->setObjectName(QString::fromUtf8("BMSADWindowSizeSlider")); BMSADWindowSizeSlider->setMinimumSize(QSize(0, 26)); formLayout_6->setWidget(1, QFormLayout::FieldRole, BMSADWindowSizeSlider); BMMinimumDisparityLabel = new QLabel(formLayoutWidget_5); BMMinimumDisparityLabel->setObjectName(QString::fromUtf8("BMMinimumDisparityLabel")); formLayout_6->setWidget(2, QFormLayout::LabelRole, BMMinimumDisparityLabel); BMMinimumDisparitySlider = new MyQSlider(formLayoutWidget_5); BMMinimumDisparitySlider->setObjectName(QString::fromUtf8("BMMinimumDisparitySlider")); BMMinimumDisparitySlider->setMinimumSize(QSize(0, 26)); formLayout_6->setWidget(2, QFormLayout::FieldRole, BMMinimumDisparitySlider); BMNumberOfDisparitiesLabel = new QLabel(formLayoutWidget_5); BMNumberOfDisparitiesLabel->setObjectName(QString::fromUtf8("BMNumberOfDisparitiesLabel")); formLayout_6->setWidget(3, QFormLayout::LabelRole, BMNumberOfDisparitiesLabel); BMNumberOfDisparitiesSlider = new MyQSlider(formLayoutWidget_5); BMNumberOfDisparitiesSlider->setObjectName(QString::fromUtf8("BMNumberOfDisparitiesSlider")); BMNumberOfDisparitiesSlider->setMinimumSize(QSize(0, 26)); formLayout_6->setWidget(3, QFormLayout::FieldRole, BMNumberOfDisparitiesSlider); BMTextureThresholdLabel = new QLabel(formLayoutWidget_5); BMTextureThresholdLabel->setObjectName(QString::fromUtf8("BMTextureThresholdLabel")); formLayout_6->setWidget(4, QFormLayout::LabelRole, BMTextureThresholdLabel); BMTextureThresholdSlider = new MyQSlider(formLayoutWidget_5); BMTextureThresholdSlider->setObjectName(QString::fromUtf8("BMTextureThresholdSlider")); BMTextureThresholdSlider->setMinimumSize(QSize(0, 26)); formLayout_6->setWidget(4, QFormLayout::FieldRole, BMTextureThresholdSlider); BMUniquenessRatioLabel = new QLabel(formLayoutWidget_5); BMUniquenessRatioLabel->setObjectName(QString::fromUtf8("BMUniquenessRatioLabel")); formLayout_6->setWidget(5, QFormLayout::LabelRole, BMUniquenessRatioLabel); BMUniquenessRatioSlider = new MyQSlider(formLayoutWidget_5); BMUniquenessRatioSlider->setObjectName(QString::fromUtf8("BMUniquenessRatioSlider")); BMUniquenessRatioSlider->setMinimumSize(QSize(0, 26)); formLayout_6->setWidget(5, QFormLayout::FieldRole, BMUniquenessRatioSlider); BMSpeckleWindowSizeLabel = new QLabel(formLayoutWidget_5); BMSpeckleWindowSizeLabel->setObjectName(QString::fromUtf8("BMSpeckleWindowSizeLabel")); formLayout_6->setWidget(6, QFormLayout::LabelRole, BMSpeckleWindowSizeLabel); BMSpeckleWindowSizeSlider = new MyQSlider(formLayoutWidget_5); BMSpeckleWindowSizeSlider->setObjectName(QString::fromUtf8("BMSpeckleWindowSizeSlider")); BMSpeckleWindowSizeSlider->setMinimumSize(QSize(0, 26)); formLayout_6->setWidget(6, QFormLayout::FieldRole, BMSpeckleWindowSizeSlider); BMSpeckleRangeLabel = new QLabel(formLayoutWidget_5); BMSpeckleRangeLabel->setObjectName(QString::fromUtf8("BMSpeckleRangeLabel")); formLayout_6->setWidget(7, QFormLayout::LabelRole, BMSpeckleRangeLabel); BMSpeckleRangeSlider = new MyQSlider(formLayoutWidget_5); BMSpeckleRangeSlider->setObjectName(QString::fromUtf8("BMSpeckleRangeSlider")); BMSpeckleRangeSlider->setMinimumSize(QSize(0, 26)); formLayout_6->setWidget(7, QFormLayout::FieldRole, BMSpeckleRangeSlider); BMMaximumDisparityDifferenceLabel = new QLabel(formLayoutWidget_5); BMMaximumDisparityDifferenceLabel->setObjectName(QString::fromUtf8("BMMaximumDisparityDifferenceLabel")); formLayout_6->setWidget(8, QFormLayout::LabelRole, BMMaximumDisparityDifferenceLabel); BMMaximumDisparityDifferenceSlider = new MyQSlider(formLayoutWidget_5); BMMaximumDisparityDifferenceSlider->setObjectName(QString::fromUtf8("BMMaximumDisparityDifferenceSlider")); BMMaximumDisparityDifferenceSlider->setMinimumSize(QSize(0, 26)); formLayout_6->setWidget(8, QFormLayout::FieldRole, BMMaximumDisparityDifferenceSlider); tabWidget->addTab(tab, QString()); tab_3 = new QWidget(); tab_3->setObjectName(QString::fromUtf8("tab_3")); formLayoutWidget_6 = new QWidget(tab_3); formLayoutWidget_6->setObjectName(QString::fromUtf8("formLayoutWidget_6")); formLayoutWidget_6->setGeometry(QRect(20, 20, 632, 301)); formLayout_7 = new QFormLayout(formLayoutWidget_6); formLayout_7->setSpacing(6); formLayout_7->setContentsMargins(11, 11, 11, 11); formLayout_7->setObjectName(QString::fromUtf8("formLayout_7")); formLayout_7->setFieldGrowthPolicy(QFormLayout::AllNonFixedFieldsGrow); formLayout_7->setContentsMargins(0, 0, 0, 0); SGBMPreFilterCapLabel = new QLabel(formLayoutWidget_6); SGBMPreFilterCapLabel->setObjectName(QString::fromUtf8("SGBMPreFilterCapLabel")); formLayout_7->setWidget(0, QFormLayout::LabelRole, SGBMPreFilterCapLabel); SGBMPreFilterCapSlider = new MyQSlider(formLayoutWidget_6); SGBMPreFilterCapSlider->setObjectName(QString::fromUtf8("SGBMPreFilterCapSlider")); SGBMPreFilterCapSlider->setMinimumSize(QSize(420, 26)); formLayout_7->setWidget(0, QFormLayout::FieldRole, SGBMPreFilterCapSlider); SGBMSADWindowSizeLabel = new QLabel(formLayoutWidget_6); SGBMSADWindowSizeLabel->setObjectName(QString::fromUtf8("SGBMSADWindowSizeLabel")); formLayout_7->setWidget(1, QFormLayout::LabelRole, SGBMSADWindowSizeLabel); SGBMSADWindowSizeSlider = new MyQSlider(formLayoutWidget_6); SGBMSADWindowSizeSlider->setObjectName(QString::fromUtf8("SGBMSADWindowSizeSlider")); SGBMSADWindowSizeSlider->setMinimumSize(QSize(0, 26)); formLayout_7->setWidget(1, QFormLayout::FieldRole, SGBMSADWindowSizeSlider); SGBMMinimumDisparityLabel = new QLabel(formLayoutWidget_6); SGBMMinimumDisparityLabel->setObjectName(QString::fromUtf8("SGBMMinimumDisparityLabel")); formLayout_7->setWidget(2, QFormLayout::LabelRole, SGBMMinimumDisparityLabel); SGBMMinimumDisparitySlider = new MyQSlider(formLayoutWidget_6); SGBMMinimumDisparitySlider->setObjectName(QString::fromUtf8("SGBMMinimumDisparitySlider")); SGBMMinimumDisparitySlider->setMinimumSize(QSize(0, 26)); formLayout_7->setWidget(2, QFormLayout::FieldRole, SGBMMinimumDisparitySlider); SGBMNumberOfDisparitiesLabel = new QLabel(formLayoutWidget_6); SGBMNumberOfDisparitiesLabel->setObjectName(QString::fromUtf8("SGBMNumberOfDisparitiesLabel")); formLayout_7->setWidget(3, QFormLayout::LabelRole, SGBMNumberOfDisparitiesLabel); SGBMNumberOfDisparitiesSlider = new MyQSlider(formLayoutWidget_6); SGBMNumberOfDisparitiesSlider->setObjectName(QString::fromUtf8("SGBMNumberOfDisparitiesSlider")); SGBMNumberOfDisparitiesSlider->setMinimumSize(QSize(0, 26)); formLayout_7->setWidget(3, QFormLayout::FieldRole, SGBMNumberOfDisparitiesSlider); SGBMUniquenessRatioLabel = new QLabel(formLayoutWidget_6); SGBMUniquenessRatioLabel->setObjectName(QString::fromUtf8("SGBMUniquenessRatioLabel")); formLayout_7->setWidget(4, QFormLayout::LabelRole, SGBMUniquenessRatioLabel); SGBMUniquenessRatioSlider = new MyQSlider(formLayoutWidget_6); SGBMUniquenessRatioSlider->setObjectName(QString::fromUtf8("SGBMUniquenessRatioSlider")); SGBMUniquenessRatioSlider->setMinimumSize(QSize(0, 26)); formLayout_7->setWidget(4, QFormLayout::FieldRole, SGBMUniquenessRatioSlider); SGBMSpeckleWindowSizeLabel = new QLabel(formLayoutWidget_6); SGBMSpeckleWindowSizeLabel->setObjectName(QString::fromUtf8("SGBMSpeckleWindowSizeLabel")); formLayout_7->setWidget(5, QFormLayout::LabelRole, SGBMSpeckleWindowSizeLabel); SGBMSpeckleWindowSizeSlider = new MyQSlider(formLayoutWidget_6); SGBMSpeckleWindowSizeSlider->setObjectName(QString::fromUtf8("SGBMSpeckleWindowSizeSlider")); SGBMSpeckleWindowSizeSlider->setMinimumSize(QSize(0, 26)); formLayout_7->setWidget(5, QFormLayout::FieldRole, SGBMSpeckleWindowSizeSlider); SGBMSpeckleRangeLabel = new QLabel(formLayoutWidget_6); SGBMSpeckleRangeLabel->setObjectName(QString::fromUtf8("SGBMSpeckleRangeLabel")); formLayout_7->setWidget(6, QFormLayout::LabelRole, SGBMSpeckleRangeLabel); SGBMSpeckleRangeSlider = new MyQSlider(formLayoutWidget_6); SGBMSpeckleRangeSlider->setObjectName(QString::fromUtf8("SGBMSpeckleRangeSlider")); SGBMSpeckleRangeSlider->setMinimumSize(QSize(0, 26)); formLayout_7->setWidget(6, QFormLayout::FieldRole, SGBMSpeckleRangeSlider); SGBMMaximumDisparityDifferenceLabel = new QLabel(formLayoutWidget_6); SGBMMaximumDisparityDifferenceLabel->setObjectName(QString::fromUtf8("SGBMMaximumDisparityDifferenceLabel")); formLayout_7->setWidget(7, QFormLayout::LabelRole, SGBMMaximumDisparityDifferenceLabel); SGBMMaximumDisparityDifferenceSlider = new MyQSlider(formLayoutWidget_6); SGBMMaximumDisparityDifferenceSlider->setObjectName(QString::fromUtf8("SGBMMaximumDisparityDifferenceSlider")); SGBMMaximumDisparityDifferenceSlider->setMinimumSize(QSize(0, 26)); formLayout_7->setWidget(7, QFormLayout::FieldRole, SGBMMaximumDisparityDifferenceSlider); SGBMFullScale2xPassLabel = new QLabel(formLayoutWidget_6); SGBMFullScale2xPassLabel->setObjectName(QString::fromUtf8("SGBMFullScale2xPassLabel")); formLayout_7->setWidget(8, QFormLayout::LabelRole, SGBMFullScale2xPassLabel); SGBMFullScale2xPassComboBox = new QComboBox(formLayoutWidget_6); SGBMFullScale2xPassComboBox->setObjectName(QString::fromUtf8("SGBMFullScale2xPassComboBox")); SGBMFullScale2xPassComboBox->setMinimumSize(QSize(200, 0)); SGBMFullScale2xPassComboBox->setMaximumSize(QSize(200, 16777215)); formLayout_7->setWidget(8, QFormLayout::FieldRole, SGBMFullScale2xPassComboBox); tabWidget->addTab(tab_3, QString()); tab_2 = new QWidget(); tab_2->setObjectName(QString::fromUtf8("tab_2")); formLayoutWidget_2 = new QWidget(tab_2); formLayoutWidget_2->setObjectName(QString::fromUtf8("formLayoutWidget_2")); formLayoutWidget_2->setGeometry(QRect(20, 20, 630, 301)); formLayout_2 = new QFormLayout(formLayoutWidget_2); formLayout_2->setSpacing(6); formLayout_2->setContentsMargins(11, 11, 11, 11); formLayout_2->setObjectName(QString::fromUtf8("formLayout_2")); formLayout_2->setSizeConstraint(QLayout::SetFixedSize); formLayout_2->setContentsMargins(0, 0, 0, 0); VarIterationsLabel = new QLabel(formLayoutWidget_2); VarIterationsLabel->setObjectName(QString::fromUtf8("VarIterationsLabel")); formLayout_2->setWidget(0, QFormLayout::LabelRole, VarIterationsLabel); VarIterationsSlider = new MyQSlider(formLayoutWidget_2); VarIterationsSlider->setObjectName(QString::fromUtf8("VarIterationsSlider")); VarIterationsSlider->setMinimumSize(QSize(420, 26)); VarIterationsSlider->setMaximumSize(QSize(16777215, 26)); formLayout_2->setWidget(0, QFormLayout::FieldRole, VarIterationsSlider); VarMinimumDisparityLabel = new QLabel(formLayoutWidget_2); VarMinimumDisparityLabel->setObjectName(QString::fromUtf8("VarMinimumDisparityLabel")); formLayout_2->setWidget(1, QFormLayout::LabelRole, VarMinimumDisparityLabel); VarMinimumDisparitySlider = new MyQSlider(formLayoutWidget_2); VarMinimumDisparitySlider->setObjectName(QString::fromUtf8("VarMinimumDisparitySlider")); VarMinimumDisparitySlider->setMinimumSize(QSize(0, 26)); formLayout_2->setWidget(1, QFormLayout::FieldRole, VarMinimumDisparitySlider); VarMaximumDisparityLabel = new QLabel(formLayoutWidget_2); VarMaximumDisparityLabel->setObjectName(QString::fromUtf8("VarMaximumDisparityLabel")); formLayout_2->setWidget(2, QFormLayout::LabelRole, VarMaximumDisparityLabel); VarMaximumDisparitySlider = new MyQSlider(formLayoutWidget_2); VarMaximumDisparitySlider->setObjectName(QString::fromUtf8("VarMaximumDisparitySlider")); VarMaximumDisparitySlider->setMinimumSize(QSize(0, 26)); formLayout_2->setWidget(2, QFormLayout::FieldRole, VarMaximumDisparitySlider); VarOrderOfPolynomialLabel = new QLabel(formLayoutWidget_2); VarOrderOfPolynomialLabel->setObjectName(QString::fromUtf8("VarOrderOfPolynomialLabel")); formLayout_2->setWidget(3, QFormLayout::LabelRole, VarOrderOfPolynomialLabel); VarOrderOfPolynomialSlider = new MyQSlider(formLayoutWidget_2); VarOrderOfPolynomialSlider->setObjectName(QString::fromUtf8("VarOrderOfPolynomialSlider")); VarOrderOfPolynomialSlider->setMinimumSize(QSize(0, 26)); formLayout_2->setWidget(3, QFormLayout::FieldRole, VarOrderOfPolynomialSlider); VarStandardDeviationLabel = new QLabel(formLayoutWidget_2); VarStandardDeviationLabel->setObjectName(QString::fromUtf8("VarStandardDeviationLabel")); formLayout_2->setWidget(4, QFormLayout::LabelRole, VarStandardDeviationLabel); VarStandardDeviationSlider = new MyQSlider(formLayoutWidget_2); VarStandardDeviationSlider->setObjectName(QString::fromUtf8("VarStandardDeviationSlider")); VarStandardDeviationSlider->setMinimumSize(QSize(0, 26)); formLayout_2->setWidget(4, QFormLayout::FieldRole, VarStandardDeviationSlider); VarSmoothnessLabel = new QLabel(formLayoutWidget_2); VarSmoothnessLabel->setObjectName(QString::fromUtf8("VarSmoothnessLabel")); formLayout_2->setWidget(5, QFormLayout::LabelRole, VarSmoothnessLabel); VarSmoothnessSlider = new MyQSlider(formLayoutWidget_2); VarSmoothnessSlider->setObjectName(QString::fromUtf8("VarSmoothnessSlider")); VarSmoothnessSlider->setMinimumSize(QSize(0, 26)); formLayout_2->setWidget(5, QFormLayout::FieldRole, VarSmoothnessSlider); VarThresholdLabel = new QLabel(formLayoutWidget_2); VarThresholdLabel->setObjectName(QString::fromUtf8("VarThresholdLabel")); formLayout_2->setWidget(6, QFormLayout::LabelRole, VarThresholdLabel); VarThresholdLineEdit = new QLineEdit(formLayoutWidget_2); VarThresholdLineEdit->setObjectName(QString::fromUtf8("VarThresholdLineEdit")); VarThresholdLineEdit->setMaximumSize(QSize(200, 16777215)); formLayout_2->setWidget(6, QFormLayout::FieldRole, VarThresholdLineEdit); tabWidget->addTab(tab_2, QString()); ImageDepth->setCentralWidget(centralWidget); statusBar = new QStatusBar(ImageDepth); statusBar->setObjectName(QString::fromUtf8("statusBar")); ImageDepth->setStatusBar(statusBar); retranslateUi(ImageDepth); algorithmComboBox->setCurrentIndex(1); tabWidget->setCurrentIndex(1); SGBMFullScale2xPassComboBox->setCurrentIndex(1); QMetaObject::connectSlotsByName(ImageDepth); } // setupUi void retranslateUi(QMainWindow *ImageDepth) { ImageDepth->setWindowTitle(QApplication::translate("ImageDepth", "ImageDepth", 0, QApplication::UnicodeUTF8)); algorithmLabel->setText(QApplication::translate("ImageDepth", "Algorithm", 0, QApplication::UnicodeUTF8)); algorithmComboBox->clear(); algorithmComboBox->insertItems(0, QStringList() << QApplication::translate("ImageDepth", "Block Matching Algorithm", 0, QApplication::UnicodeUTF8) << QApplication::translate("ImageDepth", "Semi-global block matching algorithm", 0, QApplication::UnicodeUTF8) << QApplication::translate("ImageDepth", "Variational matching algorithm", 0, QApplication::UnicodeUTF8) ); BMPreFilterCapLabel->setText(QApplication::translate("ImageDepth", "PreFilterCap", 0, QApplication::UnicodeUTF8)); BMSADWindowSizeLabel->setText(QApplication::translate("ImageDepth", "SADWindowSize", 0, QApplication::UnicodeUTF8)); BMMinimumDisparityLabel->setText(QApplication::translate("ImageDepth", "Minimum Disparity", 0, QApplication::UnicodeUTF8)); BMNumberOfDisparitiesLabel->setText(QApplication::translate("ImageDepth", "Number of Disparities", 0, QApplication::UnicodeUTF8)); BMTextureThresholdLabel->setText(QApplication::translate("ImageDepth", "Texture Threshold", 0, QApplication::UnicodeUTF8)); BMUniquenessRatioLabel->setText(QApplication::translate("ImageDepth", "Uniqueness Ratio", 0, QApplication::UnicodeUTF8)); BMSpeckleWindowSizeLabel->setText(QApplication::translate("ImageDepth", "Speckle Window Size", 0, QApplication::UnicodeUTF8)); BMSpeckleRangeLabel->setText(QApplication::translate("ImageDepth", "Speckle Range", 0, QApplication::UnicodeUTF8)); BMMaximumDisparityDifferenceLabel->setText(QApplication::translate("ImageDepth", "Maximum Disparity Difference", 0, QApplication::UnicodeUTF8)); tabWidget->setTabText(tabWidget->indexOf(tab), QApplication::translate("ImageDepth", "BM", 0, QApplication::UnicodeUTF8)); SGBMPreFilterCapLabel->setText(QApplication::translate("ImageDepth", "PreFilterCap", 0, QApplication::UnicodeUTF8)); SGBMSADWindowSizeLabel->setText(QApplication::translate("ImageDepth", "SADWindowSize", 0, QApplication::UnicodeUTF8)); SGBMMinimumDisparityLabel->setText(QApplication::translate("ImageDepth", "Minimum Disparity", 0, QApplication::UnicodeUTF8)); SGBMNumberOfDisparitiesLabel->setText(QApplication::translate("ImageDepth", "Number of Disparities", 0, QApplication::UnicodeUTF8)); SGBMUniquenessRatioLabel->setText(QApplication::translate("ImageDepth", "Uniqueness Ratio", 0, QApplication::UnicodeUTF8)); SGBMSpeckleWindowSizeLabel->setText(QApplication::translate("ImageDepth", "Speckle Window Size", 0, QApplication::UnicodeUTF8)); SGBMSpeckleRangeLabel->setText(QApplication::translate("ImageDepth", "Speckle Range", 0, QApplication::UnicodeUTF8)); SGBMMaximumDisparityDifferenceLabel->setText(QApplication::translate("ImageDepth", "Maximum Disparity Difference", 0, QApplication::UnicodeUTF8)); SGBMFullScale2xPassLabel->setText(QApplication::translate("ImageDepth", "Full Scale 2x Pass", 0, QApplication::UnicodeUTF8)); SGBMFullScale2xPassComboBox->clear(); SGBMFullScale2xPassComboBox->insertItems(0, QStringList() << QApplication::translate("ImageDepth", "True", 0, QApplication::UnicodeUTF8) << QApplication::translate("ImageDepth", "False", 0, QApplication::UnicodeUTF8) ); tabWidget->setTabText(tabWidget->indexOf(tab_3), QApplication::translate("ImageDepth", "SGBM", 0, QApplication::UnicodeUTF8)); VarIterationsLabel->setText(QApplication::translate("ImageDepth", "Iterations", 0, QApplication::UnicodeUTF8)); VarMinimumDisparityLabel->setText(QApplication::translate("ImageDepth", "Minimum Disparity", 0, QApplication::UnicodeUTF8)); VarMaximumDisparityLabel->setText(QApplication::translate("ImageDepth", "Maximum Disparity", 0, QApplication::UnicodeUTF8)); VarOrderOfPolynomialLabel->setText(QApplication::translate("ImageDepth", "Order of Polynomial ", 0, QApplication::UnicodeUTF8)); VarStandardDeviationLabel->setText(QApplication::translate("ImageDepth", "Standard Deviation", 0, QApplication::UnicodeUTF8)); VarSmoothnessLabel->setText(QApplication::translate("ImageDepth", "Smoothness", 0, QApplication::UnicodeUTF8)); VarThresholdLabel->setText(QApplication::translate("ImageDepth", "Threshold", 0, QApplication::UnicodeUTF8)); VarThresholdLineEdit->setText(QApplication::translate("ImageDepth", "0.03", 0, QApplication::UnicodeUTF8)); tabWidget->setTabText(tabWidget->indexOf(tab_2), QApplication::translate("ImageDepth", "Var", 0, QApplication::UnicodeUTF8)); } // retranslateUi }; namespace Ui { class ImageDepth: public Ui_ImageDepth {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_IMAGEDEPTH_H <file_sep>/src/imagedepth.cpp #include "imagedepth.h" #include "ui_imagedepth.h" #include <QDebug> ImageDepth::ImageDepth(QWidget *parent) : QMainWindow(parent), ui(new Ui::ImageDepth) { ui->setupUi(this); //setting BM constraints ui->BMPreFilterCapSlider->setRange(0, 31); ui->BMSADWindowSizeSlider->setRange(9, 200); ui->BMMaximumDisparityDifferenceSlider->setRange(0, 320); ui->BMSpeckleWindowSizeSlider->setRange(0, 300); ui->BMMaximumDisparityDifferenceSlider->setStepSize(16); ui->BMNumberOfDisparitiesSlider->setStepSize(16); //Setting SGBM constraints ui->SGBMNumberOfDisparitiesSlider->setStepSize(16); ui->SGBMNumberOfDisparitiesSlider->setRange(16,108); ui->SGBMSADWindowSizeSlider->setStepSize(2); ui->SGBMUniquenessRatioSlider->setRange(1, 200); ui->SGBMSADWindowSizeSlider->setRange(3, 15); ui->SGBMSpeckleWindowSizeSlider->setRange(0, 400); ui->SGBMSpeckleRangeSlider->setStepSize(16); //Setting Var Constraints ui->VarOrderOfPolynomialSlider->setRange(1, 7); //Setting BM values ui->BMPreFilterCapSlider->setPosition(31); ui->BMMinimumDisparitySlider->setPosition(0); ui->BMSADWindowSizeSlider->setPosition(9); ui->BMMaximumDisparityDifferenceSlider->setPosition((640/8 + 15) & -16); ui->BMTextureThresholdSlider->setPosition(10); ui->BMUniquenessRatioSlider->setPosition(15); ui->BMSpeckleWindowSizeSlider->setPosition(100); ui->BMSpeckleRangeSlider->setPosition(32); ui->BMMaximumDisparityDifferenceSlider->setPosition(1); ui->BMNumberOfDisparitiesSlider->setPosition(16); //Setting SGBM values ui->SGBMPreFilterCapSlider->setPosition(89); ui->SGBMSADWindowSizeSlider->setPosition(6); ui->SGBMMinimumDisparitySlider->setPosition(0); ui->SGBMNumberOfDisparitiesSlider->setPosition((640/8 + 15) & -16); ui->SGBMUniquenessRatioSlider->setPosition(99); ui->SGBMSpeckleWindowSizeSlider->setPosition(300); ui->SGBMSpeckleRangeSlider->setPosition(80); ui->SGBMMaximumDisparityDifferenceSlider->setPosition(51); //Setting Var values ui->VarIterationsSlider->setPosition(25); ui->VarMinimumDisparitySlider->setPosition(0); ui->VarMaximumDisparitySlider->setPosition((640/8 + 15) & -16); ui->VarOrderOfPolynomialSlider->setPosition(3); ui->VarSmoothnessSlider->setPosition(15); //connect all input signals to recalculate function QList<MyQSlider *> allSliders = findChildren<MyQSlider *>(); for(int i=0; i<allSliders.count(); i++) { connect(allSliders[i], SIGNAL(valueChanged(int)), this, SLOT(recalculate()) ); } connect(ui->VarThresholdLineEdit, SIGNAL(editingFinished()), this, SLOT(recalculate())); connect(ui->SGBMFullScale2xPassComboBox, SIGNAL(currentIndexChanged(QString)), this, SLOT(recalculate())); connect(ui->algorithmComboBox, SIGNAL(currentIndexChanged(QString)), this, SLOT(recalculate())); bmVariables = new BMVariables(); sgbmVariables = new SGBMVariables(); varVariables = new VarVariables(); mapValues(); emit(valuesChanged(*this->bmVariables, *this->sgbmVariables, *this->varVariables, 1)); } ImageDepth::~ImageDepth() { delete ui; } void ImageDepth::recalculate() { mapValues(); int algorithm; if( ui->algorithmComboBox->currentIndex() == 0 ) algorithm = ALG_BM; else if( ui->algorithmComboBox->currentIndex() == 1) algorithm = ALG_SGBM; else algorithm = ALG_VAR; qDebug() << "Algorithm:=" << algorithm; emit(valuesChanged(*this->bmVariables, *this->sgbmVariables, *this->varVariables, algorithm)); } void ImageDepth::mapValues() { bmVariables->preFilterCap = ui->BMPreFilterCapSlider->value(); bmVariables->SADWindowSize = ui->BMSADWindowSizeSlider->value(); bmVariables->minimumDisparity = ui->BMMinimumDisparitySlider->value(); bmVariables->numberofDisparities = ui->BMNumberOfDisparitiesSlider->value(); bmVariables->textureThreshold = ui->BMTextureThresholdSlider->value(); bmVariables->uniquenessRatio = ui->BMUniquenessRatioSlider->value(); bmVariables->speckleWindowSize = ui->BMSpeckleWindowSizeSlider->value(); bmVariables->speckleRange = ui->BMSpeckleWindowSizeSlider->value(); bmVariables->maximumDisparityDifference = ui->BMMaximumDisparityDifferenceSlider->value(); sgbmVariables->preFilterCap = ui->SGBMPreFilterCapSlider->value(); sgbmVariables->SADWindowSize = ui->SGBMSADWindowSizeSlider->value(); sgbmVariables->minimumDisparity = ui->SGBMMinimumDisparitySlider->value(); sgbmVariables->numberOfDisparities = ui->SGBMNumberOfDisparitiesSlider->value(); sgbmVariables->uniquenessRatio = ui->SGBMUniquenessRatioSlider->value(); sgbmVariables->speckleWindowSize = ui->SGBMSpeckleWindowSizeSlider->value(); sgbmVariables->speckleRange = ui->SGBMSpeckleRangeSlider->value(); sgbmVariables->maximumDisparityDifference = ui->SGBMMaximumDisparityDifferenceSlider->value(); sgbmVariables->setFullScale2xPass(ui->SGBMFullScale2xPassComboBox->currentText()); varVariables->iterations = ui->VarIterationsSlider->value(); varVariables->minimumDisparity = ui->VarMinimumDisparitySlider->value(); varVariables->maximumDisparity = ui->VarMaximumDisparitySlider->value(); varVariables->orderOfPolynomial = ui->VarOrderOfPolynomialSlider->value(); varVariables->standardDeviation = ui->VarStandardDeviationSlider->value(); varVariables->smoothness = ui->VarSmoothnessSlider->value(); varVariables->setThreshold(ui->VarThresholdLineEdit->text()); } <file_sep>/src/myqslider.h #ifndef MYQSLIDER_H #define MYQSLIDER_H #include <QWidget> #include <QSlider> namespace Ui { class MyQSlider; } class MyQSlider : public QWidget { Q_OBJECT public: explicit MyQSlider(QWidget *parent = 0); void setRange(int minimum, int maximum); void setPosition(int value); void setStepSize(int value); int value(); QSlider *Slider; ~MyQSlider(); public slots: void updateValue(); signals: void valueChanged(const int); private: int stepSize; Ui::MyQSlider *ui; }; #endif // MYQSLIDER_H <file_sep>/src/bmvariables.cpp #include "bmvariables.h" BMVariables::BMVariables() { } <file_sep>/src/imagedepthprocessor.h #ifndef IMAGEDEPTHPROCESSOR_H #define IMAGEDEPTHPROCESSOR_H #include <ros/ros.h> #include <image_transport/image_transport.h> #include <cv_bridge/cv_bridge.h> #include <sensor_msgs/image_encodings.h> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/contrib/contrib.hpp> #include <opencv2/calib3d/calib3d.hpp> #include <QObject> #include "bmvariables.h" #include "sgbmvariables.h" #include "varvariables.h" namespace enc = sensor_msgs::image_encodings; using namespace cv; static const char WINDOW[] = "Stereo vision"; class ImageDepthProcessor : public QObject { Q_OBJECT public: explicit ImageDepthProcessor(QObject *parent = 0); void imageLeftGetData(const sensor_msgs::ImageConstPtr& msg); void imageRightGetDataAndProcess(const sensor_msgs::ImageConstPtr& msg); void killProcess(); ~ImageDepthProcessor(); signals: void finished(); void error(QString err); public slots: void process(); void deleteLater(); void updateValues(const BMVariables &bm, const SGBMVariables &sgbm, const VarVariables &var, const int algorithm); private: int algorithm; BMVariables bmVariables; SGBMVariables sgbmVariables; VarVariables varVariables; ros::NodeHandle nh_; image_transport::ImageTransport it_; image_transport::Subscriber imageLeftSubscribe; image_transport::Subscriber imageRightSubscribe; image_transport::Publisher imageStereoPublish; Mat imageLeft; Mat imageRight; bool imageLeftUpdated; bool valuesInitialized; }; #endif // IMAGEDEPTHPROCESSOR_H <file_sep>/CMakeLists.txt cmake_minimum_required(VERSION 2.4.6) include($ENV{ROS_ROOT}/core/rosbuild/rosbuild.cmake) # Set the build type. Options are: # Coverage : w/ debug symbols, w/o optimization, w/ code-coverage # Debug : w/ debug symbols, w/o optimization # Release : w/o debug symbols, w/ optimization # RelWithDebInfo : w/ debug symbols, w/ optimization # MinSizeRel : w/o debug symbols, w/ optimization, stripped binaries #set(ROS_BUILD_TYPE RelWithDebInfoa) rosbuild_init() FIND_PACKAGE(Qt4 REQUIRED) SET(image_depth_ui_SOURCES src/imagedepth.cpp src/main.cpp src/myqslider.cpp src/imagedepthprocessor.cpp src/bmvariables.cpp src/sgbmvariables.cpp src/varvariables.cpp) SET(image_depth_ui_HEADERS src/imagedepth.h src/ui_imagedepth.h src/myqslider.h src/ui_myqslider.h src/imagedepthprocessor.h src/bmvariables.h src/sgbmvariables.h src/varvariables.h) SET(image_depth_ui_FORMS src/imagedepth.ui src/myqslider.ui) QT4_WRAP_UI(image_depth_ui_FORMS_HEADERS ${image_depth_ui_FORMS}) QT4_WRAP_CPP(image_depth_ui_HEADERS_MOC ${image_depth_ui_HEADERS}) INCLUDE(${QT_USE_FILE}) ADD_DEFINITIONS(${QT_DEFINITIONS}) INCLUDE_DIRECTORIES( ${PROJECT_SOURCE_DIR}/bin ) #set the default path for built executables to the "bin" directory set(EXECUTABLE_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/bin) #set the default path for built libraries to the "lib" directory set(LIBRARY_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/lib) #uncomment if you have defined messages #rosbuild_genmsg() #uncomment if you have defined services #rosbuild_gensrv() #common commands for building c++ executables and libraries #rosbuild_add_library(${PROJECT_NAME} src/example.cpp) #target_link_libraries(${PROJECT_NAME} another_library) #rosbuild_add_boost_directories() #rosbuild_link_boost(${PROJECT_NAME} thread) rosbuild_add_executable(image_depth_ui src/main.cpp ${image_depth_ui_FORMS_HEADERS} ${image_depth_ui_SOURCES} ${image_depth_ui_HEADERS_MOC} ) target_link_libraries(image_depth_ui ${QT_LIBRARIES}) #target_link_libraries(example ${PROJECT_NAME}) <file_sep>/src/varvariables.h #ifndef VARVARIABLES_H #define VARVARIABLES_H #include <QString> class VarVariables { public: VarVariables(); int iterations; int minimumDisparity; int maximumDisparity; int orderOfPolynomial; int standardDeviation; int smoothness; float threshold; void setThreshold(QString value); }; #endif // VARVARIABLES_H <file_sep>/src/ui_myqslider.h /******************************************************************************** ** Form generated from reading UI file 'myqslider.ui' ** ** Created: Tue Dec 25 17:18:14 2012 ** by: Qt User Interface Compiler version 4.8.1 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_MYQSLIDER_H #define UI_MYQSLIDER_H #include <QtCore/QVariant> #include <QtGui/QAction> #include <QtGui/QApplication> #include <QtGui/QButtonGroup> #include <QtGui/QHeaderView> #include <QtGui/QLabel> #include <QtGui/QSlider> #include <QtGui/QWidget> QT_BEGIN_NAMESPACE class Ui_MyQSlider { public: QLabel *valueLabel; QSlider *slider; void setupUi(QWidget *MyQSlider) { if (MyQSlider->objectName().isEmpty()) MyQSlider->setObjectName(QString::fromUtf8("MyQSlider")); MyQSlider->resize(420, 26); valueLabel = new QLabel(MyQSlider); valueLabel->setObjectName(QString::fromUtf8("valueLabel")); valueLabel->setGeometry(QRect(345, 2, 66, 22)); slider = new QSlider(MyQSlider); slider->setObjectName(QString::fromUtf8("slider")); slider->setGeometry(QRect(0, 2, 330, 22)); slider->setOrientation(Qt::Horizontal); retranslateUi(MyQSlider); QMetaObject::connectSlotsByName(MyQSlider); } // setupUi void retranslateUi(QWidget *MyQSlider) { MyQSlider->setWindowTitle(QApplication::translate("MyQSlider", "Form", 0, QApplication::UnicodeUTF8)); valueLabel->setText(QApplication::translate("MyQSlider", "TextLabel", 0, QApplication::UnicodeUTF8)); } // retranslateUi }; namespace Ui { class MyQSlider: public Ui_MyQSlider {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_MYQSLIDER_H <file_sep>/src/main.cpp #include <QtGui/QApplication> #include <QThread> #include <QObject> #include <QMetaType> #include <QDebug> #include <ros/ros.h> #include "imagedepth.h" #include "imagedepthprocessor.h" #include "bmvariables.h" #include "sgbmvariables.h" #include "varvariables.h" int main(int argc, char *argv[]) { QApplication a(argc, argv); ImageDepth *w = new ImageDepth(); w->show(); ros::init(argc, argv, "image_3D_stereo"); QThread *thread = new QThread; ImageDepthProcessor *imgDepth = new ImageDepthProcessor(); imgDepth->moveToThread(thread); QObject::connect(thread, SIGNAL(started()), imgDepth, SLOT(process())); QObject::connect(imgDepth, SIGNAL(finished()), thread, SLOT(quit())); QObject::connect(imgDepth, SIGNAL(finished()), imgDepth, SLOT(deleteLater())); QObject::connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater())); qRegisterMetaType<BMVariables>("BMVariables"); qRegisterMetaType<SGBMVariables>("SGBMVariables"); qRegisterMetaType<VarVariables>("VarVariables"); QObject::connect(w, SIGNAL(valuesChanged(BMVariables,SGBMVariables,VarVariables, int)), imgDepth, SLOT(updateValues(BMVariables,SGBMVariables,VarVariables, int))); thread->start(); a.exec(); imgDepth->killProcess(); } <file_sep>/src/sgbmvariables.cpp #include "sgbmvariables.h" #include <QString> SGBMVariables::SGBMVariables() { } void SGBMVariables::setFullScale2xPass(const QString value) { QString trueValue("true"); if( trueValue == value ) fullScale2xPass = true; else fullScale2xPass = false; } <file_sep>/src/myqslider.cpp #include "myqslider.h" #include "ui_myqslider.h" MyQSlider::MyQSlider(QWidget *parent) : QWidget(parent), ui(new Ui::MyQSlider) { ui->setupUi(this); connect(ui->slider, SIGNAL(valueChanged(int)), this, SLOT(updateValue())); Slider = ui->slider; stepSize = 1; updateValue(); } MyQSlider::~MyQSlider() { delete ui; } void MyQSlider::updateValue() { QString value; int sliderValue = ui->slider->value(); if( sliderValue % stepSize != 0 ) { sliderValue = sliderValue - sliderValue % stepSize; ui->slider->setValue(sliderValue); } value.append(QString("%1").arg(sliderValue)); ui->valueLabel->setText(value); emit(valueChanged(sliderValue)); } void MyQSlider::setRange(int minimum, int maximum) { ui->slider->setRange(minimum, maximum); } void MyQSlider::setPosition(int value) { ui->slider->setValue(value); } void MyQSlider::setStepSize(int value) { stepSize = value; ui->slider->setTickInterval(value); ui->slider->setPageStep(value*2); ui->slider->setSingleStep(value); } int MyQSlider::value() { return ui->slider->value(); }
1ad0e1083c95164e793b695c20d4c12eca0e5083
[ "Markdown", "CMake", "C++" ]
17
C++
Hudhaifa/ros-stereo-vision-tuner
12075c4b640ca2052262159eafe862bc4c6614e9
96f29eb2f9e7fe6b9a7913dfc418952aa902a34e
refs/heads/main
<repo_name>Uzair41293/DemoPos<file_sep>/app/Http/Controllers/investorController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Controllers\accountsController; use App\Http\Controllers\LedgerPartiesController; use Carbon\Carbon; use DB; class investorController extends Controller { public static function addInvestorProduct(Request $request, $CO){ $ata=json_decode($CO); $investorID=$ata[0]; $data=$ata[1]; $totalProfit=0; foreach ($data as $obj){ $PID=$obj[0]; $salePrice=$obj[1]; $purchasePrice=$obj[2]; $profit=$obj[3]; $selfProfit=$obj[4]; $investorProfit=$obj[5]; $investorProfitRatio=$investorProfit/$profit; $selfProfitRatio=$selfProfit/$profit; $id=DB::table('tbl_investor_product')->insertGetId([ 'PID'=>$PID, 'LID'=>$investorID, 'totalProfit'=>$profit, 'LIDProfit'=>$investorProfit, 'LIDProfitRatio'=>$investorProfitRatio, 'SelfProfit'=>$selfProfit, 'SelfProfitRatio'=>$selfProfitRatio, 'Status'=>"Pending" ]); $totalProfit=$totalProfit+$investorProfit; } $oldCompanyBalance=LedgerPartiesController::getPartyBalance($investorID); $currentCompanyBalance=floatval($oldCompanyBalance)+floatval($totalProfit); LedgerPartiesController::UpdatePartiesBalance($investorID,$currentCompanyBalance); return $id; } /* $oldSelfBalance = LedgerPartiesController::getPartyBalance(2); $newBalance = $oldSelfBalance - $amount; LedgerPartiesController::UpdatePartiesBalance(2, $newBalance); $balanceForParty=LedgerPartiesController::getPartyBalance($paidTo); $newBalanceOfParty=$balanceForParty-$amount; LedgerPartiesController::UpdatePartiesBalance($paidTo, $newBalanceOfParty); $oldAccountBalance = accountsController::getAccountBalance($paidBy); $newAccountBalance = $oldAccountBalance - $amount; accountsController::UpdateNewBalance($paidBy, $newAccountBalance); */ public static function insertInvestor(Request $request, $CO){ $obj=json_decode($CO); $name=$obj[0]; $category=$obj[1]; $investment=$obj[2]; $contantNo=$obj[3]; $address=$obj[4]; $selfRatio=$obj[5]; $investorRatio=$obj[6]; $id=DB::table('tblledgerparties')->insertGetId([ 'PartyName'=>$name, 'Category'=>$category, 'InitialInvestment'=>$investment, 'ContantNo'=>$contantNo, 'Address'=>$address, 'OurProfitRatio'=>$selfRatio, 'InvestorProfitRatio'=>$investorRatio ]); return $id; } function getInvestorData(){ $data=DB:: select('select * from vw_stockdetails where Category = 20'); return $data; } public static function getInvestors(){ $data=DB:: select('select * from tblledgerparties where Category = "Investor"'); $option='<option value=" "></option>'; foreach ($data as $d){ //print $option; $option=$option.' <option value= '.$d->LID.'>'.$d->LID.') '.$d->PartyName.'</option>'; } return $option; } public static function getInvestorDetails(Request $request, $LID){ $investorDetails=DB:: select('select * from tblledgerparties where LID ='.$LID); return $investorDetails; } function getInvestorStock($InvestorID){ $data=DB:: select('select * from vw_investor_product where LID='.$InvestorID); $table=''; foreach ($data as $d){ //print $option; $table=$table.' <tr> <td>'.$d->ProductID.'</td> <td>'.$d->ProductName.'</td> <td>'.$d->TotalSaleAmount.'</td> <td>'.$d->TotalCost.'</td> <td>'.$d->totalProfit.'</td> <td>'.$d->SelfProfit.'</td> <td>'.$d->LIDProfit.'</td> <td>'.$d->EngineNumber.'</td> <td>'.$d->ChasisNumber.'</td> <td style=" display:none;">1</td> </tr>'; } return $table; } } <file_sep>/app/Http/Controllers/LedgerPartiesController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use DB; class LedgerPartiesController extends Controller { public static function UpdatePartiesBalance($LID,$amount){ // LID int(11) AI PK // PartyName varchar(45) // Category varchar(45) // Balance float // ContantNo varchar(45) // Address varchar(100) // Status varchar(45) // $OldBalance=DB::select('select Balance from tblledgerparties where LID='.$LID); // $currentBalance=floatval ($OldBalance)+floatval ($amount); DB::table('tblledgerparties') ->where('LID', $LID) ->update(['Balance' =>$amount ]); return 'update New Balance'; } public static function getPartyBalance($LID){ $re = DB::table('tblledgerparties') ->where('LID', '=', $LID) ->first()->Balance; return $re; } public static function getAllSuplierParties(){ $results=DB::select('select * from tblledgerparties where Category="Supplier"' ); $sOp='<option value=" "></option>'; $tableOfHtml=""; foreach ($results as $ro){ $tableOfHtml=$tableOfHtml." <option value=".$ro->LID.">".$ro->PartyName."</option>"; } $endSelect="</select>"; $allHtml=$sOp . $tableOfHtml . $endSelect; return $allHtml; } public function getPartyDetail($SID){ $results=DB::select('select * from tblledgerparties where LID= '.$SID); // mysql_insert_id() return $results; } } <file_sep>/app/Http/Controllers/AddMenucontroller.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; // use DB; // class AddMenucontroller extends Controller // { // public function insertProduct(Request $request, $CO) // { // $obj=json_decode($CO); // $Pname=$obj[0]; // $Pcateg=$obj[1]; // $Psaleprice=$obj[2]; // $Ppurchaseprice=$obj[3]; // self:: insertintblproductdefination( $Pname,$Pcateg,$Psaleprice,$Ppurchaseprice); // $StockProductSerial=DB::table("productdefination")->max('ProductSerial'); // DB::table('productdefination') // ->where('ProductSerial', $StockProductSerial) // ->update(['ProductID' =>$StockProductSerial // ]); // //$e=DB::table("productdefination")->insertGetId(['ProductName'=>$Pname // //] // //); // //return print(mysql_insert_id()); // // return $e; // print("Agya yha tk"); // self:: insertintblinstock(null,$StockProductSerial,"404","0",$Ppurchaseprice,$Psaleprice,null,$Psaleprice,$Ppurchaseprice,null); // return "Getting from controller".$StockProductSerial; // } // public function insertintblproductdefination( // $PDProductName, // $PDCategory, // $PproductCost, // $Pproductsaleprice // ){ // $result= DB::insert('insert into productdefination (ProductName,Category,productCost, // productsaleprice) // value(?,?,?,?)', // [$PDProductName, $PDCategory,$PproductCost, // $Pproductsaleprice]); // if ($result==1){ // print("product"); // } // } // public function insertstock() // { // $obj=json_decode($CO); // $StockID=$obj[0]; // $StockProductSerial=$obj[1]; // $StockIn=$obj[2]; // $PreviousStock=$obj[3]; // $stockPerUnitPurchasePrice=$obj[4]; // $StockPerUnitSalePrice=$obj[5]; // $StockExpairyDate=$obj[6]; // $StockAverageSalePricePerUnit=$obj[7]; // $StockAveragePurchasePricePerUnit=$obj[8]; // $dateNow= Carbon::now()->toDateTimeString(); // $StockdateStamp=$dateNow; // self:: insertintblproductdefination($StockID,$StockProductSerial,$StockIn,$PreviousStock,$stockPerUnitPurchasePrice,$StockPerUnitSalePrice,null,$StockAverageSalePricePerUnit,$StockAveragePurchasePricePerUnit,null); // return "Getting from controller".$obj[0]; // } // public function insertintblinstock ( // $SStockID, // $SProductSerial, // $SStockIn, // $SPreviousStock, // $SPerUnitPurchasePrice, // $SPerUnitSalePrice, // $SExpairyDate, // $SAverageSalePricePerUnit, // $SAveragePurchasePricePerUnit, // $SdateStamp // ){ // $result= DB::insert('insert into instock (ProductSerial,StockIn,PreviousStock, // PerUnitPurchasePrice, PerUnitSalePrice, // AverageSalePricePerUnit,AveragePurchasePricePerUnit) // value(?,?,?,?,?,?,?)', // [$SProductSerial,$SStockIn,$SPreviousStock, $SPerUnitPurchasePrice, $SPerUnitSalePrice, // $SAverageSalePricePerUnit,$SAveragePurchasePricePerUnit]); // if ($result==1){ // print("einstock"); // } // } // } use DB; class AddMenucontroller extends Controller { public function fetchMenu($CID){ $results=DB::select('select * from vw_stockdetails where Category='.$CID); $MenuTable=""; foreach ($results as $ro){ $MenuTable=$MenuTables.'<div class="card"> <div class="myPare"> <div class="item-5"> <img src="./img/khyberpass_menustarter.jpg" class="img-fluid" style="height:70px;width:70px;border-radius:10px;" > </div> <div class="item-1"> <!-- <h5 id="demo"></h5> --> <h5>'.$ro->ProductName.'<input type="text" style="width: 100px;" value=\''.$ro->ProductName.'\' name="" id="pname"><input type="text" value='.$ro->ProductCat.' style="width: 100px;" name="" id="pid"> <input style="width: 100px;" value='.$ro->PerUnitSalePrice.' type="number" name="" id="salePrice"><input style="width: 100px;" value='.$ro->PerUnitSalePrice.' type="text" name="" id="inp-4"></h5> <p>'.$ro->productDescription.'</p> </div> <div class="item-3"> <div class="itemPricing"> <div id="demo-2">£'.$ro->PerUnitSalePrice.'</div> </div> </div> <div class="item-4"> <button class="btn btn-success" onclick="addItem(this)" value="Increment Value">Add</button> </div> </div> </div>'; } return $menuCard; } function getCategories(){ $results=DB::select('select * from tblpcategory'); $pill=""; foreach ($results as $ro){ $pill=$pill.' <li class="nav-item"> <a class="nav-link active" id="pills-Starter-tab" data-toggle="pill" href="#pills-Starter" role="tab" aria-controls="pills-Starter" aria-selected="true" onclick="FetchMenu('.$ro->PCID.') ">'.$ro->CategoryName.'</a> </li>'; } return $pill; } function getAllCategories(){ $results=DB::select('select * from tblpcategory'); $option='<option value=" "></option>'; foreach ($results as $ro){ $options=$options.'<option value='.$ro->PCID.'>'.$ro->CategoryName.'</option>'; } return $options; } public function fetchAllMenu(){ $results=DB::select('select * from vw_stockdetails'); return $results; } public static function loadProductCategory(){ $data=DB:: select('select * from tblpcategory where CategoryName <> "Autos"'); $option='<option value=" "></option>'; foreach ($data as $d){ //print $option; $option=$option.' <option value= '.$d->PCID.'>'.$d->CategoryName.'</option>'; } return $option; } public static function insertProducts(Request $request, $CO){ $array=json_decode($CO); foreach($array as $obj){ $ProductName=$obj[0]; $ProductCat=$obj[1]; $Productsaleprice=$obj[2]; $ProductCost=$obj[3]; $Description=$obj[4]; $ProductSerial=DB::table('productdefination')->insertGetId([ 'ProductName'=>$ProductName, 'Category'=>$ProductCat, ]); DB::table('productdefination') ->where('ProductSerial', $ProductSerial) ->update(['ProductID' =>$ProductSerial, 'Barcode' =>'*'.$ProductSerial.'*' ]); $id2=DB::table('instock')->insertGetId([ 'ProductSerial'=>$ProductSerial, 'StockIn'=>'0', 'TotalCost'=>$ProductCost, 'TotalSaleAmount'=>$Productsaleprice, 'PerUnitSalePrice'=>$Productsaleprice, 'PerUnitPurchasePrice'=>$ProductCost, 'Remarks'=>$Description, ]); } return "Done all"; } } <file_sep>/app/Http/Controllers/saleInvoiceEditController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use db; use Carbon\Carbon; use App\Http\Controllers\salesFlow; use App\Http\Controllers\UpdateStocksController; class saleInvoiceEditController extends Controller { public function UpdateSaleInvoice(Request $request,$data,$InvoiceID){ $Array=json_decode($data); $tot=$Array[1]; $OverAllDiscount= $Array[2]; $AmountAfterDiscount=$Array[3]; $tax =$Array[4]; $netTotal=$Array[5]; $AP=$Array[6]; $RBI=$Array[7]; $CID=$Array[8]; $CLB=$Array[9]; $CCB=$Array[10]; $AID=$Array[11]; $ProductsInTable=$Array[0]; ////getAllInvoiceDetails $oldSalesDetails=salesFlow::getAllInvoiceDetails($InvoiceID); foreach($oldSalesDetails as $product){ $qty=$product->Quantity; $PID=$product->ProductSerial; $oldStock= UpdateStocksController::getCurrentStock($PID); $newStock= floatval($oldStock)+floatval($qty); UpdateStocksController::updateStock($PID,$newStock); } //Restoring Balance $amount = DB::table('tbltransactionflow') ->where('InvoiceNo', '=', $InvoiceID) ->first()->Amount; $cumstomerBalance = DB::table('customeinformation') ->where('CustomerID', '=', $CID) ->first()->Balance; //return $amount; $SelfBalance = LedgerPartiesController::getPartyBalance(2); $newSelfBalance = $SelfBalance - $amount; $newCumstomerBalance =$cumstomerBalance - $amount; LedgerPartiesController::UpdatePartiesBalance(2, $newSelfBalance); DB::table('customeinformation') ->where('CustomerID', $CID) ->update([ 'Balance'=>$newCumstomerBalance ]); self::deleteInTnblSaleInvoiceDetails($InvoiceID); //+++++++++++++++++++++++++++++++++++++++++++++++++++// //_________________// $dateNow= Carbon::now()->toDateTimeString(); self::insertInDetailedOrder($Array[0],$InvoiceID,$dateNow); self::updateintblSaleInvoice($InvoiceID,$tot,$OverAllDiscount,$tax,$netTotal,$AP,$RBI); } public function insertInDetailedOrder($OrderDetails,$InvoiceID,$date){ foreach ($OrderDetails as $row){ $DSID=DB::table('tblsaledetailedinvoice')->insertGetId(['InvoiceNumber'=>$InvoiceID, 'ProductSerial'=>$row[0], 'SalePrice'=>$row[1], 'Quantity'=>$row[2], 'DiscountOffered'=>$row[3], 'DateStamp'=>$date, 'TotalAmount'=>0, 'NetAmount'=>$row[4], 'Activity'=>"Sales", 'RentedDays'=>0 ]); $oldStock= UpdateStocksController::getCurrentStock($row[0]); $newStock= floatval($oldStock)-floatval($row[2]); UpdateStocksController::updateStock($row[0],$newStock); } return $InvoiceID; } public function deleteInTnblSaleInvoiceDetails($IID){ $Deleted = DB:: delete("delete from tblsaledetailedinvoice where InvoiceNumber=".$IID); print($Deleted); } public function updateintblSaleInvoice($InvoiceID,$tot,$OverAllDiscount,$tax,$netTotal,$AP,$RBI){ DB::table('tblsaleinvoice') ->where('InvoiceNumber', $InvoiceID) ->update([ 'TotalAmount'=>$tot, 'Discount'=>$OverAllDiscount, 'VAT'=>$tax, 'NetTotal'=>$netTotal, 'AmountPaid'=>$AP, 'Balance'=>$RBI, ]); } public function updateBalnce($AP,$RBI){ $oldSelfBalance = LedgerPartiesController::getPartyBalance(2); $newBalance = $oldSelfBalance + $AP; $newCumstomerBalance =$cumstomerBalance - $AP; LedgerPartiesController::UpdatePartiesBalance(2, $newBalance); DB::table('customeinformation') ->where('CustomerID', $CID) ->update([ 'Balance'=>$newCumstomerBalance ]); } } <file_sep>/app/Http/Controllers/salesFlow.php <?php namespace App\Http\Controllers; use Carbon\Carbon; use NumberToWords\NumberToWords; //https://github.com/kwn/number-to-words use Illuminate\Http\Request; use App\Http\Controllers\CustomerController; use App\Http\Controllers\saleRequestController; use App\Http\Controllers\UpdateStocksController; use App\Http\Controllers\TransactionFlow; use App\Http\Controllers\LedgerPartiesController; use App\Http\Controllers\accountsController; use DB; use PDF; class salesFlow extends Controller { function viewSales(){ $data=DB:: select('select * from vw_customersale_invoice'); return $data; } public function SalesFlow(Request $request,$data){ // order = [pid,totwT,discount,netTotal,amp,rmb,CID]; $Array=json_decode($data); $pid=$Array[0]; $tot=$Array[1]; $OverAllDiscount= $Array[2]; $AmountAfterDiscount=$Array[3]; $amp =$Array[4]; $rmb=$Array[5]; $CID=$Array[6]; $TransactionMode=$Array[7]; $AID=$Array[8]; $customerName =$Array[9]; $CNIC=$Array[10]; $address=$Array[11]; $contact=$Array[12]; $fatherName=$Array[13]; $engineNo=$Array[14]; $chassisNo=$Array[15]; $color=$Array[16]; $description=$Array[17]; $productName=$Array[18]; $city=$Array[19]; $receivedBy=$Array[20]; $totalCost=$Array[21]; //return $TransactionMode; $dateNow= Carbon::now()->toDateString();//->format('Y-m-d h:iA'); // $d= Carbon::createFromFormat('dd/mm/YYYY HH:MM:SS', $dateNow); //return $dateNow; //tot,discount,gross,tax,netTotal,amp,rmb,CID,CLB,CCB //insert into sales order if( $rmb>0){ $invoiceStatus="Not Cleared"; } else{ $invoiceStatus="CLEARED"; } $invoiceNumber=DB::table('tblsaleinvoice')->insertGetId(['CustomerID'=>$CID, 'TotalAmount'=>$tot, 'Discount'=>$OverAllDiscount, 'DateStamp'=>$dateNow, 'VAT'=>NULL, 'NetTotal'=>$AmountAfterDiscount, 'AmountPaid'=>$amp, 'Balance'=>$rmb, 'BillStatus'=>$invoiceStatus, 'HoldStatus'=>'0', 'CustomerBalanceBeforeInvoiceBill'=>NULL, 'CustomerBalanceAfterInvoiceBill'=>NULL, 'CashPaidBack'=>NULL, 'CashNote'=>NULL, 'Remarks'=>NULL, 'dliveryDate'=>NULL, 'returnDate' =>NULL ]); // $TransactionMode='2'; $detailedOrder=array($pid,$tot,"1",$OverAllDiscount,$AmountAfterDiscount,$tot); // return $detailedOrder[1]; self::insertInDetailedOrder($detailedOrder,$invoiceNumber,$dateNow); // TransactionFlow::addInTransactionFlowForSales("1",$invoiceNumber,$dateNow,$amp,"1",NULL,NULL,NULL); $oldSelfBalance= LedgerPartiesController::getPartyBalance(2); $oldCompanyBalance= LedgerPartiesController::getPartyBalance(1); $LID=2; $paidVia=$AID; $selfBalance=$oldSelfBalance+$amp; TransactionFlow::addTransaction($invoiceNumber,"Debit","Sales", $amp,$dateNow,"1",$oldSelfBalance,$selfBalance,NULL,NULL,$LID,"0",$CID,"0",$paidVia,NULL); LedgerPartiesController::UpdatePartiesBalance(2, $selfBalance); $OldAccBalance=accountsController::getAccountBalance($AID); $newAccountBalance=floatval($OldAccBalance)+floatval($amp); accountsController::UpdateNewBalance($AID,$newAccountBalance); if($TransactionMode==2){ $LID=2; $paidVia=$AID; $oldBalance= LedgerPartiesController::getPartyBalance($LID); $currentBalance=floatval ($oldBalance)-floatval ($amp); TransactionFlow::addTransaction($invoiceNumber,"Credit","Customer Paid to Company", $amp,$dateNow,"2", $oldBalance,$currentBalance,NULL,NULL,$LID,"0",$CID,"1",$paidVia,NULL); $oldSelfBalance= LedgerPartiesController::getPartyBalance(2); $companyBalance=$oldCompanyBalance-$amp; $selfBalance=$oldSelfBalance-$amp; LedgerPartiesController::UpdatePartiesBalance(1, $companyBalance); LedgerPartiesController::UpdatePartiesBalance(2, $selfBalance); $OldAccBalance=accountsController::getAccountBalance($AID); $newAccountBalance=floatval($OldAccBalance)-floatval($amp); // accountsController::getAccountBalance($AID); accountsController::UpdateNewBalance($AID,$newAccountBalance); } UpdateStocksController::UpdateStockStatus($pid,"Sold"); saleRequestController::getInvoiceSaleRequest($invoiceNumber); return $invoiceNumber; } public function insertInDetailedOrder($row,$InvoiceID,$date){ $DSID=DB::table('tblsaledetailedinvoice')->insertGetId(['InvoiceNumber'=>$InvoiceID, 'ProductSerial'=>$row[0], 'SalePrice'=>$row[1], 'Quantity'=>$row[2], 'DiscountOffered'=>$row[3], 'DateStamp'=>$date, 'TotalAmount'=>$row[5], 'NetAmount'=>$row[4], 'Activity'=>"Sales", 'RentedDays'=>0 ]); return $DSID; } public function apiCheck() { $obj = (object) [ 'aString' => 'some string', 'anArray' => [ 1, 2, 3 ] ]; return json_encode($obj); # code... } public function getInvoiceNewID(){ $IID=DB::table('tblsaleinvoice')->max("InvoiceNumber"); return $IID+1; } public static function getAllInvoiceDetails($InvoiceNo){ $results=DB::select('select * from vw_customersale_invoice where InvoiceNumber= '.$InvoiceNo); return $results; } public function printSaleInvoice() { $newHTML='<table border="0"> <thead> <tr> <th><br><h1>FORLAND MODREN MOTORS</h1></th> </tr> </thead> <tbody> <tr> <br> <td> NTN:82588676-6 <br> STRN:3277876204764 <br> Customer\'s Copy </td> </tr> <tr><td align="center"><h1>Sales Invoice</h1></td></tr> </tbody> </table> <br> <br> <br> <table border="0"> <tbody> <tr> <td><br><span style="font-size: medium;">Customer Name</span></td> <td align="center"><br>____________</td> <td><br><span style="font-size: medium;">Booking No</span></td> <td align="center"><br>____________</td> </tr> <tr> <td><br><span style="font-size: medium;">Address</span></td> <td align="center"><br>____________</td> <td><br><span style="font-size: medium;">Invoice Number</span></td> <td align="center"><br>____________</td> </tr> <tr> <td><br><span style="font-size: medium;">CNIC/NTN</span></td> <td align="center"><br>____________</td> <td><br><span style="font-size: medium;">Invoice Date</span></td> <td align="center"><br>____________</td> </tr> <tr> <td><br><span style="font-size: medium;">Contact</span></td> <td align="center"><br>____________</td> <td><br><span style="font-size: medium;"></span></td> <td align="center"><br>____________</td> </tr> </tbody> </table> <br> <br> <br> <br> <table border="1" > <tr ><td> <table border="0"> <thead> <tr> <td align="left" bgcolor="#C0C0C0" > Description </td> <td align="center" bgcolor="#C0C0C0" >color</td> <td align="center"bgcolor="#C0C0C0" >Engine No</td> <td align="center" bgcolor=" #C0C0C0">Chassis No</td> <td align="center" bgcolor=" #C0C0C0">Amount</td> </tr> </thead> <tbody > <tr > <td ></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> </tbody> </table> </td> </tr> </table> <table border="0"> <thead> <tr> <th width="60%" border="1" align="center"> Total in Word </th> <th width="40%" border="1" align="center"> Tootal PKR</th> </tr> </thead> <tbody> <tr> <td width="60%" border="1" align="center">1000</td> <td width="40%" border="1" align="center">10000</td> </tr> <br> <br> <br> <br> <br> <br> <br> <tr> <td width="60%" border="0"></td> <td width="40%" align="center" border="0">_______________________</td> </tr> <tr> <br> <td width="60%" border="0"></td> <td width="40%" align="center" border="0">Sign and Signature</td> </tr> </tbody> </table> <br><br> <br> <br> <table border="0"> <tr> <td bgcolor="crimson" align="center" border="0"><h4>8-km Sheikhupura Road, Opposite Milat Tractors Limited,Lahore,Tel:0300-0600061 </h4></td> </tr> <tr> <td bgcolor="crimson" align="center" border="0"><h5> Email Adress: <EMAIL> </h5></td> </tr> </table> '; // $html= $htmldata; PDF::SetTitle('Sale Invoice'); PDF::AddPage(); PDF::writeHTML($newHTML, true, false, true, false, ''); PDF::Output('saleInvoice.pdf'); } } <file_sep>/app/Http/Controllers/salePrintInvoice.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Carbon\Carbon; use DB; use PDF; use NumberToWords\NumberToWords; class salePrintInvoice extends Controller { public function serviceSalesRequest() { $newHTML='<table border="0"> <thead> <tr> <th><br><h1>FORLAND MODREN MOTORS</h1></th> </tr> </thead> <tbody> <tr> <br> <td> NTN:82588676-6 <br> STRN:3277876204764 <br> Customer\'s Copy </td> </tr> <tr><td align="center"><h1>Service Sale Invoice</h1></td></tr> </tbody> </table> <br> <br> <br> <table border="0"> <tbody> <tr> <td><br><span style="font-size: medium;">Customer Name:</span></td> <td align="center"><br>'.session()->get("customerName").'</td> <td><br><span style="font-size: medium;">Booking No:</span></td> <td align="center"><br>BO-FMM-'.session()->get("invoiceNo").'</td> </tr> <tr> <td><br><span style="font-size: medium;">Address:</span></td> <td align="center"><br>'.session()->get("address").'</td> <td><br><span style="font-size: medium;">Invoice Number:</span></td> <td align="center"><br>'.session()->get("invoiceNo").'</td> </tr> <tr> <td><br><span style="font-size: medium;">CNIC/NTN:</span></td> <td align="center"><br>'.session()->get("CNIC").'</td> <td><br><span style="font-size: medium;">Invoice Date:</span></td> <td align="center"><br>'.session()->get("invoiceDate").'</td> </tr> <tr> <td><br><span style="font-size: medium;">Contact:</span></td> <td align="center"><br>'.session()->get("contact").'</td> <td><br><span style="font-size: medium;"></span></td> <td align="center"><br></td> </tr> </tbody> </table> <br> <br> <br> <br> <table border="1" > <tr ><td> <table border="0"> <thead> <tr> <td align="center" bgcolor="#C0C0C0" > Description </td> <td align="center" bgcolor="#C0C0C0" >color</td> <td align="center"bgcolor="#C0C0C0" >Engine No</td> <td align="center" bgcolor=" #C0C0C0">Chassis No</td> <td align="center" bgcolor=" #C0C0C0">Amount</td> </tr> </thead> <tbody > <tr> <td align="center">'.session()->get("description").'</td> <td align="center">'.session()->get("color").'</td> <td align="center">'.session()->get("engineNo").'</td> <td align="center">'.session()->get("chassisNo").'</td> <td align="center">'.session()->get("unitPrice").'</td> </tR> <tr> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> </tbody> </table> </td> </tr> </table> <table border="0"> <thead> <tr> <th width="70%" border="1" align="center"> Total in Word </th> <th width="30%" border="1" align="center" style="line-height: 100%;"> Total PKR</th> </tr> </thead> <tbody> <tr> <td width="70%" border="1" align="center">'.session()->get("amountInWords").'/-Only.</td> <td width="30%" border="1" align="center">'.session()->get("amountPaid").'</td> </tr> <br> <br> <br> <br> <br> <br> <br> <tr> <td width="60%" border="0"></td> <td width="40%" align="center" border="0">_______________________</td> </tr> <tr> <br> <td width="60%" border="0"></td> <td width="40%" align="center" border="0">Sign and Signature</td> </tr> </tbody> </table> <br><br> <br> <br> <table border="0"> <tr> <td bgcolor="crimson" align="center" border="0"><h4>8-km Sheikhupura Road, Opposite Milat Tractors Limited,Lahore,Tel:0300-0600061 </h4></td> </tr> <tr> <td bgcolor="crimson" align="center" border="0"><h5> Email Adress: <EMAIL> </h5></td> </tr> </table> '; // $html= $htmldata; PDF::SetTitle('Request for Invoice'); PDF::AddPage(); PDF::writeHTML($newHTML, true, false, true, false, ''); PDF::Output('invoiceRequest.pdf'); } } <file_sep>/app/Http/Controllers/CustomerController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use DB; class CustomerController extends Controller { public function check(Request $request, $CO){ $obj=json_decode($CO); $name=$obj[0]; $pass=$obj[1]; $CusContact=$obj[2]; $cusprofesn=$obj[3]; $CusBalnc=$obj[4]; $cusAddr=$obj[5]; $cuscomnt=$obj[6]; self:: insertintblcustomeinformation($name,$cusAddr,$CusContact,null,$CusBalnc,$cuscomnt,null,$cusprofesn); return "Getting from controller".$obj[0]; } public function insertintblcustomeinformation( $CCustomerName, $CAddress, $CContect, $CCNIC, $CBalance, $CComments, $CCustomerCatogery, $COcupation ){ $result= DB::insert('insert into customeinformation (CustomerName,Address, Contect,CNIC,Balance,Comments,CustomerCatogery,Ocupation) value(?,?,?,?,?,?,?,?)', [$CCustomerName, $CAddress, $CContect, $CCNIC,$CBalance,$CComments, $CCustomerCatogery, $COcupation]); if ($result==1){ print("escccc"); } } public static function UpdateCustomerBalance($CID,$newBalance){ DB::table('customeinformation') ->where('CustomerID', $CID) ->update(['Balance' =>$newBalance ]); } public static function getCustomerBalance($CID){ $re = DB::table('customeinformation') ->where('CustomerID', '=', $CID) ->first()->Balance; return $re; } public function getAllCustomers(){ $results=DB::select('select * from customeinformation'); // $sOp=" <select style=\"height: 45px !important; width: 298px !important;\" class=\"form-control selectpicker\" // data-live-search=\"true\" tabindex=\"null\" onchange=\"getRecipes()\" id=\"SelectMenu\">"; // $sOp='<select data-live-search="true" class="form-control ">'; $sOp='<option value=" "></option>'; $tableOfHtml=""; foreach ($results as $ro){ $tableOfHtml=$tableOfHtml." <option value=".$ro->CustomerID.">".$ro->CustomerName."</option>"; } $endSelect="</select>"; $allHtml=$sOp . $tableOfHtml . $endSelect; return $allHtml; } public function getCustomerDetail($CID){ $results=DB::select('select * from customeinformation where CustomerID= '.$CID); // mysql_insert_id() return $results; } public function addCustomer(Request $request, $CO){ $obj=json_decode($CO); $customerName=$obj[0]; $fatherName=$obj[1]; $contact=$obj[2]; $profession=$obj[3]; $balance=$obj[4]; $address=$obj[5]; $comments=$obj[6]; $cnic=$obj[7]; $CID=DB::table('customeinformation')->insertGetId([ 'CustomerName'=>$customerName, 'FatherName'=>$fatherName, 'Contect'=>$contact, 'Ocupation'=>$profession, 'Balance'=>$balance, 'Address'=>$address, 'Comments'=>$comments, 'CNIC'=>$cnic, ]); return $CID." ID customer added"; } public function getInvoiceCustomer($InvoiceNo){ $results=DB::select('select * from vw_customersale_invoice where InvoiceNumber= '.$InvoiceNo); $product = collect([1,2,3,4]); $re = DB::table('vw_customersale_invoice') ->where('InvoiceNumber', '=', $InvoiceNo); session(['invoiceNo' => $InvoiceNo]); session(['customerID' => $re[0]->CustomerID]); session(['itemNo' => $re->ProductSerial]); session(['quantity' => $re->Quantity]); session(['unitPrice' => $re->PerUnitSalePrice]); session(['productName' => $re->ProductName]); session(['price' => $re->PerUnitSalePrice]); session(['contact' => $re->Contect]); session(['customerName' => $re->CustomerName]); session(['CNIC' => $re->CNIC]); session(['address' => $re->Address]); session(['engineNo' => $re->EngineNumber]); session(['chassisNo' => $re->ChasisNumber]); session(['color' => $re->color]); session(['fatherName' => $re->FatherName]); session(['total' => $re->AmountPaid]); session(['referenceNumber' => 'FMM-GDP-'.$InvoiceNo]); session(['amountPaid' => $re->AmountPaid]); session(['description' => $re->description]); session(['balance' => $re->Balance]); session(['totalCost' => $re->TotalCost]); session(['tax' => $re->VAT]); session(['endTotal' => $re->NetTotal]); return $results; } public function getCustomers(){ $results=DB::select('select * from customeinformation'); return $results; } public static function editCustomer(Request $request, $CO){ $ata=json_decode($CO); $CID = $ata[0]; $customerName = $ata[1]; $fatherName = $ata[2]; $address = $ata[3]; $contact = $ata[4]; $CNIC = $ata[5]; $balance = $ata[6]; $comments = $ata[7]; $re = DB::table('customeinformation') ->where('CustomerID', $CID) ->update([ 'CustomerName'=>$customerName, 'FatherName'=>$fatherName, 'Address'=>$address, 'Contect'=>$contact, 'CNIC'=>$CNIC, 'Balance'=>$balance, 'Comments'=>$comments ]); return $CID; } } <file_sep>/app/Http/Controllers/userAccountController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use DB; class userAccountController extends Controller { public static function singIn($userName,$passcode){ $re = DB::table('userinfo') ->where([['UserName', '=', $userName ],['Password', '=', $passcode ]]) ->get(); //->first()->UserName; if($re=="[]"){ session(['userName' =>null]); return "Invalid Username"; }else{ session(['userName' => $re[0]->UserName]); session(['userCategory' => $re[0]->Designation]); session(['userID' => $re[0]->UserID]); return $re; } } } <file_sep>/app/Http/Controllers/taskController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Carbon\Carbon; use DB; class taskController extends Controller { public static function insertTasks(Request $request, $CO){ $ata=json_decode($CO); $subject=$ata[1]; $assignedTo=$ata[2]; $dueDate=$ata[3]; $category=$ata[4]; $priority=$ata[5]; // $remarks=$ata[6]; $assignedDate=Carbon::now()->toDateString(); $st=$ata[0]; $tid=DB::table('tbl_tasks')->insertGetId([ 'Subject'=>$subject, 'DueDate'=>$dueDate, 'AssignedTo'=>$assignedTo, 'Status'=>'Pending', 'Priority'=>$priority, 'CategoryID'=>$category, 'AssignedDate'=>$assignedDate, ]); foreach ($st as $obj){ $taskDetails=$obj[0]; $id=DB::table('tbl_subtasks')->insertGetId([ 'taskDetails'=>$taskDetails, 'TaskID'=>$tid, 'DueDate'=>$dueDate, 'AssignedTo'=>$assignedTo, 'Status'=>'Pending' ]); } } public static function employeeData(){ $card=""; $data=DB:: select('select * from vw_tasks'); foreach ($data as $obj){ $card=$card.'<div class="card" > <div class="card-body" data-toggle="modal" data-target="#exampleModal" onclick="loadTaskDetails('.$obj->TaskID.')"> <div class="mainCardBody"> <div class="leftCardBody"> <button style="border-radius: 20px; background-color: #e61d2f; border-color: #e61d2f; color: #fff;">Sales</button> </div> <div class="rightCardBody"> <span><i class="fa fa-fire"></i></span> <span><i class="fa fa-wifi"></i></span> </div> </div> <h4 style="font-size: 20px; font-weight: 600px;" class="text-left mt-5">'.$obj->Subject.'</h4> <div class="mainCardBody" style="padding-top: 20px;"> <div class="leftCardBody"> <div style="background-color: #e61d2f; color: #fff; border-radius: 50%; padding: 10px; display: inline-block;"> W A</div> <span>'.$obj->FirstName.' '.$obj->LastName.'</span> </div> <div class="rightCardBody"> <div>Overdue</div> <div class="mainDots text-center"> <div style="height: 10px;width: 10px;border-radius: 50%; background-color: #e61d2f; display: inline-block;"> </div> <div style="height: 10px;width: 10px;border-radius: 50%; background-color: pink; display: inline-block;"> </div> <div style="height: 10px;width: 10px;border-radius: 50%; background-color: black; display: inline-block;"> </div> </div> </div> </div> </div></div>'; } return $card; } public static function getEmployees(){ $data=DB:: select('select * from tblemployees'); $option='<option value=" "></option>'; foreach ($data as $d){ //print $option; $option=$option.' <option value= '.$d->EID.'>'.$d->FirstName.' '.$d->LastName.'</option>'; } return $option; } public static function getCategory(){ $data=DB:: select('select * from tbl_taskcategory'); $option='<option value=" "></option>'; foreach ($data as $d){ //print $option; $option=$option.' <option value= '.$d->CategoryID.'>'.$d->Category.'</option>'; } return $option; } public static function searchEmployeeData($EID, $name){ $card=""; $data=DB:: select('select * from vw_tasks where EID='.$EID); foreach ($data as $obj){ $card=$card.'<div class="card" > <div class="card-body" data-toggle="modal" data-target="#exampleModal" onclick="loadTaskDetails('.$obj->TaskID.')"> <div class="mainCardBody"> <div class="leftCardBody"> <button style="border-radius: 20px; background-color: #e61d2f; border-color: #e61d2f; color: #fff;">Sales</button> </div> <div class="rightCardBody"> <span><i class="fa fa-fire"></i></span> <span><i class="fa fa-wifi"></i></span> </div> </div> <h4 style="font-size: 20px; font-weight: 600px;" class="text-left mt-5">'.$obj->Subject.'</h4> <div class="mainCardBody" style="padding-top: 20px;"> <div class="leftCardBody"> <div style="background-color: #e61d2f; color: #fff; border-radius: 50%; padding: 10px; display: inline-block;"> W A</div> <span>'.$name.'</span> </div> <div class="rightCardBody"> <div>Overdue</div> <div class="mainDots text-center"> <div style="height: 10px;width: 10px;border-radius: 50%; background-color: #e61d2f; display: inline-block;"> </div> <div style="height: 10px;width: 10px;border-radius: 50%; background-color: pink; display: inline-block;"> </div> <div style="height: 10px;width: 10px;border-radius: 50%; background-color: black; display: inline-block;"> </div> </div> </div> </div> </div></div>'; } return $card; } public static function searchTaskWithStatus($EID, $status, $name){ $card=""; $data=DB:: select('select * from vw_tasks where EID='.$EID.' AND Status="'.$status.'"'); foreach ($data as $obj){ $card=$card.'<div class="card" > <div class="card-body" data-toggle="modal" data-target="#exampleModal" onclick="loadTaskDetails('.$obj->TaskID.')"> <div class="mainCardBody"> <div class="leftCardBody"> <button style="border-radius: 20px; background-color: #e61d2f; border-color: #e61d2f; color: #fff;">Sales</button> </div> <div class="rightCardBody"> <span><i class="fa fa-fire"></i></span> <span><i class="fa fa-wifi"></i></span> </div> </div> <h4 style="font-size: 20px; font-weight: 600px;" class="text-left mt-5">'.$obj->Subject.'</h4> <div class="mainCardBody" style="padding-top: 20px;"> <div class="leftCardBody"> <div style="background-color: #e61d2f; color: #fff; border-radius: 50%; padding: 10px; display: inline-block;"> W A</div> <span>'.$name.'</span> </div> <div class="rightCardBody"> <div>Overdue</div> <div class="mainDots text-center"> <div style="height: 10px;width: 10px;border-radius: 50%; background-color: #e61d2f; display: inline-block;"> </div> <div style="height: 10px;width: 10px;border-radius: 50%; background-color: pink; display: inline-block;"> </div> <div style="height: 10px;width: 10px;border-radius: 50%; background-color: black; display: inline-block;"> </div> </div> </div> </div> </div></div>'; } return $card; } public static function loadTaskDetails($TID){ $data=DB:: select('select * from vw_subtasks where TaskID='.$TID); return $data; } public static function updateTaskStatus(Request $request, $CO){ $ata=json_decode($CO); $mainTaskID = $ata[0][0]; $comment = $ata[1][0]; $employeeID = $ata[2][0]; $overallStatus = $ata[3][0]; DB::table('tbl_tasks') ->where('TaskID', '=', $mainTaskID) ->update(['Status'=>$overallStatus ]); for ($i=4; $i<sizeof($ata); $i++) { $subTaskID = $ata[$i][0]; $subTaskStatus = $ata[$i][1]; DB::table('tbl_subtasks') ->where([['TaskID', '=', $mainTaskID ],['STaskID', '=', $subTaskID ]]) ->update(['Status'=>$subTaskStatus ]); } $dateTime=Carbon::now(); $chat=DB::table('tbl_chatbox')->insertGetId([ 'TaskID'=>$mainTaskID, 'Comment'=>$comment, 'CommentedBy'=>$employeeID, 'DateTime'=>$dateTime ]); return $employeeID; } public static function updateAdminTaskStatus(Request $request, $CO){ $obj=json_decode($CO); $employeeID = $obj[0][0]; $mainTaskID = $obj[1][0]; $remarks = $obj[2][0]; $status = $obj[3][0]; $date = $obj[4][0]; $data = DB::table('tbl_tasks') ->where('TaskID', '=', $mainTaskID) ->update([ 'Status'=>$status, 'Remarks'=>$remarks, 'DueDate'=>$date ]); return $status; } } <file_sep>/routes/web.php <?php use Illuminate\Support\Facades\Route; use App\Http\Controllers\signInSignUPcontroller; use App\Http\Controllers\employeeController; use App\Http\Controllers\saleInvoiceEditController; use App\Http\Controllers\AddMenucontroller; use App\Http\Controllers\CustomerViewcotroller; use App\Http\Controllers\OrderFlowController; use App\Http\Controllers\CustomerViewController; use App\Http\Controllers\UpdateStocksController; use App\Http\Controllers\quotationController; use App\Http\Controllers\payController; use App\Http\Controllers\salePrintInvoice; use App\Http\Controllers\TransactionFlow; use App\Http\Controllers\userAccountController; use App\Http\Controllers\expenseController; use App\Http\Controllers\investorController; use App\Http\Controllers\salesFlow; use App\Http\Controllers\taskController; use App\Http\Controllers\attendanceController; use App\Http\Controllers\accountsController; use App\Http\Controllers\getProducts; use App\Http\Controllers\CustomerController; use App\Http\Controllers\serviceSalesFlow; use App\Http\Controllers\AdditionalTaxesAndCommissionsController; use App\Http\Controllers\LedgerPartiesController; use App\Http\Controllers\AISessionController; use App\Http\Controllers\saleRequestController; use App\Http\Controllers\TEST; use App\Http\Controllers\printServiceInvoice; /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ //Route::get('/getsignin1/{data}',[signInSignUPcontroller::class, 'signIn']); Route::get('/editEmployee/{UE}',[employeeController::class, 'editEmployee']); Route::get('/fetchAllmenu',[AddMenucontroller::class, 'fetchAllMenu']); Route::get('/fetchCategories',[AddMenucontroller::class, 'getCategories']); Route::get('/fetchMenu/{CID}',[AddMenucontroller::class, 'fetchMenu']); Route::get('/fetchCategoriesInOptions',[AddMenucontroller::class, 'getCategoriesForSelectMenu']); Route::get('/addNewEmployee/{data}',[employeeController::class, 'addNewEmployee']); Route::get('/getAllEmployees',[employeeController::class, 'getAllEmployees']); Route::get('/getsignin/{data}',[signInSignUPcontroller::class, 'InsertAdmin']); Route::get('/placeOrder/{data}',[OrderFlowController::class, 'OrderFlow']); Route::get('/getOrderId/{oid}',[OrderFlowController::class, 'getOrderItem']); Route::get('/getAllProducts',[getProducts::class, 'getAllProducts']); Route::get('/getProductByCategory/{CID}',[getProducts::class, 'getProductByCategory']); Route::get('/updateTaskStatus/{data}',[taskController::class, 'updateTaskStatus']); Route::get('/getPartsAndServices',[getProducts::class, 'getPartsAndServices']); Route::get('/getAllSupliers',[LedgerPartiesController::class, 'getAllSuplierParties']); Route::get('/testpdf',[TEST::class, 'getInfo']); Route::get('/testpdf/2',[TEST::class, 'saleServiceInvoice1']); Route::get('/testpdf/3',[TEST::class, 'saleInvoiceRequest']); //qutationRequest Route::get('/testpdf/4',[TEST::class, 'gatePass']); Route::get('/testpdf/5',[TEST::class, 'qutationRequestFinal']); Route::get('/oqp',[quotationController::class, 'qoutationToPDF']); //---------------------------//LedgerPartiesController Route::get('/addCustomer/{data}',[CustomerController::class, 'check']); Route::get('/insertCustomer/{data}',[CustomerController::class, 'addCustomer']); Route::get('/getAllCustomers/',[CustomerController::class, 'getAllCustomers']); Route::get('/getCustomerNames/',[CustomerViewController::class, 'getCustomerNames']); //Route::get('/getAllSupliers/',[CustomerController::class, 'getAllCustomers']); Route::get('/getCustomersInfo/{CID}',[CustomerController::class, 'getCustomerDetail']); Route::get('/getCustomers',[CustomerController::class, 'getCustomers']); Route::get('/getSuppliersInfo/{SID}',[LedgerPartiesController::class, 'getPartyDetail']); //__________________________Sales Flow___________________________________ Route::get('/addSalesForSS/{data}',[serviceSalesFlow::class, 'SalesFlow']); //getInvoiceCustomer/{data} Route::get('/getSaleInvReq/{id}',[saleRequestController::class, 'getInvoiceSaleRequest']); Route::get('/addPurchaseForSS/{data}',[OrderFlowController::class, 'PurchaseOrderWithStockUpdate']); Route::get('/getInvoiceID',[salesFlow::class, 'getInvoiceNewID']); Route::get('/loadComissionHeads',[AdditionalTaxesAndCommissionsController::class, 'getComissionHeads']); Route::get('/getInvoiceCustomer/{data}',[CustomerController::class, 'getInvoiceCustomer']); Route::get('/getQuotation/{data}',[quotationController::class, 'getQuotation']); Route::get('/AddProduct/{data}',[CUDproduct::class, 'insertProduct']); Route::get('/invetorDetails/{data}',[investorController::class, 'getInvestorDetails']); Route::get('/getAllInvoiceDetails/{data}',[salesFlow::class, 'getAllInvoiceDetails']); Route::get('/getInvoiceStock/{data}',[UpdateStocksController::class, 'getInvoiceStock']); Route::get('/addUser/{data}',[userController::class, 'addnewuser']); Route::get('/addInvestorProduct/{data}',[investorController::class, 'addInvestorProduct']); Route::get('/getsignin/{data}',[signInSignUPcontroller::class, 'InsertAdmin']); Route::get('/placeOrder/{data}',[OrderFlowController::class, 'OrderFlow']); Route::get('/getOrderId/{oid}',[OrderFlowController::class, 'getOrderItem']); Route::get('/getOrderId',[OrderFlowController::class, 'getOrderID']); Route::get('/viewCustomer',[OrderFlowController::class, 'viewCustomer']); Route::get('/transactionHistory',[OrderFlowController::class, 'transactionHistory']); Route::get('/transactionHistoryAccounts/{AID}',[TransactionFlow::class, 'getTransactionsForAccounts']); Route::get('/transactionHistoryParties/{LID}',[TransactionFlow::class, 'getTransactionsForParties']); Route::get('/companyLedger',[OrderFlowController::class, 'companyLedger']); Route::get('/viewStock',[OrderFlowController::class, 'viewStock']); Route::get('/viewSales',[salesFlow::class, 'viewSales']); Route::get('/viewExpense',[expenseController::class, 'viewExpense']); Route::get('/viewAllStock',[OrderFlowController::class, 'viewAllStock']); Route::get('/spareParts',[OrderFlowController::class, 'spareParts']); Route::get('/getInvestorData',[investorController::class, 'getInvestorData']); Route::get('/getExpenseHeads',[expenseController::class, 'getExpenseHeads']); Route::get('/getAccountHeads',[accountsController::class, 'getAccountHeads']); Route::get('/customer/{data}',[CustomerViewcotroller::class, 'customerinfo']); Route::get('/getAllSoldProducts',[UpdateStocksController::class, 'getAllSoldProducts']); Route::get('/getAllAutos/{CID}',[UpdateStocksController::class, 'getAllAutos']); Route::get('/viewSoldStock',[UpdateStocksController::class, 'viewSoldStock']); Route::get('/getInvestors',[investorController::class, 'getInvestors']); Route::get('/insertProducts/{data}',[AddMenucontroller::class, 'insertProducts']); Route::get('/dailySaleAmount',[AISessionController::class, 'dailySaleAmount']); Route::get('/loadAutos',[getProducts::class, 'getAutosNames']); // Test Functions Route::get('/getTransaction',[OrderFlowController::class, 'getTransaction']); Route::get('/scratchFunc',[OrderFlowController::class, 'scratchFunc']); Route::get('/setStockIdeal/{data}',[UpdateStocksController::class, 'UpdateInStock']); Route::get('/ruautos/{data}',[UpdateStocksController::class, 'updateStockDetails']); Route::get('/getAvailableProducts',[UpdateStocksController::class, 'getAllAvailableProducts']); Route::get('/addSales/{data}',[salesFlow::class, 'SalesFlow']); Route::get('/addInvestor/{data}',[investorController::class, 'insertInvestor']); Route::get('/addExpense/{data}',[expenseController::class, 'insertExpense']); Route::get('/addPayment/{data}',[payController::class, 'insertPayment']); Route::get('/getPaymentHistory/{data}',[payController::class, 'getPayRecivingHistory']); Route::get('/addTasks/{data}',[taskController::class, 'insertTasks']); Route::get('/updateAdminStatus/{data}',[taskController::class, 'updateAdminTaskStatus']); Route::get('/markAttendance/{data}',[attendanceController::class, 'markAttendance']); Route::get('/getEmployeeData',[taskController::class, 'employeeData']); Route::get('/getAttendance',[attendanceController::class, 'getAttendance']); Route::get('/getEmpbyID/{id}',[payController::class, 'getEmpbyID']); Route::get('/getEmployeeName',[payController::class, 'getEmployeeName']); Route::get('/getEmployeeCNIC',[payController::class, 'getEmployeeCNIC']); Route::get('/getEmployeeID',[payController::class, 'getEmployeeID']); Route::get('/getEmployeeContact',[payController::class, 'getEmployeeContact']); Route::get('/loadProductCategory',[AddMenuController::class, 'loadProductCategory']); Route::get('/getEmployee',[expenseController::class, 'getEmployee']); Route::get('/updatePay/{data}',[payController::class, 'updatePay']); Route::get('/getTotalPay/{EID}',[payController::class, 'getTotalPay']); Route::get('/insertInCommission/{data}',[AdditionalTaxesAndCommissionsController::class, 'AddTaxOrCommission']); Route::get('/ruautos/{data}',[UpdateStocksController::class, 'updateStockDetails']); Route::get('/getAvailableProducts',[UpdateStocksController::class, 'getAllAvailableProducts']); Route::get('/addSales/{data}',[salesFlow::class, 'SalesFlow']); Route::get('/editCustomer/{data}',[CustomerController::class, 'editCustomer']); Route::get('/addInvestor/{data}',[investorController::class, 'insertInvestor']); Route::get('/addExpense/{data}',[expenseController::class, 'insertExpense']); Route::get('/addTasks/{data}',[taskController::class, 'insertTasks']); Route::get('/markAttendance/{data}',[attendanceController::class, 'markAttendance']); Route::get('/getEmployeeData',[taskController::class, 'employeeData']); Route::get('/searchEmployeeData/{EID}/{name}',[taskController::class, 'searchEmployeeData']); Route::get('/searchTaskWithStatus/{EID}/{status}/{name}',[taskController::class, 'searchTaskWithStatus']); Route::get('/loadTaskDetails/{TID}',[taskController::class, 'loadTaskDetails']); Route::get('/getAttendance',[attendanceController::class, 'getAttendance']); Route::get('/getEmpbyID/{id}',[payController::class, 'getEmpbyID']); Route::get('/getEmployeeName',[payController::class, 'getEmployeeName']); Route::get('/getEmployeeCNIC',[payController::class, 'getEmployeeCNIC']); Route::get('/getEmployeeID',[payController::class, 'getEmployeeID']); Route::get('/getEmployeeContact',[payController::class, 'getEmployeeContact']); Route::get('/loadProductCategory',[AddMenuController::class, 'loadProductCategory']); Route::get('/getPartyNames',[expenseController::class, 'getPartyNames']); Route::get('/getAccounts',[expenseController::class, 'getAccounts']); Route::get('/getCategory',[taskController::class, 'getCategory']); Route::get('/getEmployees',[taskController::class, 'getEmployees']); Route::get('/getInvestorStock/{data}',[investorController::class, 'getInvestorStock']); Route::get('/createQuotation/{data}',[quotationController::class, 'createQuotation']); Route::get('/getAutoData/{data}',[getProducts::class, 'getAutoData']); Route::get('/login/{un}/{pass}',[userAccountController::class, 'singIn']); Route::get('/updateInvoice/{data}/{id}',[saleInvoiceEditController::class, 'UpdateSaleInvoice']); Route::get('/viewQuotations',[quotationController::class, 'viewQuotations']); Route::get('/negativeComission/{data}',[AdditionalTaxesAndCommissionsController::class, 'AddTaxOrCommissionNegative']); Route::get('/PostiveCommision/{data}',[AdditionalTaxesAndCommissionsController::class, 'AddTaxOrCommissionPositive']); Route::get('/testpdf',[TEST::class, 'getInfo']); Route::get('/testpdf/2',[TEST::class, 'saleServiceInvoice1']); Route::get('/testpdf/3',[TEST::class, 'saleInvoiceRequest']); //qutationRequest Route::get('/testpdf/4',[TEST::class, 'gatePass']); Route::get('/testpdf/5',[TEST::class, 'qutationRequestFinal']); Route::get('/testpdf/6',[salePrintInvoice::class, 'serviceSalesRequest']); Route::get('/', function () { session(['userCategory' =>1]); return view('signInSignUp'); }); Route::get('/ed', function () { return view('EmpDashboard'); }); Route::get('/sh', function () { return view('StockHistory'); }); Route::get('/chksessions',function(){ // $request->session()->forget('name'); session(['key' => '88888888']); // $request->session()->put('key', '8'); $value = session()->get('CID'); echo $value; }); Route::get('/ss', function () { return view('sales'); }); Route::get('/qt', function () { return view('quotation'); }); //61bd06c Route::get('/logout', function () { session(['userName' =>null]); return view('signInSignUp'); }); Route::get('/db', function () { // $UN = session()->get('userName'); // if($UN!=NULL){ return view('dashboard'); // }else{ // return "Invalid Username Or Password"; // } }); Route::get('/AddProduct/{data}',[AddMenucontroller::class, 'insertProduct']); Route::get('/ps', function () { return view('PurchaseStock'); }); Route::get('/as', function () { return view('addNewStock'); }); Route::get('/bo', function () { return view('bookorder'); }); Route::get('/cl', function () { return view('companyLedger'); }); Route::get('/dl', function () { return view('deliveryLetter'); }); Route::get('/ip', function () { return view('increaseInPrice'); }); Route::get('/is', function () { return view('invoiceServices'); }); Route::get('/psi', function () { return view('printSaleInvoice'); }); Route::get('/rec', function () { return view('Receiving'); }); Route::get('/sc', function () { return view('salesandc'); }); Route::get('/stock', function () { return view('stock'); }); Route::get('/th', function () { return view('transactionHistory'); }); Route::get('/loop', function () { return view('forLoopCheck'); }); Route::get('/vc', function () { return view('viewCustomers'); }); Route::get('/sp', function () { return view('viewSpareParts'); }); Route::get('/vs', function () { return view('viewStock'); }); Route::get('/ajax', function () { return view('ajax'); }); Route::get('/scratch', function () { return view('scratch'); }); Route::get('/ex', function () { return view('expense'); }); Route::get('/ct', function () { return view('comissionAndTaxes'); }); Route::get('/s', function () { return view('salesAndComission'); }); Route::get('/ev', function () { return view('employerView'); }); Route::get('/etv', function () { session(['EMPID' => '1']); return view('EmployeeTaskView'); }); Route::get('/emptv', function () { return view('employertasksViews'); }); Route::get('/e', function () { return view('Employee'); }); Route::get('/at', function () { return view('attendance'); }); Route::get('/atv', function () { return view('attendanceView'); }); Route::get('/l', function () { return view('investorLedger'); }); Route::get('/igl', function () { return view('investorGeneralLedger'); }); Route::get('/pr', function () { return view('payRoll'); }); Route::get('/inv', function () { return view('investors'); }); Route::get('/pr', function () { return view('payRoll'); }); Route::get('/es', function () { return view('editStock'); }); Route::get('/cr', function () { return view('cr'); }); Route::get('/d', function () { return view('delivery'); }); Route::get('/nd', function () { return view('newDashboard'); }); Route::get('/SalarySlip', function () { return view('SalarySlip'); }); Route::get('/l', function () { return view('investorLedger'); }); Route::get('/ql', function () { return view('quotation'); }); Route::get('/e', function () { return view('Employee'); }); Route::get('/prc', function () { return view('paymentReceipt'); }); Route::get('/fgp', function () { return view('ForlandGatePass'); }); Route::get('/slip', function () { return view('SalarySlip'); }); Route::get('/sheet', function () { return view('inventorysheet'); }); Route::get('/vd', function () { return view('vehicleDetail'); }); Route::get('/sir', function () { return view('solutions'); }); Route::get('/ql', function () { return view('quotationList'); }); Route::get('/ac', function () { return view('addcategory'); }); Route::get('/gb', function () { return view('generateBarcode'); }); Route::get('/adc', function () { return view('addcustomer'); }); Route::get('/ads', function () { return view('addsuplier'); }); Route::get('/dp', function () { return view('dailypurchase'); }); Route::get('/pay', function () { return view('payments'); }); Route::get('/ep', function () { return view('employeePayment'); }); Route::get('/sales', function () { return view('viewSales'); }); Route::get('/exv', function () { return view('viewExpenses'); }); Route::get('/pdfvs', function () { ini_set('max_execution_time', 60); $data=TransactionFlow::getTransactionsForAccounts(1); view()->share('viewExpenses',$data); $pdf = PDF::loadView('viewExpenses', $data); // download PDF file with download method return $pdf->download('pdf_file.pdf'); }); Route::get('/vd', function () { return view('vehicleDetail'); }); Route::get('/ssi2', function () { return view('printSaleInvoice'); }); Route::get('/ssi', function () { return view('servicesalesinvoice'); }); Route::get('/ed', function () { return view('EmpDashboard'); }); Route::get('/ae', function () { return view('addEmployees'); }); Route::get('/ee', function () { return view('editEmployee'); }); Route::get('/ec', function () { return view('editCustomer'); }); Route::get('/pdf', function () { return view('test'); });<file_sep>/app/Http/Controllers/OrderFlowController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Controllers\TransactionFlow; use App\Http\Controllers\LedgerPartiesController; use Carbon\Carbon; use App\Http\Controllers\accountsController; use App\Http\Controllers\UpdateStocksController; use DB; class OrderFlowController extends Controller { public function OrderFlow(Request $request,$data){ // var Order=[mainTotal,totlpaid,totRemaining,orderDetails]; $Array=json_decode($data); $mainTotal=$Array[0]; $totlpaid= $Array[1]; $totRemaining=$Array[2]; $orderDetails =$Array[3]; $AID=$Array[4]; $dateNow= Carbon::now()->toDateTimeString();//->format('Y-m-d h:iA'); // $d= Carbon::createFromFormat('dd/mm/YYYY HH:MM:SS', $dateNow); $invoiceNumber=DB::table('tblpurchaseorder')->insertGetId(['SupplierID'=>'1', 'TotalAmount'=>$mainTotal, 'Discount'=>'0', 'DateStamp'=>$dateNow, 'VAT'=>'0', 'NetTotal'=>$mainTotal, 'AmountPaid'=>$totlpaid, 'Balance'=>$totRemaining, 'BillStatus'=>"Pending", 'HoldStatus'=>'0', 'SupplierBalanceBeforeInvoiceBill'=>NULL, 'SupplierBalanceAfterInvoiceBill'=>NULL, 'CashPaidBack'=>NULL, 'CashNote'=>NULL, 'Remarks'=>NULL, 'dliveryDate'=>NULL, 'returnDate' =>NULL, 'VATRate'=>NULL ]); self::insertInDetailedPurchaseOrder($orderDetails,$invoiceNumber,$dateNow); $LID=2; $oldSelfBalance=LedgerPartiesController::getPartyBalance(2); $oldCompanyBalance=LedgerPartiesController::getPartyBalance(1); $paidVia=$AID; $currentCompanyBalance=floatval($oldCompanyBalance)+floatval($totRemaining); LedgerPartiesController::UpdatePartiesBalance(1,$currentCompanyBalance); TransactionFlow::addTransaction($invoiceNumber,"Credit","Booking Order", $totlpaid,$dateNow,"1",$oldCompanyBalance,$currentCompanyBalance,NULL,NULL,$LID,"0",NULL,'1',$paidVia,NULL); $OldAccBalance=accountsController::getAccountBalance($AID); $newAccountBalance=floatval($OldAccBalance)-floatval($totlpaid); accountsController::UpdateNewBalance($AID,$newAccountBalance); $selfBalance=floatval($oldSelfBalance)-floatval($totlpaid); LedgerPartiesController::UpdatePartiesBalance(2,$selfBalance); // $companyBalance=floatval($oldCompanyBalance)+floatval($totlpaid); return "Your order ".$invoiceNumber; } function getOrderID(){ $IID=DB::table('tblpurchaseorder')->max("InvoiceNumber"); return $IID+1; } function addProductOnlyForAutos($Pname,$Pcateg,$Psubcat,$Pbarcode,$UnitPurchasePrice,$OrderID,$description,$INP){ $ProductSerial=DB::table('productdefination')->insertGetId(['ProductName'=> $Pname, 'Category'=>$Pcateg, 'subCategory'=>$Psubcat , 'Company'=>'Forland', 'Year'=>'2021' ]); DB::table('productdefination') ->where('ProductSerial', $ProductSerial) ->update([ 'ProductID' =>$ProductSerial, 'description' =>$description, 'Barcode' =>'*'.$ProductSerial.'*' ]); $SID=DB::table('instock')->insertGetId(['ProductSerial'=> $ProductSerial, 'StockIn'=>'1', 'PerUnitPurchasePrice'=> $UnitPurchasePrice, 'PerUnitSalePrice'=>$INP, 'ExpairyDate'=>NULL, 'TotalCost'=>$UnitPurchasePrice, 'TotalSaleAmount'=>$UnitPurchasePrice, 'Remarks'=>'Pending In Order No: '.$OrderID, 'Status'=>'Pending' ]); return $ProductSerial; } public function insertInDetailedPurchaseOrder($OrderDetails,$InvoiceID,$date){ foreach ($OrderDetails as $row){ // $(tr).find('td:eq(0)').text(), //AutoCategory // $(tr).find('td:eq(2)').text(), //Price // $(tr).find('td:eq(3)').text(), //qty $autoCategory=$row[0]; $purchasePrice=$row[1]; $qty=$row[2]; $amountTot=$row[3]; $AmountPaid=$row[4]; $remAmount=$row[5]; $Pname=$row[6]; $description=$row[7]; $invoicePrice=$row[8]; for($i=0;$i<$qty;$i++){ // $(tr).find('td:eq(4)').text(), //totamount // $(tr).find('td:eq(5)').text(), //Paid // $(tr).find('td:eq(6)').text() //remAmount $productSerial= self::addProductOnlyForAutos($Pname,"20",NULL,NULL,$purchasePrice,$InvoiceID,$description,$invoicePrice); print ($productSerial); $DSID=DB::table('tblpurchaseoorderdetaile')->insertGetId(['InvoiceNumber'=>$InvoiceID, 'ProductSerial'=>$productSerial, 'PurchasePricePerUnit'=>$purchasePrice, 'ProductCategory'=>$autoCategory, 'DiscountOffered'=>'0', 'DateStamp'=>$date, 'TotalAmount'=>$amountTot, 'NetAmount'=>$amountTot, 'Activity'=>"Place Order", 'OrderedQuantiy'=>'1', 'RetailPricePerUnit'=>$purchasePrice, 'DilevedStatus'=>'Pending', 'AmountPaid'=>$AmountPaid, 'Balance'=>$remAmount, 'DeliveredQuantity'=>0 ]); } } return $DSID; } ///// public function insertInDetailedPurchaseOrderForSP($OrderDetails,$InvoiceID,$date){ foreach ($OrderDetails as $row){ // $(tr).find('td:eq(0)').text(), //productID // $(tr).find('td:eq(3)').text(), //purchase // $(tr).find('td:eq(4) input[type="text"]').val(), //qty // $(tr).find('td:eq(5) input[type="text"]').val(), //discount // $(tr).find('td:eq(6)').text() //totamount $pid=$row[0]; $purchasePrice=$row[1]; $qty=$row[2]; $dis=$row[3]; $totamount=$row[4]; // for($i=0;$i<$qty;$i++){ // $(tr).find('td:eq(4)').text(), //totamount // $(tr).find('td:eq(5)').text(), //Paid // $(tr).find('td:eq(6)').text() //remAmount $DSID=DB::table('tblpurchaseoorderdetaile')->insertGetId(['InvoiceNumber'=>$InvoiceID, 'ProductSerial'=>$pid, 'PurchasePricePerUnit'=>$purchasePrice, 'DiscountOffered'=>$dis, 'DateStamp'=>$date, 'TotalAmount'=>$totamount, 'NetAmount'=>$totamount, 'Activity'=>"Purchased Stock", 'OrderedQuantiy'=>$qty, 'RetailPricePerUnit'=>$purchasePrice, 'DilevedStatus'=>'Delivered', 'AmountPaid'=>$totamount, 'Balance'=>"0", 'DeliveredQuantity'=>$qty ]); $oldStock= UpdateStocksController::getCurrentStock($pid); $newStock= floatval($oldStock)+floatval($qty); UpdateStocksController::updateStock($pid,$newStock); // } } return $DSID; } ///// public function addInTransactionFlowForPurchase($invoiceNumber,$dateNow,$AP,$userID,$pattyCash,$CLB,$CCB){ // [TransactionID] $TID=DB::table('tblTransactionFlow')->insertGetId(['InvoiceNo'=>$invoiceNumber, 'TransectionCatogery'=>"Booking Order", 'Amount'=>$AP, 'DateStamp'=>$dateNow, 'UserID'=>$userID, 'PattyCash'=>$pattyCash, 'TransactionType'=>"Debit", 'SBB'=>NULL, 'SBA'=>NULL, 'CBB'=>$CLB, 'CBA'=>$CCB ]); } function spareParts(){ $data=DB:: select('select * from vw_stockdetails where Category = 21'); return $data; } function viewStock(){ $data=DB:: select('select * from vw_stockdetails where Category = 20'); return $data; } function viewAllStock(){ $data=DB:: select('select * from vw_stockdetails'); return $data; } function viewCustomer(){ $data=DB:: select('select * from customeinformation'); return $data; } function transactionHistory(){ $data=DB:: select('select * from tbltransactionflow'); return $data; } function companyLedger(){ $data=DB:: select('select * from vw_purchase_transactions where paidTo = 1'); return $data; } function scratchFunc(){ $data=DB:: select('select CustomerName, Contect, Address, Balance, CNIC from customeinformation'); $table=' <table id="myTable" class=" table-striped" style="width: 100%; text-align: center;"> <thead> <tr> <th id ="Cusname">Name</th> <th id="CusCont">Contact</th> <th id ="Cusaddr">Address</th> <th id="CusIntrs">Interested In</th> <th id ="CusMeet"> Who Meet</th> </tr> </thead> <tbody>'; foreach ($data as $d){ //print $option; $table=$table.' <tr> <td>'.$d->CustomerName.'</td> <td>'.$d->Contect.'</td> <td>'.$d->Address.'</td> <td>'.$d->Balance.'</td> <td>'.$d->CNIC.'</td> </tr>'; } return $table.'<table>'; } function getTransaction(){ $data=DB:: select('select * from companyinfo'); $i=1; $table=" <table> <tr> <td>Increment</td> <td>Transaction ID</td> <td>Invoice Number</td> <td>Transection Catogery</td> </tr>"; foreach ($data as $d){ //print $option; $table=$table.' <tr> <td>'.$i.'</td> <td>'.$d->CompanyName.'</td> <td>'.$d->StoreName.'</td> <td>'.$d->Address.'</td> </tr>'; $i++; } return $table.'<table>'; } //// //// function getOrderItem($OID){ $results=DB::select('select * from vw_purchaseorderdetails where InvoiceNumber='.$OID); $table=""; $i=1; $option='<option value=" "></option>'; foreach ($results as $ro){ $charges= TransactionFlow::getChargesOrComissions($ro->ProductID,"Transportation Charges","Cost"); //return $charges; if( $ro->DilevedStatus!="Pending"){ $option=$ro->DilevedStatus; } else{ $option='<select id="category" tabindex="null"><option value=1 >Received</option><option value=2 selected>Pending</option></select></td>'; } if($charges==0){ $tc=' value='.$charges; } else{ $tc=' value='.$charges.' readonly ="true"'; } if($ro->ChasisNumber==""){ $CHN=' value='.$ro->ChasisNumber; } else{ $CHN=' value='.$ro->ChasisNumber.' readonly ="true"'; } if($ro->EngineNumber==""){ $EN=' value='.$ro->EngineNumber; } else{ $EN=' value='.$ro->EngineNumber.' readonly ="true"'; } if($ro->Color==""){ $color=' value='.$ro->Color; } else{ $color=' value='.$ro->Color.' readonly ="true"'; } //print $option; $table=$table.' <tr> <td>'.$i.'</td> <td style="display:none">'.$ro->ProductID.'</td> <td>'.$ro->ProductName.'</td> <td><input type="text" '.$color.'></td> <td><input type="text" '.$CHN.'></td> <td><input type="text" '.$EN.'></td> <td><input type="text"'.$tc.'></td> <td> '.$option.'</td> </tr>'; $i++; $option=""; } return $table; } public function PurchaseOrderWithStockUpdate(Request $request,$data){ //myRow2 = [myTrows, tot, discount, gross, tax, netTotal, amp, rmb, SID, SLB, SCB]; $Array=json_decode($data); $mainTotal=$Array[1]; $netTotal=$Array[5]; $totlpaid= $Array[6]; $totRemaining=$Array[7]; $orderDetails =$Array[0]; //$pid=$orderDetails[0]; $SID=$Array[8]; $SLB=$Array[9]; $SCB=$Array[10]; $AID=$Array[11]; $dateNow= Carbon::now()->toDateTimeString();//->format('Y-m-d h:iA'); // $d= Carbon::createFromFormat('dd/mm/YYYY HH:MM:SS', $dateNow); $invoiceNumber=DB::table('tblpurchaseorder')->insertGetId(['SupplierID'=>$SID, 'TotalAmount'=>$mainTotal, 'Discount'=>'0', 'DateStamp'=>$dateNow, 'VAT'=>'0', 'NetTotal'=>$netTotal, 'AmountPaid'=>$totlpaid, 'Balance'=>$totRemaining, 'BillStatus'=>"Pending", 'HoldStatus'=>'0', 'SupplierBalanceBeforeInvoiceBill'=>$SLB, 'SupplierBalanceAfterInvoiceBill'=>$SCB, 'CashPaidBack'=>NULL, 'CashNote'=>NULL, 'Remarks'=>NULL, 'dliveryDate'=>NULL, 'returnDate' =>NULL, 'VATRate'=>NULL ]); self::insertInDetailedPurchaseOrderForSP($orderDetails,$invoiceNumber,$dateNow); $LID=2; $oldSelfBalance=LedgerPartiesController::getPartyBalance(2); $oldCompanyBalance=LedgerPartiesController::getPartyBalance($SID); $paidVia=$AID; $currentCompanyBalance=floatval($oldCompanyBalance)+floatval($totRemaining); LedgerPartiesController::UpdatePartiesBalance($SID,$currentCompanyBalance); $selfBalance=floatval($oldSelfBalance)-floatval($totlpaid); LedgerPartiesController::UpdatePartiesBalance(2,$selfBalance); TransactionFlow::addTransaction($invoiceNumber,"Credit","Stock Purchased", $totlpaid,$dateNow,"1",$oldCompanyBalance,$currentCompanyBalance,$oldSelfBalance,$selfBalance,$LID,"0",NULL,$SID,$paidVia,NULL); $OldAccBalance=accountsController::getAccountBalance($AID); $newAccountBalance=floatval($OldAccBalance)-floatval($totlpaid); accountsController::UpdateNewBalance($AID,$newAccountBalance); // $companyBalance=floatval($oldCompanyBalance)+floatval($totlpaid); return "Your order ".$invoiceNumber; } } <file_sep>/app/Http/Controllers/quotationController.php <?php use NumberToWords\NumberToWords; namespace App\Http\Controllers; use Illuminate\Http\Request; use Carbon\Carbon; use NumberToWords\NumberToWords; //https://github.com/kwn/number-to-words use DB; use PDF; class quotationController extends Controller { public function createQuotation(Request $request,$data){ $Array=json_decode($data); $customerName = $Array[0]; $fatherName = $Array[1]; $CNIC = $Array[2]; $city = $Array[3]; $address = $Array[4]; $contact = $Array[5]; $description = $Array[6]; $color = $Array[7]; $unitPrice = $Array[8]; $quantity = $Array[9]; $totalPrice = $Array[10]; $model = $Array[11]; $deliverTime = $Array[12]; $qoutationValidityTime = $Array[13]; $payTo = $Array[14]; $date = Carbon::now()->toDateString(); $numberToWords = new NumberToWords(); $numberTransformer = $numberToWords->getNumberTransformer('en'); $a= $numberTransformer->toWords($totalPrice); //there will query that will store information to database $b=ucwords($a); session(['amountInWords' => $b]); session(['customerName' => $customerName]); session(['fatherName' => $fatherName]); session(['CNIC' => $CNIC]); session(['address' => $address]); session(['price' => number_format($unitPrice)]); session(['contact' => $contact]); session(['total' => number_format($totalPrice)]); session(['invoiceDate' => $date]); session(['description' => $description]); session(['color' => $color]); session(['productName' => $model]); session(['quantity' => $quantity]); session(['city' => $city]); session(['DeliveryTime' => $deliverTime]); session(['ValidityPeriod' => $qoutationValidityTime]); session(['PayTo' => $payTo]); DB::table('tbl_quotations')->insertGetId([ 'CustomerName'=>$customerName, 'FatherName'=>$fatherName, 'CNIC'=>$CNIC, 'City'=>$city, 'Contact'=>$contact, 'Address'=>$address, 'Discription'=>$description, 'Color'=>$color, 'UnitPrice'=>$unitPrice, 'Quantity'=>$quantity, 'TotalPrice'=>$totalPrice, 'Model'=>$model, 'Date'=>$date, 'DeliveryTime'=>$deliverTime, 'ValidityPeriod'=>$qoutationValidityTime, 'PayTo'=>$payTo ]); DB::table('customeinformation')->insertGetId([ 'CustomerName'=>$customerName, 'FatherName'=>$fatherName, 'Contect'=>$contact, 'Balance'=>0, 'Address'=>$address, 'CNIC'=>$CNIC, ]); return 'for '.$description.' '; } public function viewQuotations(){ $data=DB:: select('select * from tbl_quotations'); return $data; } public function getQuotation($QID){ $data = DB::table('tbl_quotations') ->where('QID', '=', $QID) ->first(); $numberToWords = new NumberToWords(); $numberTransformer = $numberToWords->getNumberTransformer('en'); $a= $numberTransformer->toWords($data->TotalPrice); session(['amountInWords' => ucwords($a)]); session(['customerName' => $data->CustomerName]); session(['fatherName' => $data->FatherName]); session(['CNIC' => $data->CNIC]); session(['address' => $data->Address]); session(['price' => number_format($data->UnitPrice)]); session(['contact' => $data->Contact]); session(['total' => number_format($data->TotalPrice)]); session(['invoiceDate' => $data->Date]); session(['description' => $data->Discription]); session(['color' => $data->Color]); session(['' => $data->Model]); session(['quantity' => $data->Quantity]); session(['city' => $data->City]); session(['DeliveryTime' => $data->DeliveryTime]); session(['ValidityPeriod' => $data->ValidityPeriod]); session(['PayTo' => $data->PayTo]); } public function qoutationToPDF() { $html = '<table cellpadding="1" cellspacing="1" border="1" style="text-align:center;"> <tr><td> <img src="/assets/img/logo.jpg" border="0" height="100" width="300" align="center" /></td></tr> <tr> <td align="Left"> '.session()->get("customerName").' </td> </tr> <tr> <td align="right">Date: '.session()->get("Date").' </td> </tr> <tr> <td > Qoutation For '.session()->get("productName").' </td> </tr> </table> <br> <table cellpadding="1" cellspacing="1" border="1" style="text-align:center;"> <thead> <tr> <th>Description</th> <th>Color</th> <th>Unit Price</th> <th width="40">Qty</th> <th width="173">Total Price</th> </tr> </thead> <tbody> <tr><td>'.session()->get("description").'</td> <td rowspan="2">'.session()->get("color").'</td> <td >Rs</td> <td rowspan="2" width="40">'.session()->get("quantity").'</td> <td width="173">Rs</td></tr> <tr><td >'.session()->get("city").'</td> <td>'.session()->get("price").'</td> <td width="173">'.session()->get("total").'</td> </tr> <tr><td colspan="5">'.session()->get("amountInWords").' </td></tr> </tbody> </table> <br><br> <table border="0"> <tr ><td colspan="5" align ="left" ><h3>Terms & Conditions<br><br> </h3> </td></tr> </table> <table> </table> <table border="1" cellpadding="3"> <tbody> <tr> <td width="30%" border="0" align="left" >Delivery Time</td> <td width="70%" border="0" align="left">'.session()->get("DeliveryTime").'Days after recipt of 100% advance payment</td> </tr> <tr> <td width="30%" border="0">Validity</td> <td width="70%" align="left" border="0">This Qoutation is valid for '.session()->get("ValidityPeriod").'days only</td> </tr> <tr> <td width="30%" border="0">Payment</td> <td width="70%" align="left" border="0">100% Advance payment in shape of DD/PO in favor of '.session()->get("PayTo").'</td> </tr> <tr> <td width="30%" border="0">Duty/Taxes #</td> <td width="70%" align="left" border="0">Any change in Govt.faisal Policies,RGST/VAT and tariff structures will be on coustumer accounts</td> </tr> <tr> <td width="30%" border="0">Force Majeure</td> <td width="70%" align="left" border="0">Manufacture will will not be responsible for any delay in delivery due to force majeure circumstance </td> </tr> <tr> <td width="30%" border="0">Warranty</td> <td width="70%" align="left" border="0"> Manufacture will not br responsible for any delay in delivery due to forcemajor circumstance</td> </tr> <tr> <td width="30%" border="0">Model</td> <td width="70%" align="left" border="0">'.session()->get("Model").'</td> </tr> </tbody> </table> <table border="0"> <thead> <br> <br> <br> <br><br> <br> <br> <br> <br> <br> <br> <br> <tr> <td width="60%" border="0"></td> <td width="40%" align="center" border="0">_______________________</td> </tr> <tr> <br> <td width="60%" border="0"></td> <td width="40%" align="center" border="0">Sign and Signature</td> </tr> </tbody> </table> '; PDF::SetTitle('Hello World'); PDF::AddPage(); PDF::writeHTML($html, true, false, true, false, ''); PDF::Output('hello_world.pdf'); } } <file_sep>/app/Http/Controllers/TransactionFlow.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use DB; use Carbon\Carbon; class TransactionFlow extends Controller { public static function addTransaction($InvoiceNo,$TType,$Tcate,$amount,$dateStamp, $UserID,$SBB,$SBA,$CBB,$CBA,$LID,$pattyCash,$paidBy,$paidTo,$paidVia,$CID) { // InvoiceNo bigint(20) // TransactionCatogery varchar(50) // Amount,jjjjjjjjjjj8 // SBB varchar(50) // SBA varchar(50) // CBB varchar(50) // CBA varchar(50) // PaidTo varchar(50) // PaidBy varchar(50) // PaidVia $dateNow= Carbon::now()->toDateTimeString(); $TID=DB::table('tbltransactionflow')->insertGetId(['InvoiceNo'=> $InvoiceNo, 'TransactionType' =>$TType, 'TransactionCatogery'=>$Tcate, 'Amount' =>$amount, 'DateStamp' =>$dateStamp, 'ModifiedOn' =>$dateNow, 'UserID' =>$UserID, 'LID'=>$LID, 'SBB' =>$SBB, 'SBA' =>$SBA, 'CBB' =>$CBB, 'CBA' =>$CBA, 'PattyCash'=>$pattyCash, 'PaidTo'=>$paidTo, 'PaidBy'=>$paidBy, 'PaidVia'=>$paidVia, 'CID'=>$CID ]); return $TID; } public static function getTransactionsForAccounts($AID){ $data=DB:: select('select * from tbltransactionflow where PaidVia='.$AID); return $data; } public static function getTransactionsForParties($LID){ $data=DB:: select('select * from tbltransactionflow where PaidTo='.$LID); return $data; } public static function addInTransactionFlowForSales($LID,$invoiceNumber,$dateNow,$AP,$userID,$pattyCash,$CLB,$CCB){ // [TransactionID] $TID=DB::table('tblTransactionFlow')->insertGetId(['InvoiceNo'=>$invoiceNumber, 'TransactionCatogery'=>"Sales", 'Amount'=>$AP, 'LID'=>$LID, 'DateStamp'=>$dateNow, 'UserID'=>$userID, 'PattyCash'=>$pattyCash, 'SBB'=>NULL, 'SBA'=>NULL, 'CBB'=>$CLB, 'CBA'=>$CCB ]); } public static function UpdateCaT($PID,$TTname,$amount,$ttype,$dateNow){ $CID=DB::table('tbladditionalcostandprofits')->insertGetId(['PID'=> $PID, 'CPName' =>$TTname, 'Amount' =>$amount, 'TType' =>$ttype, 'DateStamp'=>$dateNow ]); return $CID; } public static function getChargesOrComissions($PID,$TTname,$ttype){ $amount = DB::table('tbladditionalcostandprofits') ->where([['PID', '=', $PID], ['CPName', '=', $TTname], ['TType', '=', $ttype]] ) ->get(); if($amount->isEmpty()){ return 0; }else{ return $amount[0]->Amount; } } } <file_sep>/app/Http/Controllers/payController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Carbon\Carbon; use DB; class payController extends Controller { public static function insertPayment(Request $request, $CO){ $ata=json_decode($CO); foreach ($ata as $obj){ $date=$obj[0]; $LID=2; $amount=$obj[1]; $expenseName=$obj[2]; $expenseID=$obj[3]; $paidTo=$obj[4]; $paidVia=$obj[5]; $remarks=$obj[6]; $id=DB::table('tbltransactionflow')->insertGetId([ 'DateStamp'=>$date, 'Amount'=>$amount, 'TransactionCatogery'=>"Payment", 'EID'=>$expenseID, 'PaidTo'=>$paidTo, 'PaidVia'=>$paidVia, 'TransactionType'=>"Credit" ]); $oldSelfBalance = LedgerPartiesController::getPartyBalance($LID); $newBalance = $oldSelfBalance - $amount; LedgerPartiesController::UpdatePartiesBalance($LID, $newBalance); $balanceForParty=LedgerPartiesController::getPartyBalance($paidTo); $newBalanceOfParty=$balanceForParty-$amount; LedgerPartiesController::UpdatePartiesBalance($paidTo, $newBalanceOfParty); $oldAccountBalance = accountsController::getAccountBalance($paidVia); $newAccountBalance = $oldAccountBalance - $amount; accountsController::UpdateNewBalance($paidVia, $newAccountBalance); } return $id; } public static function getEmployeeName(){ $data=DB:: select('select * from tblemployees'); $option='<option value=" "></option>'; foreach ($data as $d){ //print $option; $option=$option.' <option value= '.$d->EID.'>'.$d->FirstName.'</option>'; } return $option; } public static function getEmployeeCNIC(){ $data=DB:: select('select * from tblemployees'); $option='<option value=" "></option>'; foreach ($data as $d){ //print $option; $option=$option.' <option value= '.$d->EID.'>'.$d->CNIC.'</option>'; } return $option; } public static function getEmployeeID(){ $data=DB:: select('select * from tblemployees'); $option='<option value=" "></option>'; foreach ($data as $d){ //print $option; $option=$option.' <option value= '.$d->EID.'>'.$d->EID.'</option>'; } return $option; } public static function getEmployeeContact(){ $data=DB:: select('select * from tblemployees'); $option='<option value=" "></option>'; foreach ($data as $d){ //print $option; $option=$option.' <option value= '.$d->EID.'>'.$d->ContactNo.'</option>'; } return $option; } public static function getEmpbyID(Request $request, $ID){ // return $ID; $data=DB:: select('select * from vw_employeealowncspay where EID ='.$ID ); return $data; } public static function updatePay($data){ $obj=json_decode($data); $basicPay=$obj[0]; $allowedHolidays=$obj[1]; $comission=$obj[2]; $saleTarget=$obj[3]; $allownces=$obj[4]; $total=$obj[5]; $workingHours=$obj[6]; $EID=$obj[7]; $perDayPay=floatval($total)/floatval(30); $perHourPay=$perDayPay/floatval($workingHours); DB::table('tblemployeepay') ->where('EID', $EID) ->update([ 'BasicPay' =>$basicPay, 'AllowedHolidays' =>$allowedHolidays, 'CommisionOnSale' =>$comission, 'SaleTarget' =>$saleTarget, 'Alownces' =>$allownces, 'TotalPay' =>$total, 'WorkingHours' =>$workingHours, 'PerHourPay'=>$perHourPay, 'PayPerDay'=>$perDayPay ]); return "Pay Updated"; } public static function getCalculatedPay($EMPID) { } public static function getPayRecivingHistory($EID) { $data=DB:: select('select * from tbltransactionflow where EmpID='.$EID); return $data; } public static function getTotalPay($empID){ $totatlPay = DB::table('vw_employeealowncspay') ->where('EID', $empID) ->first()->TotalPay; return $totatlPay; } } <file_sep>/app/Http/Controllers/TEST.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use PDF; class TEST extends Controller { public function index() { $html = '<h1>Hello World</h1>'; PDF::SetTitle('Hello World'); PDF::AddPage(); PDF::writeHTML($html, true, false, true, false, ''); PDF::Output('hello_world.pdf'); } public function saleServiceInvoice1() { $newHTML='<table border="0"> <thead> <tr> <th><br><h1>FORLAND MODREN MOTORS</h1></th> </tr> </thead> <tbody> <tr> <br> <td> NTN:82588676-6 <br> STRN:3277876204764 <br> Customer\'s Copy </td> </tr> <tr><td align="center"><h1>Sales Invoice</h1></td></tr> </tbody> </table> <br> <br> <br> <table border="0"> <tbody> <tr> <td><br><span style="font-size: medium;">Customer Name:</span></td> <td align="center"><br>'.session()->get("customerName").'</td> <td><br><span style="font-size: medium;">Booking No:</span></td> <td align="center"><br>BO-FMM-'.session()->get("invoiceNo").'</td> </tr> <tr> <td><br><span style="font-size: medium;">Address:</span></td> <td align="center"><br>'.session()->get("address").'</td> <td><br><span style="font-size: medium;">Invoice Number:</span></td> <td align="center"><br>'.session()->get("invoiceNo").'</td> </tr> <tr> <td><br><span style="font-size: medium;">CNIC/NTN:</span></td> <td align="center"><br>'.session()->get("CNIC").'</td> <td><br><span style="font-size: medium;">Invoice Date:</span></td> <td align="center"><br>'.session()->get("invoiceDate").'</td> </tr> <tr> <td><br><span style="font-size: medium;">Contact:</span></td> <td align="center"><br>'.session()->get("contact").'</td> <td><br><span style="font-size: medium;"></span></td> <td align="center"><br></td> </tr> </tbody> </table> <br> <br> <br> <br> <table border="1" > <tr ><td> <table border="0"> <thead> <tr> <td align="left" bgcolor="#C0C0C0" > Description </td> <td align="center" bgcolor="#C0C0C0" >color</td> <td align="center"bgcolor="#C0C0C0" >Engine No</td> <td align="center" bgcolor=" #C0C0C0">Chassis No</td> <td align="center" bgcolor=" #C0C0C0">Amount</td> </tr> </thead> <tbody > <tr> <td>'.session()->get("description").'</td> <td>'.session()->get("color").'</td> <td>'.session()->get("engineNo").'</td> <td>'.session()->get("chassisNo").'</td> <td>'.session()->get("unitPrice").'</td> </tr> <tr> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> </tbody> </table> </td> </tr> </table> <table border="0"> <thead> <tr> <th width="60%" border="1" align="center"> Total in Word </th> <th width="40%" border="1" align="center" style="line-height: 100%;"> Total PKR</th> </tr> </thead> <tbody> <tr> <td width="60%" border="1" align="center">'.session()->get("amountInWords").'/-Only.</td> <td width="40%" border="1" align="center">'.session()->get("amountPaid").'</td> </tr> <br> <br> <br> <br> <br> <br> <br> <tr> <td width="60%" border="0"></td> <td width="40%" align="center" border="0">_______________________</td> </tr> <tr> <br> <td width="60%" border="0"></td> <td width="40%" align="center" border="0">Sign and Signature</td> </tr> </tbody> </table> <br><br> <br> <br> <table border="0"> <tr> <td bgcolor="crimson" align="center" border="0"><h4>8-km Sheikhupura Road, Opposite Milat Tractors Limited,Lahore,Tel:0300-0600061 </h4></td> </tr> <tr> <td bgcolor="crimson" align="center" border="0"><h5> Email Adress: <EMAIL> </h5></td> </tr> </table> '; // $html= $htmldata; PDF::SetTitle('Request for Invoice'); PDF::AddPage(); PDF::writeHTML($newHTML, true, false, true, false, ''); PDF::Output('invoiceRequest.pdf'); } public function saleInvoiceRequest() { $newHTML='<table border="0" cellpadding="2"> <thead> <tr> <th><br><h1>FORLAND MODREN MOTORS</h1></th> </tr> </thead> <tbody> <tr> <br> <td> To, <br> Foton JW Auto Park (PVT) <br> </td> </tr> <tr> <td width="30%" border="0" align="left" >Subject</td> <td width="70%" border="0" align="right"><h4>Date: '.session()->get("invoiceDate").'</h4></td> </tr> </tbody> </table> <br> <br> <br> <br> <table border="1" cellpadding="9"> <tbody> <tr> <td width="30%" border="0" align="left" >Customer Name</td> <td width="70%" border="0" align="center">'.session()->get("customerName").'</td> </tr> <tr> <td width="30%" border="0">Address</td> <td width="70%" align="center" border="0">'.session()->get("address").'</td> </tr> <tr> <td width="30%" border="0">Contact Details</td> <td width="70%" align="center" border="0">'.session()->get("contact").'</td> </tr> <tr> <td width="30%" border="0">NTN/CNIC #</td> <td width="70%" align="center" border="0">'.session()->get("CNIC").'</td> </tr> <tr> <td width="30%" border="0">SalesPerson</td> <td width="70%" align="center" border="0">Forland Modern Motors</td> </tr> <tr> <td width="30%" border="0">Dealer</td> <td width="70%" align="center" border="0">Forland Modern Motors</td> </tr> <tr> <td width="30%" border="0">Vehicle</td> <td width="70%" align="center" border="0">'.session()->get("productName").'</td> </tr> <tr> <td width="30%" border="0">Chassis No</td> <td width="70%" align="center" border="0">'.session()->get("chassisNo").'</td> </tr> <tr> <td width="30%" border="0">Engine NO</td> <td width="70%" align="center" border="0">'.session()->get("engineNo").'</td> </tr> <tr> <td width="30%" border="0">Color</td> <td width="70%" align="center" border="0">'.session()->get("color").'</td> </tr> <tr> <td width="30%" border="0">Amount</td> <td width="70%" align="center" border="0">'.session()->get("amountPaid").'</td> </tr> <tr> <td width="30%" border="0">Payment Detail</td> <td width="70%" align="center" border="0">Payment Details Attached</td> </tr> </tbody> </table> <br> <br><br> <br> <br> <table border="0"> <tr> <td align="right"> _______________________</td> </tr> <tr> <td align="right"> Sign & Signature </td> </tr> </table> '; // $html= $htmldata; PDF::SetTitle('Request for Invoice'); PDF::AddPage(); PDF::writeHTML($newHTML, true, false, true, false, ''); PDF::Output('invoiceRequest.pdf'); } //+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ public function gatePass() { $newHTML='<table border="0"> <thead> <tr> <th align="center"><h1><br><br><br>FORLAND MODREN MOTORS</h1></th> </tr> <tr> <th align="center"><h1>Gate Pass</h1></th> </tr> </thead> <tbody> </tbody> </table> <br> <table border="0"> <tbody> <tr> <td><br><span style="font-size: medium;">Refrence Number</span></td> <td align="center"><br>'.session()->get("referenceNumber").'</td> <td><br><span style="font-size: medium;">Customer Name</span></td> <td align="center"><br>'.session()->get("customerName").'</td> </tr> <tr> <td><br><span style="font-size: medium;">Date</span></td> <td align="center"><br>'.session()->get("invoiceDate").'</td> <td><br><span style="font-size: medium;">CNIC/NTN</span></td> <td align="center"><br>'.session()->get("CNIC").'</td> </tr> </tbody> </table> <br> <br> <table border="0" > <tr ><td> <table border="0"> <thead> <tr> <td align="left" bgcolor="#C0C0C0" width="60" > Sr# </td> <td align="center" bgcolor="#C0C0C0" width="140">Product Description</td> <td align="center"bgcolor="#C0C0C0" >Engine No</td> <td align="center" bgcolor=" #C0C0C0">Chassis No</td> <td align="center" bgcolor=" #C0C0C0">Color</td> </tr> </thead> <tbody > <tr > <td >1</td> <td>'.session()->get("description").'</td> <td>'.session()->get("engineNo").'</td> <td>'.session()->get("chassisNo").'</td> <td>'.session()->get("color").'</td> </tr> </tbody> </table> </td> </tr> </table> <table border="0"> <thead> <br> <br> <br> <tr> <td width="60%" border="0"></td> <td width="40%" align="center" border="0">_______________________</td> </tr> <tr> <td width="60%" border="0"></td> <td width="40%" align="center" border="0">Sign and Signature</td> </tr> </tbody> </table> <br><br> <table border="0"> <tr> <td bgcolor="crimson" align="center" border="0"><h4>8-km Sheikhupura Road, Opposite Milat Tractors Limited,Lahore,Tel:0300-0600061 </h4></td> </tr> <tr> <td bgcolor="crimson" align="center" border="0"><h5> Email Adress: <EMAIL> </h5></td> </tr> </table> <br><br><br> <hr> <table border="0"> <thead> <tr> <th align="center"><br><h1>FORLAND MODREN MOTORS<br></h1></th> </tr> <tr> <th align="center"><h1> Passage Certificate</h1></th> </tr> </thead> <tbody> </tbody> </table> <br> <table border="0"> <tbody> <tr> <td><br><span style="font-size: medium;">Refrence Number</span></td> <td align="center"><br>'.session()->get("referenceNumber").'</td> <td><br><span style="font-size: medium;">Customer Name</span></td> <td align="center"><br>'.session()->get("customerName").'</td> </tr> <tr> <td><br><span style="font-size: medium;">Date</span></td> <td align="center"><br>'.session()->get("invoiceDate").'</td> <td><br><span style="font-size: medium;">CNIC/NTN</span></td> <td align="center"><br>'.session()->get("CNIC").'</td> </tr> </tbody> </table> <br> <br> <br> <br> <table border="1" > <tr > <table border="0"> <thead> <tr> <td align="left" bgcolor="#C0C0C0" width="60" > Sr# </td> <td align="center" bgcolor="#C0C0C0" width="140">Product Description</td> <td align="center"bgcolor="#C0C0C0" >Engine No</td> <td align="center" bgcolor=" #C0C0C0">Chassis No</td> <td align="center" bgcolor=" #C0C0C0">City/Area</td> </tr> </thead> <tbody > <tr > <td >1</td> <td>'.session()->get("description").'</td> <td>'.session()->get("engineNo").'</td> <td>'.session()->get("chassisNo").'</td> <td>'.session()->get("color").'</td> </tr> </tbody> </table> <table border="0"> <thead> <br> <br> <br> <tr> <td width="60%" border="0"></td> <td width="40%" align="center" border="0">_______________________</td> </tr> <tr> <br> <td width="60%" border="0"></td> <td width="40%" align="center" border="0">Sign and Signature</td> </tr> </tbody> </table> <table border="0"> <tr> <td bgcolor="crimson" align="center" border="0"><h4>8-km Sheikhupura Road, Opposite Milat Tractors Limited,Lahore,Tel:0300-0600061 </h4></td> </tr> <tr> <td bgcolor="crimson" align="center" border="0"><h5> Email Adress: <EMAIL> </h5></td> </tr> </table> '; // $html= $htmldata; PDF::SetTitle('Request for Invoice'); PDF::AddPage(); PDF::writeHTML($newHTML, true, false, true, false, ''); PDF::Output('invoiceRequest.pdf'); } public function qutationRequestFinal(){ $newHTML='<table cellpadding="1" cellspacing="1" border="1" style="text-align:center;"> <tr><td> <img src="/assets/img/forLogo.jpg" border="0" height="100" width="300" align="center" /></td></tr> <tr> <td align="Left"> '.session()->get("customerName").' Date: '.session()->get("invoiceDate").' </td> </tr> <tr> <td > Qoutation For '.session()->get("productName").' </td> </tr> </table> <br> <table cellpadding="1" cellspacing="1" border="1" style="text-align:center;"> <thead> <tr> <th>Description</th> <th>Color</th> <th>Unit Price</th> <th width="40">Qty</th> <th width="173">Total Price</th> </tr> </thead> <tbody> <tr> <td>'.session()->get("productName").'</td> <td rowspan="2">'.session()->get("color").'</td> <td >Rs</td> <td rowspan="2" width="40">'.session()->get("quantity").'</td> <td width="173">Rs</td></tr> <tr><td >'.session()->get("description").'</td> <td>'.session()->get("price").'</td> <td width="173">'.session()->get("total").'</td> </tr> <tr><td colspan="5">('.session()->get("amountInWords").'/-Only).</td></tr> </tbody> </table> <br><br> <table border="0"> <tr ><td colspan="5" align ="left" ><h3>Terms & Conditions<br><br> </h3> </td></tr> </table> <table> </table> <table border="1" cellpadding="3"> <tbody> <tr> <td width="30%" border="0" align="left" >Delivery Time</td> <td width="70%" border="0" align="left">'.session()->get("DeliveryTime").' days after recipt of 100% advance payment</td> </tr> <tr> <td width="30%" border="0">Validity</td> <td width="70%" align="left" border="0">This Qoutation is valid for '.session()->get("ValidityPeriod").' days only</td> </tr> <tr> <td width="30%" border="0">Payment</td> <td width="70%" align="left" border="0">100% Advance payment in shape of DD/PO in favor of '.session()->get("PayTo").'</td> </tr> <tr> <td width="30%" border="0">Duty/Taxes #</td> <td width="70%" align="left" border="0">Any change in Govt.faisal Policies,RGST/VAT and tariff structures will be on coustumer accounts</td> </tr> <tr> <td width="30%" border="0">Force Majeure</td> <td width="70%" align="left" border="0">Manufacture will will not be responsible for any delay in delivery due to force majeure circumstance </td> </tr> <tr> <td width="30%" border="0">Warranty</td> <td width="70%" align="left" border="0"> Manufacture will not br responsible for any delay in delivery due to forcemajor circumstance</td> </tr> <tr> <td width="30%" border="0">Model</td> <td width="70%" align="left" border="0">'.session()->get("productName").'(2021)</td> </tr> </tbody> </table> <table border="0"> <thead> <br> <br> <br> <br><br> <br> <br> <br> <br> <br> <br> <br> <tr> <td width="60%" border="0"></td> <td width="40%" align="center" border="0">_______________________</td> </tr> <tr> <br> <td width="60%" border="0"></td> <td width="40%" align="center" border="0">Sign and Signature</td> </tr> </tbody> </table> '; PDF::SetTitle('Qoutation'); PDF::AddPage(); PDF::writeHTML($newHTML, true, false, true, false, ''); PDF::Output('qty.pdf'); } } <file_sep>/app/Http/Controllers/getProducts.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use DB; class getProducts extends Controller { public static function getAllProducts(){ $results=DB::select('select * from vw_stockdetails where category = 21'); return $results; } public static function getProductByCategory(Request $request,$CID){ $results=DB::select('select * from vw_stockdetails where Category='.$CID ); return $results; } public static function getPartsAndServices(){ $results=DB::select('select * from vw_stockdetails where Category=21 or Category=22' ); return $results; } public static function getAutosNames(){ $data=DB:: select('select * from tbl_auto_models'); $option='<option value=" "></option>'; foreach ($data as $d){ //print $option; $option=$option.' <option value= '.$d->ModelID.'>'.$d->Company.' '.$d->ModelName.'</option>'; } return $option; } public static function getAutoData($AID){ $results=DB::select('select * from tbl_auto_models where ModelID='.$AID); return $results; } } <file_sep>/app/Http/Controllers/UpdateStocksController.php <?php namespace App\Http\Controllers; use App\Http\Controllers\TransactionFlow; use Illuminate\Http\Request; use App\Http\Controllers\AdditionalTaxesAndCommissionsController; use DB; use Carbon\Carbon; use App\Http\Controllers\accountsController; class UpdateStocksController extends Controller { function updateStockDetails(Request $request,$data){ $Array=json_decode($data); $InvoiceNumber=$Array[1]; $AID=$Array[2]; foreach($Array[0] as $oneProduct){ if($oneProduct[5]==1){ $PID=$oneProduct[0]; $color=$oneProduct[1]; $chasisNumber= $oneProduct[2]; $EngineNumber=$oneProduct[3]; $TransportCharges =$oneProduct[4]; $status=$oneProduct[5]; $dateNow= Carbon::now()->toDateTimeString(); $LID=2; $oldBalance= LedgerPartiesController::getPartyBalance($LID); $currentBalance=floatval($oldBalance)-floatval($TransportCharges); LedgerPartiesController::UpdatePartiesBalance($LID,$currentBalance); $paidVia=$AID; $CID= AdditionalTaxesAndCommissionsController::AddTaxOrComminssion ( "Transportation Charges", $TransportCharges,NULL,"COST",$PID,NULL,NULL,$dateNow); TransactionFlow::addTransaction($InvoiceNumber,"Credit",'Transportation Charges',$TransportCharges,$dateNow, "1",null,null,NULL,null,NULL,NULL,NULL,NULL,$paidVia,$CID); $AID=$paidVia;//This needs o be changed in production $OldAccBalance=accountsController::getAccountBalance($AID); $newAccountBalance=floatval($OldAccBalance)-floatval($TransportCharges); accountsController::UpdateNewBalance($AID,$newAccountBalance); $OldPrice = DB::table('instock') ->where('ProductSerial', '=', $PID) ->get(); $CurrentPrice=floatval($OldPrice[0]->TotalCost)+floatval($TransportCharges); DB::table('productdefination') ->where('ProductSerial', $PID) ->update(['EngineNumber' =>$EngineNumber, 'ChasisNumber' =>$chasisNumber, 'color' =>$color ]); DB::table('instock') ->where('ProductSerial', $PID) ->update(['Remarks'=>"Delivered on ".$dateNow, 'TotalCost' =>$CurrentPrice, 'Status'=>'Available' ]); DB::table('tblpurchaseoorderdetaile') ->where('ProductSerial', $PID) ->update(['DilevedStatus'=>"Received" ]); }//if condition } //->format('Y-m-d h:iA'); // $d= Carbon::createFromFormat('dd/mm/YYYY HH:MM:SS', $dateNow); return "."; } public function getAllProducts(){ $results=DB::select('select * from vw_stockdetails'); return $results; } public function getAllAutos($PC){ $results=DB::select('select * from vw_stockdetails where Category='.$PC.' and StatusInStock<>"Pending"'); return $results; } public function getAllAvailableProducts(){ $results=DB::select('select * from vw_stockdetails where Status = "Available"'); return $results; } public function viewSoldStock(){ $results=DB::select('select * from vw_stockdetails where StatusInStock="Sold"'); return $results; } public static function UpdateStockStatus($PID,$Status){ DB::table('instock') ->where('ProductSerial', $PID) ->update([ 'Status'=>$Status ]); } public static function getTotalCost($PID){ $OldPrice = DB::table('instock') ->where('ProductSerial', '=', $PID) ->get(); return $OldPrice[0]->TotalCost; } public static function getTotalSoldPrice($PID){ $OldPrice = DB::table('instock') ->where('ProductSerial', '=', $PID) ->get(); return $OldPrice[0]->TotalSaleAmount; } public static function setTotalCost($PID,$amount){ DB::table('instock') ->where('ProductSerial', $PID) ->update(['TotalCost'=>$amount ]); return "Cost Updated"; } public static function setTotalSaleAmount($PID,$amount){ DB::table('instock') ->where('ProductSerial', $PID) ->update(['TotalSaleAmount'=>$amount ]); return "Sale Amount Updated"; } public static function updateStock($PID,$stkIn){ DB::table('instock') ->where('ProductSerial', $PID) ->update(['StockIn'=>$stkIn ]); return "Sale Amount Updated"; } public function UpdateInStock(Request $request,$CO){ $obj = json_decode($CO); $PID=$obj[0]; $productName=$obj[1]; $company=$obj[2]; $salePrice=$obj[3]; $purchasePrice=$obj[4]; $stockIn=$obj[5]; $color=$obj[6]; $engineNumber=$obj[7]; $chasisNumber=$obj[8]; $status=$obj[5]; self :: updateProducts($PID, $company, $engineNumber, $chasisNumber, $productName, $stockIn, $color, $salePrice, $purchasePrice, $status); return $obj; //return "Getting from controller".$obj[0]; } public function getInvoiceStock($InvoiceNo){ $results=DB::select('select * from vw_suppliersale_invoice where InvoiceNumber= '.$InvoiceNo); // mysql_insert_id() return $results; } public static function updateProducts($PID, $company, $engineNumber, $chasisNumber, $productName, $stockIn, $color, $salePrice, $purchasePrice, $status){ DB::table('productdefination') ->where('ProductSerial', $PID) ->update([ 'Company'=>$company, 'color'=>$color, 'EngineNumber'=>$engineNumber, 'ChasisNumber'=>$chasisNumber, 'ProductName'=>$productName ]); DB::table('instock') ->where('StockID', $PID) ->update([ 'StockIn'=>$stockIn, // 'Status'=>$status, 'PerUnitSalePrice'=>$salePrice, 'PerUnitPurchasePrice'=>$purchasePrice ]); } public static function getCurrentStock($PID){ $re = DB::table('instock') ->where('ProductSerial', '=', $PID) ->get(); return $re[0]->StockIn; } } <file_sep>/app/Http/Controllers/AISessionController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use DB; use Carbon\Carbon; class AISessionController extends Controller { public static function getDashboardInformations($key,$Value){ } public static function dailySaleAmount(){ $date = Carbon::now()->toDateString(); $data=DB:: select('select * from vw_daily_stock_sales where Date ="2021-2-4"'); return $data; } } <file_sep>/app/Http/Controllers/expenseController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Carbon\Carbon; use DB; class expenseController extends Controller { public static function insertExpense(Request $request, $CO){ $ata=json_decode($CO); foreach ($ata as $obj){ $date=$obj[0]; $LID=2; $amount=$obj[1]; $expenseName=$obj[2]; $expenseID=$obj[3]; $paidVia=$obj[4]; $remarks=$obj[5]; $id=DB::table('tbltransactionflow')->insertGetId([ 'DateStamp'=>$date, 'Amount'=>$amount, 'TransactionCatogery'=>"Expense", 'EID'=>$expenseID, 'PaidVia'=>$paidVia, 'TransactionType'=>"Credit" ]); DB::table('tblexpanseflow')->insertGetId([ 'ExpanseID'=>$expenseID, 'ExpanseHeadID'=>$amount, 'Remarks'=>"$remarks", 'DateStamp'=>$date, 'Amount'=>$amount, ]); $oldSelfBalance = LedgerPartiesController::getPartyBalance($LID); $newBalance = $oldSelfBalance - $amount; LedgerPartiesController::UpdatePartiesBalance($LID, $newBalance); //$balanceForParty=LedgerPartiesController::getPartyBalance($paidTo); //$newBalanceOfParty=$balanceForParty-$amount; //LedgerPartiesController::UpdatePartiesBalance($paidTo, $newBalanceOfParty); $oldAccountBalance = accountsController::getAccountBalance($paidVia); $newAccountBalance = $oldAccountBalance - $amount; accountsController::UpdateNewBalance($paidVia, $newAccountBalance); } return $id; } public static function getPartyNames(){ $data=DB:: select('select * from tblledgerparties'); $option='<option value=" "></option>'; foreach ($data as $d){ //print $option; $option=$option.' <option value= '.$d->LID.'>'.$d->LID.') '.$d->PartyName.'</option>'; } return $option; } public static function getAccounts(){ $data=DB:: select('select * from tblaccounts'); $option='<option value=" "></option>'; foreach ($data as $d){ //print $option; $option=$option.' <option value= '.$d->AID.'>'.$d->AID.') '.$d->AccountName.'</option>'; } return $option; } public static function getExpenseHeads(){ $data=DB:: select('select * from tblexpenseheads where ExpenseHead <> "Payment"'); $option='<option value=" "></option>'; foreach ($data as $d){ //print $option; $option=$option.' <option value= '.$d->ID.'>'.$d->ID.') '.$d->ExpenseHead.'</option>'; } return $option; } function viewExpense(){ $data=DB:: select('select * from vw_expensetransactionflow'); return $data; } } <file_sep>/app/Http/Controllers/serviceSalesFlow.php <?php namespace App\Http\Controllers; use Carbon\Carbon; use Illuminate\Http\Request; use App\Http\Controllers\CustomerController; use App\Http\Controllers\LedgerPartiesController; use App\Http\Controllers\accountsController; use App\Http\Controllers\UpdateStocksController; use DB; use NumberToWords\NumberToWords; class serviceSalesFlow extends Controller { public function SalesFlow(Request $request,$data){ $Array=json_decode($data); $tot=$Array[1]; $OverAllDiscount= $Array[2]; $AmountAfterDiscount=$Array[3]; $tax =$Array[4]; $netTotal=$Array[5]; $AP=$Array[6]; $RBI=$Array[7]; $CID=$Array[8]; $CLB=$Array[9]; $CCB=$Array[10]; $AID=$Array[11]; // return $CLB; $dateNow= Carbon::now()->toDateTimeString();//->format('Y-m-d h:iA'); // $d= Carbon::createFromFormat('dd/mm/YYYY HH:MM:SS', $dateNow); //return $dateNow; //tot,discount,gross,tax,netTotal,amp,rmb,CID,CLB,CCB //insert into sales order $invoiceNumber=DB::table('tblsaleinvoice')->insertGetId(['CustomerID'=>$CID, 'TotalAmount'=>$tot, 'Discount'=>$OverAllDiscount, 'DateStamp'=>$dateNow, 'VAT'=>$tax, 'NetTotal'=>$netTotal, 'AmountPaid'=>$AP, 'Balance'=>$RBI, 'BillStatus'=>"CLEAR", 'HoldStatus'=>'0', 'CustomerBalanceBeforeInvoiceBill'=>$CLB, 'CustomerBalanceAfterInvoiceBill'=>$CCB, 'CashPaidBack'=>NULL, 'CashNote'=>NULL, 'Remarks'=>NULL, 'dliveryDate'=>NULL, 'returnDate' =>NULL ]); $totlpaid=$AP; self::insertInDetailedOrder($Array[0],$invoiceNumber,$dateNow); $LID=2; $oldSelfBalance=LedgerPartiesController::getPartyBalance(2); $oldCustomerBalance=CustomerController::getCustomerBalance($CID); $paidVia=$AID; $currentCustomerBalance=floatval($oldCustomerBalance)+floatval($RBI); CustomerController::UpdateCustomerBalance($CID,$currentCustomerBalance); $selfBalance=floatval($oldSelfBalance)-floatval($totlpaid); LedgerPartiesController::UpdatePartiesBalance(2,$selfBalance); TransactionFlow::addTransaction($invoiceNumber,"Credit","Stock and Service", $totlpaid,$dateNow,"1",$oldCustomerBalance,$currentCustomerBalance,$oldSelfBalance,$selfBalance,$LID,"0",NULL,$CID,$paidVia,NULL); $OldAccBalance=accountsController::getAccountBalance($AID); $newAccountBalance=floatval($OldAccBalance)-floatval($totlpaid); accountsController::UpdateNewBalance($AID,$newAccountBalance); $invoiceDetails=self::getAllInvoiceDetails($invoiceNumber); //session(['invoiceDetails' => $invoiceDetails]); $ProductDetailsArray=array(); $oneProductInInvoice=array(); foreach($invoiceDetails as $product){ $qty=$product->Quantity; $contact=$product->ProductSerial; $customerName=$product->CustomerName; $PID=$product->ProductSerial; $productName=$product->ProductName; $IN=$product->InvoiceNumber; $tax=$product->VAT; $Pt =$product->NetAmount; $unitPrice=$product->PerUnitSalePrice; $CNIC=$product->CNIC; $productName=$product->ProductName; $contact=$product->Contect; $TotalAmount=$product->TotalAmount; $tax=$product->VAT; $Discount=$product->Discount; $NetTotal=$product->NetTotal; $AmountPaid=$product->AmountPaid; $Balance=$product->Balance; $dat=$product->DateStamp; $BillStatus=$product->BillStatus; $AmountPaid=$product->AmountPaid; $InvoiceBalance=$product->Balance; array_push($oneProductInInvoice,$PID,$productName,$qty,$unitPrice,$tax,$Pt); array_push($ProductDetailsArray,$oneProductInInvoice); $oneProductInInvoice=array(); session(['ProductNames' => $ProductDetailsArray]); session(['ivd' => $dat]); session(['iu' => $IN]); session(['customerID' => $CID]); session(['customerName' => $customerName]); session(['contact' => $contact]); session(['model' => $productName]); session(['invoiceNo' => $invoiceNumber]); session(['CNIC' => $CNIC]); session(['tax' => $tax]); session(['total' => $TotalAmount]); session(['netTotal' => $netTotal]); session(['InvBalance' => $InvoiceBalance]); session(['amountPaid' => number_format($AmountPaid)]); session(['overallDiscount' => $Discount]); $numberToWords = new NumberToWords(); $numberTransformer = $numberToWords->getNumberTransformer('en'); $a= $numberTransformer->toWords($AmountPaid); session(['amountInWords' => ucwords($a)]); } } //insert into order details //inster in transaction Flow //update customer balance //frf()) public function insertInDetailedOrder($OrderDetails,$InvoiceID,$date){ foreach ($OrderDetails as $row){ $DSID=DB::table('tblsaledetailedinvoice')->insertGetId(['InvoiceNumber'=>$InvoiceID, 'ProductSerial'=>$row[0], 'SalePrice'=>$row[1], 'Quantity'=>$row[2], 'DiscountOffered'=>$row[3], 'DateStamp'=>$date, 'TotalAmount'=>0, 'NetAmount'=>$row[4], 'Activity'=>"Sales", 'RentedDays'=>0 ]); $oldStock= UpdateStocksController::getCurrentStock($row[0]); $newStock= floatval($oldStock)-floatval($row[2]); UpdateStocksController::updateStock($row[0],$newStock); } return $DSID; } public function apiCheck() { $obj = (object) [ 'aString' => 'some string', 'anArray' => [ 1, 2, 3 ] ]; return json_encode($obj); # code... } public function addInTransactionFlowForSales($invoiceNumber,$dateNow,$AP,$userID,$pattyCash,$CLB,$CCB){ // [TransactionID] $TID=DB::table('tblTransactionFlow')->insertGetId(['InvoiceNo'=>$invoiceNumber, 'TransactionCatogery'=>"Sales", 'Amount'=>$AP, 'DateStamp'=>$dateNow, 'UserID'=>$userID, 'PattyCash'=>$pattyCash, 'SBB'=>NULL, 'SBA'=>NULL, 'CBB'=>$CLB, 'CBA'=>$CCB ]); } public function getInvoiceNewID(){ $IID=DB::table('tblsaleinvoice')->max("InvoiceNumber"); return $IID+1; } public function UpdateRecipe(Request $request,$RecipeTable,$MenuID,$Ecost,$salePrice){ print($MenuID); self::deleteintblrecipetoraw($MenuID); $obj = json_decode($RecipeTable); foreach ($obj as $row){ $RMID=$row[0]; $RMName=$row[1]; $qty=$row[2]; $unit=$row[3]; $unitCost=$row[4]; $TotalCostOfThisItem=$row[5]; // print("RMID".$RMID); // print(" Name".$RMName); // print(" Qty".$qty); // print(" unt".$unit); // print(" unit cost".$unitCost); // print(" Cost Total cost".$unitCost); self::insertinrecipetblraw($MenuID,$RMID,$unit,$qty," ",$TotalCostOfThisItem); } self::updateIntblMenuproductsForSaleAndPurchase($MenuID,$Ecost,$salePrice); return 0; } public function deleteintblrecipetoraw($MenuID){ $Deleted = DB:: delete("delete from tblrecipetoraw where PID=".$MenuID); print($Deleted); } public function getAllInvoiceDetails($InvoiceNo){ $results=DB::select('select * from vw_customersale_invoice where InvoiceNumber= '.$InvoiceNo); return $results; } public function insertinrecipetblraw($Rpid,$Rrawid,$Runit,$Rquantity,$remarks,$REcost){ $result= DB::insert('insert into tblrecipetoraw (PID, RAWID, Unit, Quantity, Remarks, ECost ) values (?, ?,?,?,?,?)', [$Rpid,$Rrawid,$Runit,$Rquantity,$remarks, $REcost]); if($result==1){ print('nextone'); } } public function updateIntblMenuproductsForSaleAndPurchase($PID,$ERCost,$SalePrice){ $qr="UPDATE tblmenuproducts SET SalePrice='".$SalePrice."', RecipeCost ='".$ERCost."' WHERE PID =".$PID; $affected = DB::update($qr); print("Number of Rows Affacted".$affected); } public function saleServiceInvoice() { $newHTML='<table border="0"> <thead> <tr> <th><br><h1>FORLAND MODREN MOTORS</h1></th> </tr> </thead> <tbody> <tr> <br> <td> NTN:82588676-6 <br> STRN:3277876204764 <br> Customer\'s Copy </td> </tr> <tr><td align="center"><h1>Sales Invoice</h1></td></tr> </tbody> </table> <br> <br> <br> <table border="0"> <tbody> <tr> <td><br><span style="font-size: medium;">Customer Name</span></td> <td align="center"><br>____________</td> <td><br><span style="font-size: medium;">Booking No</span></td> <td align="center"><br>____________</td> </tr> <tr> <td><br><span style="font-size: medium;">Address</span></td> <td align="center"><br>____________</td> <td><br><span style="font-size: medium;">Invoice Number</span></td> <td align="center"><br>____________</td> </tr> <tr> <td><br><span style="font-size: medium;">CNIC/NTN</span></td> <td align="center"><br>____________</td> <td><br><span style="font-size: medium;">Invoice Date</span></td> <td align="center"><br>____________</td> </tr> <tr> <td><br><span style="font-size: medium;">Contact</span></td> <td align="center"><br>____________</td> <td><br><span style="font-size: medium;"></span></td> <td align="center"><br>____________</td> </tr> </tbody> </table> <br> <br> <br> <br> <table border="1" > <tr ><td> <table border="0"> <thead> <tr> <td align="left" bgcolor="#C0C0C0" > Description </td> <td align="center" bgcolor="#C0C0C0" >color</td> <td align="center"bgcolor="#C0C0C0" >Engine No</td> <td align="center" bgcolor=" #C0C0C0">Chassis No</td> <td align="center" bgcolor=" #C0C0C0">Amount</td> </tr> </thead> <tbody > <tr > <td ></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> </tbody> </table> </td> </tr> </table> <table border="0"> <thead> <tr> <th width="60%" border="1" align="center"> Total in Word </th> <th width="40%" border="1" align="center"> Tootal PKR</th> </tr> </thead> <tbody> <tr> <td width="60%" border="1" align="center">1000</td> <td width="40%" border="1" align="center">10000</td> </tr> <br> <br> <br> <br> <br> <br> <br> <tr> <td width="60%" border="0"></td> <td width="40%" align="center" border="0">_______________________</td> </tr> <tr> <br> <td width="60%" border="0"></td> <td width="40%" align="center" border="0">Sign and Signature</td> </tr> </tbody> </table> <br><br> <br> <br> <table border="0"> <tr> <td bgcolor="crimson" align="center" border="0"><h4>8-km Sheikhupura Road, Opposite Milat Tractors Limited,Lahore,Tel:0300-0600061 </h4></td> </tr> <tr> <td bgcolor="crimson" align="center" border="0"><h5> Email Adress: <EMAIL> </h5></td> </tr> </table> '; // $html= $htmldata; PDF::SetTitle('Sale Invoice'); PDF::AddPage(); PDF::writeHTML($newHTML, true, false, true, false, ''); PDF::Output('saleInvoice.pdf'); } } <file_sep>/app/Http/Controllers/printServiceInvoice.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use PDF; use DB; // session(['invoiceNo' => $InvoiceNo]); // session(['customerID' => $re[0]->CustomerID]); // session(['itemNo' => $re->ProductSerial]); // session(['quantity' => $re->Quantity]); // session(['unitPrice' => $re->PerUnitSalePrice]); // session(['productName' => $re->ProductName]); // session(['price' => $re->PerUnitSalePrice]); // session(['contact' => $re->Contect]); // session(['customerName' => $re->CustomerName]); // session(['CNIC' => $re->CNIC]); // session(['address' => $re->Address]); // session(['engineNo' => $re->EngineNumber]); // session(['chassisNo' => $re->ChasisNumber]); // session(['color' => $re->color]); // session(['fatherName' => $re->FatherName]); // session(['total' => $re->AmountPaid]); // session(['referenceNumber' => 'FMM-GDP-'.$InvoiceNo]); // session(['amountPaid' => $re->AmountPaid]); // session(['description' => $re->description]); // session(['balance' => $re->Balance]); // session(['totalCost' => $re->TotalCost]); // session(['tax' => $re->VAT]); // session(['endTotal' => $re->NetTotal]); class printServiceInvoice extends Controller { public function printSaleInvoice(){ $html= '<table border="1"> <thead> <tr> <th><br><h1>FORLAND MODREN MOTORS</h1></th> </tr> </thead> <tbody> <tr> <br> <td> NTN:82588676-6 <br> STRN:3277876204764 <br> Customer\'s Copy </td> </tr> <tr><td align="center"><h1>Sales Invoice</h1></td></tr> </tbody> </table> <br> <br> <br> <table border="0"> <tbody> <tr> <td><br><span style="font-size: medium;">Customer Name:</span></td> <td align="center"><br>'.session()->get("customerName").'</td> <td><br><span style="font-size: medium;">Booking No:</span></td> <td align="center"><br>'.session()->get("invoiceNo").'</td> </tr> <tr> <td><br><span style="font-size: medium;">Address:</span></td> <td align="center"><br>'.session()->get("address").'</td> <td><br><span style="font-size: medium;">Invoice Number:</span></td> <td align="center"><br>'.session()->get("invoiceNo").'</td> </tr> <tr> <td><br><span style="font-size: medium;">CNIC/NTN #</span></td> <td align="center"><br>'.session()->get("CNIC").'</td> <td><br><span style="font-size: medium;">Invoice Date:</span></td> <td align="center"><br>'.session()->get("invoiceDate").'</td> </tr> <tr> <td><br><span style="font-size: medium;">Contact:</span></td> <td align="center"><br>'.session()->get("contact").'</td> <td><br><span style="font-size: medium;"></span></td> </tr> </tbody> </table> <br> <br> <br> <br> <table border="1" > <tr ><td> <table border="0"> <thead> <tr> <td align="left" bgcolor="#C0C0C0" > Description </td> <td align="center" bgcolor="#C0C0C0" >color</td> <td align="center"bgcolor="#C0C0C0" >Engine No</td> <td align="center" bgcolor=" #C0C0C0">Chassis No</td> <td align="center" bgcolor=" #C0C0C0">Amount</td> </tr> </thead> <tbody > <tr > <td style="text-align:center" >'.session()->get("description").'</td> <td style="text-align:center">'.session()->get("engineNo").'f</td> <td style="text-align:center">'.session()->get("amoutPaid").'a</td> <td style="text-align:center">'.session()->get("chassisNo").'q</td> <td style="text-align:center">'.session()->get("amoutPaid").'w</td> </tr> <tr> <td></td> </tr> <tr> <td></td> </tr> <tr> <td></td> </tr> <tr> <td></td> </tr> <tr> <td></td> </tr> <tr> <td></td> </tr> <tr> <td></td> </tr> <tr> <td></td> </tr> <tr> <td></td> </tr> <tr> <td></td> </tr> </tbody> </table> </td> </tr> </table> <table border="0"> <thead> <tr> <th width="60%" border="1" align="center"> Total in Word </th> <th width="40%" border="1" align="center" style="line-height: 100%;"> Total PKR</th> </tr> </thead> <tbody border="1 "> <tr> <td width="60%" border="1" align="center">'.session()->get("total").'</td> <td width="40%" border="1" align="center">100007</td> </tr> <br> <br> <br> <br> <br> <br> <br> <tr> <td width="60%" border="0"></td> <td width="40%" align="center" border="0">'.session()->get("address").'</td> </tr> <tr> <br> <td width="60%" align="right" border="0">_________________</td> <td width="40%" align="right" border="0">Sign and Signature</td> </tr> </tbody> </table> <br><br> <br> <br> <table border="0"> <tr> <td bgcolor="crimson" align="center" border="0"><h4>8-km Sheikhupura Road, Opposite Milat Tractors Limited,Lahore,Tel:0300-0600061 </h4></td> </tr> <tr> <td bgcolor="crimson" align="center" border="0"><h5> Email Adress: <EMAIL> </h5></td> </tr> </table>'; PDF::SetTitle('Request for Invoice'); PDF::AddPage(); PDF::writeHTML($html, true, false, true, false, ''); PDF::Output('sales.pdf'); } } <file_sep>/app/Http/Controllers/attendanceController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Carbon\Carbon; use DB; class attendanceController extends Controller { public static function markAttendance(Request $request, $CO){ $EID=json_decode($CO); //->format('Y-m-d h:iA'); $date=Carbon::now(); $dateToday = Carbon::now()->toDateString(); $timeToday = Carbon::now(); $reportingTime =Carbon::parse( DB::table('tblemployeepay') ->where('EID', '=', $EID) ->first()->ReportingTime); // return $reportingTime; $status = 'LATE'; print("Today Time ".$timeToday."\n"); print("Reporting Time ".$reportingTime."\n"); $minLate= $timeToday->diffInMinutes($reportingTime); print("Late in Minutes".$minLate."\n"); $hm= $timeToday->diffForHumans($reportingTime); if ($minLate<=15) { $status = 'On Time';//$today->eq($last) $rm="On Time"; // return "Wow On time"; } else { $status = 'Late'; $rm="You are ".$hm." the Reporting Time"; } $tid=DB::table('tbl_employeeattendance')->insertGetId([ 'EID'=>$EID, 'Date'=>$date, 'TimeIn'=>$timeToday, 'ReportingTime'=>$reportingTime, 'Status'=>$status, 'Remarks'=>$rm ]); } public static function getAttendance(){ $data=DB:: select('select * from vw_emoloyeeattendance order by Date DESC'); return $data; } } <file_sep>/app/Http/Controllers/saleRequestController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use DB; use Carbon\Carbon; use NumberToWords\NumberToWords; //https://github.com/kwn/number-to-words class saleRequestController extends Controller { public function saveQuoations($dateNow, $invoiceNumber, $city, $receivedBy){ DB::table('tbl_print_docs')->insertGetId([ 'invoiceDate' => $dateNow, 'invoiceNo' => $invoiceNumber, 'city' => $city, 'receivedBy' => $receivedBy, ]); } public static function getInvoiceSaleRequest($InvoiceNo){ $dateNow= Carbon::now()->toDateString();//->format('Y-m-d h:iA'); $re = DB::table('vw_customersale_invoice') ->where('InvoiceNumber', '=', $InvoiceNo) ->first(); session(['invoiceNo' => $InvoiceNo]); session(['customerID' => $re->CustomerID]); session(['itemNo' => $re->ProductSerial]); session(['quantity' => $re->Quantity]); session(['unitPrice' => number_format($re->PerUnitSalePrice)]); session(['productName' => $re->ProductName]); session(['price' => number_format($re->PerUnitSalePrice)]); session(['contact' => $re->Contect]); session(['customerName' => $re->CustomerName]); session(['CNIC' => $re->CNIC]); session(['address' => $re->Address]); session(['engineNo' => $re->EngineNumber]); session(['chassisNo' => $re->ChasisNumber]); session(['color' => $re->color]); session(['fatherName' => $re->FatherName]); session(['invoiceDate' => $re->DateStamp]); session(['referenceNumber' => 'FMM-GDP-'.$InvoiceNo]); session(['amountPaid' => number_format($re->AmountPaid)]); session(['description' => $re->ProductName]); session(['balance' => number_format($re->Balance)]); session(['totalCost' => number_format($re->TotalCost)]); session(['tax' => number_format($re->VAT)]); session(['endTotal' => number_format($re->NetTotal)]); $numberToWords = new NumberToWords(); $numberTransformer = $numberToWords->getNumberTransformer('en'); $a= $numberTransformer->toWords($re->AmountPaid); session(['amountInWords' => ucwords($a)]); session(['receiptNumber' => 'FMM-'.$dateNow.'-'.$InvoiceNo]); //session(['vehRegNo' => '']); //session(['distanceTraveled' => '']); session(['Amount' =>'']); session(['receivedBy' => '']); session(['tax' => '0']); session(['total' => '']); session(['S&H' => '-']); session(['others' => '-']); session(['city' => '']); session(['province' => '']); //return $results; } } <file_sep>/app/Http/Controllers/accountsController.php <?php namespace App\Http\Controllers; use DB; use Illuminate\Http\Request; class accountsController extends Controller { public static function getAccountHeads(){ $data=DB:: select('select * from tblaccounts'); $option='<option value=""></option>'; foreach ($data as $d){ //print $option; $option=$option.' <option value= '.$d->AID.'>'.$d->AccountName.' # '.$d->AccountNumber.'</option>'; } return $option; } public static function getAccountBalance($AID){ $re = DB::table('tblaccounts') ->where('AID', '=', $AID) ->first()->Balance; return $re; } public static function UpdateNewBalance($AID,$amount){ DB::table('tblaccounts') ->where('AID', $AID) ->update(['Balance' =>$amount ]); return 'update New Balance'; } } <file_sep>/app/Http/Controllers/AdditionalTaxesAndCommissionsController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use DB; use Carbon\Carbon; use App\Http\Controllers\CustomerController; use App\Http\Controllers\UpdateStocksController; use App\Http\Controllers\TransactionFlow; use App\Http\Controllers\LedgerPartiesController; class AdditionalTaxesAndCommissionsController extends Controller { public static function AddTaxOrComminssion ( $CPName,$amount,$Remarks,$TTYPE,$PID,$CPercent,$POA, $dateHere){ $CID=DB::table('tbladditionalcostandprofits')->insertGetId(['PID'=> $PID, 'CPName' =>$CPName, 'Amount' =>$amount, 'TType' =>$TTYPE, 'DateStamp'=>$dateHere, 'Remarks'=>$Remarks, 'CPercent'=>$CPercent, 'percentOfAmount'=>$POA ]); // TransactionFlow:: addTransaction(NULL,"Credit",$CPName,$amount,$dateHere, // "1",NULL,NULL,NULL,NULL,NULL,"0",NULL,NULL,NULL,$CID); return $CID; } public function AddTaxOrCommissionNegative(Request $request,$data){ // $(tr).find('td:eq(0)').text(),//head // $(tr).find('td:eq(1)').text(), //Amount // $(tr).find('td:eq(2)').text(), //Remarks // $(tr).find('td:eq(4)').text() //ComID $dateNow= Carbon::now()->toDateTimeString(); $Array=json_decode($data); $PID=$Array[0]; $AID=$Array[1]; $totCostHere=0; foreach($Array[2] as $item){ $amp=$item[1]; self:: AddTaxOrComminssion ( $item[0],$item[1],$item[2],"Cost",$PID,NULL,NULL, $dateNow); $oldSelfBalance= LedgerPartiesController::getPartyBalance(2); $selfBalance=$oldSelfBalance-$item[1]; LedgerPartiesController::UpdatePartiesBalance(2, $selfBalance); $totCostHere=floatval($totCostHere)+floatval($item[1]); TransactionFlow:: addTransaction(NULL,"Credit",$item[0],$item[1],$dateNow, "1",$oldSelfBalance,$selfBalance,NULL,NULL,"2","0","2",NULL,"5",null); $OldAccBalance=accountsController::getAccountBalance($AID); $newAccountBalance=floatval($OldAccBalance)-floatval($amp); accountsController::UpdateNewBalance($AID,$newAccountBalance); // public static function addTransaction($InvoiceNo,$TType,$Tcate,$amount,$dateStamp, // $UserID,$SBB,$SBA,$CBB,$CBA,$LID,$pattyCash,$paidBy,$paidTo,$paidVia,$CID) } $oldCost=UpdateStocksController::getTotalCost($PID); $newCost=floatval($totCostHere)+floatval($oldCost); UpdateStocksController::setTotalCost($PID,$newCost); return "HOLA"; } public function AddTaxOrCommissionPositive(Request $request,$data){ $dateNow= Carbon::now()->toDateTimeString(); $Array=json_decode($data); $PID=$Array[0]; $TotalSaleAmount=0; $AID=$Array[1];; foreach($Array[2] as $item){ $amp=$item[1]; self:: AddTaxOrComminssion ( $item[0],$item[1],$item[2],"Profit",$PID,NULL,NULL, $dateNow); $oldSelfBalance= LedgerPartiesController::getPartyBalance(2); $selfBalance=$oldSelfBalance+$item[1]; LedgerPartiesController::UpdatePartiesBalance(2, $selfBalance); $TotalSaleAmount=floatval($TotalSaleAmount)+floatval($item[1]); TransactionFlow:: addTransaction(NULL,"Debit",$item[0],$item[1],$dateNow, "1",$oldSelfBalance,$selfBalance,NULL,NULL,"2","0","2",NULL,"5",null); $OldAccBalance=accountsController::getAccountBalance($AID); $newAccountBalance=floatval($OldAccBalance)+floatval($amp); accountsController::UpdateNewBalance($AID,$newAccountBalance); // public static function addTransaction($InvoiceNo,$TType,$Tcate,$amount,$dateStamp, // $UserID,$SBB,$SBA,$CBB,$CBA,$LID,$pattyCash,$paidBy,$paidTo,$paidVia,$CID) } $oldCost=UpdateStocksController::getTotalSoldPrice($PID); $newCost=floatval($TotalSaleAmount)+floatval($oldCost); UpdateStocksController::setTotalSaleAmount($PID,$newCost); return 'Hola'; } public static function getComissionHeads(){ $data=DB:: select('select * from tbl_comissionheads'); $option='<option value=" "></option>'; foreach ($data as $d){ //print $option; $option=$option.' <option value= '.$d->ComissionID.'>'.$d->ComissionName.'</option>'; } return $option; } } <file_sep>/app/Http/Controllers/signInSignUPcontroller.php <?php namespace App\Http\Controllers; use DB; use Illuminate\Http\Request; class signInSignUPcontroller extends Controller { public function InsertAdmin(Request $request, $CO) { $obj=json_decode($CO); $Username=$obj[0]; $Userpaswd=$obj[1]; $desigtn="Admin"; $UID=DB::table('userinfo')->insertGetId(['UserName'=>$Username, 'Password'=>$<PASSWORD>, 'Designation'=>$desigtn ]); //return "Getting from controller".$obj[0]; return self::signIn($Username,$Userpaswd); } public function signIn($Username,$Userpaswd){ $user=DB:: select('select * from userinfo where UserName='.$Username.'and Password='.$<PASSWORD>); return $user; return "es"; } } <file_sep>/app/Http/Controllers/uzairController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use DB; class uzairController extends Controller { function function(){ $data=DB:: select('select * from tblaccounts'); return $data; } function myfunction() { $record = DB::select('select * from productdefination'); return $record; } }<file_sep>/app/Http/Controllers/employeeController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use DB; class employeeController extends Controller { public static function addNewEmployee(Request $request, $CO){ $ata=json_decode($CO); $firstName =$ata[0]; $lastName =$ata[1]; $CNIC =$ata[2]; $contact =$ata[3]; $address =$ata[4]; $email =$ata[5]; $designation =$ata[6]; $date =$ata[7]; $data=DB::table('tblemployees')->insertGetId([ 'FirstName'=>$firstName, 'LastName'=>$lastName, 'CNIC'=>$CNIC, 'ContactNo'=>$contact, 'HomeAddress'=>$address, 'EmailID'=>$email, 'DesignationID'=>$designation, 'JoiningDate'=>$date ]); return "New Employee Added at ".$data; } function getAllEmployees(){ $data=DB:: select('select * from tblemployees'); return $data; } public static function editEmployee(Request $request, $CO){ $ata=json_decode($CO); $EID = $ata[0]; $firstName = $ata[1]; $lastName = $ata[2]; $CNIC = $ata[3]; $contact = $ata[4]; $address = $ata[5]; $email = $ata[6]; $designation = $ata[7]; $date = $ata[8]; $re = DB::table('tblemployees') ->where('EID', $EID) ->update([ 'FirstName'=>$firstName, 'LastName'=>$lastName, 'CNIC'=>$CNIC, 'ContactNo'=>$contact, 'HomeAddress'=>$address, 'EmailID'=>$email, 'DesignationID'=>$designation, 'JoiningDate'=>$date ]); return $EID; } }<file_sep>/app/Http/Controllers/CustomerViewController.php <?php namespace App\Http\Controllers; use DB; use Illuminate\Http\Request; class CustomerViewController extends Controller { public function customerinfo(Request $request, $CO){ $obj=json_decode($CO); $Cname=$obj[0]; $CusContact=$obj[1]; $cusaddres=$obj[2]; $CusIntr=$obj[3]; $cusmet=$obj[4]; self:: insertintblcustomeinformation($Cname,$CusContact,$cusaddres,$CusIntr,$cusmet); return "Getting from controller".$obj[0]; } public function insertintblcustomeinformation( $CCustomerName, $CAddress, $CContect, $Cusint, $cusmt ){ $result= DB::insert('insert into customeinformation (CustomerName,Address, Contect,Who meet,interested In) value(?,?,?,?,?)', [$CCustomerName, $CContect, $CAddress,$Cusint,$cusmt]); if ($result==1){ print("escccc"); } } public static function getCustomerNames(){ $data=DB:: select('select * from customeinformation'); $option='<option value=" "></option>'; foreach ($data as $d){ //print $option; $option=$option.' <option value= '.$d->CustomerID.'>'.$d->CustomerName.'</option>'; } return $option; } }
8a8833add8da779fdafe60fca0fc14bfb661e31d
[ "PHP" ]
29
PHP
Uzair41293/DemoPos
e045a4a5b727002c2c96804c40f47c2de9fcd6bc
42804aff11b7ee6bcb0a979811f675afd972fd9e
refs/heads/master
<file_sep>package com.call.calendly.app; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.InetSocketAddress; import java.nio.charset.Charset; import java.util.List; import java.util.Map; import org.json.JSONArray; import org.json.JSONObject; import com.sun.net.httpserver.BasicAuthenticator; import com.sun.net.httpserver.HttpContext; import com.sun.net.httpserver.HttpServer; class CalendlyApi { void callCalendly() throws IOException { int serverPort = 9000; HttpServer server = HttpServer.create(new InetSocketAddress(serverPort), 0); HttpContext context =server.createContext("/calendly/scheduleddata", (exchange -> { if ("POST".equals(exchange.getRequestMethod())) { InputStream is = exchange.getRequestBody(); // retrieve the request json data ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] buffer = new byte[2048]; int len; while ((len = is.read(buffer))>0) { bos.write(buffer, 0, len); } String data = new String(bos.toByteArray(), Charset.forName("UTF-8")); //print the scheduled data coming from webhooks System.out.println("Request: \n " + data); System.out.println("\n"); //formating JSON data JSONObject mainResponseObject = new JSONObject(data.toString()); JSONObject payLoadObject = mainResponseObject.getJSONObject("payload"); JSONObject eventTypeObject = payLoadObject.getJSONObject("event_type"); JSONObject eventObject = payLoadObject.getJSONObject("event"); JSONArray assignedto_value = eventObject.getJSONArray("assigned_to"); JSONObject inviteeObject = payLoadObject.getJSONObject("invitee"); System.out.println("Event Status:"+" "+mainResponseObject.getString("event")); System.out.println("UUID:"+" "+eventTypeObject.getString("uuid")); System.out.println("Meeting Type:"+" "+eventTypeObject.getString("kind")); System.out.println("Duration:"+" "+eventTypeObject.getString("slug")); System.out.println("Name:"+" "+eventTypeObject.getString("name")); System.out.println("Assigned to:"+" "+assignedto_value.getString(0)); System.out.println("Start Time:"+" "+eventObject.getString("start_time")); System.out.println("End Time:"+" "+eventObject.getString("end_time")); System.out.println("Invitee Name:"+" "+inviteeObject.getString("name")); System.out.println("Invitee email:"+" "+inviteeObject.getString("email")); OutputStream os = exchange.getResponseBody(); os.close(); } })); server.setExecutor(null); // creates a default executor server.start(); } } class Application { } <file_sep>package com.call.calendly.app; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.math.BigInteger; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class Test_Calendly { public static void main(String[] args) throws IOException { // TODO Auto-generated method stub CalendlyApi calendly = new CalendlyApi(); WebhookReg webhook = new WebhookReg(); WebhookModel webModel = new WebhookModel(); Scanner in = new Scanner(System.in); System.out.println("Please Choose to Operate: "+ "\n"+ "1. Webhook Operation"+ "\n"+ "2. Calling Calendly for Scheduled Data"+"\n"); int choice = 0; choice = in.nextInt(); String url; String events = "invitee.created"; BigInteger hookId; switch(choice) { case 1: String c = ""; do { System.out.println("Please give input for Webhook: "+ "\n"+ "1. Auhtorization Token"+ "\n"+ "2. Webhook Registration"+"\n"+ "3. Get all the registered Webhook"+"\n"+"4. Get a speific Webhook"+"\n"+ "5. Delete a Webhok"+"\n"); choice = in.nextInt(); switch(choice) { case 1: webhook.authToken(); break; case 2: BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Please Enter the url you want to Register: "); url = br.readLine(); url+="/calendly/scheduleddata"; System.out.println("Please give input for any of the Following: "+ "\n"+"1. for invitee.created"+"\n"+"2. for invitee.canceled"+"\n"); choice = in.nextInt(); switch(choice) { case 1: events = "invitee.created"; break; case 2: events = "invitee.canceled"; break; } webModel.setEvents(events); webModel.setUrl(url); webhook.subscribeHook(webModel); break; case 3: webhook.getAlltheHooks(); break; case 4: hookId = in.nextBigInteger(); System.out.println("Please Enter Hook Id: "); webModel.setHookId(hookId); webhook.getAHook(webModel); break; case 5: System.out.println("Please Enter Hook Id You Want to Delete: "); hookId = in.nextBigInteger(); webModel.setHookId(hookId); webhook.deleteAHook(webModel); break; } System.out.println("Do you want to continue? Type y for Yes or n for No"); c = in.next(); }while(c.equalsIgnoreCase("Y")); break; case 2: calendly.callCalendly(); break; } } } <file_sep>package com.call.zoom.app; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.math.BigInteger; import java.util.Scanner; import org.json.JSONArray; import org.json.JSONObject; import com.google.gson.Gson; import lombok.Setter; import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; class CallingZoom { OkHttpClient client = new OkHttpClient().newBuilder() .build(); MediaType mediaType = MediaType.parse("application/json,application/json"); String access_toke = "<KEY>"; String UserId = ""; String base_url = "https://api.zoom.us/v2/"; void createMeeting(MeetingDataModel md) throws IOException { Gson gson = new Gson(); // Create an object of gson Class String queryString = gson.toJson(md);; // gson to serialize data of the object for the param of the api RequestBody body = RequestBody.create(mediaType,queryString); UserId = getUserId(); System.out.println(queryString); // check the query_string data base_url+="users/ "+UserId+""; Request request = new Request.Builder() .url(base_url) .method("POST", body) .addHeader("Content-Type", "application/json") .addHeader("Authorization", "Bearer "+access_toke+"") .build(); try { Response response = client.newCall(request).execute(); if(response.code() == 201) { System.out.println("Meeting has been created successfully"); } else if(response.code() == 300){ System.out.println("Invalid enforce_login_domains, separate multiple domains by semicolon."); } else { System.out.println("User not found."); } System.out.println(response.message()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } Boolean cancelMeeting(MeetingDataModel md) { Boolean flag = true; base_url += "meetings/"+md.getMeetingID()+""; RequestBody body = RequestBody.create(mediaType, ""); Request request = new Request.Builder() .url(base_url) .method("DELETE", body) .addHeader("Content-Type", "application/json") .addHeader("Authorization", "Bearer "+access_toke+"") .build(); try { Response response = client.newCall(request).execute(); if(response.code() == 204) { flag= true; } else { flag= false; } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return flag; } void getMeetingInformation(MeetingDataModel md) { base_url += "meetings/"+md.getMeetingID()+""; Request request = new Request.Builder() .url(base_url) .method("GET", null) .addHeader("Authorization", "Bearer "+access_toke+"") .build(); try { Response response = client.newCall(request).execute(); JSONObject myon = new JSONObject(response.body().string()); System.out.println("Meeting topc:"+" "+myon.getString("topic")); System.out.println("Meeting Status:"+" "+myon.getString("status")); System.out.println("Start Time:"+" "+myon.getString("start_time")); System.out.println("Meeting Duration:"+" "+myon.getInt("duration")); System.out.println("Start Url:"+" "+myon.getString("start_url")); System.out.println("Join Url:"+" "+myon.getString("join_url")); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } String getUserId() throws IOException { Request request = new Request.Builder() .url("https://api.zoom.us/v2/users/") .method("GET", null) .addHeader("content-type", "application/json") .addHeader("Authorization", "Bearer "+access_toke+"") .build(); Response response = client.newCall(request).execute(); JSONObject myon = new JSONObject(response.body().string()); JSONArray lineItems = myon.getJSONArray("users"); for (Object o : lineItems) { JSONObject jsonLineItem = (JSONObject) o; String key = jsonLineItem.optString("id"); UserId=key; } return UserId; } } public class ZoomTestMeeting { public static void main(String[] args) throws IOException { CallingZoom cz = new CallingZoom(); // Create an object of Zoom Class MeetingDataModel md = new MeetingDataModel(); // Create an object of Model Class Scanner in = new Scanner(System.in); System.out.println("Make your choice for Zoom: "+ "\n"+ "1. Create a Zoom Meeting"+ "\n"+ "2. Cancel a Meeting"+ "\n"+ "3. Get Meeting Information"+ "\n"); int choice = 0; BigInteger meetingID; System.out.println("Your Choice: "+ " "); //choose option for the input choice = in.nextInt(); switch(choice) { case 1: BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); String topic, startTime, timeZone, password, agenda; int type,duration; System.out.println("Topic: "); topic= br.readLine(); System.out.println("Meeting Type: "+"\ninput 1 for 'Instant Meeting'"+ "\ninput 2 for 'Scheduled Meeting'"+ "\ninput 3 for 'Recurring Meeting with no Fixed Time'"+ "\ninput 8 for 'Recurring Meeting with Fixed Time'"+"): "); type = in.nextInt(); System.out.println("startTime (YYYY-MM-DD HH:MM:ss):"); startTime = br.readLine(); for(;!(startTime.substring(4, 5).contains("-") && startTime.substring(7, 8).contains("-") && startTime.substring(13, 14).contains(":") && startTime.substring(16, 17).contains(":"));) { System.out.println("Wrong format. Input startTime correctly like (YYYY-MM-DD HH:MM:ss):"); startTime = br.readLine(); } System.out.println("duration(in minutes): "); duration = in.nextInt(); System.out.println("timeZone: "+ " "+ "example: America/Los_Angeles"); timeZone = br.readLine(); System.out.println("password: "); password = br.readLine(); System.out.println("agenda: "); agenda = br.readLine(); //assigning value to the lombok setter md.setTopic(topic); md.setType(type); md.setStartTime(startTime); md.setDuration(duration); md.setTimezone(timeZone); md.setPassword(<PASSWORD>); md.setAgenda(agenda); cz.createMeeting(md); // Call the create meeting method on the object break; case 2: Boolean delMeeting; System.out.println("Please enter the meeting ID you want to delete: "); meetingID = in.nextBigInteger(); md.setMeetingID(meetingID); delMeeting = cz.cancelMeeting(md); if(delMeeting == true) { System.out.println("Meeting has been canceled successfully"); } else { System.out.println("Please enter the valid meeting ID"); } break; case 3: System.out.println("Please enter the meeting ID you want to get info: "); meetingID = in.nextBigInteger(); // assign value to the lombok setter md.setMeetingID(meetingID); cz.getMeetingInformation(md); break; } } }
a4267e13219403e0354bef1eb32d3a2ef9bd0532
[ "Java" ]
3
Java
Shahidur48/TestZoomCalendlyAPI
bbb75ae3ba9ffa7778b50e39f24d60f916476c22
e2db6088162a92da99d7b9a88dbcb75e19f14b3a
refs/heads/master
<file_sep>vet1 = c(1,2,3,4,5,6,7,8,9,10,11,12) vet2 = seq(1,10,0.5) vet3 = seq(1,16) mtz = matrix(vet3,4,4) View(mtz) ###-----------------### idade = c(13,15,12,18) sexo = c('F','M','F','M') curso = c('cc','adm','eco','est') dataF = data.frame(idade,sexo,curso) View(dataF) <file_sep>x = c(6,4) mean(x,na.rm=TRUE) <file_sep># Definindo diretório de trabalho: setwd("/home/caiom/Documentos/CompUFCG/CursoR") # Trabalhando com DataFrames: clientes = read.csv("clientes.csv",header = TRUE,sep = ",") # Explorando a base de dados: View(clientes) #Visualiza a planilha; str(clientes) #verifica o tipo das variáveis; names(clientes) #informa os nomes das variáveis/colunas; dados_clientes = clientes[ ,2:9] #retirar as variáveis x e Canal_Vendas_Cat; View(dados_clientes) str(dados_clientes) names(dados_clientes) dados_clientes$canal_vendas_cat = ifelse(dados_clientes$Canal_Vendas == 1,"Mercadinho","Atacarejo") #Adicionando a variave canal_vendas_cat, a partir do valor em Cana_Vendas. View(dados_clientes) str(dados_clientes) # Ajustar a variável nova para Factor(Fator) - pode ser contado,tirado média,etc; class(dados_clientes$canal_vendas_cat) dados_clientes$canal_vendas_cat = as.factor(dados_clientes$canal_vendas_cat) class(dados_clientes$canal_vendas_cat) levels(dados_clientes$canal_vendas_cat) # Mostra os níveis que o Factor possui; # Criando a variável regiao_Cat: count = 1 for (i in dados_clientes$Regiao) { if(dados_clientes$Regiao[count] == "1") { dados_clientes$regiao_cat[count] = "Centro" } else if(dados_clientes$Regiao[count] == "2") { dados_clientes$regiao_cat[count] = "Zona Norte" } else if(dados_clientes$Regiao[count] == "3") { dados_clientes$regiao_cat[count] = "Zona Sul" } count = count + 1 } View(dados_clientes) str(dados_clientes) class(dados_clientes$regiao_cat) dados_clientes$regiao_cat = as.factor(dados_clientes$regiao_cat) class(dados_clientes$regiao_cat) View(dados_clientes) # Salvar a base atualizada (a nova planilha que criamos: "dados_clientes"): write.csv(dados_clientes,"Dados_Clientes.csv") # Trabalhando com Pacotes: # Instalar Pacotes: install.packages("dplyr") # Instala os pacotes de biblioteca (Só precisa fazer uma vez); library(dplyr) # Importa a biblioteca; search() #Mostra os pacotes ativos; <file_sep># Definindo o diretório de trabalho: setwd("/home/caiom/Documentos/CompUFCG/CursoR") # Importando a nova base de dados "Dados Clientes": clientes = read.csv("Dados_Clientes.csv",header = TRUE,sep = ",") dados_clientes = clientes[,2:11] # removendo a coluna X; write.csv(dados_clientes,"Dados_Clientes.csv") # Salvando o arquivo; #---------------------------------------------------------------------------------# View(dados_clientes) # Visualiza o objeto inteiro; str(dados_clientes) # Mostra todas as variáveis da tabela; library(dplyr) # Importando o pacote "dplyr" já instalado; search() # Verifica os pacotes que estão carregados e disponíveis; is.numeric(dados_clientes$Regiao) # Checa se é numérico dados_clientes$regiao_cat = ifelse(dados_clientes$Regiao == 1,"CENTRO",ifelse(dados_clientes$Regiao == 2,"ZONA NORTE","ZONA SUL")) View(dados_clientes) write.csv(dados_clientes,"Dados_Clientes.csv") str(dados_clientes) dados_clientes$regiao_cat = as.factor(dados_clientes$regiao_cat) str(dados_clientes) write.csv(dados_clientes,"Dados_Clientes.csv") dados_clientes = dados_clientes %>% #PIPE = então; mutate(.,Regiao_cat = case_when(Regiao == 1 ~ "Centro",Regiao == 2 ~ "Norte",TRUE ~"Sul")) # O ponto é pra dizer que pega a própria base de dados; str(dados_clientes) # Extraindo colunas de forma prática: #dados_clientes[,-c(1:3,9)] # Remove asc olunas em sequencia 1 a 3, e a 9 isolada; (NÃO USAR NESTE MOMENTO!!) dados_clientes = dados_clientes[,-c(1:2,11)] str(dados_clientes) colnames(dados_clientes)[8] = "Regiao_cat" # Muda o nome de uma coluna específica; View(dados_clientes) write.csv(dados_clientes,"Clientes_Varejo.csv") #----------------------------------------------------------------------------------------------------------# clients = dados_clientes View(clients) summary(clients) # Retorna o sumário de todas as variáveis; summary(clients[,1:6]) # Está retornando só o sumário das variáveis quantitativas; # Desvio-Padrão de cada coluna: sd(clients$Hortifruti) sd(clients$Deriv_Leite) sd(clients$Proteinas) sd(clients$Congelados) sd(clients$Prod_Limpeza) sd(clients$Guloseimas) sapply(clients[,1:6], sd) # Faz o calculo de uma função direta(Desvio Padrão), de todas as colunas; sapply(clients[,1:6], var) # Faz o calculo de uma função direta (Variância), de todas as colunas; v = var(clients$Hortifruti) # Tira a variância de uma coluna específica e atribui a uma variável; sqrt(v) # Tira o raíz quadrada de um número; summary(clients[,7:8]) table(clients$canal_vendas_cat) # table - Cria uma tabela prop.table(table(clients$canal_vendas_cat)) # Calcula a frequencia relativa table_01 = prop.table(table(clients$canal_vendas_cat)) * 100 # Calcula a frequencia relativa - em porcentagem table_02 = prop.table(table(clients$Regiao_cat)) * 100 print(round(table_02,2)) # Especifica o arredondamente com 2 casas de precisão; print(mean(clients$Guloseimas)) print(tapply(clients$Guloseimas,clients$canal_vendas_cat,mean)) # verifica a MÉDIA da venda de guloseimas entre mercadinho ou atacarejo (bivariavel); print(tapply(clients$Guloseimas,clients$canal_vendas_cat,median)) # Verifica a MEDIANA da venda de guloseimas entre mercadinho ou atacarejo (bivariavel); print(tapply(clients$Guloseimas,clients$canal_vendas_cat,max)) # Verifica o maior valor encontrado na relação; print(tapply(clients$Guloseimas,clients$canal_vendas_cat,min)) # Verifica o maior valor encontrado na relação; print(tapply(clients$Guloseimas,clients$Regiao_cat,mean)) # verifica a MÉDIA da venda de guloseimas entre mercadinho ou atacarejo (bivariavel); print(tapply(clients$Guloseimas,clients$Regiao_cat,median)) # Verifica a MEDIANA da venda de guloseimas entre mercadinho ou atacarejo (bivariavel); print(tapply(clients$Guloseimas,clients$Regiao_cat,max)) # Verifica o maior valor encontrado na relação; print(tapply(clients$Guloseimas,clients$Regiao_cat,min)) # Verifica o maior valor encontrado na relação; table_03 = prop.table(table(clients$canal_vendas_cat,clients$Regiao_cat)) * 100 # Carregar Pacotes: install.packages("ggplot2") install.packages("psych") install.packages("PerformanceAnalytics") <file_sep>### Curso de R - Aula_01 ### getwd() # Mostar o diretório atual; setwd("/home/caiom/Documentos/CompUFCG/CursoR") # Define o novo diretório de trabalho; #Criando vetor: vector = c(23,25,24,29,32) x = mean(vector) #Média median(vector) # Mediana sd(vector) # Desvido Padrão var(vector) # Variância age = c(20,32,21,18,19) gender = c("F","M","M","M","F") as.integer(x) # Torna o numérico em inteiro; class(age) # Retorna o tipo de dado da variável as.factor(gender) class(gender) # Matrizes: vet = c("la","casa","de","papel") mtz = matrix(vet,2,2) View(mtz) View(vet) colnames(mtz) = c("c1","c2") View(mtz)
fdcf5815f36c1a92783a1a0327111e635268e000
[ "R" ]
5
R
caiohrgm/R
cd70de879b048cf9bff030d6321ade6eab1c3931
12bbcea8ad3a8f2bb3cdb91b925c7b2d815fc2c0
refs/heads/master
<file_sep>#include "orderSystem.h" #include <stdio.h> //Arrays of orders. 0 equals no order, 1 for order int ordersUp[4] = {0,0,0,0}; int ordersDown[4] = {0,0,0,0}; elev_motor_direction_t previousDirection = DIRN_STOP; int isOrdersBelow(int floor){ for(int i = 0; i < floor; i++){ if (ordersUp[i] || ordersDown[i]) return 1; } return 0; } int isOrdersAbove(int floor){ for(int i = floor+1; i < 4;i++){ if(ordersUp[i] || ordersDown[i]) return 1; } return 0; } void storePreviousDirection(elev_motor_direction_t direction) { previousDirection = direction; } elev_motor_direction_t getDirection(int currentFloor, int previousFloor, elev_motor_direction_t elevatorDirection){ //Dersom heisen er stoppet mellom etasjer (nødstopp) if(currentFloor == -1){ if(elevatorDirection == DIRN_STOP){ if(isOrdersAbove(previousFloor) || (previousDirection == DIRN_DOWN && (ordersDown[previousFloor] || ordersUp[previousFloor]))) return DIRN_UP; if(isOrdersBelow(previousFloor) || (previousDirection == DIRN_UP && (ordersDown[previousFloor] || ordersUp[previousFloor]))) return DIRN_DOWN; } } if(elevatorDirection == DIRN_UP && ordersUp[currentFloor]){ ordersUp[currentFloor] = 0; ordersDown[currentFloor]=0; return DIRN_STOP; } else if(elevatorDirection == DIRN_DOWN && ordersDown[currentFloor]){ ordersDown[currentFloor]=0; ordersUp[currentFloor] = 0; return DIRN_STOP; } else if((currentFloor == 0 || currentFloor == 3) && (ordersUp[currentFloor] || ordersDown[currentFloor])){ ordersUp[currentFloor] = 0; ordersDown[currentFloor] = 0; return DIRN_STOP; } else if (isOrdersBelow(currentFloor) && elevatorDirection == DIRN_DOWN) return DIRN_DOWN; else if(isOrdersAbove(currentFloor) && elevatorDirection == DIRN_UP) return DIRN_UP; else if(isOrdersAbove(currentFloor) && elevatorDirection == DIRN_DOWN) return DIRN_UP; else if(isOrdersBelow(currentFloor) && elevatorDirection == DIRN_UP) return DIRN_DOWN; else if (isOrdersAbove(currentFloor) && elevatorDirection == DIRN_STOP) return DIRN_UP; else if (isOrdersBelow(currentFloor) && elevatorDirection == DIRN_STOP) return DIRN_DOWN; return DIRN_STOP; } void insertElevatorOrder(int previousFloor, int orderedFloor, int currentFloor, elev_motor_direction_t direction, elev_button_type_t panelType){ printf("currentFloor: %d, previousFloor: %d\n",currentFloor,previousFloor); if(panelType == BUTTON_COMMAND){ if(previousFloor < orderedFloor) ordersUp[orderedFloor] = 1; else if (previousFloor > orderedFloor) ordersDown[orderedFloor] = 1; else if(currentFloor == -1 && direction == DIRN_DOWN) ordersUp[orderedFloor] = 1; else if(currentFloor == -1 && direction == DIRN_DOWN) ordersDown[orderedFloor] = 1; } if(currentFloor != orderedFloor){ if(panelType == BUTTON_CALL_DOWN) ordersDown[orderedFloor] = 1; else ordersUp[orderedFloor] = 1; } } void printOrders() { printf("Orders up: "); for(int i = 0; i < 4; i++){ printf("%d ", ordersUp[i]); } printf("Orders down: "); for(int i = 0; i < 4; i++){ printf("%d ", ordersDown[i]); } printf("\n"); } void deleteAllOrders(){ for(int i = 0; i < 4; i++){ ordersUp[i] = 0; ordersDown[i] = 0; } } <file_sep>#ifndef INPUTMANAGER_H #define INPUTMANAGER_H //Sjekker alle io-inputs og kjører tilsvarende events void checkInputs(); #endif<file_sep>#include "inputManager.h" #include "elev.h" #include "eventManager.h" #include "functions.h" #include "orderSystem.h" int stopBtnPressed = 0; int buttonStates[3][4] = {{0,0,0,0},{0,0,0,0},{0,0,0,0}}; int getButtonSignal(elev_button_type_t panelType, int orderedFloor){ if(panelType == BUTTON_CALL_UP && orderedFloor < 3) return elev_get_button_signal(panelType,orderedFloor); else if(panelType == BUTTON_CALL_DOWN && orderedFloor > 0) return elev_get_button_signal(panelType,orderedFloor); else if(panelType == BUTTON_COMMAND) return elev_get_button_signal(panelType,orderedFloor); else return 0; } void checkInputs() { int currentFloor = elev_get_floor_sensor_signal(); //Stoppknappen trykket for første gang if(stopBtnPressed == 0 && elev_get_stop_signal() == 1){ stopBtnPressed = 1; fsmEvStopBtnPressed(); } //Stoppknappen sluppet else if (stopBtnPressed == 1 && elev_get_stop_signal() == 0){ stopBtnPressed = 0; fsmEvStopBtnReleased(); } if(stopBtnPressed == 0){ //Sjekker alle panelknapper for(elev_button_type_t panelType = BUTTON_CALL_UP; panelType <= BUTTON_COMMAND; panelType++){ for(int orderedFloor = 0; orderedFloor < 4; orderedFloor++){ if(getButtonSignal(panelType, orderedFloor) && !buttonStates[panelType][orderedFloor]){ buttonStates[panelType][orderedFloor] = 1; fsmEvBtnPressed(currentFloor,orderedFloor, panelType); } else if(!getButtonSignal(panelType, orderedFloor) && buttonStates[panelType][orderedFloor]){ buttonStates[panelType][orderedFloor] = 0; } } } if(currentFloor != -1) { fsmEvFloorSignal(currentFloor); } } } <file_sep>#ifndef ORDERSYSTEM_H #define ORDERSYSTEM_H #include "elev.h" //Gir neste retning heisen skal kjøre elev_motor_direction_t getDirection(int currentFloor, int previousFloor, elev_motor_direction_t elevatorDirection); //Legger til en ny bestilling void insertElevatorOrder(int previousFloor, int orderedFloor, int currentFloor, elev_motor_direction_t direction, elev_button_type_t panelType); //Fjerner alle bestillinger void deleteAllOrders(); int isOrdersBelow(int floor); int isOrdersAbove(int floor); void storePreviousDirection(elev_motor_direction_t direction); void printOrders(); #endif<file_sep>#include "eventManager.h" #include "elev.h" #include <stdio.h> #include "orderSystem.h" #include "functions.h" typedef enum { stateIdle, stateMoving, stateDoorOpen } TState; TState currentState = stateIdle; elev_motor_direction_t direction = DIRN_STOP; int previousFloor = -1; void fsmEvBtnPressed(int currentFloor,int orderedFloor,elev_button_type_t panelType) { insertElevatorOrder(previousFloor, orderedFloor,elev_get_floor_sensor_signal(), direction, panelType); if(currentFloor != orderedFloor){ setBtnLight(panelType, orderedFloor, 1); } switch(currentState){ case stateIdle: direction = getDirection(currentFloor,previousFloor, direction); elev_set_motor_direction(direction); if(direction == DIRN_STOP) { startTimer(); elev_set_door_open_lamp(1); currentState = stateDoorOpen; } else { currentState = stateMoving; } break; case stateDoorOpen: if(currentFloor == orderedFloor) { startTimer(); } default: break; } printOrders(); } void fsmEvStopBtnPressed() { elev_set_stop_lamp(1); turnOffBtnLights(); storePreviousDirection(direction); elev_set_motor_direction(DIRN_STOP); direction = DIRN_STOP; if(elev_get_floor_sensor_signal() != -1){ elev_set_door_open_lamp(1); startTimer(); } } void fsmEvStopBtnReleased() { elev_set_stop_lamp(0); deleteAllOrders(); if (elev_get_floor_sensor_signal() != -1) currentState = stateDoorOpen; else currentState = stateIdle; } void fsmEvFloorSignal(int currentFloor) { previousFloor = currentFloor; elev_motor_direction_t currentDirection; switch(currentState){ case stateMoving: currentDirection = getDirection(currentFloor, previousFloor, direction); elev_set_motor_direction(currentDirection); if(currentDirection == DIRN_STOP) { elev_set_door_open_lamp(1); setBtnLight(BUTTON_COMMAND, currentFloor, 0); setBtnLight(BUTTON_CALL_UP, currentFloor, 0); setBtnLight(BUTTON_CALL_DOWN, currentFloor, 0); startTimer(); currentState = stateDoorOpen; } break; case stateDoorOpen: if(getTime() > 3){ elev_set_door_open_lamp(0); direction = getDirection(currentFloor, previousFloor, direction); elev_set_motor_direction(direction); if(direction == DIRN_STOP) currentState = stateIdle; else currentState = stateMoving; } break; default: break; } } <file_sep>#ifndef FUNCTIONS_H #define FUNCTIONS_H #include "elev.h" //Kjører ned til en etasje er nådd void initElevator(); //Setter etasjelys til den sist besøkte etasjen void updateFloorLight(); //Skrur av alle knappelys void turnOffBtnLights(); //Setter et spesifisert knappelys på eller av void setBtnLight(elev_button_type_t panelType, int btn, int toggleLight); void startTimer(); //Returnerer tiden siden sist kall på startTimer() int getTime(); #endif<file_sep>#include "elev.h" #include <stdio.h> #include "functions.h" #include "inputManager.h" int main() { // Initialize hardware if (!elev_init()) { printf("Unable to initialize elevator hardware!\n"); return 1; } initElevator(); while(1) { checkInputs(); updateFloorLight(); } return 0; } <file_sep>#include "functions.h" #include <time.h> time_t start,end; void initElevator(){ if(elev_get_floor_sensor_signal() == -1){ elev_set_motor_direction(DIRN_DOWN); while(elev_get_floor_sensor_signal() == -1); elev_set_motor_direction(DIRN_STOP); } } void updateFloorLight() { int currentFloor = elev_get_floor_sensor_signal(); if (currentFloor != -1) { elev_set_floor_indicator(currentFloor); } } void turnOffBtnLights() { for (int i = 0; i < 4; i++) { setBtnLight(BUTTON_COMMAND, i, 0); setBtnLight(BUTTON_CALL_DOWN, i, 0); setBtnLight(BUTTON_CALL_UP, i, 0); } } void setBtnLight(elev_button_type_t panelType, int btn, int toggleLight) { if(((panelType == BUTTON_CALL_DOWN) && (btn > 0)) || ((panelType == BUTTON_CALL_UP) && (btn < 3))) elev_set_button_lamp(panelType, btn, toggleLight); else if (panelType == BUTTON_COMMAND) elev_set_button_lamp(panelType,btn,toggleLight); } void startTimer(){ start = clock(); } int getTime() { end = clock(); return (end - start) / CLOCKS_PER_SEC; }<file_sep>#ifndef EVENTMANAGER_H #define EVENTMANAGER_H #include "elev.h" void fsmEvBtnPressed(int currentFloor,int orderedFloor,elev_button_type_t panelType); void fsmEvStopBtnPressed(); void fsmEvStopBtnReleased(); void fsmEvFloorSignal(int currentFloor); #endif
3650affbfb6b0e9ae5473958ba66a2a44a35b931
[ "C" ]
9
C
holwech/heislab-datastyring
9e4076fe88f82f493f9a56a65d24456b1812fb65
777fc7b4cd3e031e70979df32d0d133a588affb1
refs/heads/master
<file_sep><?php namespace Affinity\LaravelElasticSearch\Commands; use Illuminate\Console\Command; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputArgument; use Elastica\Query; use Elastica\Result; class SearchCommand extends Command { /** * The console command name. * * @var string */ protected $name = 'elastic-search:search'; /** * The console command description. * * @var string */ protected $description = 'Searches Elastic Search for documents in a given type and index'; /** * @var IndexManager */ private $indexManager; /** * @var Resetter */ private $resetter; /** * Create a new command instance. * * @return void */ public function __construct() { parent::__construct(); $app = app(); $this->indexManager = $app['laravel-elastic-search.index_manager']; $this->resetter = $app['laravel-elastic-search.resetter']; } /** * Execute the console command. * * @return void */ public function fire() { $app = app(); $indexName = $this->option('index'); /** @var $index \Elastica\Index */ $index = $app['laravel-elastic-search.index_manager']->getIndex($indexName ? $indexName : null); $type = $index->getType($this->argument('type')); $query = Query::create($this->argument('query')); $query->setSize($this->option('limit')); if ($this->option('explain')) { $query->setExplain(true); } $resultSet = $type->search($query); $this->output->writeLn(sprintf('Found %d results', $type->count($query))); foreach ($resultSet->getResults() as $result) { $this->output->writeLn($this->formatResult($result, $this->option('show-field'), $this->option('show-source'), $this->option('show-id'), $this->option('explain'))); } } protected function formatResult(Result $result, $showField, $showSource, $showId, $explain) { $source = $result->getSource(); if ($showField) { $toString = isset($source[$showField]) ? $source[$showField] : '-'; } else { $toString = reset($source); } $string = sprintf('[%0.2f] %s', $result->getScore(), var_export($toString, true)); if ($showSource) { $string = sprintf('%s %s', $string, json_encode($source, JSON_PRETTY_PRINT)); } if ($showId) { $string = sprintf('{%s} %s', $result->getId(), $string); } if ($explain) { $string = sprintf('%s %s', $string, json_encode($result->getExplanation(), JSON_PRETTY_PRINT)); } return $string; } /** * Get the console command arguments. * * @return array */ protected function getArguments() { return array( array('type', InputArgument::REQUIRED, 'The type to search in'), array('query', InputArgument::REQUIRED, 'The text to search'), ); } /** * Get the console command options. * * @return array */ protected function getOptions() { return array( array('index', null, InputOption::VALUE_REQUIRED, 'The index to search in'), array('limit', null, InputOption::VALUE_REQUIRED, 'The maximum number of documents to return', 20), array('show-field', null, InputOption::VALUE_REQUIRED, 'Field to show, null uses the first field'), array('show-source', null, InputOption::VALUE_NONE, 'Show the documents sources'), array('show-id', null, InputOption::VALUE_NONE, 'Show the documents ids'), array('explain', null, InputOption::VALUE_NONE, 'Enables explanation for each hit on how its score was computed.'), ); } } <file_sep><?php return [ 'clients' => [ 'default' => [ 'host' => 'localhost', 'port' => '9200' ], ], // 'serializer' => NULL, 'serializer' => [ 'callback_class' => 'FOS\ElasticaBundle\Serializer\Callback', 'serializer' => 'serializer', ], 'prefix' => 'example-1', 'indexes' => [ 'EXAMPLE_INDEX' => [ 'client' => 'default', 'finder' => TRUE, 'types' => [ 'EXAMPLE_TYPE' => [ 'mappings' => [ 'title' => [ 'type' => 'string' ], ], 'persistence' => [ 'driver' => 'orm', // orm, mongodb, propel are available 'model' => 'MODELS\EXAMPLEMODEL', 'identifier' => 'id', 'provider' => [ 'query_builder_method' => 'createQueryBuilder', 'batch_size' => 100, 'clear_object_manager' => TRUE, ], 'listener' => array( 'insert' => TRUE, 'update' => TRUE, 'delete' => TRUE, 'is_indexable_callback' => NULL, ), 'elastica_to_model_transformer' => [ 'hydrate' => TRUE, 'ignore_missing' => FALSE, 'query_builder_method' => 'createQueryBuilder', 'service' => NULL, ], ], ], ], // 'settings' => [ // 'index' => [ // 'analysis' => [ // 'analyzer' => [ // 'my_analyzer' => [ // 'type' => 'snowball', // 'language' => 'English', // ], // ], // ], // ], // ], ], ], 'parameters' => [ 'ClientClass' => 'FOS\ElasticaBundle\Client', 'IndexClass' => 'Elastica\Index', 'TypeClass' => 'Elastica\Type', 'LoggerClass' => 'FOS\ElasticaBundle\Logger\ElasticaLogger', 'DataCollectorClass' => 'FOS\ElasticaBundle\DataCollector\ElasticaDataCollector', 'ManagerClass' => 'FOS\ElasticaBundle\Manager\RepositoryManager', 'ElasticaToModelTransformerCollectionClass' => 'FOS\ElasticaBundle\Transformer\ElasticaToModelTransformerCollection', 'ProviderRegistryClass' => 'Affinity\LaravelElasticSearch\Provider\LaravelProviderRegistry', 'PropertyAccessorClass' => 'Symfony\Component\PropertyAccess\PropertyAccessor', ], 'default_manager' => 'orm', 'default_client' => NULL, 'default_index' => NULL, ]; <file_sep><?php namespace Affinity\LaravelElasticSearch\Commands; use Illuminate\Console\Command; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputArgument; class PopulateCommand extends Command { /** * The console command name. * * @var string */ protected $name = 'elastic-search:populate'; /** * The console command description. * * @var string */ protected $description = 'Populates Elastic Search indexes from providers.'; /** * @var IndexManager */ private $indexManager; /** * @var ProviderRegistry */ private $providerRegistry; /** * @var Resetter */ private $resetter; /** * Create a new command instance. * * @return void */ public function __construct() { parent::__construct(); $app = app(); $this->indexManager = $app['laravel-elastic-search.index_manager']; $this->providerRegistry = $app['laravel-elastic-search.provider_registry']; $this->resetter = $app['laravel-elastic-search.resetter']; } /** * Execute the console command. * * @return void */ public function fire() { $index = $this->option('index'); $type = $this->option('type'); $reset = $this->option('no-reset') ? false : true; $noInteraction = $this->option('no-interaction'); $options = $this->option(); if (!$noInteraction && $reset && $this->option('offset')) { if (!$this->confirm('<question>You chose to reset the index and start indexing with an offset. Do you really want to do that?</question>', TRUE)) { return; } } if (null === $index && null !== $type) { throw new \InvalidArgumentException('Cannot specify type option without an index.'); } if (null !== $index) { if (null !== $type) { $this->populateIndexType($index, $type, $reset, $options); } else { $this->populateIndex($index, $reset, $options); } } else { $indexes = array_keys($this->indexManager->getAllIndexes()); foreach ($indexes as $index) { $this->populateIndex($index, $reset, $options); } } } /** * Recreates an index, populates its types, and refreshes the index. * * @param string $index * @param boolean $reset * @param array $options */ private function populateIndex($index, $reset, $options) { $output = $this->output; if ($reset) { $output->writeln(sprintf('<info>Resetting</info> <comment>%s</comment>', $index)); $this->resetter->resetIndex($index); } /** @var $providers ProviderInterface[] */ $providers = $this->providerRegistry->getIndexProviders($index); foreach ($providers as $type => $provider) { $loggerClosure = function($message) use ($output, $index, $type) { $output->writeln(sprintf('<info>Populating</info> %s/%s, %s', $index, $type, $message)); }; $provider->populate($loggerClosure, $options); } $output->writeln(sprintf('<info>Refreshing</info> <comment>%s</comment>', $index)); $this->indexManager->getIndex($index)->refresh(); } /** * Deletes/remaps an index type, populates it, and refreshes the index. * * @param string $index * @param string $type * @param boolean $reset * @param array $options */ private function populateIndexType($index, $type, $reset, $options) { $output = $this->output; if ($reset) { $output->writeln(sprintf('<info>Resetting</info> <comment>%s/%s</comment>', $index, $type)); $this->resetter->resetIndexType($index, $type); } $loggerClosure = function($message) use ($output, $index, $type) { $output->writeln(sprintf('<info>Populating</info> %s/%s, %s', $index, $type, $message)); }; $provider = $this->providerRegistry->getProvider($index, $type); $provider->populate($loggerClosure, $options); $output->writeln(sprintf('<info>Refreshing</info> <comment>%s</comment>', $index)); $this->indexManager->getIndex($index)->refresh(); } /** * Get the console command arguments. * * @return array */ protected function getArguments() { return array(); } /** * Get the console command options. * * @return array */ protected function getOptions() { return array( array('index', null, InputOption::VALUE_OPTIONAL, 'The index to repopulate'), array('type', null, InputOption::VALUE_OPTIONAL, 'The type to repopulate'), array('no-reset', null, InputOption::VALUE_NONE, 'Do not reset index before populating'), array('offset', null, InputOption::VALUE_REQUIRED, 'Start indexing at offset', 0), array('sleep', null, InputOption::VALUE_REQUIRED, 'Sleep time between persisting iterations (microseconds)', 0), array('batch-size', null, InputOption::VALUE_REQUIRED, 'Index packet size (overrides provider config option)'), ); } } <file_sep><?php namespace Affinity\LaravelElasticSearch\Commands; use Illuminate\Console\Command; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputArgument; class ResetCommand extends Command { /** * The console command name. * * @var string */ protected $name = 'elastic-search:reset'; /** * The console command description. * * @var string */ protected $description = 'Reset Elastic Search indexes.'; /** * @var IndexManager */ private $indexManager; /** * @var Resetter */ private $resetter; /** * Create a new command instance. * * @return void */ public function __construct() { parent::__construct(); $app = app(); $this->indexManager = $app['laravel-elastic-search.index_manager']; $this->resetter = $app['laravel-elastic-search.resetter']; } /** * Execute the console command. * * @return void */ public function fire() { $index = $this->option('index'); $type = $this->option('type'); if (null === $index && null !== $type) { throw new \InvalidArgumentException('Cannot specify type option without an index.'); } if (null !== $type) { $this->output->writeln(sprintf('<info>Resetting</info> <comment>%s/%s</comment>', $index, $type)); $this->resetter->resetIndexType($index, $type); } else { $indexes = null === $index ? array_keys($this->indexManager->getAllIndexes()) : array($index); foreach ($indexes as $index) { $this->output->writeln(sprintf('<info>Resetting</info> <comment>%s</comment>', $index)); $this->resetter->resetIndex($index); } } } /** * Get the console command arguments. * * @return array */ protected function getArguments() { return array(); } /** * Get the console command options. * * @return array */ protected function getOptions() { return array( array('index', null, InputOption::VALUE_OPTIONAL, 'The index to reset'), array('type', null, InputOption::VALUE_OPTIONAL, 'The type to reset'), ); } } <file_sep><?php namespace Affinity\LaravelElasticSearch\Drivers; use Illuminate\Support\ServiceProvider; use FOS\ElasticaBundle\Doctrine\ORM\Provider; use FOS\ElasticaBundle\Doctrine\ORM\Listener; use FOS\ElasticaBundle\Doctrine\RepositoryManager; use FOS\ElasticaBundle\Doctrine\ORM\ElasticaToModelTransformer; class OrmServiceProvider extends ServiceProvider { /** * Register the service provider. * * @return void */ public function register() { $this->app['laravel-elastic-search.provider.prototype.orm'] = function ($app, $params) { list($persister, $model, $options) = $params; return new Provider($persister, $model, $options, $app['doctrine.registry']); }; $this->app['laravel-elastic-search.listener.prototype.orm'] = function ($app, $params) { list($persister, $model, $events, $id) = $params; return new Listener($persister, $model, $events, $id); }; $this->app['laravel-elastic-search.elastica_to_model_transformer.prototype.orm'] = function ($app, $params) { list($unknown, $model, $options) = $params; $trans = new ElasticaToModelTransformer($app['doctrine.registry'], $model, $options); $trans->setPropertyAccessor($app['laravel-elastic-search.property_accessor']); return $trans; }; $this->app->singleton('laravel-elastic-search.manager.orm', function ($app) { return new RepositoryManager($app['doctrine.registry'], $app['doctrine.annotation_reader']); }); } } <file_sep><?php namespace Affinity\LaravelElasticSearch; use Illuminate\Support\ServiceProvider; use JMS\Serializer\SerializerBuilder; use Doctrine\Common\Annotations\AnnotationRegistry; use FOS\ElasticaBundle\Finder\TransformedFinder; use FOS\ElasticaBundle\Resetter; use FOS\ElasticaBundle\IndexManager; use FOS\ElasticaBundle\Subscriber\PaginateElasticaQuerySubscriber; class LaravelElasticSearchServiceProvider extends ServiceProvider { private $default_index; private $default_client; private $default_manager; private $indexConfigs = array(); private $typeFields = array(); private $serializerConfig = array(); private $implementations = array(); private $indexes = array(); private $indexIdsByName = array(); private $drivers = array( 'orm' => 'Affinity\LaravelElasticSearch\Drivers\OrmServiceProvider', ); /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = false; /** * Bootstrap the application events. * * @return void */ public function boot() { // TODO: Move this out of here. $base_path = base_path(); AnnotationRegistry::registerAutoloadNamespace('FOS\ElasticaBundle\Configuration', "$base_path/vendor/friendsofsymfony/elastica-bundle"); AnnotationRegistry::registerAutoloadNamespace('JMS\Serializer\Annotation', "$base_path/vendor/jms/serializer/src"); if ($this->app['config']->get('laravel-elastic-search::disabled', FALSE)) { return; } $this->loadIndexes(); $this->transformerPass(); $this->providersPass(); $this->doctrineSubscribersPass(); } protected function loadIndexes() { $app = $this->app; foreach ($this->indexes as $name => $index) { $indexId = sprintf('laravel-elastic-search.index.%s', $name); $typePrototypeConfig = isset($index['type_prototype']) ? $index['type_prototype'] : array(); $this->loadTypes(isset($index['types']) ? $index['types'] : array(), $name, $indexId, $typePrototypeConfig); $indexId = $this->indexConfigs[$name]['index']; $this->indexConfigs[$name]['index'] = $app[$indexId]; } $indexRefsByName = array_map(function ($id) use ($app) { return $app[$id]; }, $this->indexIdsByName); $this->registerIndexManager($indexRefsByName); $this->registerResetter($this->indexConfigs); $app['laravel-elastic-search.client'] = $app[sprintf('laravel-elastic-search.client.%s', $this->default_client)]; $app['laravel-elastic-search.index'] = $app[sprintf('laravel-elastic-search.index.%s', $this->default_index)]; $this->createDefaultManagerAlias($this->default_manager); } protected function transformerPass() { if (!isset($this->app['laravel-elastic-search.elastica_to_model_transformer.collection'])) { return; } $transformers = array(); foreach ($this->app['laravel-elastic-search.elastica_to_model_transformers'] as $id => $tag) { if (empty($tag['index']) || empty($tag['type'])) { throw new \InvalidArgumentException('The Transformer must have both a type and an index defined.'); } $transformers[$tag['index']][$tag['type']] = $this->app[$id]; } foreach ($transformers as $index => $indexTransformers) { $transformerId = sprintf('laravel-elastic-search.elastica_to_model_transformer.collection.%s', $index); if (!isset($this->app[$transformerId])) { continue; } $this->app->singleton($transformerId, function ($app) use ($indexTransformers) { $transformerCollectorClass = $app['config']->get('laravel-elastic-search::parameters.ElasticaToModelTransformerCollectionClass', NULL); return new $transformerCollectorClass($indexTransformers); }); } } protected function providersPass() { if (!isset($this->app['laravel-elastic-search.provider_registry'])) { return; } // Infer the default index name from the service alias $defaultIndex = 'default';//substr($this->app->getAlias('laravel-elastic-search.index'), 29); foreach ($this->app['laravel-elastic-search.providers'] as $providerId => $tag) { $index = $type = null; $provider = $this->app[$providerId]; $class = get_class($provider); if (!$class || !$this->isProviderImplementation($class)) { throw new \InvalidArgumentException(sprintf('Elastica provider "%s" with class "%s" must implement ProviderInterface.', $providerId, $class)); } if (!isset($tag['type'])) { throw new \InvalidArgumentException(sprintf('Elastica provider "%s" must specify the "type" attribute.', $providerId)); } $index = isset($tag['index']) ? $tag['index'] : $defaultIndex; $type = $tag['type']; $this->app->extend('laravel-elastic-search.provider_registry', function ($registry) use ($index, $type, $providerId) { $registry->addProvider($index, $type, $providerId); return $registry; }); } } /** * TODO: Move this out of here. */ protected function doctrineSubscribersPass() { foreach ($this->app['doctrine.event_subscribers'] as $listenerId) { $this->app['doctrine']->getEventManager()->addEventSubscriber($this->app[$listenerId]); } } /** * Returns whether the class implements ProviderInterface. * * @param string $class * @return boolean */ private function isProviderImplementation($class) { if (!isset($this->implementations[$class])) { $refl = new \ReflectionClass($class); $this->implementations[$class] = $refl->implementsInterface('FOS\ElasticaBundle\Provider\ProviderInterface'); } return $this->implementations[$class]; } /** * Register the service provider. * * @return void */ public function register() { $this->package('affinity/laravel-elastic-search'); $app = $this->app; if ($app['config']->get('laravel-elastic-search::disabled', FALSE)) { return; } $this->loadCommands(); $app['serializer'] = SerializerBuilder::create()->build(); // NOTE: Poor-man's equivalent to Symfony's "tagged services" (store a // list of service ids in an array on the container for lookup later). $app['laravel-elastic-search.elastica_to_model_transformers'] = array(); $app['laravel-elastic-search.providers'] = array(); $app['doctrine.event_subscribers'] = array(); $app['laravel-elastic-search.drivers'] = array_keys($this->drivers); $this->loadServices(); // Prefix indexes to allow for multiple instances of site. $prefix = $app['config']->get('laravel-elastic-search::prefix', NULL); $this->indexes = []; foreach ($app['config']->get('laravel-elastic-search::indexes', array()) as $name => $index) { if ($prefix) $name = "{$prefix}-{$name}"; $this->indexes[$name] = $index; } $clients = $app['config']->get('laravel-elastic-search::clients', array()); $serializer = $app['config']->get('laravel-elastic-search::serializer', NULL); $this->default_client = $app['config']->get('laravel-elastic-search::default_client', array()); $this->default_index = $app['config']->get('laravel-elastic-search::default_index', array()); $this->default_manager = $app['config']->get('laravel-elastic-search::default_manager', array()); if (empty($clients) || empty($this->indexes)) { throw new \InvalidArgumentException('You must define at least one client and one index'); } if (empty($this->default_client)) { $keys = array_keys($clients); $this->default_client = reset($keys); } if (empty($this->default_index)) { $keys = array_keys($this->indexes); $this->default_index = reset($keys); } $clientIdsByName = $this->loadClients($clients); $this->serializerConfig = $serializer; $this->indexIdsByName = $this->registerIndexes($this->indexes, $clientIdsByName, $this->default_client); foreach ($this->drivers as $driver => $class) { $this->app->register($class); } } protected function loadCommands() { $this->commands(array( 'Affinity\LaravelElasticSearch\Commands\PopulateCommand', 'Affinity\LaravelElasticSearch\Commands\ResetCommand', 'Affinity\LaravelElasticSearch\Commands\SearchCommand', )); } protected function loadServices() { $this->app->singleton('laravel-elastic-search.logger', function ($app) { $debug = $app['config']->get('debug', FALSE); $loggerClass = $app['config']->get('laravel-elastic-search::parameters.LoggerClass', NULL); return new $loggerClass(Log::getMonolog(), $debug); }); $this->app->singleton('laravel-elastic-search.data_collector', function ($app) { $dataCollectorClass = $app['config']->get('laravel-elastic-search::parameters.DataCollectorClass', NULL); return new $dataCollectorClass($app['laravel-elastic-search.logger']); }); $this->app->singleton('laravel-elastic-search.elastica_to_model_transformer.collection', function ($app) { $transformerCollectorClass = $app['config']->get('laravel-elastic-search::parameters.ElasticaToModelTransformerCollectionClass', NULL); return new $transformerCollectorClass(array()); }); $this->app->singleton('laravel-elastic-search.provider_registry', function ($app) { $providerRegistryClass = $app['config']->get('laravel-elastic-search::parameters.ProviderRegistryClass', NULL); $registry = new $providerRegistryClass(); return $registry; }); $this->app->singleton('laravel-elastic-search.paginator.subscriber', function ($app) { // TODO: Should be 'tagged' with knp_paginator.subscriber. return new PaginateElasticaQuerySubscriber(); }); $this->app->singleton('laravel-elastic-search.property_accessor', function ($app) { $propertyAccessorClass = $app['config']->get('laravel-elastic-search::parameters.PropertyAccessorClass', NULL); return new $propertyAccessorClass(); }); } /** * Loads the configured clients. * * @param array $clients An array of clients configurations * @return array */ protected function loadClients(array $clients) { $clientIds = array(); $this->app['laravel-elastic-search.clients'] = array(); $clientClass = $this->app['config']->get('laravel-elastic-search::parameters.ClientClass', NULL); if (!$clientClass) throw new InvalidArgumentException("You must define a laravel-elastic-search parameter: ClientClass"); foreach ($clients as $name => $clientConfig) { $clientId = sprintf('laravel-elastic-search.client.%s', $name); $this->app->singleton($clientId, function ($app) use ($clientClass, $clientConfig) { $client = new $clientClass($clientConfig); $logger = isset($clientConfig['servers']) && !empty($clientConfig['servers']) ? $clientConfig['servers'][0]['logger'] : FALSE; if (false !== $logger) { $client->setLogger($app[$logger]); } return $client; }); // NOTE: Poor-man's equivalent to Symfony's "tagged services" (store a // list of service ids in an array on the container for lookup later). $this->app->extend('laravel-elastic-search.clients', function ($tags, $app) use ($clientId, $clientConfig) { $tags[] = [$clientId, $clientConfig]; return $tags; }); $clientIds[$name] = $clientId; } return $clientIds; } /** * Loads the configured indexes. * * @param array $indexes An array of indexes configurations * @param array $clientIdsByName * @param $defaultClientName * @throws \InvalidArgumentException * @return array */ protected function registerIndexes(array $indexes, array $clientIdsByName, $defaultClientName) { $indexIds = array(); // $indexClass = $this->app['config']->get('laravel-elastic-search::parameters.IndexClass', NULL); // if (!$indexClass) throw new InvalidArgumentException("You must define a laravel-elastic-search parameter: IndexClass"); foreach ($indexes as $name => $index) { if (isset($index['client'])) { $clientName = $index['client']; if (!isset($clientIdsByName[$clientName])) { throw new InvalidArgumentException(sprintf('The elastica client with name "%s" is not defined', $clientName)); } } else { $clientName = $defaultClientName; } $clientId = $clientIdsByName[$clientName]; $indexId = sprintf('laravel-elastic-search.index.%s', $name); $indexName = isset($index['index_name']) ? $index['index_name'] : $name; $indexDefArgs = array($indexName); $this->app->singleton($indexId, function ($app) use ($clientId, $indexName) { return $app[$clientId]->getIndex($indexName); }); $indexIds[$name] = $indexId; $this->indexConfigs[$name] = array( 'index' => $indexId, 'config' => array( 'mappings' => array() ) ); if (isset($index['finder']) && $index['finder']) { $this->loadIndexFinder($name, $indexId); } if (!empty($index['settings'])) { $this->indexConfigs[$name]['config']['settings'] = $index['settings']; } } return $indexIds; } /** * Loads the configured index finders. * * @param string $name The index name * @param string $indexId The index service identifier * @return string */ protected function loadIndexFinder($name, $indexId) { /* Note: transformer services may conflict with "collection.index", if * an index and type names were "collection" and an index, respectively. */ $transformerId = sprintf('laravel-elastic-search.elastica_to_model_transformer.collection.%s', $name); $this->app->singleton($transformerId, function ($app) { $transformerCollectorClass = $app['config']->get('laravel-elastic-search::parameters.ElasticaToModelTransformerCollectionClass', NULL); return new $transformerCollectorClass(array()); }); $finderId = sprintf('laravel-elastic-search.finder.%s', $name); $this->app->singleton($finderId, function ($app) use ($indexId, $transformerId) { return new TransformedFinder($app[$indexId], $app[$transformerId]); }); return $finderId; } /** * Loads the configured types. * * @param array $types An array of types configurations * @param $indexName * @param $indexId * @param array $typePrototypeConfig * @param $serializerConfig */ protected function loadTypes(array $types, $indexName, $indexId, array $typePrototypeConfig) { foreach ($types as $name => $type) { $type = self::deepArrayUnion($typePrototypeConfig, $type); $typeId = sprintf('%s.%s', $indexId, $name); $serializerConfig = $this->serializerConfig; $this->app->singleton($typeId, function ($app) use ($indexId, $name, $serializerConfig, $type) { $type_instance = $app[$indexId]->getType($name); if ($serializerConfig) { $callbackId = sprintf('%s.%s.serializer.callback', $indexId, $name); $app->singleton($callbackId, function ($app) use ($serializerConfig, $type) { $callback = new $serializerConfig['callback_class'](); $callback->setSerializer($app[$serializerConfig['serializer']]); if (isset($type['serializer']['groups'])) { $callback->setGroups($type['serializer']['groups']); } if (isset($type['serializer']['version'])) { $callback->setVersion($type['serializer']['version']); } return $callback; }); $type_instance->setSerializer(array($app[$callbackId], 'serialize')); } return $type_instance; }); $this->indexConfigs[$indexName]['config']['mappings'][$name] = array( "_source" => array("enabled" => true), // Add a default setting for empty mapping settings ); if (isset($type['_id'])) { $this->indexConfigs[$indexName]['config']['mappings'][$name]['_id'] = $type['_id']; } if (isset($type['_source'])) { $this->indexConfigs[$indexName]['config']['mappings'][$name]['_source'] = $type['_source']; } if (isset($type['_boost'])) { $this->indexConfigs[$indexName]['config']['mappings'][$name]['_boost'] = $type['_boost']; } if (isset($type['_routing'])) { $this->indexConfigs[$indexName]['config']['mappings'][$name]['_routing'] = $type['_routing']; } if (isset($type['mappings']) && !empty($type['mappings'])) { $this->indexConfigs[$indexName]['config']['mappings'][$name]['properties'] = $type['mappings']; $typeName = sprintf('%s/%s', $indexName, $name); $this->typeFields[$typeName] = $type['mappings']; } if (isset($type['_parent'])) { $this->indexConfigs[$indexName]['config']['mappings'][$name]['_parent'] = array('type' => $type['_parent']['type']); $typeName = sprintf('%s/%s', $indexName, $name); $this->typeFields[$typeName]['_parent'] = $type['_parent']; } if (isset($type['persistence'])) { $this->loadTypePersistenceIntegration($type['persistence'], $typeId, $indexName, $name); } if (isset($type['index_analyzer'])) { $this->indexConfigs[$indexName]['config']['mappings'][$name]['index_analyzer'] = $type['index_analyzer']; } if (isset($type['search_analyzer'])) { $this->indexConfigs[$indexName]['config']['mappings'][$name]['search_analyzer'] = $type['search_analyzer']; } if (isset($type['index'])) { $this->indexConfigs[$indexName]['config']['mappings'][$name]['index'] = $type['index']; } if (isset($type['_all'])) { $this->indexConfigs[$indexName]['config']['mappings'][$name]['_all'] = $type['_all']; } if (!empty($type['dynamic_templates'])) { $this->indexConfigs[$indexName]['config']['mappings'][$name]['dynamic_templates'] = array(); foreach ($type['dynamic_templates'] as $templateName => $templateData) { $this->indexConfigs[$indexName]['config']['mappings'][$name]['dynamic_templates'][] = array($templateName => $templateData); } } } } /** * Merges two arrays without reindexing numeric keys. * * @param array $array1 An array to merge * @param array $array2 An array to merge * * @return array The merged array */ static protected function deepArrayUnion($array1, $array2) { foreach ($array2 as $key => $value) { if (is_array($value) && isset($array1[$key]) && is_array($array1[$key])) { $array1[$key] = self::deepArrayUnion($array1[$key], $value); } else { $array1[$key] = $value; } } return $array1; } /** * Loads the optional provider and finder for a type * * @param array $typeConfig * @param $typeId * @param $indexName * @param $typeName */ protected function loadTypePersistenceIntegration(array $typeConfig, $typeId, $indexName, $typeName) { $elasticaToModelTransformerId = $this->loadElasticaToModelTransformer($typeConfig, $indexName, $typeName); $modelToElasticaTransformerId = $this->loadModelToElasticaTransformer($typeConfig, $indexName, $typeName); $objectPersisterId = $this->loadObjectPersister($typeConfig, $typeId, $indexName, $typeName, $modelToElasticaTransformerId); if (isset($typeConfig['provider'])) { $this->loadTypeProvider($typeConfig, $objectPersisterId, $indexName, $typeName); } if (isset($typeConfig['finder'])) { $this->loadTypeFinder($typeConfig, $elasticaToModelTransformerId, $typeId, $indexName, $typeName); } if (isset($typeConfig['listener'])) { $this->loadTypeListener($typeConfig, $objectPersisterId, $indexName, $typeName); } } protected function loadElasticaToModelTransformer(array $typeConfig, $indexName, $typeName) { if (isset($typeConfig['elastica_to_model_transformer']['service'])) { return $typeConfig['elastica_to_model_transformer']['service']; } /* Note: transformer services may conflict with "prototype.driver", if * the index and type names were "prototype" and a driver, respectively. */ $abstractId = sprintf('laravel-elastic-search.elastica_to_model_transformer.prototype.%s', $typeConfig['driver']); $serviceId = sprintf('laravel-elastic-search.elastica_to_model_transformer.%s.%s', $indexName, $typeName); $this->app->singleton($serviceId, function ($app) use ($abstractId, $typeConfig) { $args = array(NULL); // Doctrine has a mandatory service as first argument $argPos = ('propel' === $typeConfig['driver']) ? 0 : 1; $args[$argPos] = $typeConfig['model']; $args[$argPos + 1] = array( 'hydrate' => $typeConfig['elastica_to_model_transformer']['hydrate'], 'identifier' => $typeConfig['identifier'], 'ignore_missing' => $typeConfig['elastica_to_model_transformer']['ignore_missing'], 'query_builder_method' => $typeConfig['elastica_to_model_transformer']['query_builder_method'] ); return $app->make($abstractId, $args); }); $this->app->extend('laravel-elastic-search.elastica_to_model_transformers', function ($tags) use ($serviceId, $typeName, $indexName) { $tags[$serviceId] = ['type' => $typeName, 'index' => $indexName]; return $tags; }); return $serviceId; } protected function loadModelToElasticaTransformer(array $typeConfig, $indexName, $typeName) { if (isset($typeConfig['model_to_elastica_transformer']['service'])) { return $typeConfig['model_to_elastica_transformer']['service']; } if ($this->serializerConfig) { $baseClass = 'FOS\ElasticaBundle\Transformer\ModelToElasticaIdentifierTransformer'; } else { $baseClass = 'FOS\ElasticaBundle\Transformer\ModelToElasticaAutoTransformer'; } $serviceId = sprintf('laravel-elastic-search.model_to_elastica_transformer.%s.%s', $indexName, $typeName); $this->app->singleton($serviceId, function ($app) use ($baseClass, $typeConfig) { $trans = new $baseClass(array( 'identifier' => $typeConfig['identifier'] )); $trans->setPropertyAccessor($app['laravel-elastic-search.property_accessor']); return $trans; }); return $serviceId; } protected function loadObjectPersister(array $typeConfig, $typeId, $indexName, $typeName, $transformerId) { $arguments = array( $this->app[$typeId], $this->app[$transformerId], $typeConfig['model'], ); if ($this->serializerConfig) { $baseClass = 'FOS\ElasticaBundle\Persister\ObjectSerializerPersister'; $callbackId = sprintf('%s.%s.serializer.callback', $this->indexConfigs[$indexName]['index'], $typeName); $arguments[] = array($this->app[$callbackId], 'serialize'); } else { $baseClass = 'FOS\ElasticaBundle\Persister\ObjectPersister'; $arguments[] = $this->typeFields[sprintf('%s/%s', $indexName, $typeName)]; } $serviceId = sprintf('laravel-elastic-search.object_persister.%s.%s', $indexName, $typeName); $this->app->singleton($serviceId, function ($app) use ($baseClass, $arguments) { $reflector = new \ReflectionClass($baseClass); return $reflector->newInstanceArgs($arguments); }); return $serviceId; } protected function loadTypeProvider(array $typeConfig, $objectPersisterId, $indexName, $typeName) { if (isset($typeConfig['provider']['service'])) { return $typeConfig['provider']['service']; } /* Note: provider services may conflict with "prototype.driver", if the * index and type names were "prototype" and a driver, respectively. */ $providerId = sprintf('laravel-elastic-search.provider.%s.%s', $indexName, $typeName); $this->app->singleton($providerId, function ($app) use ($typeConfig, $objectPersisterId) { $abstractId = sprintf('laravel-elastic-search.provider.prototype.%s', $typeConfig['driver']); $args = array( $app[$objectPersisterId], $typeConfig['model'], // Propel provider can simply ignore Doctrine-specific options array_diff_key($typeConfig['provider'], array('service' => 1)) ); return $app->make($abstractId, $args); }); $this->app->extend('laravel-elastic-search.providers', function ($tags) use ($providerId, $indexName, $typeName) { $tags[$providerId] = array('index' => $indexName, 'type' => $typeName); return $tags; }); return $providerId; } protected function loadTypeListener(array $typeConfig, $objectPersisterId, $indexName, $typeName) { if (isset($typeConfig['listener']['service'])) { return $typeConfig['listener']['service']; } $events = $this->getDoctrineEvents($typeConfig); $args = array($this->app[$objectPersisterId], $typeConfig['model'], $events, $typeConfig['identifier']); /* Note: listener services may conflict with "prototype.driver", if the * index and type names were "prototype" and a driver, respectively. */ $abstractId = sprintf('laravel-elastic-search.listener.prototype.%s', $typeConfig['driver']); $listenerId = sprintf('laravel-elastic-search.listener.%s.%s', $indexName, $typeName); $this->app->singleton($listenerId, function ($app) use ($abstractId, $args) { $listener = $app->make($abstractId, $args); if (isset($typeConfig['listener']['is_indexable_callback'])) { $callback = $typeConfig['listener']['is_indexable_callback']; if (is_array($callback)) { list($class) = $callback + array(null); if (is_string($class) && !class_exists($class)) { $callback[0] = $app[$class]; } } $listener->setIsIndexableCallback($callback); } return $listener; }); // TODO: This might not work for MongoDB ODM. $this->app->extend('doctrine.event_subscribers', function ($tags) use ($listenerId) { $tags[] = $listenerId; return $tags; }); return $listenerId; } private function getDoctrineEvents(array $typeConfig) { $events = array(); $eventMapping = array( 'insert' => array('postPersist'), 'update' => array('postUpdate'), 'delete' => array('postRemove', 'preRemove') ); foreach ($eventMapping as $event => $doctrineEvents) { if (isset($typeConfig['listener'][$event]) && $typeConfig['listener'][$event]) { $events = array_merge($events, $doctrineEvents); } } return $events; } protected function loadTypeFinder(array $typeConfig, $elasticaToModelId, $typeId, $indexName, $typeName) { if (isset($typeConfig['finder']['service'])) { $finderId = $typeConfig['finder']['service']; } else { $finderId = sprintf('laravel-elastic-search.finder.%s.%s', $indexName, $typeName); $this->app->singleton($finderId, function ($app) use ($typeId, $elasticaToModelId) { return new TransformedFinder($app[$typeId], $app[$elasticaToModelId]); }); } $managerId = sprintf('laravel-elastic-search.manager.%s', $typeConfig['driver']); $arguments = array($typeConfig['model'], $this->app[$finderId]); if (isset($typeConfig['repository'])) { $arguments[] = $typeConfig['repository']; } call_user_func_array(array($this->app[$managerId], 'addEntity'), $arguments); return $finderId; } /** * Loads the index manager * * @param array $indexRefsByName * @param ContainerBuilder $container **/ protected function registerIndexManager(array $indexRefsByName) { $this->app->singleton('laravel-elastic-search.index_manager', function ($app) use ($indexRefsByName) { return new IndexManager($indexRefsByName, $app['laravel-elastic-search.index']); }); } /** * Loads the resetter * * @param array $indexConfigs * @param \Symfony\Component\DependencyInjection\ContainerBuilder $container */ protected function registerResetter(array $indexConfigs) { $this->app->singleton('laravel-elastic-search.resetter', function ($app) use ($indexConfigs) { return new Resetter($indexConfigs); }); } protected function createDefaultManagerAlias($defaultManager) { $drivers = $this->app['laravel-elastic-search.drivers']; if (0 == count($drivers)) { return; } if (count($drivers) > 1 && in_array($defaultManager, $drivers) ) { $defaultManagerService = $defaultManager; } else { $defaultManagerService = $drivers[0]; } $this->app['laravel-elastic-search.manager'] = $this->app[sprintf('laravel-elastic-search.manager.%s', $defaultManagerService)]; } /** * Get the services provided by the provider. * * @return array */ public function provides() { return array(); } } <file_sep>laravel-elastic-search ====================== Laravel 4 (-ish) port of [FOSElasticaBundle]. Currently dependent on [AffinityBridge fork](https://github.com/affinitybridge/FOSElasticaBundle) of [FOSElasticaBundle] which removes dependency on [SymfonyFrameworkBundle]. Configuration and assembly which was handled by Symfony's DIC and Configuration components have been replaced with a (convoluted & messy) Laravel Service Provider and Laravel's array-based configuration. [FOSElasticaBundle]: https://github.com/FriendsOfSymfony/FOSElasticaBundle "Friends of Symfony Elastica Bundle" [SymfonyFrameworkBundle]: https://github.com/symfony/FrameworkBundle "Symfony Framework Bundle"
65254c74f636638d10e9bf040ced48d4c4da9fb6
[ "Markdown", "PHP" ]
7
PHP
mindis/laravel-elastic-search
f459602277de90377c16b0f1e71a1abd5c00014b
b23ef0848fde0ccd433823b68102833518c76130
refs/heads/master
<file_sep>var assert = require('assert'); var path = require('path'); var fs = require('fs'); var rm = require('rimraf'); var JPGO = require('../'); describe('jpgo', function () { afterEach(function (callback) { rm(path.join(__dirname, 'tmp'), callback); }); beforeEach(function () { fs.mkdirSync(path.join(__dirname, 'tmp')); }); it('should minify a JPG', function (callback) { var before = path.join(__dirname, 'fixtures/test.jpg'); var after = path.join(__dirname, 'tmp/test.jpg'); fs.writeFileSync(after, fs.readFileSync(before)); new JPGO(after).optimize(function (error, data) { assert(!error); assert(data.beforeSize > data.afterSize); callback(); }); }); it('should minify a JPG (upper case file)', function (callback) { var before = path.join(__dirname, 'fixtures/test-uppercase.JPG'); var after = path.join(__dirname, 'tmp/test-uppercase.JPG'); fs.writeFileSync(after, fs.readFileSync(before)); new JPGO(after).optimize(function (error, data) { assert(!error); assert(data.beforeSize > data.afterSize); callback(); }); }); });<file_sep># [jpgo](https://npmjs.org/package/jpgo) ## About Optimize JPG images. [![Build Status](https://travis-ci.org/1000ch/jpgo.svg?branch=master)](https://travis-ci.org/1000ch/jpgo) [![NPM version](https://badge.fury.io/js/jpgo.svg)](http://badge.fury.io/js/jpgo) [![Dependency Status](https://david-dm.org/1000ch/jpgo.svg)](https://david-dm.org/1000ch/jpgo) [![devDependency Status](https://david-dm.org/1000ch/jpgo/dev-status.svg)](https://david-dm.org/1000ch/jpgo#info=devDependencies) ## Usage ### as Node.js module ```js var JPGO = require('jpgo'); var jpgo = new JPGO('target.jpg'); jpgo.optimize(functoion (error, data) { if (error) { throw error; } console.log(data); }); ``` ### Command line ```sh $ jpgo target.jpg ``` ## License MIT<file_sep>#!/usr/bin/env node var fs = require('fs'); var path = require('path'); var async = require('async'); var glob = require('glob'); var minimist = require('minimist'); var chalk = require('chalk'); var filesize = require('filesize'); var JPGO = require('./'); var argv = minimist(process.argv.slice(2)); var jpgs = []; argv._.filter(function (arg) { return fs.existsSync(arg); }).forEach(function (arg) { if (fs.statSync(arg).isFile()) { jpgs.push(path.resolve(arg)); } else if (fs.statSync(arg).isDirectory()) { fs.readdirSync(arg).forEach(function(file) { jpgs.push(path.resolve(path.join(arg, file))); }); } else { glob(arg, function (error, files) { if (error) { throw error; } files.forEach(function (file) { jpgs.push(path.resolve(file)); }); }); } }); jpgs = jpgs.filter(function (jpg) { return path.extname(jpg).toLowerCase() === '.jpg'; }); async.eachLimit(jpgs, 10, function iterator(jpg) { new JPGO(jpg).optimize(function (error, data) { console.log( chalk.green('✔ ') + jpg, chalk.gray(' before=') + chalk.yellow(filesize(data.beforeSize)), chalk.gray(' after=') + chalk.cyan(filesize(data.afterSize)), chalk.gray(' reduced=') + chalk.green.underline(filesize(data.beforeSize - data.afterSize)) ); }); });
2c413aa2bcfaa2d22f4ad36f2f1bbf6a8dfefe77
[ "JavaScript", "Markdown" ]
3
JavaScript
1000ch/jpgo
9586cd69c0a821110723c8ad89798ce808bb6a76
87fb55dce225cefced2474eb963e353b0f7cffd6
refs/heads/master
<file_sep>![git hub ](https://github.com/thisismrsanjay/mini-projects/blob/master/texttospeech/Capture.PNG) <file_sep>const soundElement = document.querySelector('#sounds'); (async ()=>{ const sounds = await getSounds(); addSoundsToPage(sounds); })(); // const sounds = await getSounds(); // addSoundsToPage(sounds); async function getSounds(){ const response = await fetch('./sounds.json'); const json = await response.json(); return json; } function addSoundsToPage(sounds){ const players = []; sounds.forEach(sound=>{ const soundDiv = document.createElement('div'); soundDiv.className = 'sound'; const soundTitle = document.createElement('h2'); soundTitle.textContent = sound.title; soundDiv.appendChild(soundTitle); // const playButton= document.createElement('button'); // playButton.textContent = '🎵'; // soundDiv.appendChild(playButton); const player = document.createElement('audio'); player.setAttribute('src',`sounds/${sound.src}`) soundDiv.appendChild(player); players.push({player,soundDiv}); soundDiv.addEventListener('mousedown',()=>{ soundDiv.style.background = '#0941a1'; player.currentTime = 0; player.play(); }) soundDiv.addEventListener('mouseup',()=>{ soundDiv.style.background = ''; }) soundElement.appendChild(soundDiv); }) const keyCodes ={ 65:0, 83:1, 68:2, 70:3, 71:4, 72:5, 74:6, 75:7, 76:8, 186:9, 222:10, 90:11 } document.addEventListener('keydown',(event)=>{ const playerIndex= keyCodes[event.keyCode]; const playerAndDiv = players[playerIndex]; if(playerAndDiv){ playerAndDiv.soundDiv.style.background = '#0941a1'; playerAndDiv.player.currentTime = 0; playerAndDiv.player.play(); } }) document.addEventListener('keyup',(event)=>{ const playerIndex= keyCodes[event.keyCode]; const playerAndDiv = players[playerIndex]; if(playerAndDiv){ playerAndDiv.soundDiv.style.background = ''; } }) }<file_sep>![git hub ](https://github.com/thisismrsanjay/mini-projects/blob/master/pet-finder/Capture.PNG) # Parcel # Babel * jsonp cross orgin something? * parcel build file<file_sep>export function isValidZip(zip){ return /^\d{5}(-\d{4})?$/.test(zip); } export function showAlert(message,className){ const div = document.createElement('div'); //setting class & text inside the div div.className = `alert alert-${className}`; div.appendChild(document.createTextNode(message)); const container = document.querySelector('.container'); const form = document.querySelector('#pet-form'); container.insertBefore(div,form); setTimeout(()=>document.querySelector('.alert').remove(),3000); }<file_sep>![git hub ](https://github.com/thisismrsanjay/mini-projects/blob/master/google-maps/Capture.PNG) * api requires payment try something else<file_sep>![git hub ](https://github.com/thisismrsanjay/mini-projects/blob/master/coming-soon-landingpage/Capture.PNG) <file_sep>window.addEventListener('load',init); let time = 5; let score = 0; let isPlaying= true; const wordInput = document.querySelector('#word-input'); const currentWord = document.querySelector('#current-word'); const scoreDisplay = document.querySelector('#score'); const timeDisplay = document.querySelector('#time'); const message = document.querySelector('#message'); const seconds = document.querySelector('#seconds'); const words = [ "Apples", "Bananas", "Pears", "robot", "inferno", "giga", "infinity", "pow", "smash", "boom", "crunch", "robot", "inferno","bad","easy","lol","Hurt","gay","code","hate","kill","ice","fire","icecream","hangman","destroy","computer","book","dictionary","technology","power","thunder","controller","dexterity","keyboard","thunderous","blizzard","hazardous","algorithm","destruction","operation","assignment","despicable" ]; function init(){ showWord(words); //matching word input wordInput.addEventListener('input',startMatch); setInterval(countdown,1000);//change time setInterval(checkStatus,50);//check isPlaying or not } //Start Match function startMatch(){ if(matchWords()){ isPlaying = true; time = 6; showWord(words); wordInput.value = ''; score++; } scoreDisplay.innerHTML = score; } function matchWords(){ if(wordInput.value=== currentWord.innerHTML){ message.innerHTML ='Correct!!'; return true; }else{ message.innerHTML= ''; return false; } } function showWord(words){ const randIndex = Math.floor(Math.random()*words.length); currentWord.innerHTML = words[randIndex]; } function countdown(){ if(time >0 ){ time--; }else if(time===0){ isPlaying =false; } //Show time timeDisplay.innerHTML = time; } //check status function checkStatus(){ if(!isPlaying && time ===0){ message.innerHTML = 'Game Over!!!'; score = 0; } }<file_sep>![git hub ](https://github.com/thisismrsanjay/mini-projects/blob/master/typefast/Capture.PNG)<file_sep>const express = require('express'); const app = express(); const path = require('path'); const server = require('http').createServer(app); const io = require('socket.io').listen(server); const port = process.env.PORT || 3000; io.on('connection',(socket)=>{ socket.broadcast.emit('announce', { message:'New Client ' }); socket.on('send',(data)=>{ socket.broadcast.emit('message',{ message:data.message, author:data.author }) }) socket.on('signal',(data)=>{ socket.broadcast.emit('signaling_message',{ type:data.type, message:data.message }) }) }) app.set('views',path.join(__dirname,'views')); app.set('view engine','ejs'); app.get('/',(req,res)=>{ res.render('index'); }) server.listen(port,()=>{ console.log('server started ') })<file_sep>![git hub ](https://github.com/thisismrsanjay/mini-projects/blob/master/sound-board/Capture.PNG) # Sound Board * Request Sounds JSON (async) * Add sounds to page * Click to play * Button to stop all sounds<file_sep>![git hub ](https://github.com/thisismrsanjay/mini-projects/blob/master/speech-recognition/Capture.PNG) # text to speech ## requires http server
a79a8493886cba204c11055bdfa44809ad50b43e
[ "Markdown", "JavaScript" ]
11
Markdown
thisismrsanjay/mini-projects
f7f85ae45aeb4906e51ce22367ff7cbacded4bae
12cb7c62b6c139a05da76ea8dcca9808d51f9c2d
refs/heads/master
<repo_name>FoXTecktoniK/bigjson<file_sep>/bigjson/__init__.py from .filereader import FileReader def load(file): reader = FileReader(file) return reader.read()
d9a87197b031fd5bc37b721687a2ad5ea63b9ad5
[ "Python" ]
1
Python
FoXTecktoniK/bigjson
e66f796b84485586db91a4055bcba8c21ac1e32a
7d6cca3c67860685e46d130b95a699c92bb3a5a5
refs/heads/master
<file_sep># VL-UI Visual Law front-end CMS <file_sep>"use strict"; var service = [ { cat: "service", title: "Forensic Mapping", hash: "" }, { cat: "service", title: "Forensic Animation", hash: "" }, { cat: "service", title: "Strategy Consulting", hash: "" }, { cat: "service", title: "Trial Technology", hash: "" }, { cat: "service", title: "Settlement Documentaries", hash: "" }, { cat: "company", title: "About Visual Law", hash: "" }, { cat: "company", title: "<NAME>", hash: "" } ] // CSS will not be dynamic /* var serviceLinks = function(obj){ var formatedArr = sections.map(function(obj, i) { if (obj.cat === "service"){ var servObj = {}; servObj[obj.cat] = obj.title; servObj.hash = obj.hash; return servObj; } }); }*/ //Remove or add class to animate submenu var classAnimate = function(classID){ var subMenu = document.getElementsByClassName(classID)[0].className; if (subMenu === "subMenu") document.getElementsByClassName(classID)[0].className += " active"; else document.getElementsByClassName(classID)[0].className = "subMenu"; }; var SubLinks = React.createClass({ handleClick: function() { classAnimate("subMenu"); return 1; }, render: function() { var linkList = sections.map(function(obj, i){ return <li key={i} className="" > <a className="testA" onClick={this.handleClick}> {obj.title} </a> </li>; }, this); return <ul > { linkList } </ul>; } }); var SubMenu = React.createClass({ render: function() { return <div className="subMenu"> <SubLinks /> </div>; } }); var MainLinks = React.createClass({ handleClick: function() { console.log("Inside Main Links"); classAnimate("subMenu"); return 1; }, render: function() { var linkList = sections.map(function(obj, i){ return <li key={i} className="" > <a className="testA" onClick={this.handleClick} > {obj.title} </a> <SubMenu /> </li>; }, this); return <ul > { linkList } </ul>; } }); var MainMenu = React.createClass({ handleClick: function() { classAnimate("subMenu"); return 1; }, render: function() { return <section id="navPage" className="text-center"> <h1> Visual Law </h1> <a onClick={this.handleClick} >Test Button</a> <MainLinks /> </section>; } }); ReactDOM.render(<MainMenu />, document.getElementById('navPage')); <file_sep> var el = document.getElementsByClassName("scene-1-btn"), targEl = []; var stg1; //console.log( targEl[0] ); function gridLaunch(e){ targEl[0] = $(".stage"); console.log(e.currentTarget.dataset.service); var $target = e.currentTarget.dataset.service; $("#fullpage").toggleClass("off"); if ( targEl[1].hasClass("gd") ){ console.log("Condition Test"); targEl[1].removeClass('gd'); $("#fullpage").removeClass('off'); }else { console.log("Condition Test"); targEl[1].addClass('gd'); $("#fullpage").addClass('off'); } } function toggleSD(e){ console.log(e.currentTarget.dataset.service); targEl[0] = $(".stage"); console.log( targEl[0] ); var $target = e.currentTarget.dataset.service; if ( targEl[0].hasClass("to3") ){ console.log("Condition 1"); targEl[0].removeClass('to3'); targEl[0].removeClass('to2'); }else if ( targEl[0].hasClass("to2") ) { console.log("Condition 2"); targEl[0].addClass('to3'); }else { console.log("Condition 3"); targEl[0].addClass('to2'); } return true; } function topScroll(){ console.log("swinging start"); $(document).off("scroll"); var target = this.hash, menu = target; $target = $(".b1"); $('.verbiage').animate({ 'scrollTop': 0 }, 333, 'swing', function () { console.log("swinging success"); }); } /* Content Loading */ var Picture = { items : {}, getData : function() { var loadJson = {}; //Ajax Jason files $.getJSON( "json/content.json", function( data ) { $.each( data, function( key, val ) { loadJson[key] = val; }); });//End Ajxax return this.items = loadJson; }, currentImg : 0 , //first index is defualt loadImages : function(parent, imgBtn){ var size = Picture.items[0].documentaries.imageFile.length-1; if (imgBtn == true){ if (this.currentImg == size){ this.currentImg = 0; }else { this.currentImg++; } $(parent + " .cont2").css("background-image", "url(img/uploads/"+Picture.items[0].documentaries.imageFile[this.currentImg]+".jpg)") $(parent + " .cont1")[0].children[1].innerHTML = "0"+this.currentImg+"<span id='outOf' style='font-size: 19px'>/ 0"+(size+1)+"</span>" console.log($(parent + " .cont1")[0].children[1].innerHTML); } else { if (this.currentImg == 0){ this.currentImg = size; }else { this.currentImg--; } $(parent + " .cont2").css("background-image", "url(img/uploads/"+Picture.items[0].documentaries.imageFile[this.currentImg]+".jpg)") $(parent + " .cont1")[0].children[1].innerHTML = "0"+this.currentImg+"<span id='outOf' style='font-size: 19px'>/ 0"+(size+1)+"</span>" } } } Picture.getData(); var expand = function(targ){ console.log($(targ)[0].dataset.exp); var $parent = $(targ)[0].dataset.exp, $target = $($parent + " .cont3 p#overview")[0].innerHTML; //console.log($($parent + " .cont3 p#overview")); $($parent + " .cont3").toggleClass("expand", function(){ if($target === "Click to learn more."){ console.log("empty"); $($parent + " .cont3 p#overview")[0].innerHTML = Picture.items[0].documentaries.overview; }else { $($parent + " .cont3 p#overview")[0].innerHTML = "Click to learn more."; } }); } var nextImg = function(targ){ var $parent = $(targ)[0].dataset.exp; console.log('next'); Picture.loadImages($parent, true); } var prevImg = function(targ){ var $parent = $(targ)[0].dataset.exp; Picture.loadImages($parent, false); } <file_sep> var el = document.getElementsByClassName("scene-1-btn"), targEl = []; var stg1; console.log( targEl[0] ); function gridLaunch(e){ targEl[0] = $(".stage"); console.log(e.currentTarget.dataset.service); var $target = e.currentTarget.dataset.service; $("#fullpage").toggleClass("off"); if ( targEl[1].hasClass("gd") ){ console.log("Condition Test"); targEl[1].removeClass('gd'); $("#fullpage").removeClass('off'); }else { console.log("Condition Test"); targEl[1].addClass('gd'); $("#fullpage").addClass('off'); } } function toggleSD(e){ console.log(e.currentTarget.dataset.service); targEl[0] = $(".stage"); console.log( targEl[0] ); var $target = e.currentTarget.dataset.service; if ( targEl[0].hasClass("to3") ){ console.log("Condition 1"); targEl[0].removeClass('to3'); targEl[0].removeClass('to2'); }else if ( targEl[0].hasClass("to2") ) { console.log("Condition 2"); targEl[0].addClass('to3'); }else { console.log("Condition 3"); targEl[0].addClass('to2'); } return true; } function topScroll(){ console.log("swinging start"); $(document).off("scroll"); var target = this.hash, menu = target; $target = $(".b1"); $('.verbiage').animate({ 'scrollTop': 0 }, 333, 'swing', function () { console.log("swinging success"); }); } /* Content Loading */ var itemsSD = null; function loadDoc() { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { itemSD = JSON.parse(this.responseText); }else { itemsSD = { "documentaries": { "overview": "Telling a compelling story that an audience can sympathize with is the key to the settlement process. To avoid the stresses that a client can often experience as a result from a lengthy and demanding trial, we have become highly successful in producing emotional and visually impactful settlement documentaries. A settlement is often the best case scenario in any civil case and is one of the most difficult objectives to achieve in litigation.", "imageFile": ["49ersStadium_03082014", "BakerBeachPanorama", "BakerBeackPano2", "web-point-cloud3"] } } }; xhttp.open("GET", "../json/content.json", true); xhttp.send(); } //GET Content // loadDoc(); var expanded = false; function expand(targ){ var $parent = $(targ)[0].dataset.exp, $target = $($parent + " .cont3 p#overview")[0]; $($parent + " .cont3").toggleClass("expand", function(){ console.log("Not empty"); $target.innerHTML = "Click to learn more."; }); return true; } }
dfe3850a4aa79314ae361691a22f342a560d0ffa
[ "Markdown", "JavaScript" ]
4
Markdown
mrLucianoii/VL-UI
5a12be0cf937cf6b6dbb4076dee2345002f5a6ea
b6d1ecd4a52654ab712673c1e2f84362b5809838
refs/heads/master
<file_sep>console.log("JS: Working!"); console.log("08/04/2017"); console.log("Test: Flexbox, @Media, -Webkit Animations");<file_sep>println("Hello"); var a = 12; var b = 24; func main (){ println!("testing my first function in RUST" ); } func main(){ println!("Test" + "test2"); } <file_sep>name = '<NAME>' location = 'The Moon' age = 100 intro = 'Test Python Program' print ('Name: ' + name + ' Location: ' + 'Age: ' + str(age) +'\n') print(intro) """if age > 21: print (age) else: print("Broken") for x in range(0,100): print('hello' + str(age))""" yourName = input("What is your name: ") print('\n' + yourName)<file_sep>console.log("JS: Working!"); console.log("Need to program a website template");<file_sep><!DOCTYPE html> <html lang="en"> <head> <title>Test Website</title> <link rel="stylesheet" type="text/css" href="style/style.css"> </head> <body> <div id="container"> <div id="navbarTwo"> <button class="navBtn" type="button"><a href="#about">About<a/></button> <button class="navBtn" type="button"><a href="#portfolio">Portfolio<a/></button> <button class="navBtn" type="button"><a href="#contact">Contact<a/></button> </div> <div id="content"> <h1 id="about">About</h1> <p> Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur? <br><br> Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur? </p> <p> Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur? <br><br> Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur? </p> <h1 id="portfolio">Portfolio</h1> <p> Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur? <br><br> Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur? </p> <p> Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur? <br><br> Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur? </p> <h1 id="contact">Contact</h1> <p> Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur? <br><br> Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur? </p> <p> Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur? <br><br> Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur? </p> </div> <div id="icon">IMG GOES HERE! <button class="iconBtn" type="button"><a href="#about">About<a/></button> <button class="iconBtn" type="button"><a href="#portfolio">Portfolio<a/></button> <button class="iconBtn" type="button"><a href="#contact">Contact<a/></button> </div> </div> </body> <script src="script/script.js"></script> </html><file_sep>console.log("JS: Working!")<file_sep>08/02/2017 w3schools.com -HTML Practice Quiz = 65% -CSS Practice Quiz = 80% Testing <meta name="viewport" content="width=device-width, initial-scale=1.0"> Research -Researching GitHub Repositories -Researching Udemy Programming Courses
17264bb8c0c572ac2e369d7f4b20a02353199ebb
[ "HTML", "JavaScript", "Rust", "Python", "Text" ]
7
JavaScript
brennonramsey/Other_Test_Projects
e1c53c20aabb53925ad9eba46b3c1308f06e7f69
c8ceadeed5e7c2011380c6c64dd7fa52c1ee1371
refs/heads/main
<repo_name>anushpoudel/ninja-list-nextjs<file_sep>/pages/about.js import React from "react"; import Head from "next/head"; import styles from "../styles/Home.module.css"; const About = () => { return ( <> <Head> <title>Ninja List | About</title> </Head> <div> <h1 className={styles.title}>About</h1> <p className={styles.text}> Lorem ipsum dolor sit amet consectetur adipisicing elit. Ducimus in, laboriosam excepturi hic sequi doloremque nihil perferendis quo accusantium velit exercitationem dignissimos. Natus neque, cumque maiores cupiditate sed recusandae voluptatibus? </p> <p className={styles.text}> Lorem ipsum dolor sit amet consectetur adipisicing elit. Ducimus in, laboriosam excepturi hic sequi doloremque nihil perferendis quo accusantium velit exercitationem dignissimos. Natus neque, cumque maiores cupiditate sed recusandae voluptatibus? </p> </div> </> ); }; export default About;
a63dbfb4a08308f339b0c000ae3e9e484d9e5183
[ "JavaScript" ]
1
JavaScript
anushpoudel/ninja-list-nextjs
9bfe6268672e57be42c70b6c5b88da1205cbe348
62df0a67257a458424b375f2cee13c4fff2ad6a4
refs/heads/master
<repo_name>Elder6Driver/baikespider<file_sep>/html_output.py # coding:utf8 __author__ = 'AlexPC' class HtmlOutputer(object): def __init__(self): self.datas = [] def collect_data(self,data): if data is None: return self.datas.append(data) def output_html(self): fout = open('output.html','w') fout.write('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\n') fout.write('<html xmlns="http://www.w3.org/1999/xhtml">\n') fout.write('<head>\n<meta charset="UTF-8">\n</head>\n') fout.write('<body>\n') fout.write('<table>\n') for data in self.datas: fout.write('<tr>') fout.write('<td>%s</td>' % data['url']) fout.write('<td>%s</td>' % data['title'].encode('utf-8')) #.encode('utf-8') fout.write('<td>%s</td>' % data['summary'].encode('utf-8')) fout.write('</tr>\n') fout.write('</html>\n') fout.write('</body>\n') fout.write('</table>\n') fout.close() <file_sep>/__init__.py __author__ = 'AlexPC' <file_sep>/README.md # baikespider 一个百度百科的爬虫程序,学习使用
fe30a98a7301102414c5a16916054733cc0d4842
[ "Markdown", "Python" ]
3
Python
Elder6Driver/baikespider
cd50107ced7a2358f5615bd42b65f873896d8073
59af3f1849993bac3c17f5dd8d37be4f20e37cf2
refs/heads/master
<file_sep>declare -A EmpWage #arr=() echo " Welcome to EmployeeWage Computation Program on master branch" isFullTime=1 isPartTime=2 wagePerHr=20 empHr=0 totalWage=0 randomnumber=$((RANDOM%3)) Day=1 hour=1 case $randomnumber in $isFullTime) echo "Employee is Present" ;; $isPartTime) echo "Employee is Part Time" ;; *) echo "Absent" ;; esac randomnumber=$((RANDOM%3)) while [ $Day -le 20 ] && [ $hour -le 100 ] do case $randomnumber in $isFullTime) empHr=8 hour=$((hour+8)) ;; $isPartTime) empHr=4 hour=$((hour+4)) ;; *) empHr=0 ;; esac totalWage=$(($totalWage+( $wagePerHr*$empHr ))) Day=$((Day+1)) for((i=1; i<=20; i++)) do EmpWage[$i]=$totalWage done done #sort -k1,1 -n ${EmpWage[@]} #for((i=1; i<=${!EmpWage[@]}; i++)) #do for i in ${!EmpWage[@]} do echo "Wage of Day $i is ${EmpWage[$i]}" done #echo ${EmpWage[@]} echo "Wage of Employee is:" $totalWage
3b64f30931e20faa182b6d61291e00ef887da7ac
[ "Shell" ]
1
Shell
MOHAMMAD-FATHA/EmployeeWageComputation
6aaa083589ca27a68f377e22cef49e996a05db47
a1b88241cfbbd1621760126a67448ffe7f04acf6
refs/heads/master
<repo_name>bslotty/dg<file_sep>/src/app/modules/courses/pages/detail/detail.component.ts import { ActivatedRoute } from '@angular/router'; import { Component, OnInit } from '@angular/core'; import { Location } from "@angular/common"; import { CourseBackend } from '../../services/backend.service'; import { FeedbackService } from 'src/app/shared/modules/feedback/services/feedback.service'; import { loading } from 'src/app/animations'; import { Course } from 'src/app/shared/types'; @Component({ selector: 'app-detail', templateUrl: './detail.component.html', styleUrls: ['./detail.component.css'], animations: [loading,] }) export class DetailComponent implements OnInit { public course: Course = new Course(this.route.snapshot.paramMap.get('id')); public zoom: number = 14; constructor( public courses: CourseBackend, public route: ActivatedRoute, public feed: FeedbackService, public location: Location, ) { } ngOnInit() { this.getDetail(); } getDetail() { this.courses.getDetail(this.course).subscribe((v) => { console.log("course.detail.res: ", v); }); } back() { this.location.back(); } } <file_sep>/src/app/modules/scores/scores.module.ts import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { MaterialModule } from '../../shared/modules/material/material.module'; import { ScoreSettingsComponent } from './dialogs/score-settings/score-settings.component'; import { TeamSettingsComponent } from './dialogs/team-settings/team-settings.component'; import { ScoreListItemComponent } from './components/score-list-item/score-list-item.component'; import { TeamListItemComponent } from './components/team-list-item/team-list-item.component'; import { TeamSelectComponent } from './components/team-select/team-select.component'; import { TeamListComponent } from './components/team-list/team-list.component'; import { ScoreListComponent } from './components/score-list/score-list.component'; @NgModule({ declarations: [ ScoreListItemComponent, TeamListItemComponent, ScoreSettingsComponent, TeamSettingsComponent, TeamSelectComponent, TeamListComponent, ScoreListComponent, ], imports: [ CommonModule, MaterialModule, ], exports: [ ScoreListItemComponent, TeamListItemComponent, ScoreSettingsComponent, TeamSettingsComponent, TeamSelectComponent, TeamListComponent, ScoreListComponent, ], entryComponents: [ ScoreSettingsComponent, TeamSettingsComponent, ], providers: [ ] }) export class ScoresModule { } <file_sep>/src/assets/api/teams/list.php <?php session_start(); header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS'); header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token, Authorization, X-Requested-With'); header("Access-Control-Allow-Credentials: true"); header('Access-Control-Max-Age: 1000'); header('Content-Type: application/json,text/plain'); // Load Basic Functions :: For IP Grab require ($_SERVER['DOCUMENT_ROOT'] . '/api/disc/functions.php'); require ($_SERVER['DOCUMENT_ROOT'] . '/api/disc/sql.php'); $payload = json_decode(file_get_contents('php://input'), TRUE); $return = array(); // Get List of Leagues for User $query = "SELECT `t`.`ID` AS `T.ID`, `t`.`Name` AS `T.Name`, `t`.`Color` AS `T.Color` FROM `Teams` AS `t` WHERE `t`.`SessionID`=:session ;"; // Set Values $values = array(":session"=>$payload["session"]["id"]); $sql = new SQL; $data = $sql->Query($query, $values); if (count($data) == 0) { $return = array( "status" => "success", "msg" => "No teams found", "data" => array() ); } else { $payload = []; foreach ($data as $o) { $payload[] = array( "id" => $o['T.ID'], "name" => $o['T.Name'], "color" => $o['T.Color'] ); } $return = array( "status"=>"success", "data"=> $payload ); } printf(json_encode($return)); ?><file_sep>/src/assets/api_new/controllers/scores.php <?php // Session & Header Init require_once($_SERVER['DOCUMENT_ROOT'] . '/sites/disc/api/shared/headers.php'); // Convert HTTP Vars $payload = json_decode(file_get_contents('php://input'), TRUE); // Init Return $return = array(); // Debug /** * Future feature, do not return each step in DB; only return last; Can flag with this later on */ $devMode = true; // DB require_once($_SERVER['DOCUMENT_ROOT'] . '/sites/disc/api/shared/sql.php'); $database = new DB("scores"); // Scores require_once($_SERVER['DOCUMENT_ROOT'] . '/sites/disc/api/classes/scores.php'); $scores = new Score($database); // Players require_once($_SERVER['DOCUMENT_ROOT'] . '/sites/disc/api/classes/players.php'); $player = new Player($database); switch ($payload['action']) { case "list": $return[] = $scores->getScores($payload['start'], $payload['limit']); break; case "recent": $return[] = $scores->RecentlyPlayedWith($payload['user']); break; case "search": $return[] = $player->searchPlayers($payload['term']); break; } printf(json_encode($return)); <file_sep>/src/app/modules/sessions/dialogs/select-players/select-players.component.ts import { Component, OnInit, Inject, Input } from '@angular/core'; import { FormGroup } from '@angular/forms'; import { FeedbackService } from 'src/app/shared/modules/feedback/services/feedback.service'; import { flyInPanelRow, flyIn } from 'src/app/animations'; import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material'; import { ScoresFormService } from 'src/app/modules/scores/services/scores-form.service'; import { ScoresBackend } from 'src/app/modules/scores/services/backend.service'; import { listCategories } from 'src/app/shared/types'; @Component({ selector: 'app-select-players', templateUrl: './select-players.component.html', styleUrls: ['./select-players.component.scss'], animations: [flyInPanelRow, flyIn], }) export class SelectPlayersComponent implements OnInit { @Input() options: Object = { list: ["search"], row: ["full", "email", "selector"], }; lists: Array<listCategories>; selectedList: listCategories; search: boolean = false; form: FormGroup; constructor( private _scoresForm: ScoresFormService, private _scores: ScoresBackend, private feed: FeedbackService, private dialogRef: MatDialogRef<SelectPlayersComponent>, @Inject(MAT_DIALOG_DATA) private data, ) { } ngOnInit() { this._scores.listRecient(); // List Selection this.lists = [ { name: "recent", obs: this._scores.recientPlayers$, }, { name: "search", obs: this._scores.searchedPlayers$, } ]; // Default Option this.selectedList = this.lists[0]; // Setup Form this._scoresForm.Setup('search'); this._scoresForm.form$.subscribe((f) => { this.form = f; this.feed.stopLoading("scoreSearch"); console.log ("this.form: ", this.form); }); } toggleSearch() { this.search = !this.search; if (this.search) { this.showSearch(); } else { this.hideSearch(); } } showSearch() { // Update Flag this.search = true; // Set Dropdown to Search this.selectedList = this.lists.find((l) => { return l.name == "search"; }); // Clear Field this._scoresForm.resetPlayerSearch(); // Turn Off Loader this.feed.stopLoading("scoreSearch"); } hideSearch() { // Update Flag this.search = false; // Set list to Default this.selectedList = this.lists[0]; // Turn Off Loader this.feed.stopLoading("scoreSearch"); } selectChange($event) { this.selectedList = this.lists.find((l) => { return l.name == $event.value.name; }); if ($event.value.name == 'search') { this.showSearch(); } else { this.hideSearch(); } } trackBy(index, item) { return item.id; } close() { this.dialogRef.close(); } } <file_sep>/src/app/modules/account/components/shell/shell.component.ts import { Component, OnInit } from '@angular/core'; import { FeedbackService } from 'src/app/shared/modules/feedback/services/feedback.service'; import { ServerPayload } from 'src/app/app.component'; import { AccountBackend } from '../../services/backend.service'; @Component({ selector: 'app-shell', templateUrl: './shell.component.html', styleUrls: ['./shell.component.scss'] }) export class ShellComponent implements OnInit { headerButtons = [{ icon: 'icon-log-out', action: "logout", color: "transparent-primary" }]; constructor( private account: AccountBackend, private feed: FeedbackService, ) { } ngOnInit() { } actionClick($event) { if ($event == "logout") { this.logout(); } } logout() { var payload = new ServerPayload; payload.status = "success"; payload.msg = "You are now logged out"; this.account.logout(); } } <file_sep>/src/app/modules/courses/services/backend.service.ts import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { map, catchError, distinctUntilChanged, debounceTime } from 'rxjs/operators'; import { of, pipe, BehaviorSubject, Observable } from 'rxjs'; import { environment } from 'src/environments/environment'; import { AccountBackend } from '../../account/services/backend.service'; import { Course, ServerPayload } from 'src/app/shared/types'; import { HelperService } from 'src/app/shared/services/helper.service'; @Injectable({ providedIn: 'root' }) export class CourseBackend { url: string = environment.apiUrl + '/controllers/courses.php'; // Generic private list: BehaviorSubject<Course[]> = new BehaviorSubject([]); list$: Observable<Course[]> = this.list.asObservable(); // Favorites private favoriteList: BehaviorSubject<Course[]> = new BehaviorSubject([]); favoriteList$: Observable<Course[]> = this.favoriteList.asObservable(); // Recient private recientList: BehaviorSubject<Course[]> = new BehaviorSubject([]); recientList$: Observable<Course[]> = this.recientList.asObservable(); // Search private search: BehaviorSubject<Course[]> = new BehaviorSubject([]); search$: Observable<Course[]> = this.search.asObservable(); constructor( private http: HttpClient, private account: AccountBackend, private helper: HelperService, ) { } listTop() { this.getList("list").subscribe((res: ServerPayload[]) => { this.list.next(this.helper.rGetData(res)); }); } listRecient() { this.getList("recient").subscribe((res: ServerPayload[]) => { this.recientList.next(this.helper.rGetData(res)); }); } listFavorites() { this.getList("favorites").subscribe((res: ServerPayload[]) => { this.favoriteList.next(this.helper.rGetData(res)); }); }; getList(list: string, start: number = 0, limit: number = 20) { return this.http .post(this.url, { "action": list, "start": start, "limit": limit, "user": this.account.user }).pipe(); } getDetail(course: Course) { let url = environment.apiUrl + "/courses/detail.php"; return this.http.post(url, { course: course }).pipe(map((res: ServerPayload) => { this.list.next(this.helper.rGetData(res)); })); } getSearch(term: string) { this.http.post(this.url, { action: "search", term: term }).pipe(this.helper.pipe).subscribe((res: ServerPayload) => { this.search.next(this.helper.rGetData(res)); }); } create(course) { console.log("User: ", this.account.user); return this.http.post(this.url, { action: 'create', course: course, user: this.account.user }); } setCourseList(courses: Course[]) { this.list.next(courses); } resetList() { this.list.next([]); } }<file_sep>/src/app/modules/account/components/verify/verify.component.ts import { Component, OnInit } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { FeedbackService } from 'src/app/shared/modules/feedback/services/feedback.service'; import { AccountBackend } from 'src/app/modules/account/services/backend.service'; import { ServerPayload } from 'src/app/app.component'; @Component({ selector: 'app-verify', templateUrl: './verify.component.html', styleUrls: ['./verify.component.css'], animations: [] }) export class VerifyComponent implements OnInit { constructor( public route: ActivatedRoute, public router: Router, public account: AccountBackend, ) { } ngOnInit() { this.verifyToken(); } verifyToken() { let token = this.route.snapshot.paramMap.get('token'); this.account.verify(token).subscribe((res: ServerPayload)=>{ if (this.account.rCheck(res)) { this.router.navigate(["/sessions"]); } }); } } <file_sep>/src/app/shared/components/forms/password/password.component.ts import { Component, OnInit, Input, Output } from '@angular/core'; import { FormControl } from '@angular/forms'; import { EventEmitter } from '@angular/core'; @Component({ selector: 'form-password', templateUrl: './password.component.html', styleUrls: ['./password.component.scss'] }) export class PasswordComponent implements OnInit { @Input() inputType: string = "InvalidType"; @Input() submitOnEnter: boolean = false; @Input() control: FormControl; @Output() submitEvent: EventEmitter<string> = new EventEmitter(); textType: string = "password"; // text | password constructor() { } ngOnInit() { } showPassword(show) { this.textType = show ? 'text' : 'password'; } sendSubmitEvent() { if (this.submitOnEnter) { console.log("SubmitEventSent!"); this.submitEvent.emit("submit"); } } } <file_sep>/src/app/modules/account/components/create/create.component.ts import { flyInPanelRow } from './../../../../animations'; import { Component, OnInit } from '@angular/core'; import { FeedbackService } from 'src/app/shared/modules/feedback/services/feedback.service'; import { AccountFormService } from '../../services/account-form.service'; import { FormGroup } from '@angular/forms'; @Component({ selector: 'app-create', templateUrl: './create.component.html', styleUrls: ['./create.component.css'], animations: [flyInPanelRow] }) export class CreateComponent implements OnInit { form: FormGroup; constructor( private accountForm: AccountFormService, private feed: FeedbackService, ) { } ngOnInit() { this.accountForm.Setup("register"); this.accountForm.form$.subscribe((f) => { console.log("accountForm.registerForm", f); this.form = f; this.feed.stopLoading("register"); }); } onFormSubmit() { this.accountForm.SubmitRegistration(); } } <file_sep>/src/app/shared/services/helper.service.ts import { Injectable } from '@angular/core'; import { SessionFormat, Session, Score, Player, Team, Course, ServerPayload, TeamColor } from '../types'; import { of } from 'rxjs/internal/observable/of'; import { pipe } from 'rxjs/internal/util/pipe'; import { debounceTime } from 'rxjs/internal/operators/debounceTime'; import { distinctUntilChanged } from 'rxjs/internal/operators/distinctUntilChanged'; import { catchError } from 'rxjs/internal/operators/catchError'; import { FeedbackService } from '../modules/feedback/services/feedback.service'; import { retryWhen } from 'rxjs/internal/operators/retryWhen'; import { delay } from 'rxjs/internal/operators/delay'; import { take } from 'rxjs/internal/operators/take'; import { timeout } from 'rxjs/internal/operators/timeout'; @Injectable({ providedIn: 'root' }) export class HelperService { public pipe = pipe( debounceTime(500), distinctUntilChanged(), ); public types: SessionFormat[] = [ { name: 'Free For All', enum: 'ffa', desc: `Every person for themselves! This is standard play.`, }, { name: 'Teams: Sum', enum: 'team-sum', desc: `This format will combine the scores of each player on each team. Rankings will be sorted by the Team's Total Score.`, }, { name: 'Teams: Average', enum: 'team-average', desc: `This format will average the throw totals of each player against par. Rankings will be sorted by the Team's Average Score.`, }, { name: 'Teams: Best Only', enum: 'team-best', desc: `This format will only count the best score of each hole. Scores are set from the best scores of each hole.`, } ]; constructor( private feed: FeedbackService, ) { } // Migrate all calls from other services to here // This Service should house all common service functions. /** * @param res:ServerPayload[] * @returns boolean true if the latest query ran by the server was successfull; * -- else false */ rCheck(res /*: ServerPayload[]*/): boolean { if (res != null) { var latest = res.length - 1; console.log("res[latest]", res[latest]); if (res[latest]["status"] == "success") { return true; } else { console.warn("server.error: ", res[latest]["status"]["message"]); return false; } } else { console.warn("server.error.nothing: ", res[latest]["status"]["message"]); return false; } } /** * @param ServerPayload[] * @returns Data Array * -- else [] */ rGetData(res/*: ServerPayload[]*/): Array<any> { var latest = res.length - 1; if (latest > -1) { return res[latest]["formattedResults"]; } else { return []; } } /* Server Data Conversions */ /** Take Format String and Convert to :SessionFormat * */ convertCourse(courses): Course[] { var result: Course[] = []; courses.forEach((course) => { result.push(new Course( course['id'], course['created_on'], course['created_by'], course['modified_on'], course['modified_by'], course['park_name'], course['city'], course['state'], course['zip'], +course['latitude'], +course['longitude'], )); }); return result; } convertFormatStr(str): SessionFormat { let format: SessionFormat = this.types.find(t => t.enum == str); return format; } convertSession(sessions): Session[] { var result: Session[] = []; sessions.forEach((session) => { result.push(new Session( session['id'], new Date(session['created_on']), session['created_by'], new Date(session['modified_on']), session['modified_by'], session['course'], this.convertFormatStr(session['format']), new Date(session['starts_on']), session['title'], session['par'], session['scores'], )); }); // console.log("ConvertSession: ", result); return result; } convertScores(scores): Score[] { var result: Score[] = []; console.log("raw scores: ", scores); if (scores != undefined) { scores.forEach((s) => { var score = new Score(); score.id = s['scores.id']; score.created_on = new Date(s['scores.created_on']); score.created_by = s['scores.created_by']; score.modified_on = new Date(s['scores.modified_on']); score.modified_by = s['scores.modified_by']; score.handicap = +s['scores.handicap'] != NaN ? s['scores.handicap'] : 0; score.throws = s['scores.throws']; score.player = new Player( s["scores.player.id"], s["scores.player.first_name"], s["scores.player.last_name"], s["scores.player.email"] ); if (s["scores.team.id"] != undefined) { score.team = new Team( s["scores.team.id"], s["scores.team.name"], new TeamColor( s["scores.team.name"], s["scores.team.hex"], s["scores.team.available"], ) ); } else { score.team = new Team( null, "Unassigned", new TeamColor( "Unassigned", null, null ) ); } console.log("score:", score); result.push(score); }); } return result; } convertPlayerToScore(player: Player, user): Score { var score = new Score(); score.id = "create"; score.created_on = new Date(); score.created_by = user.id; score.modified_on = new Date(); score.modified_by = null; score.handicap = 0; score.throws = []; score.player = new Player( player["id"], player["first_name"], player["last_name"], player["email"] ); score.team = new Team( null, "Unassigned", new TeamColor( "Unassigned", null, null ) ); console.log("Player'sScore: ", score); return score; } } <file_sep>/src/app/shared/modules/material/material.module.ts import { NgModule, ModuleWithProviders } from '@angular/core'; import { CommonModule } from '@angular/common'; import { RouterModule } from '@angular/router'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; // Angular Theme import 'hammerjs'; // Dependancy import { MatAutocompleteModule, MatButtonModule, MatButtonToggleModule, MatCardModule, MatCheckboxModule, MatChipsModule, MatDatepickerModule, MatDialogModule, MatDividerModule, MatExpansionModule, MatFormFieldModule, MatGridListModule, MatIconModule, MatInputModule, MatListModule, MatMenuModule, MatNativeDateModule, MatPaginatorModule, MatProgressBarModule, MatProgressSpinnerModule, MatRadioModule, MatRippleModule, MatSelectModule, MatSidenavModule, MatSliderModule, MatSlideToggleModule, MatSnackBarModule, MatSortModule, MatStepperModule, MatTableModule, MatTableDataSource, MatTabsModule, MatToolbarModule, MatTooltipModule, } from '@angular/material'; import { DragDropModule } from '@angular/cdk/drag-drop'; import { SectionHeaderComponent } from '../../components/section-header/section-header.component'; import { LoaderComponent } from '../feedback/components/loader/loader.component'; import { FeedbackComponent } from '../feedback/components/feedback/feedback.component'; import { PasswordComponent } from 'src/app/shared/components/forms/password/password.component'; import { NgxMaterialTimepickerModule } from 'ngx-material-timepicker'; @NgModule({ imports: [ CommonModule, RouterModule, FormsModule, ReactiveFormsModule, BrowserAnimationsModule, MatAutocompleteModule, MatButtonModule, MatButtonToggleModule, MatCardModule, MatCheckboxModule, MatChipsModule, MatDatepickerModule, MatDialogModule, MatDividerModule, MatExpansionModule, MatFormFieldModule, MatGridListModule, MatIconModule, MatInputModule, MatListModule, MatMenuModule, MatNativeDateModule, MatPaginatorModule, MatProgressBarModule, MatProgressSpinnerModule, MatRadioModule, MatRippleModule, MatSelectModule, MatSidenavModule, MatSliderModule, MatSlideToggleModule, MatSnackBarModule, MatSortModule, MatStepperModule, MatTableModule, MatTabsModule, MatToolbarModule, MatTooltipModule, DragDropModule, NgxMaterialTimepickerModule, ], declarations: [ FeedbackComponent, LoaderComponent, SectionHeaderComponent, PasswordComponent, ], exports: [ FormsModule, ReactiveFormsModule, BrowserAnimationsModule, MatAutocompleteModule, MatButtonModule, MatButtonToggleModule, MatCardModule, MatCheckboxModule, MatChipsModule, MatDatepickerModule, MatDialogModule, MatDividerModule, MatExpansionModule, MatFormFieldModule, MatGridListModule, MatIconModule, MatInputModule, MatListModule, MatMenuModule, MatNativeDateModule, MatPaginatorModule, MatProgressBarModule, MatProgressSpinnerModule, MatRadioModule, MatRippleModule, MatSelectModule, MatSidenavModule, MatSliderModule, MatSlideToggleModule, MatSnackBarModule, MatSortModule, MatStepperModule, MatTableModule, MatTabsModule, MatToolbarModule, MatTooltipModule, FeedbackComponent, LoaderComponent, SectionHeaderComponent, PasswordComponent, DragDropModule, NgxMaterialTimepickerModule ], entryComponents: [ ], }) export class MaterialModule { static forRoot(): ModuleWithProviders { return { ngModule: MaterialModule, providers: [] }; } } <file_sep>/src/app/modules/account/components/login/login.component.ts import { FeedbackService } from '../../../../shared/modules/feedback/services/feedback.service'; import { Component, OnInit } from '@angular/core'; import { FormGroup} from '@angular/forms'; import { AccountFormService } from '../../services/account-form.service'; @Component({ selector: 'app-login', templateUrl: './login.component.html', styleUrls: ['./login.component.css'], animations: [], }) export class LoginComponent implements OnInit { form: FormGroup; constructor( public accountForm: AccountFormService, public feed: FeedbackService, ) { } ngOnInit() { this.accountForm.Setup("login"); this.accountForm.form$.subscribe((f)=>{ this.form = f; this.feed.stopLoading("login"); }); } onFormSubmit() { this.accountForm.SubmitLogin(); } } <file_sep>/src/todo.ts /** * * Account: General Total Wins Sessions Played Most Often Opponent Most Played Course Shot Stats: Avg Score Par % Birdie % Ace % Bogey % 2x Bogey % Course: General Times Played Best Score Worst Score Shot Stats (Specific to Course): Avg Score Par % Birdie % Ace % Bogey % 2x Bogey % League: General Sessions Played Wins Win % Shot Stats (Specific to League): Avg Score Par % Birdie % Ace % Bogey % 2x Bogey % Member Win/Loss Record. Specific to Viewer**W */<file_sep>/src/assets/api_new/shared/headers.php <?php // Session session_start(); // Headers header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS'); header('Access-Control-Allow-Headers: Origin, Content-Type Authorization'); header("Access-Control-Allow-Credentials: true"); header('Access-Control-Max-Age: 1000'); header('Content-Type: application/json,text/plain'); <file_sep>/src/app/shared/modules/charts/line-settings/line-settings.component.ts import { Component, OnInit, Inject } from '@angular/core'; import { MAT_DIALOG_DATA, MatDialogRef } from '@angular/material'; import { Team, Score } from 'src/app/shared/types'; @Component({ selector: 'app-line-settings', templateUrl: './line-settings.component.html', styleUrls: ['./line-settings.component.css'] }) export class LineSettingsComponent implements OnInit { colList = this.data.scores.columns.filter((v, i) => { return v.toLowerCase() != "hole"; }); selectedColumns = this.colList; teamList; playerList; activePlayerList; activeTeamList; availableColors = this.data["colors"]; headerButtons = [{ action: 'close', color: 'transparent-primary', icon: 'icon-x', }]; // mat-select: throws | score playerFormat: string = "scores"; teamFormat: string = this.data.format; constructor( @Inject(MAT_DIALOG_DATA) public data: any, public dialogRef: MatDialogRef<LineSettingsComponent>, ) { } ngOnInit() { console.log("settings.data: ", this.data); } actionClick($event) { if ($event == "close") { this.dialogRef.close(); } } getColor(ent) { if (ent instanceof Score) { return ent.team.color.hex; } else if (ent instanceof Team) { return ent.color.hex; } } close(data) { this.dialogRef.close(data); } updateFormat($event) { this.playerFormat = $event.value; } updatePlayers($event) { this.selectedColumns = $event.value; } updateTeamFormat($event) { this.teamFormat = $event.value; } updateChart() { var data = { selectedColumns: this.selectedColumns, format: this.playerFormat, teamFormat: this.teamFormat, }; this.close(data); } toggleVisibility(person, action) { if (action == "remove") { this.selectedColumns = this.selectedColumns.filter((v) => { return person != v; }); } else if (action == "add") { this.selectedColumns.push(person); } console.log("selectedColumns: ", this.selectedColumns); } } <file_sep>/src/app/modules/sessions/services/form.service.ts import { Injectable } from '@angular/core'; import { BehaviorSubject, Observable } from 'rxjs'; import { FormGroup, FormBuilder, FormControl, Validators, FormArray } from '@angular/forms'; import { CourseBackend } from '../../courses/services/backend.service'; import { Router } from '@angular/router'; import { SessionBackend } from './backend.service'; import { HelperService } from 'src/app/shared/services/helper.service'; import { AccountBackend } from '../../account/services/backend.service'; import { ScoresBackend } from '../../scores/services/backend.service'; @Injectable({ providedIn: 'root' }) export class SessionFormService { private form: BehaviorSubject<FormGroup | undefined> = new BehaviorSubject(undefined); form$: Observable<FormGroup> = this.form.asObservable(); builder: FormBuilder = new FormBuilder; private cDate = new FormControl("", { updateOn: "blur", validators: [ Validators.required, // Validators.pattern("(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)") ] }); private cTime = new FormControl("", { updateOn: "blur", validators: [ Validators.required, // Validators.pattern("((1[0-2]|0?[1-9]):([0-5][0-9]) ?([AaPp][Mm]))") ] }); private cTerm = new FormControl("", [ Validators.required, Validators.minLength(2), Validators.maxLength(128) ]); constructor( private helper: HelperService, private session_: SessionBackend, private router: Router) { // Get Data & Populate this.session_.detail$.subscribe((s) => { this.setForm(s); }); } Setup(type) { var form = this.builder.group({}); switch (type) { case "create": form.addControl("date", this.cDate); form.addControl("time", this.cTime); break; case "edit": form.addControl("date", this.cDate); form.addControl("time", this.cTime); break; case "search": form.addControl("", this.cTerm); break; } // Push Initial Form this.form.next(form); } resetForm(): void { if (this.form.value != undefined) { this.form.value.get("date").reset(); this.form.value.get("time").reset(); } } setForm(values): void { // Date/Time if (values.starts_on != undefined) { this.setDate(values.starts_on); } } setDate(date: Date): void { var date = new Date(date); this.form.value.get("date").setValue(date); this.form.value.get("time").setValue(date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', hour12: true }).replace(":00 ", " ")); } /* TODO: FormControl Validators */ validateDate(): void { this.form.value.get("date").updateValueAndValidity(); this.form.value.get("time").updateValueAndValidity(); } } <file_sep>/src/assets/api_new/shared/email.php <?php class Email { public $headers; public $from; public $to; public $CC; public $BCC; public $subject; public $URL; public function __construct() { // Set Headers; $this->headers = "MIME-Version: 1.0" . "\r\n"; $this->headers .= "Content-type:text/html;charset=UTF-8" . "\r\n"; // Set URL For Calls // $this->URL = "https://www.disc-golf.center"; // $this->URL = "https://www.brandonslotty.com/disc"; $this->URL = "http://localhost:4200"; } // Generic Functions public function setFrom($value): void { // Store $this->from = $value; // Set Headers $this->headers .= "From: <" . $this->from . ">\r\n"; } public function setRecipients($value): void { $this->to = $value; } public function setSubject($value): void { $this->subject = $value; } public function setBody($html): void { $this->body = $html; } public function sendEmail(): bool { if (mail($this->to, $this->subject, $this->body, $this->headers)) { return true; } else { return false; } } // Templates public function formatVerificationEmail($email, $token): void { // From $this->setFrom("<EMAIL>"); // To $this->setRecipients($email); // Subject $this->setSubject("DGC Account Verification"); // Body $message = "<html><body style='color: rgb(80,100,80) !IMPORTANT;'>"; $message .= "<h1>BS Disc</h1><h3>Verify Your Account</h3>"; $message .= "<p>Click <a href='" . $this->URL . "/account/verify/" . $token . "'>Here</a> "; $message .= "to verify your account. <br><br>If you did not initiate this request, ignore this message.</p>"; $message .= "<p>If you are unable to click the link, copy this into your address bar: " . $this->URL . "/account/verify/" . $token . ""; $message .= "</body></html>"; $this->setBody($message); } public function formatPasswordResetEmail($email, $token): void { // From $this->setFrom("<EMAIL>"); // To $this->setRecipients($email); // Subject $this->setSubject("DGC Password Reset"); // Body $message = "<html stayle='color: rgb(80,100,80) !IMPORTANT;'><body>"; $message .= "<h1>BS Disc</h1><h3>Verify Your Account</h3>"; $message .= "<p>Click <a href='" . $this->URL . "/account/forgot/" . $token . "'>Here</a> "; $message .= "to reset your password. <br><br>If you did not initiate this request, ignore this message.</p>"; $message .= "<p>If you are unable to click the link, copy this into your address bar: " . $this->URL . "/account/verify/" . $token . ""; $message .= "</body></html>"; $this->setBody($message); } } <file_sep>/src/assets/api_new/shared/payload.php <?php class Payload { public $status; public $msg; public $data; public function __construct($status = "error", $msg = null) { $this->status = $status; $this->msg = $msg; } /** * @param $str: String; Descriptive Text to inform the user */ public function setMessage($str) { $this->status = $str; } /** * @param $str: String; success | error | pending */ public function setStatus($str) { $this->msg = $str; } /** * @param $array: Array<SQL Server Response>; */ public function setData($array) { $this->data = $array; } /** * @return AssocArray of Payload. */ public function getPayload() { $payload = array( "status" => $this->status, "msg" => $this->msg, "data" => $this->data ); return $payload; } } <file_sep>/src/assets/api/courses/list.php <?php session_start(); header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS'); header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token, Authorization, X-Requested-With'); header("Access-Control-Allow-Credentials: true"); header('Access-Control-Max-Age: 1000'); header('Content-Type: application/json,text/plain'); // Load Basic Functions :: For IP Grab require ($_SERVER['DOCUMENT_ROOT'] . '/api/disc/functions.php'); require ($_SERVER['DOCUMENT_ROOT'] . '/api/disc/sql.php'); $sql = new SQL; $payload = json_decode(file_get_contents('php://input'), TRUE); $section = $payload['sort']; $query = ""; switch ($section) { case "pop": $query = "SELECT * FROM `Courses` AS `c` JOIN `Flags` AS `f` ON `c`.`ID`=`f`.`Account ID` WHERE `f`.`key`='CourseViews' ORDER BY `f`.Value*1 DESC LIMIT 50;"; break; case "asc": $query = "SELECT * FROM `Courses` ORDER BY `Name` ASC LIMIT 50;"; break; case "desc": $query = "SELECT * FROM `Courses` ORDER BY `Name` DESC LIMIT 50;"; break; case "near": break; default: $query = "SELECT * FROM `Courses` ORDER BY `Name` ASC LIMIT 0;"; break; } // PDO SELECT if ($query != "") { // Set Values $values = array(); $data = $sql->Query($query, $values); if (count($data) == 0) { $return = array( "status" => "error", "message" => "No Courses Found." ); } else { $payload = []; foreach($data as $k => $o) { $payload[] = array( "id" => $o['ID'], "locationKey" => $o['LocationKey'], "parkName" => $o['ParkName'], "name" => $o['Name'], "img" => $o['IMGPath'], "city" => $o['City'], "state" => $o['State'], "zip" => $o['Zip'], "latitude" => $o['Latitude'], "longitude" => $o['Longitude'], "difficulty" => $o['Difficulty'], "holeCount" => $o['HoleCount'] ); } $return = array( "status" => "success", "data" => array("courses" => $payload), "debug" => $data ); } } printf(json_encode($return)); /* Data Model export class Course { constructor( public id: string, public name?: string, public park?: string, public difficulty?: string, public holes?: string, public img?: string, public address?: Address, ){} } export class Address { constructor( public city: string, public state: string, public zip: string, public lat?: string, public lng?: string, public address?: string, ){} } */ ?><file_sep>/src/app/modules/scores/dialogs/score-settings/score-settings.component.ts import { Component, OnInit, Inject } from '@angular/core'; import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material'; import { FormGroup, FormBuilder, Validators } from '@angular/forms'; @Component({ selector: 'score-settings', templateUrl: './score-settings.component.html', styleUrls: ['./score-settings.component.scss'] }) export class ScoreSettingsComponent implements OnInit { form: FormGroup; constructor( private dialogRef: MatDialogRef<ScoreSettingsComponent>, @Inject(MAT_DIALOG_DATA) private data, private builder: FormBuilder ) { } ngOnInit() { this.form = this.builder.group({ handicap: [this.data.handicap || "", [ Validators.required, Validators.pattern("[\-0-9]+") ]] }); console.log("data: ", this.data); } close(bool) { this.dialogRef.close(bool); } formCheck(){ if (this.form.valid && this.form.dirty && !this.form.disabled){ return true; } else { return false; } } save() { if (this.form.valid && this.form.dirty && !this.form.disabled) { this.data.handicap = this.form.get('handicap').value; this.dialogRef.close(true); } } } <file_sep>/src/app/modules/scores/components/score-list-item/score-list-item.component.ts import { Component, OnInit, Input } from '@angular/core'; import { MatDialog } from '@angular/material'; import { ScoreSettingsComponent } from '../../dialogs/score-settings/score-settings.component'; import { flyInPanelRow } from 'src/app/animations'; import { SessionBackend } from 'src/app/modules/sessions/services/backend.service'; import { Score } from 'src/app/shared/types'; import { ScoresBackend } from '../../services/backend.service'; @Component({ selector: 'score-list-item', templateUrl: './score-list-item.component.html', styleUrls: ['./score-list-item.component.scss'], animations: [flyInPanelRow] }) export class ScoreListItemComponent implements OnInit { @Input() mode: string[] = ["full"]; @Input() score: Score; private selectorCheckbox: boolean; constructor( private dialog: MatDialog, private _sessions: SessionBackend, private _scores: ScoresBackend, ) { } ngOnInit() { this.selectorCheckbox = this._scores.getScore(this.score); } remove() { this._scores.removeScore(this.score); } toggleScore($event, score) { if ($event.checked == true) { this._scores.addScore(score); } else { this._scores.removeScore(score); } } openSettings() { this.dialog.open(ScoreSettingsComponent, { data: this.score, }) } } <file_sep>/src/app/modules/courses/services/course-form.service.ts import { Injectable } from '@angular/core'; import { BehaviorSubject, Observable } from 'rxjs'; import { FormGroup, FormBuilder, FormControl, Validators } from '@angular/forms'; import { CourseBackend } from './backend.service'; import { Router } from '@angular/router'; import { FeedbackService } from '../../../shared/modules/feedback/services/feedback.service'; import { Course, ServerPayload } from 'src/app/shared/types'; import { HelperService } from 'src/app/shared/services/helper.service'; @Injectable({ providedIn: 'root' }) export class CourseFormService { private form: BehaviorSubject<FormGroup | undefined> = new BehaviorSubject(undefined); form$: Observable<FormGroup> = this.form.asObservable(); builder: FormBuilder = new FormBuilder; // Form Field Control Setup; private cParkName = new FormControl("", [ Validators.required, Validators.minLength(2), Validators.maxLength(128) ]); private cCity = new FormControl("", [ Validators.required, Validators.minLength(2), Validators.maxLength(60) ]); private cState = new FormControl("", [ Validators.required, Validators.minLength(2), Validators.maxLength(50) ]); private cZip = new FormControl("", [ Validators.required, Validators.minLength(5), Validators.maxLength(10) ]); private cLat = new FormControl("", [ /* Validators.required, */ Validators.minLength(9), Validators.maxLength(9) ]); private cLng = new FormControl("", [ /* Validators.required, */ Validators.minLength(9), Validators.maxLength(9) ]); private cTerm = new FormControl("", [ Validators.required, Validators.minLength(2) ]); constructor( private courseService: CourseBackend, private router: Router, private feed: FeedbackService, private helper: HelperService, ) { } Setup(type) { var form = this.builder.group({}); switch (type) { case "create": form.addControl("parkName", this.cParkName); form.addControl("city", this.cCity); form.addControl("state", this.cState); form.addControl("zip", this.cZip); form.addControl("lat", this.cLat); form.addControl("lng", this.cLng); break; case "edit": form.addControl("parkName", this.cParkName); form.addControl("city", this.cCity); form.addControl("state", this.cState); form.addControl("zip", this.cZip); form.addControl("lat", this.cLat); form.addControl("lng", this.cLng); break; case "search": form.addControl('search', this.cTerm); // Listen to Input changes to trigger loading and search form.get("search").valueChanges.pipe(this.helper.pipe).subscribe((s) => { if (form.valid) { this.feed.stopLoading("courseSearch"); this.courseService.getSearch(s as string); } }); // Turn off Loader when Results populate this.courseService.search$.subscribe((s) => { this.feed.stopLoading("register"); }); break; } this.form.next(form); } /** * @returns boolean * Form needs to be Valid, Touched, and not Disabled. */ ReadyForSubmission(): boolean { if (this.form.value.valid && this.form.value.dirty && !this.form.value.disabled) { return true; } else { return false; } } resetForm(): void { this.form.value.get("parkName").reset(); this.form.value.get("city").reset(); this.form.value.get("state").reset(); this.form.value.get("zip").reset(); this.form.value.get("lat").reset(); this.form.value.get("lng").reset(); } setForm(values): void { this.form.value.get("parkName").setValue(values.parkName); this.form.value.get("city").setValue(values.city); this.form.value.get("state").setValue(values.state); this.form.value.get("zip").setValue(values.zip); this.form.value.get("lat").setValue(values.lat); this.form.value.get("lng").setValue(values.lng); this.form.value.markAsDirty(); } resetSearch() { this.form.value.get("search").reset(); } SubmitCreation() { console.log("SubmitCreation.form: ", this.form); var course = new Course(); course.park_name = this.form.value.value.parkName; course.city = this.form.value.value.city; course.state = this.form.value.value.state; course.zip = this.form.value.value.zip; course.latitude = this.form.value.value.lat; course.longitude = this.form.value.value.lng; this.courseService.create(course).subscribe((res: ServerPayload[]) => { console.log("course.form.create.res: ", res); if (this.helper.rCheck(res)) { var createdCourse = this.helper.rGetData(res); this.router.navigate(["courses", createdCourse[0]['id']]); } else { console.log("Nearby?"); // Fix this.courseService.setCourseList(this.helper.rGetData(res) as Course[]); this.router.navigate(["courses/nearby"]); } }); } } <file_sep>/src/app/shared/modules/charts/charts.module.ts import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { LineComponent } from 'src/app/shared/modules/charts/line/line.component'; import { ScoreboardComponent } from './scoreboard/scoreboard.component'; import { GoogleChartsModule } from 'angular-google-charts'; import { MaterialModule } from '../material/material.module'; import { LineSettingsComponent } from './line-settings/line-settings.component'; @NgModule({ imports: [ CommonModule, GoogleChartsModule, MaterialModule, ], declarations: [ LineComponent, ScoreboardComponent, LineSettingsComponent, ], exports: [ LineComponent, ], entryComponents: [LineSettingsComponent] }) export class ChartsModule { } <file_sep>/src/assets/api/account/verify.php <?php session_start(); header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS'); header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token, Authorization, X-Requested-With'); header("Access-Control-Allow-Credentials: true"); header('Access-Control-Max-Age: 1000'); header('Content-Type: application/json,text/plain'); // Load Basic Functions :: For IP Grab require ($_SERVER['DOCUMENT_ROOT'] . '/api/disc/sql.php'); $sql = new SQL; // Get Values From HTTP $payload = json_decode(file_get_contents('php://input'), TRUE); $return = array(); // Get Account ID from Verification Request $query = "SELECT * FROM `Flags` WHERE `Value`=:value AND `Key`='AccountVerification' LIMIT 1"; // Set Values $values = array(":value" => $payload["token"]); $data = $sql->Query($query, $values); if (count($data) == 0) { $return = array( "status"=>"error", "msg"=>"Verification not found", "data"=>$data ); } else { // Store Account ID $accountID = $data[0]["Account ID"]; // Get Account Information for Return Login $query = "SELECT * FROM `Accounts` WHERE `ID`=:accountid"; // Set Values $values = array( ":accountid" => $accountID, ); $data = $sql->Query($query, $values); if (!is_array($data)) { $return = array("status"=>"error", "msg"=>"Unable to get user information"); } else { // Set Account for Return $user = $data[0]; $sid = session_id(); // Insert Account Flags $query = "INSERT INTO `Flags` (`ID`, `Account ID`, `Key`, `Value`) VALUES (:id, :accountid, :key, :value);"; $values = array(); // Insert IP for Account Verification $values[] = array( ":id" => date("U") . rand(100000, 999999), ":accountid" => $accountID, ":key" => 'PreviousIP', ":value" => hash("sha512", $_SERVER["REMOTE_ADDR"]) ); // Insert Validation Token for Persistant Account $values[] = array( ":id" => date("U") . rand(100000, 999999), ":accountid" => $accountID, ":key" => 'ValidationToken', ":value" => $sid ); /* // Insert Login Time for Account Timeout $values[] = array( ":id" => date("U") . rand(100000, 999999), ":accountid" => $accountID, ":key" => 'LastLogon', ":value" => date("U") ); */ // Insert Each Flag $insertFail = false; foreach ($values as $array) { $data = $sql->Query($query, $array); if (!is_array($data)) { $insertFail = true; } } if ($insertFail) { $return = array("status"=>"error", "msg"=>"Unable to store account properties", "values"=>json_encode($values)); } else { // Delete Previous Verification Requests $query = "DELETE FROM `Flags` WHERE `Account ID`=:id AND `Key`='AccountVerification';"; // Set Values $values = array(":id" => $accountID); $data = $sql->Query($query, $values); if (!is_array($data)) { $return = array("status"=>"error", "msg"=>"Unable to remove account verification lock"); } else { // If Solo League Doesnt Exist; Create $query = "SELECT * FROM `Leagues` AS `l` JOIN `Permissions` AS `p` ON `l`.`ID`=`p`.`LeagueID` WHERE `p`.`UserID`=:accountid AND `l`.`Visibility`='solo' LIMIT 1"; // Set Values $values = array(":accountid" => $accountID); $data = $sql->Query($query, $values); if (count($data) == 0) { // Create Private League if not found $query = "INSERT INTO `Leagues` (`ID`, `Name`, `Visibility`) VALUES (:id, 'Your Solo League', 'solo');"; $leagueID = date("U") . rand(100000, 999999); // Set Values $values = array( ":id" => $leagueID ); $data = $sql->Query($query, $values); if (!is_array($data)) { $return = array("status"=>"error", "msg"=>"Unable to create private league"); } else { // Insert Into Permissions $query = "INSERT INTO `Permissions` (`ID`, `LeagueID`, `UserID`, `Level`, `Status`) VALUES (:id, :leagueid, :accountid, 'creator', 'approved');"; // Set Values $values = array( ":id" => date("U") . rand(100000, 999999), ":leagueid" => $leagueID, ":accountid" => $accountID ); $data = $sql->Query($query, $values); if (!is_array($data)) { $return = array("status"=>"error", "msg"=>"Unable to set permissions for private league"); } else { $return = array( "status"=>"success", "msg"=>"Account verified!", "data" => array( "user" => array( "id" => $user["ID"], "first" => $user["First"], "last" => $user["Last"], "email" => $user["Email"] ) ) ); } } } else { $return = array( "status"=>"success", "msg"=>"Account verified!", "data" => array( "user" => array( "id" => $user["ID"], "first" => $user["First"], "last" => $user["Last"], "email" => $user["Email"] ) ) ); } } } } } printf(json_encode($return)); ?> <file_sep>/src/assets/api/courses/courses.php <?php header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS'); header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token, Authorization, X-Requested-With'); header("Access-Control-Allow-Credentials: true"); header('Access-Control-Max-Age: 1000'); header('Content-Type: application/json,text/plain'); /* Vars */ $method = $_SERVER['REQUEST_METHOD']; $return = []; // SQL Resource require ($_SERVER['DOCUMENT_ROOT'] . '/disc/lib/sql.php'); switch ($method) { case "GET": break; case "POST": break; case "PUT": break; case "DELETE": break; default: printf ("Unknown request type"); break; } printf (json_encode( $return )) ; ?><file_sep>/src/app/modules/sessions/dialogs/select-format/select-format.component.ts import { Component, OnInit, Input, Inject } from '@angular/core'; import { flyIn } from 'src/app/animations'; import { SessionBackend } from '../../services/backend.service'; import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material'; import { skip } from 'rxjs/operators'; import { HelperService } from 'src/app/shared/services/helper.service'; @Component({ selector: 'app-select-format', templateUrl: './select-format.component.html', styleUrls: ['./select-format.component.scss'], animations: [flyIn], }) export class SelectFormatComponent implements OnInit { constructor( private dialogRef: MatDialogRef<SelectFormatComponent>, @Inject(MAT_DIALOG_DATA) private data, private _sessions: SessionBackend, private _helper: HelperService, ) { } ngOnInit() { this._sessions.detail$.pipe(skip(1)).subscribe((s)=>{ this.close(); }); } setFormat(format) { this._sessions.setFormat(format); this.close(true); } close(bool = false) { this.dialogRef.close(bool); } } /* */<file_sep>/src/app/pipes/stroke-total.pipe.ts import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'strokeTotal' }) export class StrokeTotalPipe implements PipeTransform { transform(value: any, args?: any): any { // Get Total All Scores if (value.length == 0) { return "Error"; } else { return value.reduce((sum, current) => sum + current); } } } <file_sep>/src/app/app.module.ts import { PipesModule } from './pipes/pipes.module'; import { RouterModule } from '@angular/router'; import { BrowserModule } from '@angular/platform-browser'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; /* Component Features */ import { MaterialModule } from './shared/modules/material/material.module'; /* Sub-Module Imports */ import { NavigationModule } from './navigation.module'; import { AccountModule } from 'src/app/modules/account/account.module'; import { CoursesModule } from 'src/app/modules/courses/courses.module'; import { SessionsModule } from './modules/sessions/sessions.module'; import { PageNotFoundComponent } from './404/page-not-found.component'; import { HomeComponent } from './home/home.component'; /* Dependancies */ import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http'; import { ErrorHandlerInterceptor } from './interceptors/errorHandler.interceptor'; import { FormatterInterceptor } from './interceptors/formatter.interceptor'; import { AuthInterceptor } from './interceptors/auth.interceptor'; @NgModule({ declarations: [ AppComponent, HomeComponent, PageNotFoundComponent, ], imports: [ /* Dependancies */ HttpClientModule, RouterModule, BrowserAnimationsModule, MaterialModule.forRoot(), /* Sub Modules / Routes */ CoursesModule, SessionsModule, AccountModule, /* Root Route */ NavigationModule, PipesModule, BrowserModule ], exports: [ ], providers: [ { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true } , { provide: HTTP_INTERCEPTORS, useClass: FormatterInterceptor, multi: true } , { provide: HTTP_INTERCEPTORS, useClass: ErrorHandlerInterceptor, multi: true } , ], bootstrap: [AppComponent] }) export class AppModule { } <file_sep>/src/app/modules/sessions/pages/dashboard/dashboard.component.ts import { Component, OnInit } from '@angular/core'; import { SessionBackend } from '../../services/backend.service'; import { take, filter, map } from 'rxjs/operators'; import { FeedbackService } from 'src/app/shared/modules/feedback/services/feedback.service'; import { flyIn } from 'src/app/animations'; import { Observable } from 'rxjs'; import { Session } from 'src/app/shared/types'; @Component({ selector: 'app-dashboard', templateUrl: './dashboard.component.html', styleUrls: ['./dashboard.component.scss'], animations: [flyIn] }) export class DashboardComponent implements OnInit { upcoming: Observable<Session[]> = this._sessions.upcoming$; recient: Observable<Session[]> = this._sessions.recient$; constructor( private _sessions: SessionBackend, private _feed: FeedbackService, ) { } ngOnInit() { this._feed.startLoading("session-upcoming"); this._feed.startLoading("session-recient"); // Get List this._sessions.listCurrentSessions(); } } <file_sep>/src/assets/api/functions.php <?php function getRealIpAddr() { return $_SERVER["REMOTE_ADDR"]; // Change based on Device Type } ?><file_sep>/src/app/guards/auth.service.ts import { Injectable } from '@angular/core'; import { Router, CanActivate, RouterStateSnapshot, ActivatedRouteSnapshot } from '@angular/router'; import { AccountBackend } from 'src/app/modules/account/services/backend.service'; @Injectable({ providedIn: 'root' }) export class AuthGuard implements CanActivate { constructor( private account: AccountBackend, private router: Router, ) { } /** * canActivate(): Check if User Exists * 0 -> Store redirect; goto login; return false; * 1 -> return true */ canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot,): boolean { // If user is set; Allow console.log ("guard.account.user: ", this.account.user); if (this.account.user && this.account.user.email ) { return true } /* else if (this.account.user && this.account.user.token){ console.log ("token found:", this.account.user.token); } */ else { let url: string = state.url; // Store Url for redirect this.account.redirectUrl = url; // console.log ("auth.guard.url: ", this.account.redirectUrl); // Navigate to the login page this.router.navigate(['/account/login']); // Deny return false; } } auth() { } } <file_sep>/src/app/modules/account/components/set-password/set-password.component.ts import { Component, OnInit } from '@angular/core'; import { FeedbackService } from 'src/app/shared/modules/feedback/services/feedback.service'; import { ServerPayload } from 'src/app/app.component'; import { FormGroup } from '@angular/forms'; import { AccountFormService } from '../../services/account-form.service'; import { AccountBackend } from '../../services/backend.service'; import { ActivatedRoute } from '@angular/router'; @Component({ selector: 'app-set-password', templateUrl: './set-password.component.html', styleUrls: ['./set-password.component.css'], animations: [] }) export class SetPasswordComponent implements OnInit { private form: FormGroup = new FormGroup({}); constructor( private feed: FeedbackService, private accountForm: AccountFormService, private route: ActivatedRoute, ) { } ngOnInit() { let token = this.route.snapshot.paramMap.get('token'); this.accountForm.VerifyForgotToken(token); this.accountForm.form$.subscribe((t)=>{ this.form = t; this.feed.stopLoading("verify"); }); } onFormSubmit() { this.accountForm.SubmitSet(); } } <file_sep>/src/assets/api/permissions/list.php <?php session_start(); header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS'); header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token, Authorization, X-Requested-With'); header("Access-Control-Allow-Credentials: true"); header('Access-Control-Max-Age: 1000'); header('Content-Type: application/json,text/plain'); // Load Basic Functions :: For IP Grab require ($_SERVER['DOCUMENT_ROOT'] . '/api/disc/functions.php'); require ($_SERVER['DOCUMENT_ROOT'] . '/api/disc/sql.php'); $sql = new SQL; $payload = json_decode(file_get_contents('php://input'), TRUE); $return = array(); // Get List of Leagues for User $query = "SELECT `p`.`ID` AS `P.ID`, `p`.`Level` AS `P.Level`, `p`.`Status` AS `P.Status`, `l`.`ID` AS `L.ID`, `l`.`Name` AS `L.Name`, `l`.`Visibility` AS `L.Visibility`, `l`.`Description` AS `L.Description`, `l`.`Restrictions` AS `L.Restrictions`, `a`.`ID` AS `A.ID`, `a`.`First` AS `A.First`, `a`.`Last` AS `A.Last`, `a`.`Email` AS `A.Email` FROM `Permissions` AS `p` JOIN `Leagues` AS `l` ON `p`.`LeagueID`=`l`.`ID` JOIN `Accounts` AS `a` ON `a`.`ID`=`p`.`UserID` WHERE `l`.`ID`=:leagueid AND `p`.`Status` <> 'rejected' ORDER BY `p`.`Level`, `p`.`Status`;"; // Set Values $values = array(":leagueid"=>strtolower($payload['league']['id'])); $data = $sql->Query($query, $values); if (count($data) == 0) { $return = array("status"=>"error", "msg"=>"No Permissions Found"); } else { $payload = array(); foreach ($data as $k => $o) { $payload[] = array( "id" => $o['P.ID'], "level" => $o['P.Level'], "status" => $o['P.Status'], "league" => array( "id" => $o['L.ID'], "name" => $o['L.Name'], "visibility" => $o['L.Visibility'], "description" => $o['L.Description'], "restrictions" => $o['L.Restrictions'] ), "user" => array( "id" => $o['A.ID'], "first" => $o['A.First'], "last" => $o['A.Last'], "email" => $o['A.Email'] ) ); } $return = array("status"=>"success", "data"=>$payload); } printf(json_encode($return)); /* Data Model export class Permissions { constructor( public id: string, public league: League, public user: User, public level: string, public status: string, ) {} } export class League { constructor( public id: string, public name: string, public visibility: string, public description?: string, public restrictions?: string, ) {} } */ ?> <file_sep>/src/assets/api/stats/setPar.php <?php session_start(); header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS'); header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token, Authorization, X-Requested-With'); header("Access-Control-Allow-Credentials: true"); header('Access-Control-Max-Age: 1000'); header('Content-Type: application/json,text/plain'); // Load Basic Functions :: For IP Grab require ($_SERVER['DOCUMENT_ROOT'] . '/api/disc/functions.php'); require ($_SERVER['DOCUMENT_ROOT'] . '/api/disc/sql.php'); $sql = new SQL; $payload = json_decode(file_get_contents('php://input'), TRUE); $return = array(); // Verify Permissions $validUser = $sql->Access($payload["league"], $payload["user"]); if ($validUser["status"] == "error") { $return = array( "status"=>"error", "msg"=>"You do not have sufficent permissions to perform this action" ); } else { $query = "DELETE FROM `Flags` WHERE `Account ID`=:session AND `Key`='SessionParArray' LIMIT 1;"; $values = array( ":session" => $payload["session"]["id"] ); $data = $sql->Query($query, $values); if (!is_array($data)) { $return = array( "status" => "error", "msg" => "Unable to Delete Session, but whyyy", "data" => $data ); } else { $query = "INSERT INTO `Flags` (`ID`, `Account ID`, `Key`, `Value`) VALUES (:id, :session, 'SessionParArray', :par);"; $values = array( ":id" => date("U") . rand(100000, 999999), ":session" => $payload["session"]["id"], ":par" => $payload["par"] ); $data = $sql->Query($query, $values); if (!is_array($data)) { $return = array( "status" => "error", "msg" => "Some errors occured while updating the Par", "data" => $data ); } else { $return = array( "status" => "success", "msg" => "Par Updated", "data" => array() ); } } } printf(json_encode($return)); ?><file_sep>/src/app/modules/account/services/account-form.service.ts import { Injectable } from '@angular/core'; import { FormGroup, FormBuilder, Validators, FormControl } from '@angular/forms'; import { BehaviorSubject, Observable, pipe } from 'rxjs'; import { debounceTime, distinctUntilChanged } from 'rxjs/operators'; import { AccountBackend } from './backend.service'; import { Router } from '@angular/router'; import { ServerPayload } from 'src/app/app.component'; import { Player, Password } from 'src/app/shared/types'; @Injectable({ providedIn: 'root' }) export class AccountFormService { private form: BehaviorSubject<FormGroup | undefined> = new BehaviorSubject(undefined); form$: Observable<FormGroup> = this.form.asObservable(); builder: FormBuilder = new FormBuilder; private passwordPipe = pipe( debounceTime(888), distinctUntilChanged(), ); private searchPipe = pipe( debounceTime(300), distinctUntilChanged(), ) // Fields // First private cFirst = new FormControl("first", [ Validators.required, Validators.minLength(2), Validators.maxLength(128) ]); // Last private cLast = new FormControl("last", [ Validators.required, Validators.minLength(2), Validators.maxLength(128) ]); // Email private cEmail = new FormControl("b", [ Validators.required, Validators.minLength(8), Validators.maxLength(128), Validators.pattern("(.)+@(.)+") ]); // Password private cPass = new FormControl("<PASSWORD>", [ Validators.required, Validators.minLength(8), Validators.maxLength(128) ]); // Old Password private cOldPass = new FormControl("pass_old", [ Validators.required, Validators.minLength(8), Validators.maxLength(128) ]); // Confirm Password private cConfirmPass = new FormControl("<PASSWORD>", [ Validators.required, Validators.minLength(8), Validators.maxLength(128) ]); // Search private cTerm = new FormControl("", [ Validators.required, Validators.minLength(2), Validators.maxLength(128) ]); constructor( private router: Router, private account: AccountBackend, ) { /** * Create form from Type: * Basic Info (First, last, email) * Login (email, current) * Reset Pass (old, current, confirm) */ /** * https://medium.com/@joshblf/dynamic-nested-reactive-forms-in-angular-654c1d4a769a * * All form actions should be migrated to here. * Setup form as a Private Behavior Subject * * Fields should be determined by functions; dynamic add + validatiors * * Each component can view the form as an observable. * * * Submits will be handeled here; * * */ } /** * @param type; register | login | update | reset | set | * */ Setup(type: string) { // Create Form var form = this.builder.group({}); // Add Fields switch (type) { case "register": form.addControl("first", this.cFirst); form.addControl("last", this.cLast); form.addControl("email", this.cEmail); form.addControl("password", <PASSWORD>); form.addControl("conf", this.cConfirmPass); break; case "login": form.addControl("email", this.cEmail); form.addControl("password", this.c<PASSWORD>); break; case "update": form.addControl("first", this.cFirst); form.addControl("last", this.cLast); form.addControl("email", this.cEmail); break; case "reset": form.addControl("old", this.cOldPass); form.addControl("password", this.cPass); form.addControl("conf", this.cConfirmPass); break; case "set": form.addControl("password", this.c<PASSWORD>); form.addControl("conf", this.cConfirmPass); break; case "forgot": form.addControl("email", this.cEmail); break; /* case "search": form.addControl("term", this.cTerm); form.valueChanges.pipe(this.searchPipe).subscribe((v)=>{ this.account.searchUsers(v["term"]).subscribe((p)=>{ }); }); */ default: form.setErrors({ invalid: true }); break; } // Observe Changes for custom errors; form.valueChanges.pipe(this.passwordPipe).subscribe((t) => { // console.log("form.ValueChanges: ", form, t); // Reset Fields upon Update if (t["old"]) { form.get('old').setErrors(null); } if (t["conf"]) { form.get('conf').setErrors(null); } if (t["password"]) { form.get('password').setErrors(null); } if (t["old"] && t["old"] == t["password"]) { form.get("password").setErrors({ same: true }); } else if (t["old"] && t["conf"] && t["old"] == t["conf"]) { form.get("conf").setErrors({ same: true }); } else if (t["conf"] && t["password"] != t["conf"] && (form.get("password").dirty && form.get("conf").dirty)) { form.get("password").setErrors({ match: true }); form.get("conf").setErrors({ match: true }); } else { form.setErrors(null); } }); // Push Form this.form.next(form); } /** * @returns boolean * Form needs to be Valid, Touched, and not Disabled. */ ReadyForSubmission(): boolean { if (this.form.value.valid && this.form.value.dirty && !this.form.value.disabled) { return true; } else { return false; } } SubmitRegistration() { // If form is valid and password matches if (this.ReadyForSubmission()) { // store user var user = new Player(0); user.first_name = this.form.value.get('first').value; user.last_name = this.form.value.get('last').value; user.email = this.form.value.get('email').value; user.password = this.form.value.get('password').value; // send creation request this.account.register(user).subscribe((res) => { if (res.status == "success") { this.router.navigate(["account/login"]); } }); } } SubmitLogin() { if (this.ReadyForSubmission()) { this.form.value.disable(); // Set Data var user = new Player( null, null, null, this.form.value.get('email').value, this.form.value.get('password').value ); // Send Data this.account.login(user).subscribe((res) => { this.form.value.enable(); // Redirect if available; else Goto leagues if (this.account.rCheck(res)) { if (this.account.redirectUrl) { this.router.navigate([this.account.redirectUrl]); } else { this.router.navigate(['/sessions']); } } else { // Polish form for re-submit this.form.value.markAsPristine(); } }); } } SubmitUpdate() { if (this.ReadyForSubmission()) { var p = new Player(this.account.user.id); p.first_name = this.form.value.get('first').value; p.last_name = this.form.value.get('last').value; p.email = this.form.value.get('email').value; this.account.updateUser(p).subscribe((payload: ServerPayload) => { if (this.account.rCheck(payload)) { this.account.user.first_name = p.first_name; this.account.user.last_name = p.last_name; this.account.user.email = p.email; } }); } } SubmitForgot() { if (this.ReadyForSubmission()) { var user = new Player(null); user.email = this.form.value.get('email').value; this.account.forgotPassword(user).subscribe((res) => { // Confirmation Page? // Home Page? }); } } SubmitReset() { if (this.ReadyForSubmission()) { var newPass = new Password(); newPass.current = this.form.value.get('password').value; newPass.confirm = this.form.value.get('conf').value; newPass.old = this.form.value.get('old').value; this.account.user.password = <PASSWORD>; this.account.updatePassword(this.account.user).subscribe((res) => { this.account.user.password = <PASSWORD>; }); } } VerifyForgotToken(token) { this.account.verifyToken(token).subscribe((res: ServerPayload) => { console.log("res", res); if (this.account.rCheck(res)) { this.Setup("set"); } else { this.router.navigate(["account/forgot"]); } }); } SubmitSet() { if (this.ReadyForSubmission()) { var newPass = new Password(); newPass.current = this.form.value.get('password').value; newPass.confirm = this.form.value.get('conf').value; this.account.user.password = <PASSWORD>; this.account.setPassword(this.account.user).subscribe((res) => { this.account.user.password = <PASSWORD>; if (this.account.rCheck(res)) { this.router.navigate(["account"]); } else { } }); } } } <file_sep>/src/assets/api/sql.php <?php class SQL { protected $host; protected $db; protected $user; protected $pass; protected $charset; protected $dsn; public $stmt; public $pdo; public $data; // Init public function __construct() { $this->host = 'brandonslottycom.fatcowmysql.com'; $this->db = 'discing_1'; $this->user = 'dgadmin_1'; $this->pass = '<PASSWORD>'; $this->charset = 'utf8mb4'; $this->dsn = "mysql:host=". $this->host . ";dbname=". $this->db .";charset=". $this->charset .";"; $this->pdo = new PDO($this->dsn, $this->user, $this->pass); } // Run Query and Return Data public function Query($q, $v) { if (!$this->stmt = $this->pdo->prepare($q)){ return "Error with Query"; } else if (!$this->stmt->execute($v)) { return "Error Executing [". $this->stmt->errorCode()."]: ". $this->stmt->errorInfo(); } else { return $this->stmt->fetchAll(PDO::FETCH_ASSOC); } } public function Access($league, $user) { // Verify Permissions $validUser = false; $query = "SELECT `p`.`ID` AS `P.ID`, `p`.`Level` AS `P.Level`, `p`.`Status` AS `P.Status`, `l`.`ID` AS `L.ID`, `a`.`ID` AS `A.ID`, `a`.`First` AS `A.First`, `a`.`Last` AS `A.Last`, `a`.`Email` AS `A.Email` FROM `Permissions` AS `p` JOIN `Leagues` AS `l` ON `p`.`LeagueID`=`l`.`ID` JOIN `Accounts` AS `a` ON `a`.`ID`=`p`.`UserID` WHERE `l`.`ID`=:leagueid AND `p`.`Status` <> 'rejected' ORDER BY `p`.`Level`, `p`.`Status`;"; // Set Values $values = array( ":leagueid" => $league["id"] ); $data = $this->Query($query, $values); if (count($data) == 0) { $return = array( "status"=>"error", "msg"=>"No Permissions Found" ); } else { foreach ($data as $k => $o) { if ($o['A.ID'] == $user["id"] && ($o["P.Level"] == "moderator" || $o["P.Level"] == "creator")) { $validUser = true; } } } if ($validUser != true) { $return = array( "status"=>"error", "msg"=>"You do not have sufficent permissions to perform this action" ); } else { $return = array( "status"=>"success", "msg"=>"Valid User" ); } return $return; } } /* Cascade Delete SQL Example: ALTER TABLE posts ADD CONSTRAINT fk_cat FOREIGN KEY (category_id) REFERENCES categories(id) ON DELETE CASCADE ON UPDATE CASCADE; View Keys: SELECT TABLE_NAME,COLUMN_NAME,CONSTRAINT_NAME, REFERENCED_TABLE_NAME,REFERENCED_COLUMN_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE REFERENCED_TABLE_SCHEMA = 'discing_1' AND REFERENCED_TABLE_NAME = '<table>'; Remove Key ALTER TABLE `table_name` DROP FOREIGN KEY `id_name_fk`; Stats_ibfk_2 */ ?> <file_sep>/src/assets/api_new/controllers/favorites.php <?php // Session & Header Init require_once($_SERVER['DOCUMENT_ROOT'] . '/sites/disc/api/shared/headers.php'); // Convert HTTP Vars $payload = json_decode(file_get_contents('php://input'), TRUE); // Init Return $return = array(); // Debug /** * Future feature, do not return each step in DB; only return last; Can flag with this later on */ $devMode = true; // DB require_once($_SERVER['DOCUMENT_ROOT'] . '/sites/disc/api/shared/sql.php'); $database = new DB(); // Course require_once($_SERVER['DOCUMENT_ROOT'] . '/sites/disc/api/classes/Favorites.php'); $favorite = new Favorite($database); // Course require_once($_SERVER['DOCUMENT_ROOT'] . '/sites/disc/api/classes/players.php'); $player = new Player($database); switch ($payload['action']) { case "create": // Verify Table/ID Combo Doesnt Exist $favList = $favorite->userList($player); if ($favList["status"] == "success") { $exists = false; // Loop to Check Dupes foreach ($favList["results"] as $key => $ar) { if ( $ar["related_table"] == $payload["favorite"]["related_table"] && $ar["related_id"] == $payload["favorite"]["related_id"] ) { $exists = true; } } // Write Fav if ($exists == false) { $return[] = $favorite->create($payload["favorite"], $user); } } break; case "delete": $return[] = $favorite->delete($payload["favorite"]); break; default: $return[] = array( "status" => "error", "msg" => "Unknown Action", ); break; } printf(json_encode($return)); <file_sep>/src/app/shared/modules/feedback/components/loader/loader.component.ts import { Component, OnInit, Input } from '@angular/core'; import { FeedbackService } from '../../services/feedback.service'; import { flyInPanelRow, fall } from 'src/app/animations'; @Component({ selector: 'loader', templateUrl: './loader.component.html', styleUrls: ['./loader.component.scss'], animations: [flyInPanelRow, fall], }) export class LoaderComponent implements OnInit { @Input() small:boolean = false; diameter: number = 100; strokeWidth: number = 5; constructor( public feed: FeedbackService, ) { } ngOnInit() { if (this.small) { this.diameter = 36; this.strokeWidth = 5; } } } <file_sep>/src/app/modules/scores/dialogs/team-settings/team-settings.component.ts import { Component, OnInit, Inject } from '@angular/core'; import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material'; import { FormGroup, FormBuilder, Validators } from '@angular/forms'; import { SessionFormService } from 'src/app/modules/sessions/services/form.service'; import { ScoresBackend } from '../../services/backend.service'; @Component({ selector: 'team-settings', templateUrl: './team-settings.component.html', styleUrls: ['./team-settings.component.scss'] }) export class TeamSettingsComponent implements OnInit { form: FormGroup colorList = this._scores.teamColorList; constructor( private dialogRef: MatDialogRef<TeamSettingsComponent>, @Inject(MAT_DIALOG_DATA) private data, private builder: FormBuilder, private _scores: ScoresBackend, ) { } ngOnInit() { this.form = this.builder.group({ name: [this.data.name, [Validators.minLength(1)]] }); } close(bool) { this.dialogRef.close(bool); } formCheck() { if (this.form.valid && this.form.dirty && !this.form.disabled) { return true; } else { return false; } } save() { if (this.form.valid && this.form.dirty && !this.form.disabled) { this.data.name = this.form.get('name').value; this.dialogRef.close(true); } } pickColor(color) { if (color.available && color !== this.data.color) { this.form.markAsDirty(); // Update Availablity this._scores.teamColorList.forEach((c) => { // Restrict new if (c.name == color.name) { c.available = false; } // Allow Old if (c.name == this.data.color.name) { c.available = true; } }); // Update roster with new team Info; this._scores.updateRosterTeam(this.data.color, color); // Update Team Color this.data.color = color; } } }<file_sep>/src/app/guards/perm.service.ts import { Router, CanActivate, RouterStateSnapshot, ActivatedRouteSnapshot } from '@angular/router'; import { Injectable } from '@angular/core'; import { AccountBackend } from './../modules/account/services/backend.service'; @Injectable({ providedIn: 'root' }) export class PermGuard { constructor( private account: AccountBackend, private router: Router, ) { } /* Get Users Permission level on Navs Store as account.user.access[LEAGUE ID] = LEVEL If User is >= moderator return true, else false */ canActivate(): boolean { /* Steps Verify User exists; -> AuthGuard Verify User has access to league; -> LeagueGuard Verify User has correct permission levels; -> PermGuard if (!this.account.user && !this.leagues.league) { this.router.navigate(["/account/login"]); return false } else if (!this.account.user['access']){ this.router.navigate(["/leagues", this.leagues.league.id, "join"]); return false; } else if ( this.account.user['access'][this.leagues.league.id] != "moderator" && this.account.user['access'][this.leagues.league.id] != "creator"){ return false } else { return true; } */ return true; } }<file_sep>/src/assets/api/account/login.php <?php session_start(); header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS'); header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token, Authorization, X-Requested-With'); header("Access-Control-Allow-Credentials: true"); header('Access-Control-Max-Age: 1000'); header('Content-Type: application/json,text/plain'); $URL = "http://www.brandonslotty.com/disc/"; //$URL = "http://localhost:4200/"; // Convert HTTP Payload to PHP Array $payload = json_decode(file_get_contents('php://input'), TRUE); // Setup Feedback $return = array(); // Verify Data Set Properly if ($payload["user"]["email"] == null) { $return = array( "status" => "error", "msg" => "Improper Data", "data" => null ); } else { // Load Basic Functions :: For IP Grab require ($_SERVER['DOCUMENT_ROOT'] . '/api/disc/functions.php'); require ($_SERVER['DOCUMENT_ROOT'] . '/api/disc/sql.php'); // Query System To Check if Email Exists $query = "SELECT * FROM `Accounts` WHERE `Email`=:email LIMIT 1"; // Set Values $values = array(":email"=>strtolower($payload["user"]["email"])); $sql = new SQL; $data = $sql->Query($query, $values); if (count($data) == 0) { $return = array( "status" =>"error", "msg" =>"Account not found", "data" => null ); } else { // Store User Information for Later Use $user = $data[0]; // Verify if endpoint is trusted $trusted = false; $valid = true; $hash = hash("sha512", getRealIpAddr()); // Remove IP Validation for now $trusted = true; $valid = true; /* Remove IP Validation for now // Query System For Account Flags $query = "SELECT * FROM `Flags` WHERE `Account ID`=:account;"; // Values $values = array(":account" => $user["ID"]); $data = $sql->Query($query, $values); foreach ($data as $ka => $a) { // Compare IP to Trusted List if ($a["Value"] == $hash && $a["Key"] == "PreviousIP") { $trusted = true; } // Check Validation Token Flag if ($a["Value"] == $payload["user"]["validationToken"] && $a["Key"] == "ValidationToken"){ $trusted = true; } // Check for pending verification if ($a["Key"] == "AccountVerification") { $valid = false; } } */ // If Validation already pending if ($valid == false) { $return = array( "status" => "error", "msg" => "Account needs to be verified. Please check your email for the verification link.", "data" => null ); // If endpoint IP is not trusted -> validate } else if ($trusted == false){ // Set Token $hash = hash("sha512", date("YmdHis:U") . getRealIpAddr() . "1337" . $user["ID"]); // Set Flag Insert Query $query = "INSERT INTO `Flags` (`ID`, `Account ID`, `Key`, `Value`) VALUES (:id, :account, 'AccountVerification', :value);"; // Set Values $values = array( ":id" => date("U") . rand(100000, 999999), ":account" => $user["ID"], ":value" => $hash ); $data = $sql->Query($query, $values); if (!is_array($data)) { $return = array( "status" => "error", "msg" => "Unable to store validation token", "data" => null ); } else { // Send Email $to = $user["Email"]; $subject = "DGC Account Verification"; $message = "<html style='color: rgb(80,100,80) !IMPORTANT;'><body>"; $message .= "<h1>DGC</h1><h3>Verify Your Account</h3>"; $message .= "<p>Click <a href='".$URL."account/verify/".$hash."/'>Here</a> "; $message .= "to verify your account. If you did not initiate this request, ignore this message.</p>"; $message .= "</body></html>"; // Always set content-type when sending HTML email $headers = "MIME-Version: 1.0" . "\r\n"; $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n"; // More headers $headers .= 'From: <<EMAIL>>' . "\r\n"; if (mail($to, $subject, $message, $headers)){ $return = array( "status" =>"error", "msg" =>"Account needs to be verified. Please check your email for the verification link.", "data" => null ); } else { $return = array( "status" => "error", "msg" => "Unable to send verification email", "data" => null, ); } } // Endpoint trusted } else { $str = $payload["user"]["pass"]["current"] . "1337" . strtolower($payload["user"]["email"]); $hash = hash("sha512", $str); /* Debug printf("Debug:<pre>"); var_dump($payload); var_dump($user); printf("Hash: %s<br>:", $hash); printf ("</pre>"); */ // Compare Password to encryption if ($hash != $user["Password"]) { $return = array( "status"=> "error", "msg" => "Invalid Password", "hash" => $hash, "pass" => $user["Password"] ); } else { /* // Insert Session Cookie into DB $sid = session_id(); $query = "INSERT INTO `Flags` (`ID`, `Account ID`, `Key`, `Value`) VALUES (:id, :accountid, :key, :value);"; // Set Session Token $values = []; $values[] = array( ":id" => date("U") . rand(100000, 999999), ":accountid" => $user["ID"], ":key" => "ValidationToken", ":value" => $sid ); // Set Login Timestamp $values[] = array( ":id" => date("U") . rand(100000, 999999), ":accountid" => $user["ID"], ":key" => "LastLogon", ":value" => date("U") ); $data1 = $sql->Query($query, $values[0]); $data2 = $sql->Query($query, $values[1]); if (!is_array($data1) && !is_array($data2)) { $return = array( "status" =>"error", "msg" =>"Unable to store session flags", "data" => null ); } else { */ $return = array( "status" =>"success", "msg" =>"You are now logged in", "data" => array( "user" => array( "id" => $user["ID"], "first" => $user["First"], "last" => $user["Last"], "email" => $user["Email"] ) ) ); // } } } } } // Return Payload header("Testheader.status", "success"); printf( json_encode($return) ); ?><file_sep>/src/assets/api/account/update.php <?php session_start(); header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS'); header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token, Authorization, X-Requested-With'); header("Access-Control-Allow-Credentials: true"); header('Access-Control-Max-Age: 1000'); header('Content-Type: application/json,text/plain'); // Load Basic Functions :: For IP Grab require ($_SERVER['DOCUMENT_ROOT'] . '/api/disc/functions.php'); require ($_SERVER['DOCUMENT_ROOT'] . '/api/disc/sql.php'); $sql = new SQL; // Get Values From HTTP $payload = json_decode(file_get_contents('php://input'), TRUE); $return = array(); // Set Flag Insert Query $query = "UPDATE `Accounts` SET `First`=:first, `Last`=:last WHERE `ID`=:account"; // Set Values $values = array( ":first" => ucfirst($payload["user"]["first"]), ":last" => ucfirst($payload["user"]["last"]), ":account" => $payload["user"]["id"] ); $data = $sql->Query($query, $values); if (!is_array($data)) { $return = array( "status" => "error", "msg" => "Unable to update account" ); } else { $return = array( "status" => "success", "msg" => "Your account information has been updated.", "data" => array( "user" => array( "id" => $payload["user"]["id"], "first" => $payload["user"]["first"], "last" => $payload["user"]["last"], "email" => "" ) ) ); } printf(json_encode($return)); ?><file_sep>/src/app/modules/sessions/dialogs/select-course/select-course.component.ts import { Component, OnInit, Inject } from '@angular/core'; import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material'; import { SessionBackend } from '../../services/backend.service'; import { flyIn } from 'src/app/animations'; import { skip } from 'rxjs/operators'; @Component({ selector: 'app-select-course', templateUrl: './select-course.component.html', styleUrls: ['./select-course.component.scss'], animations: [flyIn] }) export class SelectCourseComponent implements OnInit { private options = { list: ["search"], row: ["selector"] } constructor( private dialogRef: MatDialogRef<SelectCourseComponent>, @Inject(MAT_DIALOG_DATA) private data, private sessions_: SessionBackend, ) { } ngOnInit() { // Close When Course is Updates this.sessions_.detail$.pipe(skip(1)).subscribe((s)=>{ this.close(); }); } close(bool = false) { this.dialogRef.close(bool); } } <file_sep>/src/assets/api_new/classes/scores.php <?php class Score { // Properties public $id; public $created_by; public $created_on; public $modified_by; public $modified_on; public $session_id; public $team_id; public $player_id; public $throws; public $handicap; // DB public $db; public $con; // Init public function __construct($db) { $this->db = $db; $this->con = $db->getConnection(); } public function create($session, $score, $user) { $query = "INSERT INTO `Scores` (`id`, `created_by`, `created_on`, `modified_by`, `modified_on`, `session_id`, `team_id`, `player_id`, `throws`, `handicap` ) VALUES (:id, :created_by, :created_on, :modified_by, :modified_on, :session_id, :team_id, :player_id, :throws, :handicap );"; $values = array( ':id' => $score['id'], ':created_by' => $user['id'], ':created_on' => date('c'), ':modified_by' => null, ':modified_on' => null, ':session_id' => $session['id'], ':team_id' => $score["team"]['id'], ':player_id' => $score['player']['id'], ':throws' => json_encode($score['throws']), ':handicap' => $score['handicap'] ); return $this->db->Query($query, $values); } // Need to verify that the record will still be pulled if the team is null or not found; // May need to write another function for Scores with Teams, and change the logic on the controller; public function getScores($session) { $query = "SELECT `s`.`id` AS `scores.id`, `s`.`created_by` AS `scores.created_by`, `s`.`created_on` AS `scores.created_on`, `s`.`modified_by` AS `scores.modified_by`, `s`.`modified_on` AS `scores.modified_on`, `s`.`throws` AS `scores.throws`, `s`.`handicap` AS `scores.handicap`, `p`.`id` AS `scores.player.id`, `p`.`first_name` AS `scores.player.first_name`, `p`.`last_name` AS `scores.player.last_name`, `p`.`email` AS `scores.player.email` FROM `Scores` AS `s` JOIN `Players` AS `p` WHERE `s`.`session_id` = :id AND `s`.`player_id` = `p`.`id`"; $values = array( ':id' => $session['id'] ); return $this->db->Query($query, $values); } public function getScoresWithTeams($session) { $query = "SELECT `s`.`id` AS `scores.id`, `s`.`created_by` AS `scores.created_by`, `s`.`created_on` AS `scores.created_on`, `s`.`modified_by` AS `scores.modified_by`, `s`.`modified_on` AS `scores.modified_on`, `s`.`throws` AS `scores.throws`, `s`.`handicap` AS `scores.handicap`, `t`.`id` AS `scores.team.id`, `t`.`name` AS `scores.team.name`, `t`.`color` AS `scores.team.color`, `p`.`id` AS `scores.player.id`, `p`.`first_name` AS `scores.player.first_name`, `p`.`last_name` AS `scores.player.last_name`, `p`.`email` AS `scores.player.email` FROM `Scores` AS `s` JOIN `Teams` AS `t` ON `s`.`team_id` = `t`.`id` JOIN `Players` AS `p` ON `s`.`player_id` = `p`.`id` WHERE `s`.`session_id` = :id;"; $values = array( ':id' => $session['id'] ); return $this->db->Query($query, $values); } public function setHandicap($score) { $query = "SELECT `s`.`id` AS `scores.id`, `s`.`handicap` AS `scores.handicap`, `t`.`id` AS `team.id`, `t`.`name` AS `team.name`, `t`.`color` AS `team.color`, `p`.`id` AS `player.id`, `p`.`first_name` AS `player.first_name`, `p`.`last_name` AS `player.last_name`, `p`.`email` AS `player.email` FROM `Scores` AS `s` JOIN `Teams` AS `t` ON `s`.`team_id` = `t`.`id` JOIN `Players` AS `p` ON `s`.`player_id` = `p`.`id` WHERE `s`.`session_id` = :id;"; $values = array( ':id' => $score['id'] ); return $this->db->Query($query, $values); } public function RecentlyPlayedWith($user) { $query = "SELECT `sc`.`id` AS `scores.id`, `sc`.`created_by` AS `scores.created_by`, `sc`.`created_on` AS `scores.created_on`, `sc`.`modified_by` AS `scores.modified_by`, `sc`.`modified_on` AS `scores.modified_on`, `p`.`id` AS 'scores.player.id', `p`.`created_by` AS 'scores.player.created_by', `p`.`created_on` AS 'scores.player.created_on', `p`.`modified_by` AS 'scores.player.modified_by', `p`.`modified_on` AS 'scores.player.modified_on', `p`.`first_name` AS 'scores.player.first_name', `p`.`last_name` AS 'scores.player.last_name', `p`.`email` AS 'scores.player.email', `sc`.`throws` AS `scores.throws`, `sc`.`handicap` AS `scores.handicap` FROM `Scores` AS `sc` JOIN `Sessions` AS `sn` JOIN `Players` AS `p` WHERE `sn`.`id` = `sc`.`session_id` AND `sc`.`player_id` = :userId GROUP BY `p`.`id` ORDER BY `sn`.`created_on` DESC;"; $values = array( ':userId' => $user["id"] ); return $this->db->Query($query, $values); } } <file_sep>/src/assets/api_new/classes/favorites.php <?php class Favorites { // Properties public $id; public $created_by; public $created_on; public $modified_by; public $modified_on; public $related_table; public $related_id; // DB public $db; public $con; // Init public function __construct($db) { $this->db = $db; $this->con = $db->getConnection(); } public function userList($user){ $query = "SELECT * FROM `Favorites` WHERE `created_by`=:userId;"; $values = array( ":userId" => $user["id"] ); return $this->db->Query($query, $values); } public function create($fav, $user) { $query = "INSERT INTO `Favorites` (`id`, `created_by`, `created_on`, `modified_by`, `modified_on`, `related_table`, `related_id` ) VALUES (:id, :created_by, :created_on, :modified_by, :modified_on, :related_table, :related_id);"; $values = array( ':id' => $this->db->generateGUID(), ':created_by' => $user['id'], ':created_on' => date('c'), ':modified_by' => null, ':modified_on' => null, ':related_table' => $fav['related_table'], ':related_id' => $fav['related_id'], ); return $this->db->Query($query, $values); } public function delete($fav) { $query = "DELETE FROM `Favorites` WHERE `id`=:id LIMIT 1"; $values = array( ":id" => $fav['id'] ); return $this->db->Query($query, $values); } } <file_sep>/src/assets/api/account/register.php <?php session_start(); header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS'); header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token, Authorization, X-Requested-With'); header("Access-Control-Allow-Credentials: true"); header('Access-Control-Max-Age: 1000'); header('Content-Type: application/json,text/plain'); $URL = "http://www.brandonslotty.com/disc/"; //$URL = "http://localhost:4200/"; // Load Basic Functions :: For IP Grab require ($_SERVER['DOCUMENT_ROOT'] . '/api/disc/functions.php'); require ($_SERVER['DOCUMENT_ROOT'] . '/api/disc/sql.php'); $sql = new SQL; // Get Values From HTTP $payload = json_decode(file_get_contents('php://input'), TRUE); $return = array(); // Check If Email Exists in Account Table $query = "SELECT `ID`, `Email` FROM `Accounts` WHERE `Email`=:email LIMIT 1"; // Set Values $values = array(":email" => $payload["user"]["email"]); $data = $sql->Query($query, $values); if (count($data) > 0) { $return = array("status"=>"error", "msg"=>"The email entered is already associated with an account"); } else { // Create New Account $query = "INSERT INTO `Accounts` (`ID`, `First`, `Last`, `Email`, `Password`) VALUES (:id, :first, :last, :email, :pass);"; // Hash Pass $string = $payload["user"]["pass"]["current"] . "1337" . strtolower($payload["user"]["email"]); $hash = hash("sha512", $string); // Store Account ID $accountID = date("U") . rand(100000, 999999); // Set Values $values = array( ":id" => $accountID, ":first" => ucfirst($payload["user"]["first"]), ":last" => ucfirst($payload["user"]["last"]), ":email" => strtolower($payload["user"]["email"]), ":pass" => <PASSWORD> ); $data = $sql->Query($query, $values); if (!is_array($data)) { $return = array("status"=>"error", "msg"=>"Unable to create account"); } else { // Hash AccountVerification $string = date("YmdHis:U") . getRealIpAddr() . "1337" . strtolower($payload["user"]["email"]); $hash = hash("sha512", $string); // Set Flag Insert Query $query = "INSERT INTO `Flags` (`ID`, `Account ID`, `Key`, `Value`) VALUES (:id, :accountid, 'AccountVerification', :value);"; // Set Values $values = array( ":id" => date("U") . rand(100000, 999999), ":accountid" => $accountID, ":value" => $hash ); $data = $sql->Query($query, $values); if (!is_array($data)) { $return = array("status"=>"error", "msg"=>"Unable to create account properties"); } else { // Send Email To Verify Account $to = $payload["user"]["email"]; $subject = "DG Account Verification"; $message = "<html style='color: rgb(80,100,80) !IMPORTANT;'><body>"; $message .= "<h1>BS Disc</h1><h3>Verify Your Account</h3>"; $message .= "<p>Click <a href='". $URL ."account/verify/".$hash."'>Here</a> "; $message .= "to verify your account. If you did not initiate this request, ignore this message.</p>"; $message .= "</body></html>"; // Always set content-type when sending HTML email $headers = "MIME-Version: 1.0" . "\r\n"; $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n"; // More headers $headers .= 'From: <<EMAIL>>' . "\r\n"; if (mail($to, $subject, $message, $headers)){ $return = array("status"=>"success", "msg"=>"Account needs to be verified. Please check your email."); } else { $return = array("status"=>"error", "msg"=>"Unable to send email"); } } } } printf(json_encode($return)); ?><file_sep>/src/app/modules/sessions/services/form.service.spec.ts import { TestBed } from '@angular/core/testing'; import { SessionFormService } from './form.service'; describe('FormService', () => { beforeEach(() => TestBed.configureTestingModule({})); it('should be created', () => { const service: SessionFormService = TestBed.get(SessionFormService); expect(service).toBeTruthy(); }); }); <file_sep>/src/assets/api/teams/delete.php <?php session_start(); header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS'); header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token, Authorization, X-Requested-With'); header("Access-Control-Allow-Credentials: true"); header('Access-Control-Max-Age: 1000'); header('Content-Type: application/json,text/plain'); // Load Basic Functions :: For IP Grab require ($_SERVER['DOCUMENT_ROOT'] . '/api/disc/functions.php'); require ($_SERVER['DOCUMENT_ROOT'] . '/api/disc/sql.php'); $sql = new SQL; $payload = json_decode(file_get_contents('php://input'), TRUE); $return = array(); // Verify Permissions $validUser = $sql->Access($payload["league"], $payload["user"]); if ($validUser["status"] == "error") { $return = array( "status"=>"error", "msg"=>"You do not have sufficent permissions to perform this action" ); } else { // Delete Session with ID $query = "DELETE FROM `Teams` WHERE `ID`=:id"; // Set Values $values = array( ":id" => $payload['team']['id'] ); $data = $sql->Query($query, $values); if ($data === FALSE) { $return = array( "status" => "error", "msg" => "Team not Found", "data" => array() ); } else { $return = array( "status" => "success", "msg" => "Team Removed", "data" => array() ); } } printf(json_encode($return)); ?> <file_sep>/src/app/modules/account/account-routing.module.ts import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; /* Guard */ import { AuthGuard } from 'src/app/guards/auth.service'; /* Components */ import { LoginComponent } from './components/login/login.component'; import { CreateComponent } from './components/create/create.component'; import { ForgotComponent } from './components/forgot/forgot.component'; import { SetPasswordComponent } from './components/set-password/set-password.component'; import { VerifyComponent } from './components/verify/verify.component'; import { DetailComponent } from './components/detail/detail.component'; import { ResetComponent } from './components/reset/reset.component'; import { EditComponent } from './components/edit/edit.component'; import { PageNotFoundComponent } from 'src/app/404/page-not-found.component'; import { ShellComponent } from './components/shell/shell.component'; const accountRoutes: Routes = [ { path: "account/register", component: CreateComponent, }, { path: 'account/login', component: LoginComponent, }, { path: "account/verify/:token", component: VerifyComponent, }, { path: "account/forgot", component: ForgotComponent, }, { path: "account/forgot/:token", component: SetPasswordComponent, }, { path: 'account', component: ShellComponent, canActivate: [AuthGuard], children: [ { path: '', redirectTo: 'detail', pathMatch: 'full', },{ path: 'rankings', component: PageNotFoundComponent, },{ path: 'stats', component: PageNotFoundComponent, },{ path: "update", component: EditComponent, },{ path: "reset", component: ResetComponent, },{ path: 'detail', component: DetailComponent, } ] }]; @NgModule({ imports: [RouterModule.forChild(accountRoutes)], exports: [RouterModule] }) export class AccountRoutingModule { } <file_sep>/src/app/interceptors/auth.interceptor.ts /* Placeholder for HTTP INterceptor; Will replace & contain the following features: HTTP Auth Token Can Incorperate a Timeout with always writing a new token on every request. Timeout can be calculated from modified date. X Message/Notification(Feedback) Service Include Loader boolean in this for resolve replacement Retry On Fail Possible cache? */ import { Injectable } from '@angular/core'; import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor, HttpResponse } from '@angular/common/http'; import { Observable } from 'rxjs'; import { AccountBackend } from '../modules/account/services/backend.service'; import { FeedbackService } from '../shared/modules/feedback/services/feedback.service'; import { map } from 'rxjs/operators'; @Injectable() export class AuthInterceptor implements HttpInterceptor { previousUrl: string = ''; constructor( private accountService: AccountBackend, private feedbackService: FeedbackService, ) { } intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { // console.log("request: ", request, next); // Auth Token var token = localStorage.getItem("DGC-Token"); //--! If Token not set -> Invalid -> Login request = request.clone({ setHeaders: { Authorization: token ? token : "", } }); return next.handle(request).pipe(map((event: HttpEvent<any>) => { if (event instanceof HttpResponse) { // console.log("auth.interceptor.event: ", event); } return event; }) ); } }<file_sep>/src/app/modules/scores/components/score-list/score-list.component.ts import { Component, OnInit, Input } from '@angular/core'; import { ScoresBackend } from '../../services/backend.service'; import { Observable } from 'rxjs'; import { Score, listCategories } from 'src/app/shared/types'; @Component({ selector: 'score-list', templateUrl: './score-list.component.html', styleUrls: ['./score-list.component.scss'] }) export class ScoreListComponent implements OnInit { private scores$: Observable<Score[]> = this.scores_.scores$; list: Array<listCategories>; constructor( private scores_:ScoresBackend, ) { } ngOnInit() { } } <file_sep>/src/app/modules/sessions/dialogs/select-time/select-time.component.ts import { Component, OnInit, Inject } from '@angular/core'; import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material'; import { SessionBackend } from '../../services/backend.service'; import { skip } from 'rxjs/operators'; import { FormGroup } from '@angular/forms'; import { SessionFormService } from '../../services/form.service'; import { combineLatest } from 'rxjs'; import { NgxMaterialTimepickerTheme } from 'ngx-material-timepicker'; import { NgxMaterialTimepickerContainerComponent } from 'ngx-material-timepicker/src/app/material-timepicker/components/ngx-material-timepicker-container/ngx-material-timepicker-container.component'; @Component({ selector: 'app-select-time', templateUrl: './select-time.component.html', styleUrls: ['./select-time.component.scss'] }) export class SelectTimeComponent implements OnInit { private form: FormGroup; private dataUpdated: boolean = false; /* $theme-font-header: 'Montserrat', serif; $theme-font-body: 'Roboto'; $theme-font-utility: 'Montserrat'; // Colors $theme-primary: #fafaf0; $theme-accent: #4FD3FF; $theme-warn: #ffd133; $theme-secondary: #506450; $theme-error: #ffd133; // Backgrounds $theme-bg-dark: #222422; $theme-bg-dark-surface: #506450; $theme-bg-light: #222422; $theme-bg-light-surface: #506450; // Text $theme-text-light: #fafaf0; $theme-text-dark: #1e2616; */ // Clock Theme private timeTheme: NgxMaterialTimepickerTheme = { container: { primaryFontFamily: "--primary-font-family: 'Montserrat'", bodyBackgroundColor: "", buttonColor: "", }, clockFace: { clockFaceBackgroundColor: "", clockFaceInnerTimeInactiveColor: "", clockFaceTimeActiveColor: "", clockFaceTimeDisabledColor: "", clockFaceTimeInactiveColor: "", clockHandColor: "", }, dial: { dialActiveColor: "", dialBackgroundColor: "", dialEditableActiveColor: "", dialEditableBackgroundColor: "", dialInactiveColor: "", } } constructor( private dialogRef: MatDialogRef<SelectTimeComponent>, @Inject(MAT_DIALOG_DATA) private data, private sessions_: SessionBackend, private sessionsF_: SessionFormService) { } ngOnInit() { this.sessionsF_.form$.subscribe((f) => { this.form = f; }); this.sessions_.detail$.pipe(skip(1)).subscribe((s) => { this.close(); }); } setTime() { if (this.form.get('date').valid && this.form.get('time').valid) { this.sessions_.setDate(this.form.get('date').value, this.form.get('time').value); this.dataUpdated = true; } } close() { this.dialogRef.close(this.dataUpdated); } } <file_sep>/src/app/modules/account/components/reset/reset.component.ts import { FormGroup } from '@angular/forms'; import { Component, OnInit, Input } from '@angular/core'; import { FeedbackService } from 'src/app/shared/modules/feedback/services/feedback.service'; import { AccountFormService } from '../../services/account-form.service'; @Component({ selector: 'app-account-reset', templateUrl: './reset.component.html', styleUrls: ['./reset.component.css'], animations: [], }) export class ResetComponent implements OnInit { form: FormGroup; @Input() fromToken: boolean = false; // password | text passwordType: string = '<PASSWORD>'; confirmType: string = '<PASSWORD>'; oldType: string = '<PASSWORD>'; constructor( private feed: FeedbackService, private accountForm: AccountFormService, ) { } ngOnInit() { this.accountForm.Setup("reset"); this.accountForm.form$.subscribe((t)=>{ this.form = t; this.feed.stopLoading("reset"); }); } onFormSubmit() { this.accountForm.SubmitReset(); } } <file_sep>/src/app/shared/types.ts import { Observable } from "rxjs/internal/Observable"; export class SessionFormat { name: string; enum: string; desc: string; } export class Session { constructor( public id?: string, public created_on?: Date, public created_by?: string, /* User? */ public modified_on?: Date, public modified_by?: string, /* User? */ public course?: Course, public format?: SessionFormat, public starts_on?: Date, public title?: string, public par?: Array<any>, public scores?: Score[], ) { } } export class Score { public id: string; public created_on: Date; public created_by: string; /* User? */ public modified_on: Date; public modified_by: string; /* User? */ public player: Player; public throws: Array<number>; public team: Team | null public handicap: number; constructor() { } } export class Team { constructor( public id: string, public name: string, public color: TeamColor, ) { } } export class TeamColor { constructor( public name: string, public hex: string, public available: boolean, ) { } } /** * Classes used within this service */ export class User { // Flag for League Moderation public access = {}; public token; constructor( public id, public first?, public last?, public email?, public pass?, ) { } } export class Password { public old; public confirm; public current; constructor() { } } /** * Player */ export class Player { created_by; created_on; modified_by; modified_on; token; token_expires_on; last_logon; access = {} constructor( public id, public first_name?, public last_name?, public email?, public password?, ) { } } export class Course { constructor( public id?: string, public created_on?: string, public created_by?: string, /* User? */ public modified_on?: string, public modified_by?: string, /* User? */ public park_name?: string, public city?: string, public state?: string, public zip?: string, public latitude?: number, public longitude?: number, ) { } } export interface listCategories { name: string; obs: Observable<Object[]>; } export class ServerPayload { public status: string; public msg: string; public debug: string; public affectedRows: number; public results: Array<any>; public data: Array<any>; } export class FeedbackErrorHandler { public msg: string; public code: number; public visible: boolean; public element: string; }<file_sep>/src/app/modules/scores/services/backend.service.ts import { Injectable } from '@angular/core'; import { BehaviorSubject, Observable, pipe } from 'rxjs'; import { AccountBackend } from '../../account/services/backend.service'; import { SessionBackend } from '../../sessions/services/backend.service'; import { debounceTime, distinctUntilChanged } from 'rxjs/operators'; import { ServerPayload } from 'src/app/app.component'; import { HttpClient } from '@angular/common/http'; import { environment } from 'src/environments/environment'; import { HelperService } from 'src/app/shared/services/helper.service'; import { Team, Score, TeamColor, Player } from 'src/app/shared/types'; @Injectable({ providedIn: 'root' }) export class ScoresBackend { url: string = environment.apiUrl + '/controllers/scores.php'; private scores: BehaviorSubject<Score[]> = new BehaviorSubject<Score[]>([]); scores$: Observable<Score[]> = this.scores.asObservable(); /* this._sessions.detail$.pipe(map(session => { let teams = session.scores.map((s) => s.team); let unique = teams.filter((e, i) => teams.findIndex(a => a.name === e.name) === i); return unique })) */ private teams: BehaviorSubject<Team[]> = new BehaviorSubject<Team[]>([]); teams$: Observable<Team[]> = this.teams.asObservable(); private roster: BehaviorSubject<Array<Score[]>> = new BehaviorSubject<Array<Score[]>>([]); roster$: Observable<Array<Score[]>> = this.roster.asObservable(); private searchedPlayers: BehaviorSubject<Score[]> = new BehaviorSubject<Score[]>([]) searchedPlayers$: Observable<Score[]> = this.searchedPlayers.asObservable(); private recientPlayers: BehaviorSubject<Score[]> = new BehaviorSubject<Score[]>([]) recientPlayers$: Observable<Score[]> = this.recientPlayers.asObservable(); // Team Colors teamColorList: TeamColor[] = [{ name: "red", hex: "ad0000", available: true, }, { name: "blue", hex: "3052ff", available: true, }, { name: "green", hex: "30ff30", available: true, }, { name: "yellow", hex: "fcf22f", available: true, }, { name: "orange", hex: "fcad2e", available: true, }, { name: "purple", hex: "802efc", available: true, }, { name: "pink", hex: "fc2eea", available: true, }, { name: "white", hex: "FFFFFF", available: true, },]; constructor( private _sessions: SessionBackend, private http: HttpClient, private account: AccountBackend, private helper: HelperService, ) { this._sessions.detail$.subscribe((s) => { console.log("scores.session.details: ", s); if (s != undefined) { // Scores this.scores.next(s.scores); if (this._sessions.teamGame()) { this.setTeams(s.scores); } } }); // Debug this.scores$.subscribe((s) => { console.log("scores$", s); }); this.teams$.subscribe((t) => { console.log("teams$:", t); if (t != undefined) { t.forEach((t) => { this.teamColorList.forEach((c) => { if (t.color.name == c.name) { c.available = false; } }); }); } // console.log ("updatedTeamList: ", this.teamColorList); }); this.roster$.subscribe((r) => { console.log("roster$:", r); }); } listRecient() { this.http.post(this.url, { action: "recent", user: this.account.user }).pipe(this.helper.pipe).subscribe((res: ServerPayload) => { this.recientPlayers.next(this.helper.rGetData(res)); }); } getSearch(term) { this.http.post(this.url, { action: "search", term: term }).pipe(this.helper.pipe).subscribe((res: ServerPayload) => { this.searchedPlayers.next(this.helper.rGetData(res)); }); } /* Scores */ // Read getScore(score) { return this.scores.value.find(s => s.player.id == score.player.id) != undefined; } // Create addScore(score) { console.log("AddPlayer:", score); let list = this.scores.value; let dupe = this.scores.value.find(e => e.player.id == score.player.id); if (dupe == undefined) { list.push(this.helper.convertPlayerToScore(score.player, this.account.user)); } // only update update from session Details this._sessions.setScores(list); } // Delete removeScore(score) { let updatedList = this.scores.value.filter(s => s.player.id != score.player.id); this._sessions.setScores(updatedList); } /* Teams */ getTeamsFromScoreList(scores): Team[] { if (scores != undefined) { let teamList = scores.map((s) => s.team); let unique = teamList.filter((e, i) => teamList.findIndex(a => a.name === e.name) === i); return unique; } } getTeamPlayers(uniqueTeams: Team[]): void { if (this.scores.value != undefined) { var roster = []; uniqueTeams.forEach((t, ti) => { roster[ti] = this.scores.value.filter((s, si) => { return t.name == s.team.name }); }); this.roster.next(roster); } } addTeam() { // Limit to 8 if (this.teams.value.length < 8) { var color = this.teamColorList.find((t) => { return t.available == true; }); // Disable Color color.available = false; var newList = this.teams.value; newList.push(new Team(null, color.name, new TeamColor(color.name, color.hex, color.available))); this.teams.next(newList); } else { // Too Many } } removeTeam(team) { // Remove Players From Team this.scores.value.forEach((s) => { if (s.team.name == team.name) { s.team = new Team(null, "unassigned", new TeamColor(null, null, true)); } }); // Remove Team let newList; this.teams.value.forEach((v, i) => { if (team.name == v.name) { // Update Availablity Status on Color this.teamColorList.find((c) => { if (c.name == team.name) { c.available = true; return true; } }); newList = this.teams.value.filter((ta, ti) => { return i != ti }); } }); // Remove Roster for Deleted Team this.clearRoster(team); // Emit Updates this.teams.next(newList); } setTeams(scores): void { var teamList = this.getTeamsFromScoreList(scores); this.teams.next(teamList); this.getTeamPlayers(teamList); } getRoster(team: Team): Score[] { //console.log("this.scores.value: ", this.scores, team); if (team != undefined) { return this.scores.value.filter(scores => { if (scores.team != undefined) { var scoreStr = scores.team.id + scores.team.name + scores.team.color.hex; var teamStr = team.id + team.name + team.color.hex; return scoreStr == teamStr; } }); } else { return this.scores.value; } } movePlayer(event) { // Get Destination Color Name var teamDestName = event.container.id.replace("team-", ""); // Get Team Object From Color Name var teamDest = this.teams.value.find((t) => { return t.color.name == teamDestName; }); // Move back to unassigned fix; if (teamDest == undefined) { teamDest = new Team(null, "Unassigned", new TeamColor("Unassigned", null, true)); } // Update Player's Team this.scores.value.forEach((s) => { if (event.item.data.player.id == s.player.id) { s.team = teamDest; } }); } // Call when settings changes team info; need to update each team member; updateRosterTeam(current, destination) { // console.log ("Update Team:", current, "to:", destination); this.scores.value.forEach((s) => { if (s.team.color.name == current.name) { s.team.color = destination; } }); } clearRoster(team) { this.scores.value.forEach((s, i) => { if (s.team == team) { s.team = new Team(null, "Unassigned", new TeamColor("Unassigned", null, true)); } }); } } <file_sep>/src/app/animations.ts import { trigger, state, style, animate, transition, query, group, keyframes, animateChild, stagger } from '@angular/animations'; export const fade = trigger('fade', [ transition('* <=> *', [ query(':enter', style({ opacity: 0, height: 0, }), { optional: true }), animateChild(), group([ query(':leave', animate('.1s ease', style({ opacity: 0, height: 0, })), { optional: true }), query(':enter', animate('.3s ease', style({ opacity: 1, height: "*", })), { optional: true }), animateChild() ]), ]) ]); export const loading = trigger('loading', [ // Visible state('1', style({ opacity: 1, })), // Hidden state('0', style({ opacity: 0, })), // Transitions transition('1 => 0', animate('3s ease')), transition('0 => 1', animate('3s ease')), ]); export const flyIn = trigger('flyIn', [ transition('* <=> *', [ query(':enter', style({ opacity: 0, // height: 0, transform: "translateY(-50%)", overflow: "hidden", position: 'relative', display: "block", }), { optional: true }), animateChild(), query(':leave', style({ opacity: 0, position: 'relative', display: "block", }), { optional: true }), animateChild(), group([ query(':leave', [ stagger(90, [ animate('1000ms ease', style({ // position: 'absolute', // display: "block", opacity: 0, // height: 0, // transform: "translateY(-20%)" }) ), ]) ], { optional: true }), animateChild(), query(':enter', stagger(30, [ animate('300ms ease', style({ transform: "translateY(0)", opacity: 1, height: "*", }) )] ), { optional: true }), animateChild(), ]), animateChild() ]) ]); export const scorecardSlide = trigger('scorecardSlide', [ transition(':increment', [ style({ transform: 'translateX(1em)', opacity: 0, }), animate('0.3s ease-out', style({ transform: 'translateX(0)', opacity: 1, })) ]), transition(':decrement', [ style({ transform: 'translateX(-1em)', opacity: 0, }), animate('0.3s ease-out', style({ transform: 'translateX(0)', opacity: 1, })) ]) ]); export const flyInPanelRow = trigger('flyInPanelRow', [ transition(':enter', [ style({ opacity: 0, overflow: "hidden", height: 0, display: "block", position: "relative", transform: "translateY(-10%)" /* border: "1px solid #FF00FF" */ }), animate('2s ease-out', style({ offset: 1, opacity: 1, height: "*", transform: "translateY(0)" }) ), ]), transition(':leave', [ style({ display: "block", position: "relative" }), animate('1s ease', style({ opacity: 0, overflow: "hidden", transform: "translateY(-100%)" }) ) ]), ]) // PUTT Animation for panel entry: // In: Slow Raise Up From Bottom-85% -> bounceAbove -> Fast Down to normal POS. // Out: Rotate to and fall off // Generic Animations for Chaining export const growHeight = trigger('fallOut', [ transition(':enter', [ style({ overflow: "hidden", height: 0, position: 'relative' }), animate('.3s ease', style({ offset: 1, height: "*" }) ), ]), transition(':leave', [ animate('.1s ease', style({ height: 0 }) ) ]), ]); export const fall = trigger('fall', [ transition(':enter', [ style({ opacity: 0, overflow: "hidden", display: "inline-block", position: "relative", transform: "scale(1.1)" /* border: "1px solid #FF00FF" */ }), animate('.3s ease-out', style({ offset: 1, opacity: 1, transform: "scale(1)" }) ), ]), transition(':leave', [ style({ display: "block", position: "relative" }), animate('.1s ease', style({ opacity: 0, transform: "scale(.8)" }) ) ]), ]); // Header Components export const flyLeft = trigger('flyLeft', [ transition(':enter', [ style({ transform: 'translateX(1em)', opacity: 0, overflow: "hidden", }), animate('1s ease-out', style({ transform: 'translateX(0)', opacity: 1, })), animateChild() ]), transition(':leave', [ style({ transform: 'translateX(-1em)', opacity: 0, }), animate('1s ease-out', style({ transform: 'translateX(0)', opacity: 1, })), animateChild() ]) ]); export const flyRight = trigger('flyRight', [ transition('* <=> *', [ query(':enter', style({ opacity: 0, transform: "translateX(-50%)", overflow: "hidden", position: 'relative', display: "block", }), { optional: true }), animateChild(), query(':leave', style({ opacity: 0, transform: "translateX(-50%)", }), { optional: true }), animateChild(), group([ query(':leave', [ stagger(90, [ animate('1000ms ease', style({ // position: 'absolute', // display: "block", opacity: 0, transform: "translateX(-50%)", // height: 0, // transform: "translateY(-20%)" }) ), ]) ], { optional: true }), animateChild(), query(':enter', stagger(30, [ animate('300ms ease', style({ transform: "translateX(0)", opacity: 1, height: "*", }) )] ), { optional: true }), animateChild(), ]) ]) ]);<file_sep>/src/app/modules/account/account.module.ts import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; /* Routing */ import { AccountRoutingModule } from './account-routing.module'; /* Services */ import { AccountBackend } from 'src/app/modules/account/services/backend.service'; import { AccountFormService } from './services/account-form.service'; /* Views */ import { DetailComponent } from './components/detail/detail.component'; import { LoginComponent } from './components/login/login.component'; import { EditComponent } from './components/edit/edit.component'; import { ResetComponent } from './components/reset/reset.component'; import { VerifyComponent } from './components/verify/verify.component'; import { ForgotComponent } from './components/forgot/forgot.component'; import { CreateComponent } from './components/create/create.component'; import { SetPasswordComponent } from './components/set-password/set-password.component'; import { MaterialModule } from 'src/app/shared/modules/material/material.module'; import { ShellComponent } from './components/shell/shell.component'; import { FavoritesService } from 'src/app/shared/modules/favorites/services/favorites.service'; @NgModule({ imports: [ CommonModule, AccountRoutingModule, MaterialModule, ], declarations: [ DetailComponent, LoginComponent, EditComponent, ResetComponent, VerifyComponent, ForgotComponent, CreateComponent, SetPasswordComponent, ShellComponent, ], providers: [ AccountBackend, AccountFormService, FavoritesService, ], exports: [ ] }) export class AccountModule { } <file_sep>/src/assets/api/account/forgot.php <?php session_start(); header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS'); header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token, Authorization, X-Requested-With'); header("Access-Control-Allow-Credentials: true"); header('Access-Control-Max-Age: 1000'); header('Content-Type: application/json,text/plain'); $URL = "http://www.brandonslotty.com/disc/"; //$URL = "http://localhost:4200/"; // Load Basic Functions :: For IP Grab require ($_SERVER['DOCUMENT_ROOT'] . '/api/disc/functions.php'); require ($_SERVER['DOCUMENT_ROOT'] . '/api/disc/sql.php'); $sql = new SQL; // Get Values From HTTP $payload = json_decode(file_get_contents('php://input'), TRUE); $return = array(); // Verify Data if (isset($payload['user']['email'])) { // Get ID From Email $query = "SELECT `ID`, `Email` FROM `Accounts` WHERE `Email`=:email LIMIT 1"; // Set Values $values = array(":email" => strtolower($payload["user"]["email"])); $data = $sql->Query($query, $values); if (count($data) == 0) { $return = array("status"=>"error", "msg"=>"Email not associated with any account"); } else { // Store Account ID from found account to link forgot password flag $accountID = $data[0]["ID"]; // Insert ForgotPassword Token Into Table $string = date("YmdHis:U") . getRealIpAddr() . "1337" . strtolower($payload["user"]["email"]); $hash = hash("sha512", $string); // Set Flag Insert Query $query = "INSERT INTO `Flags` (`ID`, `Account ID`, `Key`, `Value`) VALUES (:id, :accountid, 'ForgotPassword', :value);"; // Set Values $values = array( ":id" => date("U") . rand(100000, 999999), ":accountid" => $accountID, ":value" => $hash ); $data = $sql->Query($query, $values); if (!is_array($data)) { $return = array("status"=>"error", "msg"=>"Unable to store Token"); } else { // Send Email To Verify Account $to = $payload["user"]["email"]; $subject = "DG Forgot Password"; $message = "<html stayle='color: rgb(80,100,80) !IMPORTANT;'><body>"; $message .= "<h1>BS Disc</h1><h3>Verify Your Account</h3>"; $message .= "<p>Click <a href='".$URL."account/forgot/".$hash."'>Here</a> "; $message .= "to reset your password. If you did not initiate this request, ignore this message.</p>"; $message .= "</body></html>"; // Always set content-type when sending HTML email $headers = "MIME-Version: 1.0" . "\r\n"; $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n"; // More headers $headers .= 'From: <<EMAIL>>' . "\r\n"; if (mail($to, $subject, $message, $headers)){ $return = array( "status"=>"success", "msg"=>"An email has been sent to ". $payload["user"]["email"] ." for further instructions on how to reset your password."); } else { $return = array( "status"=>"error", "msg"=>"Unable to send email. Please try again."); } } } } else { $return = array("status"=>"error", "msg"=>"Data not properly set"); } printf(json_encode($return)); ?><file_sep>/src/assets/api/account/reset.php <?php session_start(); header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS'); header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token, Authorization, X-Requested-With'); header("Access-Control-Allow-Credentials: true"); header('Access-Control-Max-Age: 1000'); header('Content-Type: application/json,text/plain'); // Load Basic Functions :: For IP Grab require ($_SERVER['DOCUMENT_ROOT'] . '/api/disc/functions.php'); require ($_SERVER['DOCUMENT_ROOT'] . '/api/disc/sql.php'); $sql = new SQL; // Get Values From HTTP $payload = json_decode(file_get_contents('php://input'), TRUE); $return = array(); // Verify Data if ( isset($payload['user']['id']) && isset($payload['user']["email"]) && isset($payload['user']["pass"]["current"]) ) { // Convert Password $string = $payload["user"]["pass"]["current"] . "<PASSWORD>" . strtolower($payload['user']['email']); $hash = hash("sha512", $string); // Set Flag Insert Query $query = "UPDATE `Accounts` SET `Password`=:pass WHERE `ID`=:account"; // Set Values $values = array( ":pass" => $hash, ":account" => $payload['user']['id'] ); $data = $sql->Query($query, $values); if (!is_array($data)) { $return = array("status"=>"error", "msg"=> "Unable to update password", "values"=>$values); } else { $return = array("status"=>"success", "msg"=> "Your password has been updated."); } } else { $return = array("status"=>"error", "msg"=> "Data not properly set"); } printf(json_encode($return)); ?><file_sep>/src/environments/environment.prod.ts export const environment = { production: true, apiUrl: "http://www.brandonslotty.com/api/disc", }; <file_sep>/src/app/modules/courses/pages/create/create.component.ts import { Component, OnInit } from '@angular/core'; import { CourseFormService } from '../../services/course-form.service'; import { FormGroup } from '@angular/forms'; import { Course } from 'src/app/shared/types'; @Component({ selector: 'app-create', templateUrl: './create.component.html', styleUrls: ['./create.component.scss'] }) export class CreateComponent implements OnInit { mode: string; form: FormGroup; invalidParkAddress: Boolean = false; selectedLocation: Course; errorMessage: string = "Google was unable to find a park at that location. Try to move the pin inside a park or to another location within the park."; constructor(private courseForm: CourseFormService) { } ngOnInit() { this.courseForm.Setup("create"); this.courseForm.form$.subscribe((f)=>{ this.form = f; }); } updateAddress($event) { console.log ("Course.Location.Update", $event); if ($event == false) { this.invalidParkAddress = true; this.courseForm.resetForm(); } else { this.selectedLocation = $event; this.invalidParkAddress = false; this.courseForm.setForm($event); } console.log ("form: ", this.form); } createCourse() { if (this.courseForm.ReadyForSubmission()) { this.courseForm.SubmitCreation(); } } } <file_sep>/src/assets/api_new/controllers/courses.php <?php // Session & Header Init require_once($_SERVER['DOCUMENT_ROOT'] . '/sites/disc/api/shared/headers.php'); // Convert HTTP Vars $payload = json_decode(file_get_contents('php://input'), TRUE); // Init Return $return = array(); // Debug /** * Future feature, do not return each step in DB; only return last; Can flag with this later on */ $devMode = true; // DB require_once($_SERVER['DOCUMENT_ROOT'] . '/sites/disc/api/shared/sql.php'); $database = new DB("course"); // Course require_once($_SERVER['DOCUMENT_ROOT'] . '/sites/disc/api/classes/courses.php'); $courses = new Course($database); // Player require_once($_SERVER['DOCUMENT_ROOT'] . '/sites/disc/api/classes/players.php'); $player = new Player($database); switch ($payload['action']) { case "list": $return[] = $courses->getList($payload['start'], $payload['limit']); // Error Testing // http_response_code(402); /* $return[] = array( "status" => "error", "msg" => "Unknown Action", ); */ break; case "recient": $return[] = $courses->UserRecientlyPlayed($payload['user']); break; case "favorites": $return[] = $courses->UserFavorites($payload['user']); break; case "search": $return[] = $courses->search($payload['term']); break; case "create": // Verify User $user = $player->getPlayerByEmail($payload['user']['email']); $return[] = $user; if ($user["status"] == "success" && count($user['results']) > 0) { // Convert Keys $course = $courses->ConvertFrontBack($payload['course']); // Verify no Course within +/- .005 of lat/lng $nearby = $courses->nearBy($course); if ($nearby['status'] == 'success') { if (count($nearby["results"]) > 0) { // Update Create Status to error, as nearby courses were found; $nearby['status'] = "error"; $nearby['msg'] = 'There are similiar courses nearby'; $return[] = $nearby; } else { $return[] = $nearby; // Create Course $created = $courses->create($course, $user['results'][0]); $return[] = $created; if ($created['status'] == 'success' && $created["affectedRows"] == 1) { // Return ID for Detail View $return[] = $courses->UserRecientlyCreated($payload['user']); } } } else { $return[] = array( 'status' => 'error', 'msg' => 'Nearby course search failed.' ); } } break; case "update": break; case "delete": break; default: $return[] = array( "status" => "error", "msg" => "Unknown Action", ); break; } printf(json_encode($return)); <file_sep>/src/app/modules/courses/courses.module.ts import { NgModule, ModuleWithProviders } from '@angular/core'; import { CommonModule } from '@angular/common'; import { CoursesRoutingModule } from './courses-routing.module'; import { MaterialModule } from '../../shared/modules/material/material.module'; import { AgmCoreModule } from '@agm/core'; import { DetailComponent } from './pages/detail/detail.component'; import { MapComponent } from './components/map/map.component'; import { ShellComponent } from './pages/shell/shell.component'; import { CreateComponent } from './pages/create/create.component'; import { CourseBackend } from './services/backend.service'; import { CourseFormService } from './services/course-form.service'; import { DashboardComponent } from './pages/dashboard/dashboard.component'; import { CourseListItemComponent } from './components/course-list-item/course-list-item.component'; import { ListComponent as CourseListComponent } from './components/list/list.component'; @NgModule({ imports: [ CommonModule, MaterialModule, CoursesRoutingModule, AgmCoreModule.forRoot({ apiKey: '<KEY>', libraries: ['places'] }), ], declarations: [ CourseListComponent, DetailComponent, MapComponent, ShellComponent, CreateComponent, DashboardComponent, CourseListItemComponent, ], providers: [ CourseBackend, CourseFormService ], exports: [ CourseListComponent, CourseListItemComponent ] }) export class CoursesModule { } <file_sep>/src/assets/api/account/token.php <?php session_start(); header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS'); header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token, Authorization, X-Requested-With'); header("Access-Control-Allow-Credentials: true"); header('Access-Control-Max-Age: 1000'); header('Content-Type: application/json,text/plain'); // Load Basic Functions :: For IP Grab require ($_SERVER['DOCUMENT_ROOT'] . '/api/disc/sql.php'); $sql = new SQL; // Get Values From HTTP $payload = json_decode(file_get_contents('php://input'), TRUE); $return = array(); if (isset($payload['token']) ) { // Find Forgot Password Request $query = "SELECT `ID`, `Account ID` FROM `Flags` WHERE `Key`='ForgotPassword' AND `Value`=:value LIMIT 1"; // Set Values $values = array(":value" => $payload["token"]); $data = $sql->Query($query, $values); if (count($data) == 0) { $return = array( "status"=>"error", "msg"=>"Unable to find request", "data"=>$data); } else { // Get Timestamp from ID $time = substr($data[0]["ID"], 0, 10); // Verify Token isnt older than 10 mins if ($time < strtotime("-10 minutes")) { $return = array("status"=>"error", "msg"=> "Request expired. Please send another request."); } else { // Delete Forgot Password Requests $query = "DELETE FROM `Flags` WHERE `Key`='ForgotPassword' AND `Account ID`=:id"; $accountID = $data[0]["Account ID"]; // Set Values $values = array(":id" => $accountID); $data = $sql->Query($query, $values); if (!isset($data)) { $return = array("status"=>"error", "msg"=> "Unable to reset requests", "data"=>$data); } else { // Find Account $query = "SELECT * FROM `Accounts` WHERE `ID`=:id LIMIT 1"; // Set Values $values = array(":id" => $accountID); $data = $sql->Query($query, $values); if (count($data) == 0) { $return = array("status"=>"error", "msg"=> "Unable to find account."); } else { $return = array( "status" => "success", "msg" => "Enter a new password", "data" => array( "user" => array( "id" => $data[0]["ID"], "first" => $data[0]["First"], "last" => $data[0]["Last"], "email" => $data[0]["Email"] ) ) ); } } } } } else { $return = array("status"=>"error", "msg"=> "Data not set"); } printf(json_encode($return)); ?><file_sep>/src/app/modules/courses/components/map/map.component.ts import { Component, OnInit, ViewChild, ElementRef, NgZone, Input, Output, EventEmitter } from '@angular/core'; import { MapsAPILoader, MouseEvent } from '@agm/core'; import { Course } from 'src/app/shared/types'; @Component({ selector: 'app-map', templateUrl: './map.component.html', styleUrls: ['./map.component.scss'] }) export class MapComponent implements OnInit { @Input() course: Course; @Input() search: boolean = true; @Output() selectedLocation: EventEmitter<Course | Boolean> = new EventEmitter(); latitude: number = 42.8990; longitude: number = -87.8986; zoom: number = 7; address: string; private geoCoder; @ViewChild('search', {static: false}) public searchElementRef: ElementRef; constructor( private mapsAPILoader: MapsAPILoader, private ngZone: NgZone ) { } ngOnInit() { //load Places Autocomplete this.mapsAPILoader.load().then(() => { this.setCurrentLocation(); this.geoCoder = new google.maps.Geocoder; let autocomplete = new google.maps.places.Autocomplete(this.searchElementRef.nativeElement, { types: ["establishment"] }); autocomplete.addListener("place_changed", () => { this.ngZone.run(() => { //get the place result let place: google.maps.places.PlaceResult = autocomplete.getPlace(); //verify result if (place.geometry === undefined || place.geometry === null) { return; } //set latitude, longitude and zoom this.latitude = place.geometry.location.lat(); this.longitude = place.geometry.location.lng(); this.zoom = 15; this.getAddress(this.latitude, this.longitude); }); }); }); } // Get Current Location Coordinates private setCurrentLocation() { if ('geolocation' in navigator) { navigator.geolocation.getCurrentPosition((position) => { this.latitude = position.coords.latitude; this.longitude = position.coords.longitude; this.zoom = 12; this.getAddress(this.latitude, this.longitude); }); } } markerDragEnd($event: MouseEvent) { console.log($event); this.latitude = $event.coords.lat; this.longitude = $event.coords.lng; this.getAddress(this.latitude, this.longitude); } getAddress(latitude, longitude) { this.geoCoder.geocode({ 'location': { lat: latitude, lng: longitude } }, (results, status) => { console.log(results); // console.log(status); if (status === 'OK') { var park = this.validPark(results); if (park != false) { this.address = park.formatted_address; this.getFormattedAddress(park); } else { this.selectedLocation.next(false); } } else { window.alert('Geocoder failed due to: ' + status); } }); } /** * @param results Google Places result array * @return result containing the park entry */ validPark(results) { for (let i in results) { for (let p in results[i].address_components){ var item = results[i].address_components[p] if (item.types.indexOf("park") > -1) { // console.log ("foundParkAt: ", i); return results[i]; } } } return false; } getFormattedAddress(place) { //@params: place - Google Autocomplete place object //@returns: location_obj - An address object in human readable format let location_obj = {}; for (let i in place.address_components) { let item = place.address_components[i]; location_obj['formatted_address'] = place.formatted_address; if(item['types'].indexOf("locality") > -1) { location_obj['locality'] = item['long_name'] } else if (item['types'].indexOf("administrative_area_level_1") > -1) { location_obj['admin_area_l1'] = item['short_name'] } else if (item['types'].indexOf("postal_code") > -1) { location_obj['postal_code'] = item['short_name'] } else if (item["types"].indexOf('park') > -1) { location_obj['park'] = item['long_name'] } // console.log ("location_obj: ", location_obj); } // Only Addresses with parks are allowed; if (!location_obj['park']) { this.selectedLocation.next(false); } else { var course = new Course(); course.park_name = location_obj['park']; course.city = location_obj['locality']; course.state = location_obj['admin_area_l1'] course.zip = location_obj['postal_code'] course.latitude = this.latitude; course.longitude = this.longitude; // console.log ("newCourse: ", course) this.selectedLocation.next(course); } return location_obj; } pin(event, place){ console.log ("Map Click: ", event, place); this.latitude = event.coords.lat; this.longitude = event.coords.lng; this.getAddress(this.latitude, this.longitude); } } <file_sep>/src/app/modules/sessions/services/backend.service.ts import { AccountBackend } from 'src/app/modules/account/services/backend.service'; import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { ServerPayload } from 'src/app/app.component'; import { environment } from 'src/environments/environment'; import { pipe, BehaviorSubject, Observable, of, Subject } from 'rxjs'; import { HelperService } from 'src/app/shared/services/helper.service'; import { Session, Player, SessionFormat, Score } from 'src/app/shared/types'; import { map } from 'rxjs/internal/operators/map'; import { catchError } from 'rxjs/internal/operators/catchError'; import { ActivatedRoute, ParamMap, Router } from '@angular/router'; import { switchMap, find } from 'rxjs/operators'; import { FeedbackService } from 'src/app/shared/modules/feedback/services/feedback.service'; @Injectable({ providedIn: 'root' }) export class SessionBackend { url: string = environment.apiUrl + '/controllers/sessions.php'; // Generic private recient: BehaviorSubject<Session[]> = new BehaviorSubject([]); recient$: Observable<Session[]> = this.recient.asObservable(); // Generic private upcoming: BehaviorSubject<Session[]> = new BehaviorSubject([]); upcoming$: Observable<Session[]> = this.upcoming.asObservable(); // Favorites private favoriteList: Subject<Session[]> = new Subject(); favoriteList$: Observable<Session[]> = this.upcoming.asObservable(); // Single View private detail: BehaviorSubject<Session> = new BehaviorSubject(new Session()); detail$: Observable<Session> = this.detail.asObservable(); constructor( private http: HttpClient, private helper: HelperService, private account: AccountBackend, private route: ActivatedRoute, private router: Router, private feed: FeedbackService, ) { } /* HTTP */ // List getList(list: string, start: number = 0, limit: number = 100) { return this.http.post(this.url, { "action": list, "start": start, "limit": limit, "user": this.account.user }); } // Single getDetail(session: Session) { return this.http.post(this.url, { "action": "detail", "session": session, "user": this.account.user }); } // Create create(session: Session) { return this.http.post(this.url, { "user": this.account.user, "session": session, "action": "create" }); } // Update updateSession() { return this.http.post(this.url, { "action": "update", "user": this.account.user, "session": this.detail.value, }); } // Delete deleteSession() { return this.http.post(this.url, { "action": "delete", "user": this.account.user, "session": this.detail.value }); } // Verification validateSubmission() { const session = this.detail.value; let valid = true; // Course? if (session.course == undefined) { valid = false; this.feed.setError("session-course", "Select a Course"); } // Time? if (session.starts_on == undefined) { valid = false; this.feed.setError("session-start", "Invalid Start Date"); } // Format? if (session.format == undefined) { valid = false; this.feed.setError("session-format", "This should never fire."); } // Players? if (session.scores.length == 0) { valid = false; this.feed.setError("session-scores", "Add Players to the Match"); } else { // Teams? if (session.format != undefined && session.format.enum != "ffa") { // Verify no one on Unassigned let unassignedTeam = session.scores.filter((score) => { return score.team.name == "Unassigned"; }); if (unassignedTeam.length > 0) { valid = false; this.feed.setError("session-teams", "All Players need to be assigned to a team"); } } } return valid; } submitCreation() { if (this.validateSubmission()) { console.log("session.create: ", this.detail.value); this.create(this.detail.value).subscribe((res) => { // console.log("session.create.res:", this.helper.rGetData(res), res); // Toast let session = this.helper.rGetData(res)[0]; this.router.navigate(["/sessions", session['id']]); }); } } confirmDelete() { this.deleteSession().subscribe((res: ServerPayload[]) => { console.warn("session.deleted: ", res); if (res[res.length - 1]['status'] == 'success') { this.router.navigate(["/sessions"]); } else { // Error FeedBack } }); } listFavorites() { this.getList("favorites").subscribe((res: ServerPayload[]) => { this.favoriteList.next(this.helper.rGetData(res)); }); }; listCurrentSessions() { this.getList("list").subscribe((res: ServerPayload[]) => { let sessions = this.helper.rGetData(res); // console.log("sessions: ", sessions); var d = new Date().getTime(); let recient = sessions.filter((s: Session) => d > s.starts_on.getTime()); this.recient.next(recient); // Get Upcoming; Sort by soonest; Limit 5 let upcoming = sessions.filter((s: Session) => d < s.starts_on.getTime()); this.upcoming.next(upcoming); }); } findDetails(session_id) { console.log("Searching For: ", session_id); let session: Session = new Session(); session.id = session_id; // Find Session in Upcoming & Recient Lists; // If Found; Set details$ to matching session // if !Found; getDetail to get from server // if ServerRes Ok; Set details$ // Search List for Match let found = false; let upcoming = this.upcoming.value.find((v, i) => { return v.id = session.id; }); if (upcoming != undefined) { session = upcoming; found = true; } let recient = this.recient.value.find((v, i) => { return v.id = session.id; }); if (recient != undefined) { session = recient; found = true; } console.log("upcoming: ", upcoming); console.log("recient: ", recient); console.log("found: ", found); // ************* // Force Retrieval from server.. Course/Scores/Teams Unavailable from lists. Would need to retrieve anyway. found = false; if (found) { console.log("session found from lists!"); this.detail.next(session); } else { this.getDetail(session).subscribe((res: ServerPayload[]) => { let session = this.helper.rGetData(res)[0]; if (session != undefined) { console.log("session retrieved from server!"); this.detail.next(session); } else { console.warn("Unable to find session.", session); } }); } } resetDetails() { let session = new Session( "create", new Date(), this.account.user.id, null, null, null, this.helper.types[0], null, null, [], [] ); this.detail.next(session); } // MOD setupNewSession() { let session: Session; // Get URL Path let guid = this.route.snapshot.paramMap.get("session"); console.log("guid", guid); // If Null -> Create Default Session // If !Null -> Get From List // If !Found -> Get From Server if (guid == null) { session = new Session( "create", new Date(), this.account.user.id, null, null, null, this.helper.types[0], null, null, [], [] ) } else { } return session; } sortSession(list) { // Sort var sorted = list.sort((a, b) => { return b["start"] - a["start"]; }); return sorted; } /** * Add Save Feature Here */ setFormat(format) { this.detail.value.format = format; this.detail.next(this.detail.value); } setCourse(course) { this.detail.value.course = course; this.detail.next(this.detail.value); } setDate(date: Date, time: string): void { var d = new Date(date.toDateString() + " " + time); this.detail.value.starts_on = d; this.detail.next(this.detail.value); } setScores(scores: Score[]) { this.detail.value.scores = scores; this.detail.next(this.detail.value); } // Get Each // Status Functions admin(): boolean { let admin = this.account.user && this.detail.value.created_by == this.account.user.id; if (admin) { return true; } else { return false; } } teamGame(): boolean { if (this.detail.value.format != undefined) { var res: boolean = this.detail.value.format.enum != 'ffa'; return res; } else { return false; } } hasId(): boolean { return this.detail.value.id != "create"; } hasStarted(): boolean { // If scores are entered, session is considered started. let started = false; // check each player this.detail.value.scores.forEach((s) => { // check each attempt; return non 0s if (s.throws != null) { let changed = s.throws.filter(t => t != 0); // update flags if (changed.length > 0 && s.throws.length > 0) { started = true; } } }); return started; } }<file_sep>/src/app/modules/courses/components/course-list-item/course-list-item.component.ts import { Component, OnInit, Input } from '@angular/core'; import { FavoritesService } from 'src/app/shared/modules/favorites/services/favorites.service'; import { SessionBackend } from 'src/app/modules/sessions/services/backend.service'; import { Course } from 'src/app/shared/types'; @Component({ selector: 'course-list-item', templateUrl: './course-list-item.component.html', styleUrls: ['./course-list-item.component.scss'], animations: [] }) export class CourseListItemComponent implements OnInit { @Input() course: Course; @Input() mode: string[]; // List(Fav&&Link), Selector(emit), @Input() backdrop: boolean = false; constructor( private _favorites: FavoritesService, private _sessions: SessionBackend ) { } ngOnInit() { } setFavorite(course){ this._favorites.addFavorite("course", course); } removeFavorite(course) { this._favorites.removeFavorite("course", course); } selectCourse(course){ this._sessions.setCourse(course); } } <file_sep>/src/app/interceptors/errorHandler.interceptor.ts import { Injectable } from '@angular/core'; import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor, HttpResponse } from '@angular/common/http'; import { Observable, of, throwError, timer } from 'rxjs'; import { AccountBackend } from '../modules/account/services/backend.service'; import { FeedbackService } from '../shared/modules/feedback/services/feedback.service'; import { map, catchError, throttleTime, shareReplay, retryWhen, delayWhen, tap, delay } from 'rxjs/operators'; import { Router, NavigationEnd, NavigationStart } from '@angular/router'; @Injectable() export class ErrorHandlerInterceptor implements HttpInterceptor { previousUrl: string = ''; // Move to ErrorHandler error: boolean = false; errorMsg: string = ""; retryObs: Observable<any>; attempts: number = 0; constructor( private _account: AccountBackend, private _feed: FeedbackService, private router: Router ) { this.router.events.subscribe((e) => { if (e instanceof NavigationStart) { console.warn("RESET HTTP"); this.clearErrors(); } }); } // Impliment into ErrorInterceptor clearErrors() { this.error = false; this.attempts = 0; } setErrorMsg(error: string) { this.error = true; this.attempts++; this.errorMsg = error; } intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { console.log("request: ", request, next); return next.handle(request).pipe( tap(() => { this._feed.startLoading(request.body.action); }), catchError((error, caught) => { // HTTP Errors here console.log("catchError: ", error); this.setErrorMsg(error.status + ": " + error.statusText); this.retryObs = caught; if (this.attempts > 3) { if (!this.error) { this.setErrorMsg("Something is wrong, the server is not responding."); } this._feed.stopLoading(request.body.action); return of([]); } else { return throwError(error); } }), shareReplay(), retryWhen(errors => { return errors .pipe( /*delayWhen(() => timer(3000 + ())),*/ tap(() => { console.log('retrying ', this.attempts, 'of 3 in ', (this.attempts * 2000), '...') }), delay(this.attempts * 2000) ); }), map((event: HttpEvent<any>) => { if (event instanceof HttpResponse) { // console.log("errorHandler.interceptor.event: ", event); // Needs to be replaced with getting the message of the last status; // Toast Feedback from server if set. // if (event.body.msg) { } // // If last server event's message -> display feedback; // Success = Toast // Error = Message if (/* event.body != null */ event.status == 200) { // Get latest server event; var lastEvent = event.body[event.body.length - 1]; if (lastEvent.status == "success") { // Good // console.log("server response ok"); this.clearErrors(); } else if (lastEvent.status == "error") { // Server response bad; // console.log("server.error:", lastEvent); let msg = lastEvent.msg ? lastEvent.msg : "Unknown error"; this.setErrorMsg(msg); } } else { // HTTP response bad; // TODO: Seperate 4xx, 5xx, xxx messages, maybe different template // console.log("http.error:", event); let msg = lastEvent.status + ": " + lastEvent.statusText; this.setErrorMsg(msg); } this._feed.stopLoading(request.body.action); } return event; })); } }<file_sep>/src/assets/api/stats/set.php <?php session_start(); header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS'); header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token, Authorization, X-Requested-With'); header("Access-Control-Allow-Credentials: true"); header('Access-Control-Max-Age: 1000'); header('Content-Type: application/json,text/plain'); // Load Basic Functions :: For IP Grab require ($_SERVER['DOCUMENT_ROOT'] . '/api/disc/functions.php'); require ($_SERVER['DOCUMENT_ROOT'] . '/api/disc/sql.php'); $payload = json_decode(file_get_contents('php://input'), TRUE); $return = array(); /* printf ("<pre>"); var_dump($payload); printf ("</pre>"); */ /* Process: Get Session Drivers(IsDone/IsStarted) if both false -> Create new by: Delete All Session Stats Create new Entries for Each User if IsStarted == true and IsDone == false -> Update Existing */ $query = "SELECT * FROM `Sessions` WHERE `ID`=:session LIMIT 1;"; $values = array( ":session" => strtolower($payload["session"]["id"]) ); $sql = new SQL; $data = $sql->Query($query, $values); if (count($data) == 0) { $return = array( "status" => "error", "msg" => "Session not found", "data" => array() ); } else { // New -> Delete any existing -> Create if ($data[0]['IsDone'] == "0" && $data[0]['IsStarted'] == "0") { $query = 'DELETE FROM `Stats` WHERE `SessionID`=:session;'; $values = array( ":session" => strtolower($payload["session"]["id"]) ); $sql = new SQL; $data = $sql->Query($query, $values); if (!is_array($data)) { $return = array( "status" => "error", "msg" => "Error clearing existing data", "data" => $data ); } else { $query = "INSERT INTO `Stats` (`ID`, `AccountID`, `SessionID`, `Scores`) VALUES (:id, :account, :session, '[]')"; // flag to flip if any query fails $bulk = true; foreach($payload["roster"] as $k => $o) { // Only Store Active Users if ($o["status"] == true) { $values = array( ":id" => date("U") . rand(100000, 999999), ":account" => strtolower($o['user']["id"]), ":session" => strtolower($payload["session"]["id"]) ); $sql = new SQL; $data = $sql->Query($query, $values); if (!is_array($data)) { $bulk = false; } } } if ($bulk == true) { $return = array( "status" => "success", "msg" => "Roster Setup!", "data" => array() ); } else { $return = array( "status" => "error", "msg" => "Some errors occured while storing the Roster", "data" => $data, "values" => $values ); } } // Begun -> Update Stats } else if ($data[0]['IsDone'] == "0" && $data[0]['IsStarted'] == "1") { $query = "UPDATE `Stats` SET `Scores`=:scores WHERE `AccountID`=:account AND `SessionID`=:session ;"; // flag to flip if any query fails $bulk = true; foreach($payload["roster"] as $k => $o) { $values = array( ":scores" => strtolower($o["scores"]), ":account" => strtolower($o["user"]["id"]), ":session" => strtolower($payload["session"]["id"]) ); $sql = new SQL; $data = $sql->Query($query, $values); if (!is_array($data)) { $bulk = false; } } if ($bulk == true) { $return = array( "status" => "success", "msg" => "Scores Updated", "data" => array() ); } else { $return = array( "status" => "error", "msg" => "Some errors occured while updating the Scores", "data" => $data ); } // Finalized; Unable to Alter } else { $return = array( "status" => "error", "msg" => "Session has already been started", "data" => array() ); } } printf(json_encode($return)); ?><file_sep>/src/app/pipes/league-visibility-icon.pipe.ts import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'leagueVisibilityIcon' }) export class LeagueVisibilityIconPipe implements PipeTransform { transform(value: any, args?: any): any { switch (value) { case "public": value = "icon-eye"; break; case "private": value = "icon-eye-off"; break; case "solo": value = "icon-user"; break; default: value = "icon-bug"; break; } return value; } } <file_sep>/src/assets/api/account/logout.php <?php session_start(); header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS'); header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token, Authorization, X-Requested-With'); header("Access-Control-Allow-Credentials: true"); header('Access-Control-Max-Age: 1000'); header('Content-Type: application/json,text/plain'); // Load Basic Functions :: For IP Grab require ($_SERVER['DOCUMENT_ROOT'] . '/disc/lib/functions.php'); require ($_SERVER['DOCUMENT_ROOT'] . '/disc/lib/sql.php'); $sql = new SQL; $payload = json_decode(file_get_contents('php://input'), TRUE); $return = array(); // Query System To Check if Email Exists $query = "DELETE FROM `Flags` WHERE `Account ID`=:accountid AND (`Key`='SessionToken' OR `Key`='LastLogon')"; // Set Values $values = array(":accountid"=>$payload["user"]["id"]); $data = $sql->Query($query, $values); if (!is_array($data)) { $return = array("status"=>"error", "msg"=>"Unable to Unset Session"); } else { $return = array("status"=>"success", "msg"=>"You are now logged out!"); } printf(json_encode($return)); ?><file_sep>/src/app/modules/sessions/sessions.module.ts import { PipesModule } from '../../pipes/pipes.module'; import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { CoursesModule } from '../courses/courses.module' import { ScoresModule } from '../scores/scores.module'; // MFD import { SessionsRoutingModule } from './sessions-routing.module'; import { DetailComponent } from './pages/detail/detail.component'; import { CreateComponent } from './pages/create/create.component'; import { MaterialModule } from '../../shared/modules/material/material.module'; import { ShellComponent } from './pages/shell/shell.component'; import { DashboardComponent } from './pages/dashboard/dashboard.component'; import { SelectFormatComponent } from './dialogs/select-format/select-format.component'; import { SelectPlayersComponent } from './dialogs/select-players/select-players.component'; import { ListItemComponent as SessionListItemComponent } from './components/list-item/list-item.component'; import { SelectTimeComponent } from './dialogs/select-time/select-time.component'; import { SelectCourseComponent } from './dialogs/select-course/select-course.component'; import { PlayComponent } from './pages/play/play.component'; @NgModule({ imports: [ CommonModule, MaterialModule, ScoresModule, CoursesModule, SessionsRoutingModule, PipesModule, ], declarations: [ DetailComponent, CreateComponent, ShellComponent, DashboardComponent, SelectPlayersComponent, SelectFormatComponent, SessionListItemComponent, SelectTimeComponent, SelectCourseComponent, PlayComponent, ], exports: [], entryComponents: [ SelectPlayersComponent, SelectFormatComponent, SelectTimeComponent, SelectCourseComponent, ] }) export class SessionsModule { } <file_sep>/src/assets/api_new/controllers/sessions.php <?php // Session & Header Init require_once($_SERVER['DOCUMENT_ROOT'] . '/sites/disc/api/shared/headers.php'); // Convert HTTP Vars $payload = json_decode(file_get_contents('php://input'), TRUE); // Init Return $return = array(); /** * Get Team List From Score Array * @param $scores: Scores * @return Team[] */ function GetUniqueTeams($scores){ $teamList = array(); foreach ($scores as $key => $array) { // Get Unique TeamList if Teams if (!empty($array['team'])) { $dupe = false; foreach ($teamList as $key => $team) { if ($team['name'] == $array['team']['name']) { $dupe = true; } } if (!$dupe) { $teamList[] = $array['team']; } } } return $teamList; } // Debug /** * Future feature, do not return each step in DB; only return last; Can flag with this later on */ $devMode = true; // DB require_once($_SERVER['DOCUMENT_ROOT'] . '/sites/disc/api/shared/sql.php'); $database = new DB("session"); // Session require_once($_SERVER['DOCUMENT_ROOT'] . '/sites/disc/api/classes/sessions.php'); $sessions = new Session($database); // Player require_once($_SERVER['DOCUMENT_ROOT'] . '/sites/disc/api/classes/players.php'); $player = new Player($database); // Scores require_once($_SERVER['DOCUMENT_ROOT'] . '/sites/disc/api/classes/scores.php'); $scores = new Score($database); // Courses require_once($_SERVER['DOCUMENT_ROOT'] . '/sites/disc/api/classes/courses.php'); $courses = new Course($database); switch ($payload['action']) { /* case "recient": $return[] = $courses->UserRecientlyPlayed($payload['user']); break; case "favorites": $return[] = $courses->UserFavorites($payload['user']); break; case "search": $return[] = $courses->search($payload['term']); break; */ case "list": // Loop Each Session $sessionList = $sessions->getList($payload['start'], $payload['limit'], $payload["user"]); if ($sessionList['status'] == 'success') { $return[] = $sessionList; // Map for formatting session-format } else { $return[] = array( 'status' => 'error', 'msg' => 'Unable to get Session List', 'sessions' => $sessionList ); } break; case "create": // Verify User $user = $player->getPlayerByEmail($payload['user']['email']); $return[] = $user; if ($user["status"] == "success" && count($user['results']) > 0) { // Generate GUID $payload['session']['id'] = $database->generateGUID(); // Session Link $createdSession = $payload['session']; // Create Session $r_createSession = $sessions->create($createdSession, $payload['user']); $return[] = $r_createSession; if ($r_createSession['status'] == "success" && $r_createSession['affectedRows'] == 1) { // Scores $r_createScores = array(); $teamList = GetUniqueTeams($createdSession["scores"]); // Create Teams if Exist if (count($teamList) > 0) { $r_createTeams = array(); foreach ($teamList as $key => $array) { // Create GUID For Team $teamID = $database->generateGUID(); $teamList[$key]['id'] = $teamID; // Create $r_createTeams[] = $sessions->createTeam($createdSession, $teamList[$key], $payload["user"]); } // Verify All Teams Were Created $r_createTeams_valid = true; foreach ($r_createTeams as $key => $array) { if ($array["status"] != "success") { $r_createTeams_valid = false; } } if ($r_createTeams_valid) { $return[] = array( 'status' => 'success', 'msg' => 'Teams Created', 'mapTo' => 'session', 'debug' => $r_createTeams, 'teamList' => $teamList ); } else { $return[] = array( 'status' => 'error', 'msg' => 'Unable to Create Teams', 'teams' => $r_createTeams ); } } // Scores foreach ($createdSession["scores"] as $key => $array) { // Update Team Ids if (count($teamList) > 0) { foreach ($teamList as $tk => $ta) { if ($array["team"]["name"] == $ta["name"]) { $createdSession["scores"][$key]['team']['id'] = $ta["id"]; } } } // Create GUID For Score $scoreID = $database->generateGUID(); $createdSession["scores"][$key]['id'] = $scoreID; $r_createScores[] = $scores->create($createdSession, $createdSession["scores"][$key], $payload["user"]); } // Verify All Scores Were Created $r_createScores_valid = true; foreach ($r_createScores as $key => $array) { if ($array["status"] != "success") { $r_createScores_valid = false; } } if ($r_createScores_valid) { $return[] = array( 'status' => 'success', 'msg' => 'Scores Created', 'mapTo' => 'session', 'scores' => $r_createScores, 'results' => array($createdSession) ); } else { $return[] = array( 'status' => 'error', 'msg' => 'Unable to Create Scores', 'scores' => $r_createScores, 'results' => array($createdSession) ); } // Get Session from Server } else { $return[] = array( 'status' => 'error', 'msg' => 'Unable to Create Session', 'session' => $r_createSession ); } } else { $return[] = array( 'status' => 'error', 'msg' => 'Unable to Verify Account' ); } break; case "detail": $sessionDetails = $sessions->getDetails($payload["session"], $payload["user"]); if ($sessionDetails['status'] == 'success' && $sessionDetails['affectedRows'] == 1) { $session = $sessionDetails["results"][0]; // Get Course $r_getCourse = $courses->getDetails($session["course_id"]); $return[] = $r_getCourse; if ($r_getCourse['status'] == 'success' && $r_getCourse['affectedRows'] == 1) { // Set Course $sessionDetails["results"][0]["course"] = $r_getCourse['results'][0]; // Get Scores if (strpos($session['format'], "team") === false) { $r_scoreList = $scores->getScores($session); } else { $r_scoreList = $scores->getScoresWithTeams($session); } $return[] = $r_scoreList; // Format Scores if ($r_scoreList['status'] == 'success' && $r_scoreList['affectedRows'] > 0) { $formattedScores = array(); foreach ($r_scoreList['results'] as $pK => $p) { $formattedScores[] = array( 'id' => $p["scores.id"], 'created_on' => $p["scores.created_on"], 'created_by' => $p["scores.created_by"], 'modified_on' => $p["scores.modified_on"], 'modified_by' => $p["scores.modified_by"], 'throws' => json_decode($p["scores.throws"]), 'handicap' => $p["scores.handicap"], 'team' => array( "id" => $p['scores.team.id'], "name" => $p['scores.team.name'], "color" => json_decode($p['scores.team.color']) ), 'player' => array( "id" => $p['scores.player.id'], "first_name" => $p['scores.player.first_name'], "last_name" => $p['scores.player.last_name'], "email" => $p['scores.player.email'] ) ); } // Replace Scores with format $sessionDetails["results"][0]['scores'] = $formattedScores; $return[] = $sessionDetails; } else { $return[] = array( 'status' => 'error', 'msg' => 'Failed to retrieve Score List', 'sessions' => $sessionDetails, 'scores' => $scoreList ); } } else { $return[] = array( "status" => "error", "msg" => "Failed to retrieve Course", "debug" => $sessionDetails ); } } else { $return[] = array( "status" => "error", "msg" => "Failed to retrieve Session", "debug" => $sessionDetails ); } break; case "update": break; case "delete": // Verify They Are Creator // Get Details // Delete If So $sessionDetails = $sessions->getDetails($payload["session"], $payload["user"]); if ($sessionDetails['status'] == 'success' && $sessionDetails['affectedRows'] == 1) { $session = $sessionDetails["results"][0]; if ($session['created_by'] == $payload['user']['id']) { $r_deleteSession = $sessions->delete($session); $return[] = $r_deleteSession; if ($r_deleteSession['status'] == 'success' && $r_deleteSession['affectedRows'] > 1) { $return[] = array( "status" => "success", "msg" => "Session was deleted", ); } else { $return[] = array( "status" => "error", "msg" => "Nothing was deleted" ); } } else { $return[] = array( "status" => "error", "msg" => "Insufficent permissions" ); } } break; default: $return[] = array( "status" => "error", "msg" => "Unknown Action", ); break; } printf(json_encode($return)); <file_sep>/src/app/modules/account/components/edit/edit.component.ts import { FeedbackService } from '../../../../shared/modules/feedback/services/feedback.service'; import { flyInPanelRow } from './../../../../animations'; import { FormGroup} from '@angular/forms'; import { Component, OnInit } from '@angular/core'; import { AccountFormService } from '../../services/account-form.service'; @Component({ selector: 'app-account-edit', templateUrl: './edit.component.html', styleUrls: ['./edit.component.css'], animations: [flyInPanelRow] }) export class EditComponent implements OnInit { public form: FormGroup; constructor( public accountForm: AccountFormService, public feed: FeedbackService, ) { } ngOnInit() { this.accountForm.Setup("update"); this.accountForm.form$.subscribe((f)=>{ this.form = f; this.feed.stopLoading("update"); }); } onFormSubmit(){ this.accountForm.SubmitUpdate(); } } <file_sep>/src/app/modules/scores/components/team-list/team-list.component.ts import { Component, OnInit } from '@angular/core'; import { ScoresBackend } from '../../services/backend.service'; import { MatDialog } from '@angular/material'; import { TeamSettingsComponent } from '../../dialogs/team-settings/team-settings.component'; import { flyIn } from 'src/app/animations'; @Component({ selector: 'team-list', templateUrl: './team-list.component.html', styleUrls: ['./team-list.component.scss'], animations: [flyIn], }) export class TeamListComponent implements OnInit { private playerModes = ["full", "admin"]; constructor( private _scores: ScoresBackend, private dialog: MatDialog, ) { } ngOnInit() { } teamSettings(team) { this.dialog.open(TeamSettingsComponent, { data: team, }) } } <file_sep>/src/app/modules/scores/services/scores-form.service.ts import { Injectable } from '@angular/core'; import { BehaviorSubject, Observable } from 'rxjs'; import { FormGroup, FormControl, Validators, FormBuilder } from '@angular/forms'; import { FeedbackService } from 'src/app/shared/modules/feedback/services/feedback.service'; import { ScoresBackend } from './backend.service'; import { HelperService } from 'src/app/shared/services/helper.service'; @Injectable({ providedIn: 'root' }) export class ScoresFormService { private form: BehaviorSubject<FormGroup> = new BehaviorSubject(undefined); form$: Observable<FormGroup> = this.form.asObservable(); private cTerm = new FormControl("", [ Validators.required, Validators.minLength(2), Validators.maxLength(128) ]); constructor( private builder: FormBuilder, private feed: FeedbackService, private helper: HelperService, private _scores: ScoresBackend, ) { } Setup(type) { var form = this.builder.group({}); switch (type) { case "search": form.addControl("search", this.cTerm); // Listen to Input changes to trigger loading and search form.get("search").valueChanges.pipe(this.helper.pipe).subscribe((s) => { if (form.valid) { this.feed.stopLoading("scoreSearch"); this._scores.getSearch(s as string); } }); // Turn off Loader when Results populate this._scores.searchedPlayers$.subscribe((s) => { this.feed.stopLoading("scoreSearch"); }); break; } this.form.next(form); } resetPlayerSearch() { this.form.value.get("search").reset(); } } <file_sep>/src/app/shared/modules/feedback/services/feedback.service.ts import { Injectable, OnInit, ErrorHandler } from '@angular/core'; import { MatSnackBar } from '@angular/material'; import { ServerPayload } from 'src/app/app.component'; import { Router, NavigationEnd, NavigationStart } from '@angular/router'; import { BehaviorSubject, Observable } from 'rxjs'; import { HttpErrorResponse } from '@angular/common/http'; import { delay } from 'rxjs/internal/operators/delay'; import { timeout } from 'rxjs/internal/operators/timeout'; import { FeedbackErrorHandler } from 'src/app/shared/types'; @Injectable({ providedIn: 'root' }) export class FeedbackService implements OnInit { // loading: boolean = true; // Bank of elements that have errors private list: BehaviorSubject<FeedbackErrorHandler[]> = new BehaviorSubject([]); list$: Observable<FeedbackErrorHandler[]> = this.list.asObservable(); private loading: BehaviorSubject<string[]> = new BehaviorSubject([]); loading$: Observable<string[]> = this.loading.asObservable(); constructor( private snackBar: MatSnackBar ) { } ngOnInit() { } /* Error Message Functions */ hasError(elementName: string): boolean | FeedbackErrorHandler { let tracked = this.list.value.find(e => { e.element == elementName }); if (tracked != undefined) { return tracked; } else { return false; } } clearError(elementName: string): void { // FilterList let list = this.list.value.filter(e => { return e.element != elementName; }); // Emit Updates this.list.next(list); } setError(elementName: string, message: string): void { // Dont add an already existing let list = this.list.value; let found = list.filter(e => { return e.element == elementName; }); // console.warn ("ErrorList: ", list); // console.log ("found: ", found); // If Not In; Push if (found.length == 0) { let feed = new FeedbackErrorHandler() feed.element = elementName; feed.msg = message; list.push(feed); } // Emit Updates this.list.next(list); } /* Loading Functions */ isLoading(actionName: string): boolean { let tracked = this.list.value.find(e => { e.element == actionName }); return tracked != undefined; } startLoading(actionName: string): void { // Dont add an already existing let list = this.loading.value; if (list == undefined) { list = [actionName]; } else { let found = list.filter(e => { return e == actionName; }); // If Not In; Push if (found != undefined) { list.push(actionName); } } // Emit Updates this.loading.next(list); } stopLoading(actionName: string): void { // FilterList let list = this.loading.value.filter(e => { return e != actionName; }); // Emit Updates this.loading.next(list); } /** * @event REST Callback with result of error * To tie in with message component for form * feedback */ toast(payload: ServerPayload) { // Scale Duration based on message length var length = payload.msg.length; var scale = (length * 2) / 1000; var duration = 3000 * (scale + 1); this.snackBar.open(payload.msg, "Close", { panelClass: payload.status, duration: duration * 1.3, verticalPosition: "top" }); } } <file_sep>/src/app/interceptors/formatter.interceptor.ts /* Placeholder for HTTP INterceptor; Will replace & contain the following features: HTTP Auth Token Can Incorperate a Timeout with always writing a new token on every request. Timeout can be calculated from modified date. X Message/Notification(Feedback) Service Include Loader boolean in this for resolve replacement Retry On Fail Possible cache? */ import { Injectable } from '@angular/core'; import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor, HttpResponse } from '@angular/common/http'; import { Observable, of } from 'rxjs'; import { AccountBackend } from '../modules/account/services/backend.service'; import { FeedbackService } from '../shared/modules/feedback/services/feedback.service'; import { map, catchError } from 'rxjs/operators'; import { HelperService } from '../shared/services/helper.service'; import { Course } from '../shared/types'; @Injectable() export class FormatterInterceptor implements HttpInterceptor { previousUrl: string = ''; constructor( private _account: AccountBackend, private _feed: FeedbackService, private _helper: HelperService ) { } intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { // console.log("request: ", request, next); return next.handle(request).pipe( map((event: HttpEvent<any>) => { if (event instanceof HttpResponse) { let list = event.body; let latest = list.length - 1; switch (list[latest].mapTo) { case "course": list[latest].formattedResults = this._helper.convertCourse(list[latest].results); break; case "session": list[latest].formattedResults = this._helper.convertSession(list[latest].results); break; case "scores": list[latest].formattedResults = this._helper.convertScores(list[latest].results); break; } // console.log("formattedServerResponse: ", event); return event; } return event; })); } }<file_sep>/src/assets/api_new/shared/sql.php <?php class DB { protected $host; protected $db; protected $user; protected $pass; protected $charset; protected $dsn; public $stmt; public $pdo; public $data; public $dataType; // Init public function __construct($dataType = "") { $this->dataType = $dataType; $this->getConnection(); } // get the database connection public function getConnection(): void { $this->connection = null; $this->host = "brandonslottycom.fatcowmysql.com"; $this->username = "dg_admin_1"; $this->password = "<PASSWORD>"; $this->database = "discing_2"; $this->charset = 'utf8mb4'; $this->dsn = "mysql:host=". $this->host . ";dbname=". $this->database .";charset=". $this->charset .";"; try { $this->pdo = new PDO($this->dsn, $this->username, $this->password); } catch (PDOException $exception) { echo "Error: " . $exception->getMessage(); } } // Generate GUID public function generateGUID() { if (function_exists('com_create_guid') === true) { return trim(com_create_guid(), '{}'); } else { $data = openssl_random_pseudo_bytes(16); $data[6] = chr(ord($data[6]) & 0x0f | 0x40); $data[8] = chr(ord($data[8]) & 0x3f | 0x80); return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4)); } } // Easy Return Last ID public function lastInsertId() { return $this->pdo->lastInsertId(); } // Run Query and Return Data public function Query($q, $v) { $payload = array(); if (!$this->stmt = $this->pdo->prepare($q)) { $payload = array( "status" => "error", "msg" => "Error with query", "debug" => array( "q" => $q, "v" => $v ) ); } else if (!$this->stmt->execute($v)) { $payload = array( "status" => "error", "code" => $this->stmt->errorCode(), "phase" => "execute", "msg" => $this->stmt->errorInfo(), "debug" => array( "q" => $q, "v" => $v ) ); } else { $payload = array( "status" => "success", "mapTo" => $this->dataType, "affectedRows" => $this->stmt->rowCount(), "results" => $this->stmt->fetchAll(PDO::FETCH_ASSOC), "debug" => array( "q" => $q, "v" => $v ) ); } return $payload; } public function Access($league, $user) { // Verify Permissions $validUser = false; $query = "SELECT `p`.`ID` AS `P.ID`, `p`.`Level` AS `P.Level`, `p`.`Status` AS `P.Status`, `l`.`ID` AS `L.ID`, `a`.`ID` AS `A.ID`, `a`.`First` AS `A.First`, `a`.`Last` AS `A.Last`, `a`.`Email` AS `A.Email` FROM `Permissions` AS `p` JOIN `Leagues` AS `l` ON `p`.`LeagueID`=`l`.`ID` JOIN `Accounts` AS `a` ON `a`.`ID`=`p`.`UserID` WHERE `l`.`ID`=:leagueid AND `p`.`Status` <> 'rejected' ORDER BY `p`.`Level`, `p`.`Status`;"; // Set Values $values = array( ":leagueid" => $league["id"] ); $data = $this->Query($query, $values); if (count($data) == 0) { $return = array( "status" => "error", "msg" => "No Permissions Found" ); } else { foreach ($data as $k => $o) { if ($o['A.ID'] == $user["id"] && ($o["P.Level"] == "moderator" || $o["P.Level"] == "creator")) { $validUser = true; } } } if ($validUser != true) { $return = array( "status" => "error", "msg" => "You do not have sufficent permissions to perform this action" ); } else { $return = array( "status" => "success", "msg" => "Valid User" ); } return $return; } } ?><file_sep>/src/assets/api/stats/finish.php <?php session_start(); header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS'); header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token, Authorization, X-Requested-With'); header("Access-Control-Allow-Credentials: true"); header('Access-Control-Max-Age: 1000'); header('Content-Type: application/json,text/plain'); // Load Basic Functions :: For IP Grab require ($_SERVER['DOCUMENT_ROOT'] . '/api/disc/functions.php'); require ($_SERVER['DOCUMENT_ROOT'] . '/api/disc/sql.php'); $payload = json_decode(file_get_contents('php://input'), TRUE); $return = array(); /* Process: Set Session IsDone to True; */ // Get List of Leagues for User $query = "SELECT `st`.`ID` AS `S.ID`, `st`.`Scores` AS `S.Scores`, `a`.`ID` AS `A.ID`, `a`.`First` AS `A.First`, `a`.`Last` AS `A.Last`, `a`.`Email` AS `A.Email` FROM `Stats` AS `st` JOIN `Accounts` AS `a` ON `st`.`AccountID`=`a`.`ID` JOIN `Sessions` AS `sn` ON `st`.`SessionID`=`sn`.`ID` WHERE `sn`.`ID`=:session ;"; // Set Values $values = array(":session"=>strtolower($payload["session"]["id"])); $sql = new SQL; $data = $sql->Query($query, $values); if (count($data) == 0) { $return = array( "status" => "error", "msg" => "No stats found", "data" => array() ); } else { $payload = []; foreach ($data as $o) { $payload[] = array( "id" => $o['S.ID'], "session" => array( "id" => $payload["session"]["id"] ), "user" => array( "id" => $o['A.ID'], "first" => $o['A.First'], "last" => $o['A.Last'], "email" => $o['A.Email'] ), "scores" => $o['S.Scores'] ); } $return = array( "status"=>"success", "data"=> $payload ); } printf(json_encode($return)); ?><file_sep>/src/app/pipes/league-visibility-icon.pipe.spec.ts import { LeagueVisibilityIconPipe } from './league-visibility-icon.pipe'; describe('LeagueVisibilityIconPipe', () => { it('create an instance', () => { const pipe = new LeagueVisibilityIconPipe(); expect(pipe).toBeTruthy(); }); }); <file_sep>/src/app/modules/scores/components/team-select/team-select.component.ts import { Component, OnInit } from '@angular/core'; import { CdkDragDrop } from '@angular/cdk/drag-drop'; import { SessionFormService } from 'src/app/modules/sessions/services/form.service'; import { ScoresBackend } from '../../services/backend.service'; import { Observable } from 'rxjs'; import { MatDialog } from '@angular/material'; import { TeamSettingsComponent } from '../../dialogs/team-settings/team-settings.component'; import { SessionBackend } from 'src/app/modules/sessions/services/backend.service'; @Component({ selector: 'team-select', templateUrl: './team-select.component.html', styleUrls: ['./team-select.component.scss'] }) export class TeamSelectComponent implements OnInit { private rstr = this._scores.roster$; private playerModes = ["full", "admin", "remove"]; constructor( private _sessions: SessionBackend, private _scores: ScoresBackend, private dialog: MatDialog ) { } ngOnInit() { } rosterDrop(event: CdkDragDrop<string[]>) { this._scores.movePlayer(event); } getPlayerList(team) { return this._scores.getRoster(team); } openSettings(team) { this.dialog.open(TeamSettingsComponent, { minWidth: "75vw", data: team, }); } removeTeam(team) { this._scores.removeTeam(team); } trackTeamBy(index, item) { item.name; } } <file_sep>/src/app/shared/modules/charts/line/line.component.ts import { Component, OnInit, Input } from '@angular/core'; import { MatDialog } from '@angular/material'; import { LineSettingsComponent } from '../line-settings/line-settings.component'; import { StatsBackend } from '../../../../modules/stats/services/backend.service'; import { flyInPanelRow } from 'src/app/animations'; @Component({ selector: 'app-line', templateUrl: './line.component.html', styleUrls: ['./line.component.css'], animations: [flyInPanelRow] }) export class LineComponent implements OnInit { headerButtons = [ { action: "edit", icon: "icon-settings", color: "transparent-primary" }, { action: "rotate", icon: "icon-rotate-cw", color: "transparent-primary" } ]; resolve: boolean = false; @Input() data; @Input() format; @Input() par; @Input() teams; @Input() players; fontColor = "#EFEFEF"; // Data columnNames = []; chartData = []; initialHeaders = []; initialData = []; colList = []; // Chart Options title = ""; type = "LineChart"; width = document.getElementsByClassName("headerContainer")[0].scrollWidth; //window.innerWidth * .959; height = 400; orientation = "horizontal"; options = { /* Axis jumps to another bar; looks inconsistant */ animation: { duration: 0, easing: "linear", startup: false, }, /* Structure */ curveType: "function", enableInteractivity: true, dynamicResize: true, chartArea: { left: "5%", top: "%0", width: '90%', height: '90%', }, theme: "maximized", /* Design */ backgroundColor: "transparent", colors: [], pointsVisible: true, pointShape: "circle", pointSize: 10, lineWidth: 3, series: { 0: {}, }, /* Section Specific */ legend: { alignment: "center", position: "top", textStyle: { color: this.fontColor, } }, hAxis: { /* title: "Hole", */ textStyle: { color: this.fontColor, }, textPosition: "out", baseline: 9, baselineColor: "#fafaf0", gridlines: { color: "#506450", count: -1, } }, vAxis: { /* title: "Score", */ ticks: [], textStyle: { color: this.fontColor, }, textPosition: "out", baseline: 0, baselineColor: "#fafaf0", gridlines: { color: "#506450", count: -1, }, maxValue: 10, minValue: -10 }, }; constructor( private dialog: MatDialog, private stats: StatsBackend, ) { } ngOnInit() { // Defaults this.columnNames = this.data['columns']; this.chartData = this.data['scores']; this.options.colors = this.stats.getColorsFromBank(this.players, this.teams); // this.formatChart(this.data['columns'], this.data['scores']); this.initialHeaders = this.columnNames; this.initialData = this.chartData; console.log("chart: ", this.chartData); // Set Tick Range; this.options.vAxis.maxValue = this.getHighestScore(); this.options.vAxis.minValue = this.getLowestScore(); this.options.vAxis.ticks = this.initTicks(); this.resolve = true; } actionClick($event) { if ($event == "edit") { this.openSettings(); } else if ($event == "rotate") { this.rotateChart(); } } getLowestScore() { var score = 0 this.chartData.map((scores, i) => { var testScore = scores.sort((a, b) => { if (typeof a === "string") { return null; } else if (typeof b == "string") { return null } return a - b; })[1]; // Return 1, as 0 is the hole string; if (testScore < score) { score = testScore; } }); return score; } getHighestScore() { var score = 0 this.chartData.map((scores, i) => { var testScore = scores.sort((a, b) => { if (typeof a === "string") { return null; } else if (typeof b == "string") { return null } return b - a; })[1]; // Return 1, as 0 is the hole string; if (testScore > score) { score = testScore; } }); return score; } initTicks(): Array<any> { var ticks = []; for (var i = this.getLowestScore(); i <= this.getHighestScore(); i++) { if (i == this.options.vAxis.minValue) { var remainder = 3 - Math.abs(this.options.vAxis.minValue % 3); var paddingValue = this.options.vAxis.minValue - remainder; ticks.push(paddingValue); } else if (i == this.options.vAxis.maxValue) { var remainder = 3 - Math.abs(this.options.vAxis.maxValue % 3); var paddingValue = remainder + this.options.vAxis.maxValue; ticks.push(paddingValue); } else if (i % 3 == 0) { ticks.push(i); } } console.log("Ticks: ", ticks); return ticks; } /* Change orientation onClick */ rotateChart() { if (this.orientation == "horizontal") { this.height = window.innerWidth * .959; this.width = window.innerHeight * .8; this.orientation = "vertical"; } else { this.width = window.innerWidth * .959; this.height = 400; this.orientation = "horizontal"; } } filterData(selectedColumns) { /** Get Stuff to Save */ var keep = [0]; selectedColumns.map((ev, ei) => { this.initialHeaders.map((cv, ci) => { if (cv == ev) { keep.push(ci); } }) }); /** Filter Columns */ this.columnNames = this.initialHeaders.filter((hv, hi) => { return keep.indexOf(hi) > -1; }); /** Filter Data */ this.chartData = this.initialData.map((ia, ii) => { ia = ia.filter((v, i) => { if (keep.indexOf(i) != -1) { return true; } else { return false; } }); return ia; }); } openSettings() { const settingsDialog = this.dialog.open(LineSettingsComponent, { data: { scores: this.data, format: this.format, colors: this.stats.getColorsFromBank(this.players, this.teams), teams: this.teams, players: this.players, } }); settingsDialog.afterClosed().subscribe((diag) => { // console.log ("popup.Data: ", diag); if (diag) { // Re-Format Data From Arrays; // Get Teams for Repop var teams = this.teams.filter((t) => { return diag['selectedColumns'].indexOf(t.name) > -1; }); // Get Players for Repop var players = this.players.filter((p) => { // Shorten Name; var name = p.user.first + " " + p.user.last.substr(0, 3); return diag['selectedColumns'].indexOf(name) > -1; }); // Exception to Show Team Only if (players.length == 0 && teams.length > 0) { players = this.players; } // Rework Above player reset to account for Partial Team Selection // Team 1 No players with team 2 any players gets around the above filter and Errors // Need to count for players on teams, if teams exist // If Teams -> Loop -> // Roster Player Count vs Selected Player Count for this team // If Blank-> Assign full team roster temporarily // // Then we need to account for visibility. Which will not be accounted for // if we replace the player array with the initial array... // // Worth? // Add a sub-display to the title to show Scores/Throws this.options.colors = this.stats.getColorsFromBank(players, teams); // Data Store players = this.stats.populatePlayerScores(players, this.par); teams = this.stats.populateTeamScores(teams, players, this.par); // console.log ("AfterCheck: players: ", players, "teams: ", teams, "colors: ", this.options.colors); // Format Chart Data; var results = this.stats.formatChart(players, diag["teamFormat"], diag["format"], teams); this.chartData = results['scores']; this.columnNames = results["columns"]; // Toggles Visibility // this.filterData(diag['selectedColumns']); // console.log ("results: ", results, this.chartData); } }); } } export interface Chart { columns: Array<any>; scores: Array<any>; }<file_sep>/src/assets/api/leagues/create.php <?php session_start(); header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS'); header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token, Authorization, X-Requested-With'); header("Access-Control-Allow-Credentials: true"); header('Access-Control-Max-Age: 1000'); header('Content-Type: application/json,text/plain'); // Load Basic Functions :: For IP Grab require ($_SERVER['DOCUMENT_ROOT'] . '/api/disc/functions.php'); require ($_SERVER['DOCUMENT_ROOT'] . '/api/disc/sql.php'); $payload = json_decode(file_get_contents('php://input'), TRUE); $return = array(); // Create $query = "INSERT INTO `Leagues` (`ID`, `Name`, `Visibility`, `Restrictions`, `Description`) VALUES (:id, :name, :visibility, :restrictions, :description)"; $payload["id"] = date("U") . rand(100000, 999999); // Store ID For Return $leagueID = $payload["id"]; // Set Values $values = array( ":id" => $leagueID, ":name" => $payload['league']['name'], ":visibility" => $payload['league']['visibility'], ":restrictions" => $payload['league']['restrictions'], ":description" => $payload['league']['description'] ); // var_dump($values); $sql = new SQL; $data = $sql->Query($query, $values); if ($data === false) { $return = array("status"=>"error", "msg"=>"Unable to create League"); } else { // Set Permissions for Creator on this league when Create. $query = "INSERT INTO `Permissions` (`ID`, `LeagueID`, `UserID`, `Level`, `Status`) VALUES (:id, :league, :user, 'creator', 'approved')"; $values = array( ":id"=> date("U") . rand(100000, 999999), ":league"=> $leagueID, ":user"=> $payload["user"]["id"] ); $data = $sql->Query($query, $values); if ($data === false) { $return = array("status"=>"error", "msg"=>"Unable to create permissions"); } else { $return = array( "status" =>"success", "msg" =>"You have successfully created your league!", "insertID" =>$leagueID ); } } printf(json_encode($return)); ?><file_sep>/src/app/404/page-not-found.component.ts import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-page-not-found', templateUrl: './page-not-found.component.html', styleUrls: ['./page-not-found.component.css'] }) export class PageNotFoundComponent implements OnInit { constructor() { } ngOnInit() { } } /* Other Codes to Manage: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status 418 I'm a teapot The server refuses the attempt to brew coffee with a teapot. 429 Too Many Requests The user has sent too many requests in a given amount of time ("rate limiting"). 500 Internal Server Error The server has encountered a situation it doesn't know how to handle. 502 Bad Gateway This error response means that the server, while working as a gateway to get a response needed to handle the request, got an invalid response. 503 Service Unavailable The server is not ready to handle the request. Common causes are a server that is down for maintenance or that is overloaded. Note that together with this response, a user-friendly page explaining the problem should be sent. This responses should be used for temporary conditions and the Retry-After: HTTP header should, if possible, contain the estimated time before the recovery of the service. The webmaster must also take care about the caching-related headers that are sent along with this response, as these temporary condition responses should usually not be cached. 504 Gateway Timeout This error response is given when the server is acting as a gateway and cannot get a response in time. */ <file_sep>/src/assets/api/stats/edit.php <?php session_start(); header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS'); header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token, Authorization, X-Requested-With'); header("Access-Control-Allow-Credentials: true"); header('Access-Control-Max-Age: 1000'); header('Content-Type: application/json,text/plain'); // Load Basic Functions :: For IP Grab require ($_SERVER['DOCUMENT_ROOT'] . '/api/disc/functions.php'); require ($_SERVER['DOCUMENT_ROOT'] . '/api/disc/sql.php'); $sql = new SQL; $payload = json_decode(file_get_contents('php://input'), TRUE); $return = array(); // Verify Permissions $validUser = $sql->Access($payload["league"], $payload["user"]); if ($validUser["status"] == "error") { $return = array( "status"=>"error", "msg"=>"You do not have sufficent permissions to perform this action" ); } else { $query = " UPDATE `Stats` SET `Throws`=:throws WHERE `AccountID`=:account AND `SessionID`=:session ; UPDATE `Pars` SET `Par`=:par WHERE `SessionID`=:session; "; // flag to flip if any query fails $bulk = true; foreach($payload["roster"] as $k => $o) { $values = array( ":throws" => $o["throwString"], ":account" => $o["user"]["id"], ":session" => $payload["session"]["id"], ":par" => $payload["session"]["parString"] ); $sql = new SQL; $data = $sql->Query($query, $values); if (!is_array($data)) { $bulk = false; } } if ($bulk == true) { $return = array( "status" => "success", "msg" => "Scores Updated", "data" => array() ); } else { $return = array( "status" => "error", "msg" => "Some errors occured while updating the Scores", "data" => $data ); } } printf(json_encode($return)); ?><file_sep>/src/app/modules/sessions/pages/create/create.component.ts import { FormGroup, FormArray } from '@angular/forms'; import { Component, OnInit } from '@angular/core'; import { SessionFormService } from '../../services/form.service'; import { flyIn, flyLeft } from 'src/app/animations'; import { MatDialog } from '@angular/material'; import { SelectCourseComponent } from '../../dialogs/select-course/select-course.component'; import { SelectFormatComponent } from '../../dialogs/select-format/select-format.component'; import { SelectTimeComponent } from '../../dialogs/select-time/select-time.component'; import { SelectPlayersComponent } from '../../dialogs/select-players/select-players.component'; import { SessionBackend } from '../../services/backend.service'; import { ScoresBackend } from 'src/app/modules/scores/services/backend.service'; import { Session } from 'src/app/shared/types'; import { Observable } from 'rxjs/internal/Observable'; import { FeedbackService } from 'src/app/shared/modules/feedback/services/feedback.service'; @Component({ selector: 'app-create', templateUrl: './create.component.html', styleUrls: ['./create.component.css'], animations: [flyIn, flyLeft] }) export class CreateComponent implements OnInit { form: FormGroup; session$: Observable<Session> = this._sessions.detail$; constructor( private sessionForm: SessionFormService, private _sessions: SessionBackend, private _scores: ScoresBackend, private dialog: MatDialog, private feed: FeedbackService, ) { } ngOnInit() { this._sessions.resetDetails(); // Setup Form this.sessionForm.Setup("create"); this.sessionForm.form$.subscribe((f) => { this.form = f; }); } // Popups selectCourse() { this.dialog.open(SelectCourseComponent, { minWidth: "75vw", }); } selectFormat() { this.dialog.open(SelectFormatComponent, { minWidth: "75vw", }); } selectTime() { this.dialog.open(SelectTimeComponent, { }); } selectPlayers() { this.dialog.open(SelectPlayersComponent, { minWidth: "75vw", }); } } <file_sep>/src/app/app.component.ts import { Component, OnInit } from '@angular/core'; import { Router, ActivatedRoute } from '@angular/router'; import { flyIn, flyLeft, flyRight } from 'src/app/animations'; import { AccountBackend } from './modules/account/services/backend.service'; import { Location } from '@angular/common'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'], animations: [flyIn, flyRight, flyLeft], }) export class AppComponent implements OnInit { private crumbs: boolean = false; private paths: Array<string> = []; constructor( private router: Router, private location: Location, private route: ActivatedRoute, private account: AccountBackend, ) { } ngOnInit() { // Show/Hide Breadcrumb Nav from URL this.router.events.subscribe((r)=>{ if (this.location.path() != "/home") { this.crumbs = true; } else { this.crumbs = false; } this.paths = this.location.path().substr(1, this.location.path().length).split("/"); // console.warn("crumbs?", this.paths, this.crumbs); }); } getRoute(outlet) {} } export class ServerPayload { public status: string; public msg: string; public data: Array<any>; }<file_sep>/src/assets/api_new/classes/courses.php <?php class Course { // Properties public $id; public $created_by; public $created_on; public $modified_by; public $modified_on; public $name; public $park_name; public $city; public $state; public $zip; public $latitude; public $longitude; // DB public $db; public $con; // Init public function __construct($db) { $this->db = $db; $this->con = $db->getConnection(); } public function getList($start = 0, $limit = 100) { $query = "SELECT `id`, `created_by`, `created_on`, `modified_by`, `modified_on`, `park_name`, `city`, `state`, `zip`, `latitude`, `longitude` FROM `Courses` LIMIT " . (int) $start . ", " . (int) $limit . ";"; $values = array(); return $this->db->Query($query, $values); } public function getDetails($id) { $query = "SELECT `id`, `created_by`, `created_on`, `modified_by`, `modified_on`, `park_name`, `city`, `state`, `zip`, `latitude`, `longitude` FROM `Courses` WHERE `id`=:id LIMIT 1;"; $values = array( ":id" => $id ); return $this->db->Query($query, $values); } public function search($term, $start = 0, $limit = 100) { $query = "SELECT `id`, `created_by`, `created_on`, `modified_by`, `modified_on`, `park_name`, `city`, `state`, `zip`, `latitude`, `longitude` FROM `Courses` HAVING LOWER( CONCAT( `park_name`,';', `city`,';', `state`,';', `zip` )) LIKE CONCAT('%%', :term, '%%') LIMIT " . (int) $start . ", " . (int) $limit . ";"; $values = array( ":term" => strtolower($term) ); return $this->db->Query($query, $values); } public function create($course, $user) { $query = "INSERT INTO `Courses` (`id`, `created_by`, `created_on`, `modified_by`, `modified_on`, `park_name`, `city`, `state`, `zip`, `latitude`, `longitude` ) VALUES (:id, :created_by, :created_on, :modified_by, :modified_on, :park_name, :city, :state, :zip, :latitude, :longitude);"; $values = array( ':id' => $this->db->generateGUID(), ':created_by' => $user['id'], ':created_on' => date('c'), ':modified_by' => null, ':modified_on' => null, ':park_name' => $course['park_name'], ':city' => $course['city'], ':state' => $course['state'], ':zip' => $course['zip'], ':latitude' => $course['latitude'], ':longitude' => $course['longitude'] ); return $this->db->Query($query, $values); } public function update($course) { // Base Values on each update; $values = array( ":id" => $course["id"] ); $course["modified_on"] = date("c"); // Init Query $query = "UPDATE `Courses` SET "; // Update query and values foreach ($course as $key => $value) { if (!array_key_exists(":" . $key, $values)) { $query .= "`" . $key . "`=:" . $key . ", "; $values[":" . $key] = $value; } }; // Remove Trailing ", " $query = substr($query, 0, -2); // Finalize Query; $query .= " WHERE `id`=:id LIMIT 1"; return $this->db->Query($query, $values); } public function delete($course, $requestor) { } // For Delete public function getCreator() { } /** * Input course from frontend format to backend format */ public function ConvertFrontBack($course) { $newCourse = array( 'park_name' => $course['parkName'], 'city' => $course['city'], 'state' => $course['state'], 'zip' => $course['zip'], 'latitude' => $course['lat'], 'longitude' => $course['lng'] ); return $newCourse; } // Return Nearby Courses // 1 degree of Longitude = ~0.79585 * 69.172 = ~ 55.051 miles // To find area +/- xx.005 // Latitude for Calulations public function nearBy($course) { $values = array( ':park_name' => $course['park_name'] ); // Workaround for Lat/Lng not being set; apply values and SQL Query if they are null $whereLatLng = ""; if (!empty($course['latitude']) && !empty($course['longitude'])) { $whereLatLng = " ( :lat_top > `latitude` AND :lat_bot < `latitude` AND :lng_top > `longitude` AND :lng_bot < `longitude` ) OR "; // Set Ranges $lat_top = (float) $course['latitude'] + 0.005; $lat_bot = (float) $course['latitude'] - 0.005; $lng_top = (float) $course['longitude'] + 0.005; $lng_bot = (float) $course['longitude'] - 0.005; // Bind Values $values[':lat_top'] = $lat_top; $values[':lat_bot'] = $lat_bot; $values[':lng_top'] = $lng_top; $values[':lng_bot'] = $lng_bot; } else { } $query = "SELECT `id`, `created_by`, `created_on`, `modified_by`, `modified_on`, `park_name`, `city`, `state`, `zip`, `latitude`, `longitude` FROM `Courses` WHERE " . $whereLatLng . " LOWER(`park_name`) LIKE CONCAT('%%', :park_name, '%%') LIMIT 25"; return $this->db->Query($query, $values); } public function UserRecientlyCreated($user) { $query = "SELECT `id`, `created_by`, `created_on`, `modified_by`, `modified_on`, `park_name`, `city`, `state`, `zip`, `latitude`, `longitude` FROM `Courses` WHERE `created_by`=:userID ORDER BY `created_on` DESC LIMIT 10;"; $values = array( ':userID' => $user["id"] ); return $this->db->Query($query, $values); } public function UserFavorites($user) { $query = "SELECT `c`.`id`, `c`.`created_by`, `c`.`created_on`, `c`.`modified_by`, `c`.`modified_on`, `c`.`park_name`, `c`.`city`, `c`.`state`, `c`.`zip`, `c`.`latitude`, `c`.`longitude` FROM `Courses` AS `c` JOIN `Favorites` AS `f` WHERE `c`.`id`=`f`.`related_id` AND `f`.`related_table`=:related_table AND `f`.`created_by`=:userId GROUP BY `c`.`id` ORDER BY `f`.`created_on` DESC;"; $values = array( ':userId' => $user["id"], ':related_table' => "courses" ); return $this->db->Query($query, $values); } public function UserRecientlyPlayed($user) { $query = "SELECT `c`.`id`, `c`.`created_by`, `c`.`created_on`, `c`.`modified_by`, `c`.`modified_on`, `c`.`park_name`, `c`.`city`, `c`.`state`, `c`.`zip`, `c`.`latitude`, `c`.`longitude` FROM `Courses` AS `c` JOIN `Sessions` AS `sn` JOIN `Scores` AS `sc` WHERE `c`.`id`=`sn`.`course_id` AND `sn`.`id` = `sc`.`session_id` AND `sc`.`player_id` = :userId GROUP BY `c`.`id` ORDER BY `sn`.`created_on` DESC;"; $values = array( ':userId' => $user["id"] ); return $this->db->Query($query, $values); } } <file_sep>/src/assets/api/leagues/detail.php <?php session_start(); header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS'); header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token, Authorization, X-Requested-With'); header("Access-Control-Allow-Credentials: true"); header('Access-Control-Max-Age: 1000'); header('Content-Type: application/json,text/plain'); // Load Basic Functions :: For IP Grab require ($_SERVER['DOCUMENT_ROOT'] . '/api/disc/functions.php'); require ($_SERVER['DOCUMENT_ROOT'] . '/api/disc/sql.php'); $sql = new SQL; $payload = json_decode(file_get_contents('php://input'), TRUE); $return = array(); // Get List of Leagues for User $query = "SELECT `l`.`ID` AS `LeagueID`, `l`.`Name` AS `Name`, `l`.`Visibility` AS `Visibility`, `l`.`Description` AS `Description`, `l`.`Restrictions` AS `Restrictions`, `p`.`ID` AS `PermissionID`, `p`.`UserID` AS `UserID`, `p`.`Level` AS `Level`, `p`.`Status` AS `Status` FROM `Leagues` AS `l` JOIN `Permissions` AS `p` ON `p`.`LeagueID`=`l`.`ID` WHERE `l`.`ID`=:league AND `p`.`UserID`=:user ORDER BY `p`.`Level`;"; // Set Values $values = array( ":league" => $payload["league"]["id"], ":user" => $payload["user"]["id"] ); $sql = new SQL; $data = $sql->Query($query, $values); if (count($data) == 0) { $return = array( "status"=>"error", "msg"=>"Nothing Returned", "data" => array() ); } else { $return = array( "status" =>"success", "data" => array( "id" => $data[0]['LeagueID'], "name" => $data[0]['Name'], "visibility" => $data[0]['Visibility'], "description" => $data[0]['Description'], "restrictions" => $data[0]['Restrictions'], "level" => $data[0]['Level'] )/*, "permission" => array( "id" => $data[0]['PermissionID'], "league" => array("id"=>$data[0]['LeagueID']), "user" => array("id"=>$data[0]['UserID']), "level" => $data[0]['Level'], "status" => $data[0]['Status'] ) */ ); } printf(json_encode($return)); /* Types export class League { public userLevel: string; constructor( public id: string, public name: string, public visibility: string, public description?: string, public restrictions?: string, ) {} } export class Permission { constructor( public id: string, public league: League, public user: User, public level: string, public status: string, ) {} } */ ?><file_sep>/src/assets/api/leagues/list.php <?php session_start(); header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS'); header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token, Authorization, X-Requested-With'); header("Access-Control-Allow-Credentials: true"); header('Access-Control-Max-Age: 1000'); header('Content-Type: application/json,text/plain'); // Load Basic Functions :: For IP Grab require ($_SERVER['DOCUMENT_ROOT'] . '/api/disc/functions.php'); require ($_SERVER['DOCUMENT_ROOT'] . '/api/disc/sql.php'); $payload = json_decode(file_get_contents('php://input'), TRUE); $return = array(); // Get List of Leagues for User $query = "SELECT * FROM `Leagues` AS `l` JOIN `Permissions` AS `p` ON `p`.`LeagueID`=`l`.`ID` WHERE `p`.`UserID`=:userid AND (`p`.`Status`='approved') ORDER BY `p`.`Level` ASC, `p`.`Status` ASC, `l`.`ID` ASC;"; // Set Values $values = array(":userid"=>strtolower($payload["user"]["id"])); $sql = new SQL; $data = $sql->Query($query, $values); if (!isset($data)) { $return = array("status"=>"error", "msg"=>"No Leagues Found"); } else { $payload = []; foreach($data as $k => $o) { $payload[] = array( "id" => $o['LeagueID'], "name" => $o['Name'], "visibility" => $o['Visibility'], "restrictions" => $o['Restrictions'], "description" => $o['Description'], "level" => $o['Level'], ); } $return = array( "status" => "success", "data" => array("leagues" => $payload), "debug" => $data ); } printf(json_encode($return)); ?><file_sep>/src/assets/api/leagues/search.php <?php session_start(); header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS'); header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token, Authorization, X-Requested-With'); header("Access-Control-Allow-Credentials: true"); header('Access-Control-Max-Age: 1000'); header('Content-Type: application/json,text/plain'); // Load Basic Functions :: For IP Grab require ($_SERVER['DOCUMENT_ROOT'] . '/api/disc/functions.php'); require ($_SERVER['DOCUMENT_ROOT'] . '/api/disc/sql.php'); $payload = json_decode(file_get_contents('php://input'), TRUE); $term = $payload["term"]; $return = array(); // Get List of Leagues for User $query = " SELECT `l`.`ID`, `l`.`Name`, LOWER( CONCAT( `l`.`Name`,';', `l`.`Description` ) ) AS `Search`, `l`.`Visibility`, `l`.`Description`, `l`.`Restrictions` FROM `Leagues` AS `l` WHERE `l`.`Visibility`='public' HAVING `Search` LIKE CONCAT('%%', :term, '%%') LIMIT 50"; // Set Values $values = array( ":term" => strtolower($term) ); $sql = new SQL; $data = $sql->Query($query, $values); if (!isset($data)) { $return = array( "status" => "error", "msg" => "No Leagues Found", "data" => array() ); } else { $payload = []; foreach($data as $k => $o) { $payload[] = array( "id" => $o['ID'], "name" => $o['Name'], "visibility" => $o['Visibility'], "restrictions" => $o['Restrictions'], "description" => $o['Description'] ); } $return = array( "status" => "success", "data" => array("leagues" => $payload) /*, "debug" => $data, "query" => $query, "term" => $term */ ); } printf(json_encode($return)); /* Test Query Ambitious: Can Impliment Later "SELECT `l`.`ID`, `l`.`Name`, `f`.`Value`, CONCAT( `l`.`Name`,';', `c`.`Name`,';', `c`.`ParkName`,';', `c`.`City`,';', `c`.`State`,';', `c`.`Zip`,';', `c`.`Difficulty`,';', `l`.`Description` ) AS `Search` FROM `Leagues` AS `l` JOIN `Sessions` AS `s` ON `s`.`LeagueID`=`l`.`ID` JOIN `Courses` AS `c` ON `c`.`ID`=`s`.`CourseID` JOIN `Flags` AS `f` ON `c`.`ID`=`f`.`Account ID` WHERE POSITION(:term IN CONCAT( `l`.`Name`,';', `c`.`Name`,';', `c`.`ParkName`,';', `c`.`City`,';', `c`.`State`,';', `c`.`Zip`,';', `c`.`Difficulty`,';', `l`.`Description` )) > 0 && `l`.`Name` != 'Your Solo League' && `f`.`key` = 'CourseViews' ORDER BY `f`.Value*1 DESC LIMIT 50"; */ ?><file_sep>/src/app/modules/account/services/backend.service.ts import { Router } from '@angular/router'; import { Injectable, OnInit } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { environment } from 'src/environments/environment'; import { map, debounceTime, distinctUntilChanged } from "rxjs/operators"; import { pipe, BehaviorSubject, Observable } from 'rxjs'; import { ServerPayload } from 'src/app/app.component'; import { Player, Password } from 'src/app/shared/types'; @Injectable({ providedIn: 'root' }) export class AccountBackend implements OnInit { user: Player; redirectUrl: string; /* MOD private searched: BehaviorSubject<Player[] | undefined> = new BehaviorSubject(undefined); searched$: Observable<Player[]> = this.searched.asObservable(); */ private recient: BehaviorSubject<Player[] | undefined> = new BehaviorSubject(undefined); recient$: Observable<Player[]> = this.recient.asObservable(); private friends: BehaviorSubject<Player[] | undefined> = new BehaviorSubject(undefined); friends$: Observable<Player[]> = this.friends.asObservable(); url: string = environment.apiUrl + '/controllers/players.php'; passwordPipe = pipe( debounceTime(400), distinctUntilChanged(), ) constructor( private http: HttpClient, private router: Router, ) { } /** * @param ServerPayload res Subscription Response * @returns boolean true if the latest query ran by the server was successfull; * -- else false */ rCheck(res): boolean { var latest = res.length - 1; if (res[latest]["status"] == "success") { return true; } else { return false; } } rGetData(res): Array<any> | boolean { var latest = res.length - 1; if (latest > -1) { return res[latest]["results"]; } else { return false; } } ngOnInit() { this.resetUser(); } // Clear User; resetUser() { this.user = new Player(null); } setUser(user) { this.user = new Player(user["id"]); this.user.first_name = user["first_name"]; this.user.last_name = user["last_name"]; this.user.email = user["email"]; this.user.token = user["token"]; } setAuthToken(token) { // Set for future requests this.user.token = token; // Store Token as local cache; localStorage.setItem("DGC-Token", this.user.token); } // Might not need; getAuthToken() { return this.user.token; } /* HTTP Requests */ // Select login(user) { return this.http.post(this.url, { "action": "login", "player": user }).pipe( map((res) => { // Set user if successfull if (this.rCheck(res)) { var loggedInPlayer = res[0]['results'][0]; this.setUser(loggedInPlayer); this.setAuthToken(loggedInPlayer["token"]); } // Return Payload for Feedback return res; }) ) } // Create register(player: Player) { return this.http.post(this.url, { "action": "register", "player": player }).pipe( map((res: ServerPayload) => { return res; }) ); } // Update updateUser(player: Player) { return this.http.post(this.url, { "action": "update", "player": player }); } updatePassword(player: Player) { return this.http.post(this.url, { "action": "reset", "player": player }).pipe( map((res: ServerPayload) => { // Clear Pass this.user.password = new <PASSWORD>(); return res; }) ); } forgotPassword(player: Player) { return this.http.post(this.url, { "action": "initate-password-reset", "player": player }); } setPassword(player: Player) { return this.http.post(this.url, { "action": "password-set", "player": player }); } verify(token: string) { return this.http.post(this.url, { "action": "verify", "token": token }).pipe( map((res: ServerPayload) => { // Set user if successfull if (this.rCheck(res)) { var verifiedPlayer = this.rGetData(res); this.setUser(verifiedPlayer["player"]); this.setAuthToken(verifiedPlayer["player"]["token"]) } // Return Payload for Feedback return res; }) ); } verifyToken(token: string) { return this.http.post(this.url, { "action": "validate-password-reset", "token": token }).pipe( map((res: ServerPayload) => { // Set user if successfull if (this.rCheck(res)) { this.setUser(res["data"][0]["player"]); } // Return Payload for Feedback return res; }) ); } /* MOD searchUsers(term: string) { return this.http.post(this.url, { "action": "search", "term": term }).pipe( map((res: ServerPayload) => { // Set user if successfull if (this.rCheck(res)) { var players = this.rGetData(res); this.searched.next(players as Player[]); } // Return Payload for Feedback return res; })); } */ logout() { this.resetUser(); this.router.navigate(['account/login']); } }<file_sep>/src/app/modules/courses/components/list/list.component.ts import { Component, OnInit, Input} from '@angular/core'; import { Observable } from 'rxjs'; import { flyIn } from 'src/app/animations'; import { CourseBackend } from '../../services/backend.service'; import { AccountBackend } from 'src/app/modules/account/services/backend.service'; import { FormGroup } from '@angular/forms'; import { CourseFormService } from '../../services/course-form.service'; import { FeedbackService } from 'src/app/shared/modules/feedback/services/feedback.service'; import { listCategories } from 'src/app/shared/types'; @Component({ selector: 'app-course-list', templateUrl: './list.component.html', styleUrls: ['./list.component.css'], animations: [flyIn], }) export class ListComponent implements OnInit { @Input() options: Object = { list: ["search"], row: ["link"] } /* All Available Options @Input() options: Object = { list: ["create", "edit", "delete", "search"], row: ["link", "favorite", "selector"] } */ lists: Array<listCategories>; selectedList: listCategories; search: boolean = false; form: FormGroup; constructor( private _course: CourseBackend, private _courseForm: CourseFormService, private _account: AccountBackend, private feed: FeedbackService, ) { } ngOnInit() { // Populate Lists this._course.listTop(); // Account Required Lists if (this._account.user) { this._course.listFavorites(); this._course.listRecient(); } // List Selection this.lists = [ { name: "top", obs: this._course.list$, }, { name: "recient", obs: this._course.recientList$, }, { name: "favorites", obs: this._course.favoriteList$, }, { name: "search", obs: this._course.search$, } ]; // Default Option this.selectedList = this.lists[0]; // Setup Form this._courseForm.Setup('search'); this._courseForm.form$.subscribe((f) => { this.form = f; }); } toggleSearch() { this.search = !this.search; if (this.search) { this.showSearch(); } else { this.hideSearch(); } } showSearch() { // Update Flag this.search = true; // Set Dropdown to Search this.selectedList = this.lists.find((l) => { return l.name == "search"; }); // Clear Field this._courseForm.resetSearch(); // Turn Off Loader this.feed.stopLoading("courseSearch"); } hideSearch() { // Update Flag this.search = false; // Set list to Default this.selectedList = this.lists[0]; // Turn Off Loader this.feed.stopLoading("courseSearch"); } selectChange($event) { this.selectedList = this.lists.find((l) => { return l.name == $event.value.name; }); if ($event.value.name == 'search') { this.showSearch(); } else { this.hideSearch(); } } trackBy(index, item) { return item.id; } } <file_sep>/src/app/shared/modules/feedback/components/feedback/feedback.component.ts import { FeedbackService } from '../../services/feedback.service'; import { Component, OnInit, Input } from '@angular/core'; import { FeedbackErrorHandler } from 'src/app/shared/types'; @Component({ selector: 'feedback', templateUrl: './feedback.component.html', styleUrls: ['./feedback.component.scss'], animations: [], }) export class FeedbackComponent implements OnInit { @Input() handler: FeedbackErrorHandler; constructor( public feed: FeedbackService, ) { } ngOnInit() { console.log ("Feedback.Handler: ", this.handler); } } <file_sep>/src/assets/api/sessions/list.php <?php session_start(); header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS'); header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token, Authorization, X-Requested-With'); header("Access-Control-Allow-Credentials: true"); header('Access-Control-Max-Age: 1000'); header('Content-Type: application/json,text/plain'); // Load Basic Functions :: For IP Grab require ($_SERVER['DOCUMENT_ROOT'] . '/api/disc/functions.php'); require ($_SERVER['DOCUMENT_ROOT'] . '/api/disc/sql.php'); $payload = json_decode(file_get_contents('php://input'), TRUE); $return = array(); // Get List of Leagues for User $query = "SELECT `s`.`ID` AS `SessionID`, `c`.`ID` AS `CourseID`, `c`.`Name` AS `CourseName`, `s`.`Format`, `s`.`StartTimestamp`, `s`.`IsDone`, `s`.`Description` FROM `Sessions` AS `s` JOIN `Leagues` AS `l` ON `s`.`LeagueID`=`l`.`ID` JOIN `Courses` AS `c` ON `s`.`CourseID`=`c`.`ID` WHERE `l`.`ID`=:league ORDER BY `s`.`StartTimestamp` DESC;"; // Set Values $values = array(":league"=>strtolower($payload["league"]["id"])); $sql = new SQL; $data = $sql->Query($query, $values); if (count($data) == 0) { $return = array( "status" => "error", "msg" => "No sessions found", "data" => array() ); } else { $payload = []; foreach ($data as $o) { $payload[] = array( "id" => $o['SessionID'], "format" => $o['Format'], "start" => $o['StartTimestamp'], "done" => $o['IsDone'], "desc" => $o['Description'], "course" => array( "id" => $o['CourseID'], "name" => $o['CourseName'], ) ); } $return = array( "status"=>"success", "data"=> array( "sessions" => $payload ) ); } printf(json_encode($return)); ?><file_sep>/src/assets/api/stats/merge.php <?php session_start(); header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS'); header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token, Authorization, X-Requested-With'); header("Access-Control-Allow-Credentials: true"); header('Access-Control-Max-Age: 1000'); header('Content-Type: application/json,text/plain'); // Load Basic Functions :: For IP Grab require ($_SERVER['DOCUMENT_ROOT'] . '/api/disc/functions.php'); require ($_SERVER['DOCUMENT_ROOT'] . '/api/disc/sql.php'); $sql = new SQL; $payload = json_decode(file_get_contents('php://input'), TRUE); $return = array(); // Verify Permissions $validUser = $sql->Access($payload["league"], $payload["user"]); if ($validUser["status"] == "error") { $return = array( "status"=>"error", "msg"=>"You do not have sufficent permissions to perform this action" ); } else { $query = "UPDATE `Stats` SET `AccountID`=:existing WHERE `SessionID`=:session AND `AccountID`=:temp; DELETE FROM `Accounts` WHERE `ID`=:temp;"; $values = array( ":existing" => $payload["player"]["id"], ":session" => $payload["session"]["id"], ":temp" => $payload["temp"]["id"] ); $data = $sql->Query($query, $values); if (!is_array($data)) { $return = array( "status" => "error", "msg" => "Unable to Merge Players", "data" => array() ); } else { $return = array( "status" => "success", "msg" => "Players Successfully Merged!", "data" => array() ); } } /* Old Security Checks Temp Account [ACCOUNTS] Verify it is a tempAccount by pass=='temp' [STATS] Verify that tempAccount exists in Session Stats Existing Account [ACCOUNTS] Verify it is a registered account, [STATS] Verify it is not in Session Stats // Verify Accounts $query = "SELECT * FROM `Accounts` WHERE `ID`=:temp OR `ID`=:existing LIMIT 2"; $values = array( ":temp" => $payload["merge"]["temp"]["id"], ":existing" => $payload["merge"]["existing"]["id"] ); $data = $sql->Query($query, $values); if (count($data) == 0) { $return = array( "status" => "error", "msg" => "Provided accounts not found", "data" => $data ); } else { $valid = true; foreach($data as $o) { // Temp if ($o["ID"] == $payload["merge"]["temp"]["id"] && $o["Password"] != $payload["session"]['id']) { $valid = false; $return = array( "status" => "error", "msg" => "Temp Account not Valid", "data" => array() ); } // Existing if ($o["ID"] == $payload["merge"]["existing"]["id"] && ( $o['Password'] == $payload["session"]['id'] || $o['Email'] == "temp" ) ) { $valid = false; $return = array( "status" => "error", "msg" => "Existing Account not Valid", "data" => array() ); } } if ($valid != true) { // errors are handeled above } else { // Verify Session Stats $query = "SELECT * FROM `Stats` WHERE `SessionID`=:session"; $values = array( ":session" => $payload["session"]["id"] ); $data = $sql->Query($query, $values); if (count($data) == 0) { $return = array( "status" => "error", "msg" => "Session not found", "data" => array() ); } else { // Temp $tempValid = false; foreach($data as $o) { if ($o["AccountID"] == $payload["merge"]["temp"]["id"]) { $tempValid = true; } } // Existing $existingValid = true; foreach($data as $o) { if ($o["AccountID"] == $payload["merge"]["existing"]["id"]) { $existingValid = false; } } // If Any Errors if ($tempValid != true || $existingValid != true) { $return = array( "status" => "error", "msg" => "Session Stats not valid", "temp" => $tempValid, "exisiting" => $existingValid ); } else { // SAFE ZONE -> MERGE! $query = "UPDATE `Stats` SET `AccountID`=:existing WHERE `SessionID`=:session AND `AccountID`=:temp"; $values = array( ":existing" => $payload["merge"]["existing"]["id"], ":session" => $payload["session"]["id"], ":temp" => $payload["merge"]["temp"]["id"] ); $data = $sql->Query($query, $values); if (!is_array($data)) { $return = array( "status" => "error", "msg" => "Unable to Merge Stats", "data" => array() ); } else { // Delete Temp Account $query = "DELETE FROM `Accounts` WHERE `ID`=:temp"; $values = array( ":temp" => $payload["merge"]["temp"]["id"] ); $data = $sql->Query($query, $values); if (!is_array($data)) { $return = array( "status" => "error", "msg" => "Unable to Remove Temp Account", "data" => array() ); } else { $return = array( "status" => "success", "msg" => "Stats Successfully Merged!", "data" => array() ); } } } } } } } */ printf(json_encode($return)); ?><file_sep>/src/app/shared/components/section-header/section-header.component.ts import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core'; @Component({ selector: 'app-section-header', templateUrl: './section-header.component.html', styleUrls: ['./section-header.component.css'] }) export class SectionHeaderComponent implements OnInit { @Input() title: string; @Input() buttons: Array<HeaderButton>; @Input() back: string; @Output() actionClick = new EventEmitter<string>(); justification: string; constructor() { } ngOnInit() { if (this.buttons && this.buttons.length > 0) { this.justification = "left"; } else { this.justification = "center"; } } emit(action) { /* Router? <a mat-flat-button color="transparent-primary" routerLink="/leagues/{{ league?.id }}"> <span class="icon-pocket rotate-90"></span> </a> */ this.actionClick.emit(action); } } export interface HeaderButton { icon: string; action: string; color: string; }<file_sep>/src/app/modules/account/components/detail/detail.component.ts import { AccountBackend } from 'src/app/modules/account/services/backend.service'; import { Component, OnInit } from '@angular/core'; import { FeedbackService } from 'src/app/shared/modules/feedback/services/feedback.service'; import { ServerPayload } from 'src/app/app.component'; import { flyInPanelRow } from 'src/app/animations'; @Component({ selector: 'app-detail', templateUrl: './detail.component.html', styleUrls: ['./detail.component.css'], animations: [flyInPanelRow] }) export class DetailComponent implements OnInit { headerButtons = [{ icon: 'icon-log-out', action: "logout", color: "transparent-primary" }]; constructor( private account: AccountBackend, private feed: FeedbackService, ) { } ngOnInit() { } actionClick($event) { if ($event == "logout") { this.logout(); } } logout() { this.account.logout(); } } <file_sep>/src/assets/api_new/controllers/players.php <?php // Session & Header Init require($_SERVER['DOCUMENT_ROOT'] . '/sites/disc/api/shared/headers.php'); // Convert HTTP Vars $payload = json_decode(file_get_contents('php://input'), TRUE); // Init Return $return = array(); // Debug /** * Future feature, do not return each step in DB; only return last; Can flag with this later on */ $devMode = true; // DB require($_SERVER['DOCUMENT_ROOT'] . '/sites/disc/api/shared/sql.php'); $database = new DB; // Player require($_SERVER['DOCUMENT_ROOT'] . '/sites/disc/api/classes/players.php'); $player = new Player($database); // Return Payload /* require($_SERVER['DOCUMENT_ROOT'] . '/sites/disc/api/shared/payload.php'); $payload = new Player($database); */ switch ($payload['action']) { case "register": // Email has to be unique $potentalPlayer = $player->getPlayerByEmail($payload["player"]["email"]); $return[] = $potentalPlayer; if ($potentalPlayer["status"] == "success" && count($potentalPlayer["results"]) == 0) { // Create New Player! Yay! $registeredPlayer = $player->registerPlayer($payload["player"]); $return[] = $registeredPlayer; // Send Verification Email; if ($registeredPlayer["status"] == "success") { // Setup Email require($_SERVER['DOCUMENT_ROOT'] . '/sites/disc/api/shared/email.php'); $email = new Email(); $email->formatVerificationEmail($registeredPlayer["results"][0]["email"], $token); // Send Email if ($email->sendEmail()) { $return[] = array( "status" => "success", "msg" => "Account needs to be verified. Please check your email." ); } else { $return[] = array( "status" => "error", "msg" => "Unable to send verification email." ); } } else { $return[] = array( "status" => "error", "msg" => "Unable to register account." ); } } else { $return[] = array( "status" => "error", "msg" => "An account is already associated with: " . $payload["player"]["email"] ); } break; case "login": $foundPlayer = $player->getPlayerByEmail($payload["player"]["email"]); $return[] = $foundPlayer; if ($foundPlayer["status"] == "success" && count($foundPlayer['results']) > 0) { // Compare password; $hash = $player->saltPassword($payload["player"]); // Invalid Pass? if ($foundPlayer["results"][0]["password"] != $hash) { $return[] = array( "status" => "error", "msg" => "Invalid Password", "hash" => $hash ); // Need to Verify? } else if ($foundPlayer["results"][0]["last_login"] == null) { // Verify $token = $player->generateToken($payload["player"], "verify"); // Setup Email require($_SERVER['DOCUMENT_ROOT'] . '/sites/disc/api/shared/email.php'); $email = new Email(); $email->formatVerificationEmail($payload["player"]["email"], $token); // Send Email if ($email->sendEmail()) { $return[] = array( "status" => "error", "msg" => "Account needs to be verified. Please check your email." ); } else { $return[] = array( "status" => "error", "msg" => "Unable to send verification email." ); } } else { $return[] = array( "status" => "success", "hash" => $hash ); // yay! Login // Set Last Login to Now $foundPlayer["results"][0]["last_login"] = date("c"); // Update Auth Token $foundPlayer["results"][0]["token"] = $player->generateToken($payload["player"], "login"); $foundPlayer["results"][0]["token_expires_on"] = null; // Update Token & Login $return[] = $player->updatePlayer($foundPlayer["results"][0]); } } else { $return[] = array( "status" => "error", "msg" => $payload['player']['email'] . " is not associated with an account." ); } break; case "search": $return[] = $player->searchPlayers($payload["term"]); break; case "initate-password-reset": $lostPlayer = $player->getPlayerByEmail($payload['player']['email']); $return[] = $lostPlayer; if ($lostPlayer["status"] == "success" && count($lostPlayer['results']) > 0) { // Set Token $token = $player->generateToken($lostPlayer["results"][0], 'forgot'); $lostPlayer["results"][0]["token"] = $token; $lostPlayer["results"][0]["token_expires_on"] = $player->getTokenExpDate(); // Update Player $locatedPlayer = $player->updatePlayer($lostPlayer["results"][0]); if ($locatedPlayer["status"] == "success" && count($locatedPlayer['affectedRows']) > 0) { // Setup Email require($_SERVER['DOCUMENT_ROOT'] . '/sites/disc/api/shared/email.php'); $email = new Email(); $email->formatPasswordResetEmail($lostPlayer["results"][0]["email"], $token); // Send Email if ($email->sendEmail()) { $return[] = array( "status" => "success", "msg" => "The next steps have been sent to: " . $lostPlayer["results"][0]['email'], "debug" => array( "locatedPlayer" => $locatedPlayer, "lostPlayer" => $lostPlayer ) ); } else { $return[] = array( "status" => "error", "msg" => "Unable to send verification email." ); } } else { $return[] = array( "status" => "error", "msg" => "Unable to store token for validation. Please try again." ); } } else { $return[] = array( "status" => "error", "msg" => $payload['player']['email'] . " is not associated with an account." ); } break; case "validate-password-reset": // Forgot Password Email Link takes you to a page that will call this. // Afterwards goto finalize-password-reset to set the password // May be un-needed and we may be able to just re-use the reset case; $playerByToken = $player->verifyToken($payload["token"]); if ($playerByToken["status"] == "success" && count($playerByToken["results"]) > 0) { // Validate Expiration Date. $exp_date = strtotime($playerByToken["results"][0]["token_exp_date"]); if ($exp_date < time()) { // Set New Token for Validation $return[] = array( "status" => "success", "msg" => "Account Validated", "player" => $playerByToken["results"][0] ); } else { $return[] = array( "status" => "error", "msg" => "Token expired", "debug" => array( "playerByToken" => $playerByToken ) ); } } else { $return[] = array( "status" => "error", "msg" => "Invalid Token", "debug" => array( "playerByToken" => $playerByToken ) ); } break; case "verify": // Check Token matches $authorizedPlayer = $player->verifyToken($payload["token"]); $return[] = $authorizedPlayer; if ($authorizedPlayer["status"] == "success" && count($authorizedPlayer["results"]) > 0) { // Update Tokens $authorizedPlayer["results"][0]["token"] = $player->generateToken($authorizedPlayer["results"][0], "login"); $authorizedPlayer["results"][0]["token_expires_on"] = $player->getTokenExpDate(); $authorizedPlayer["results"][0]["last_login"] = date("c"); // Update Player $updatedPlayer = $player->updatePlayer($authorizedPlayer["results"][0]); $return[] = $updatedPlayer; if ($updatedPlayer["status"] == "success" && $updatedPlayer["affectedRows"] == 1) { // Return Player for Token used with requests; $return[] = array( "status" => "success", "msg" => "Account Verified!", "data" => array( "player" => $authorizedPlayer["results"][0] ) ); } else { $return[] = array( "status" => "error", "msg" => "Unable to update account. Please try to initiate the request again." ); } } else { $return[] = array( "status" => "error", "msg" => "Invalid Request." ); } break; case "update": $uniquePlayer = $player->getPlayerByEmail($payload["player"]["email"]); if ($uniquePlayer["status"] == "success" && count($uniquePlayer["results"]) == 0) { $updatedPlayer = $player->updatePlayer($payload["player"]); $return[] = $updatedPlayer; if ($updatedPlayer["status"] == "success") { // Return Player for Token used with requests; $return[] = array( "status" => "success", "msg" => "Account Updated!", "data" => array( "player" => $updatedPlayer["results"][0] ) ); } else { // Return Player for Token used with requests; $return[] = array( "status" => "error", "msg" => "Error updating account", "data" => array( "player" => $updatedPlayer["results"][0] ) ); } } else { // Return Player for Token used with requests; $return[] = array( "status" => "error", "msg" => $uniquePlayer["results"][0]['email'] . " is already associated with an account.", "data" => array( "player" => $uniquePlayer["results"][0] ) ); } break; case "reset": // Store Values for Replacement $old = $payload["player"]["password"]["old"]; $current = $payload["player"]["password"]["current"]; // Verify Old Pass $payload['player']['password'] = $old; $oldPassHash = $player->saltPassword($payload["player"]); $lostPlayer = $player->getPlayerByEmail($payload["player"]["email"]); if ($lostPlayer["results"][0]["password"] == $oldPassHash) { // Update Pass $lostPlayer["results"][0]["password"] = $current; // Salt Password $lostPlayer["results"][0]["password"] = $player->saltPassword($lostPlayer["results"][0]); // Update Account $return[] = $player->updatePlayer($lostPlayer["results"][0]); } else { $return[] = array( "status" => "error", "msg" => "Invalid Old Password", "debug" => array( "oldPassHash" => $oldPassHash, "lostPlayer" => $lostPlayer, "hash" => $lostPlayer["results"][0]['password'] . '<PASSWORD>' . strtolower($lostPlayer["results"][0]["email"]) ) ); } break; case "password-set": $payload['player']['password'] = $payload["player"]["password"]["current"]; $passHash = $player->saltPassword($payload["player"]); $verifiedPlayer = $player->getPlayerByEmail($payload["player"]["email"]); if ($verifiedPlayer["status"] == "success" && count($verifiedPlayer["results"]) > 0) { $verifiedPlayer["results"][0]["password"] = $passHash; // Update Account $return[] = $player->updatePlayer($verifiedPlayer["results"][0]); } else { // Return Player for Token used with requests; $return[] = array( "status" => "error", "msg" => "Unable to update account information.", "data" => array( "player" => $verifiedPlayer["results"][0], "hash" => $passHash ) ); } break; case "detail": $return[] = $player->getDetail($payload["player"]["id"]); break; default: $return[] = array( "status" => "error", "code" => "500", "phase" => "setup", "msg" => "Unknown Action", ); break; } /* if ($devMode) { printf(); } else { // Only Return last action if not in dev mode; printf(json_encode($return["data"][$i])); } */ printf(json_encode($return)); <file_sep>/src/app/modules/account/components/forgot/forgot.component.ts import { Component, OnInit } from '@angular/core'; import { FormGroup } from '@angular/forms'; import { FeedbackService } from 'src/app/shared/modules/feedback/services/feedback.service'; import { AccountFormService } from '../../services/account-form.service'; @Component({ selector: 'app-forgot', templateUrl: './forgot.component.html', styleUrls: ['./forgot.component.css'], animations: [] }) export class ForgotComponent implements OnInit { form: FormGroup; constructor( private feed: FeedbackService, private accountForm: AccountFormService, ) { } ngOnInit() { this.accountForm.Setup("forgot"); this.accountForm.form$.subscribe((t) => { this.form = t; this.feed.stopLoading("forgot"); }); } onFormSubmit() { this.accountForm.SubmitForgot(); } } <file_sep>/src/assets/api_new/classes/sessions.php <?php class Session { // Properties public $id; public $created_by; public $created_on; public $modified_by; public $modified_on; public $course_id; public $starts_on; public $title; public $format; public $par_array; // DB public $db; public $con; // Init public function __construct($db) { $this->db = $db; $this->con = $db->getConnection(); } public function getList($start = 0, $limit = 100, $user) { $query = "SELECT `sn`.`id`, `sn`.`created_by`, `sn`.`created_on`, `sn`.`modified_by`, `sn`.`modified_on`, `sn`.`starts_on`, `sn`.`title`, `sn`.`format`, `sn`.`par_array` FROM `Sessions` AS `sn` WHERE `sn`.`created_by` = :userID OR EXISTS (SELECT null FROM `Scores` AS `sc` WHERE `sc`.`player_id` = :userID AND `sc`.`session_id`=`sn`.`id`) GROUP BY `sn`.`id` ORDER BY `sn`.`starts_on` DESC LIMIT " . (int) $start . ", " . (int) $limit . ";"; $values = array( ":userID" => $user["id"] ); return $this->db->Query($query, $values); } public function getDetails($session, $user) { $query = "SELECT `sn`.`id`, `sn`.`created_by`, `sn`.`created_on`, `sn`.`modified_by`, `sn`.`modified_on`, `sn`.`starts_on`, `sn`.`title`, `sn`.`format`, `sn`.`par_array`, `sn`.`course_id` FROM `Sessions` AS `sn` LEFT JOIN `Scores` AS `sc` ON `sn`.`id`=`sc`.`session_id` WHERE `sn`.`id` = :sessionID LIMIT 1;"; $values = array( "sessionID" => $session['id'] ); return $this->db->Query($query, $values); } public function create($session, $user) { $query = "INSERT INTO `Sessions` (`id`, `created_by`, `created_on`, `modified_by`, `modified_on`, `course_id`, `starts_on`, `title`, `format`, `par_array` ) VALUES (:id, :created_by, :created_on, :modified_by, :modified_on, :course_id, :starts_on, :title, :format, :par_array);"; $values = array( ':id' => $session["id"], ':created_by' => $user['id'], ':created_on' => date('c'), ':modified_by' => null, ':modified_on' => null, ':course_id' => $session['course']["id"], ':starts_on' => $session['starts_on'], ':title' => $session['title'], ':format' => $session['format']['enum'], ':par_array' => $session['par_array'] == null ? "[]" : json_encode($session['par_array']) ); return $this->db->Query($query, $values); } public function createTeam($session, $team, $user) { $query = "INSERT INTO `Teams` (`id`, `created_by`, `created_on`, `modified_by`, `modified_on`, `session_id`, `name`, `color` ) VALUES (:id, :created_by, :created_on, :modified_by, :modified_on, :session_id, :name, :color);"; $values = array( ':id' => $team['id'], ':created_by' => $user['id'], ':created_on' => date('c'), ':modified_by' => null, ':modified_on' => null, ':session_id' => $session["id"], ':name' => $team['name'], ':color' => json_encode($team['color']) ); return $this->db->Query($query, $values); } public function update($session, $user) { // Base Values on each update; $values = array( ":id" => $session["id"] ); $course["modified_on"] = date("c"); $course["modified_by"] = $user["id"]; // Init Query $query = "UPDATE `Sessions` SET "; // Update query and values foreach ($session as $key => $value) { if (!array_key_exists(":" . $key, $values)) { $query .= "`" . $key . "`=:" . $key . ", "; $values[":" . $key] = $value; } }; // Remove Trailing ", " $query = substr($query, 0, -2); // Finalize Query; $query .= " WHERE `id`=:id LIMIT 1"; return $this->db->Query($query, $values); } public function delete($session) { $query = "DELETE FROM `Scores` WHERE `session_id`=:id; DELETE FROM `Teams` WHERE `session_id`=:id; DELETE FROM `Sessions` WHERE `id`=:id LIMIT 1;"; $values = array( ':id' => $session["id"] ); return $this->db->Query($query, $values); } // For Delete public function getCreator($session, $user) { $query = "SELECT * FROM `Sessions` WHERE `id`=:id AND `created_by`=:userId LIMIT 1"; $values = array( ':id' => $session["id"] ); return $this->db->Query($query, $values); } /** UPDATE * Input course from frontend format to backend format */ public function ConvertFrontBack($course) { $newCourse = array( 'park_name' => $course['parkName'], 'city' => $course['city'], 'state' => $course['state'], 'zip' => $course['zip'], 'latitude' => $course['lat'], 'longitude' => $course['lng'] ); return $newCourse; } public function UserRecientlyCreated($user) { $query = "SELECT `id`, `created_by`, `created_on`, `modified_by`, `modified_on`, `starts_on`, `title`, `format`, `par_array` FROM `Sessions` WHERE `created_by` = :userID ORDER BY `created_on` DESC LIMIT 10;"; $values = array( ':userID' => $user["id"] ); return $this->db->Query($query, $values); } public function UserFavorites($user) { $query = "SELECT `c`.`id`, `c`.`created_by`, `c`.`created_on`, `c`.`modified_by`, `c`.`modified_on`, `c`.`park_name`, `c`.`city`, `c`.`state`, `c`.`zip`, `c`.`latitude`, `c`.`longitude` FROM `Courses` AS `c` JOIN `Favorites` AS `f` WHERE `c`.`id`=`f`.`related_id` AND `f`.`related_table`=:related_table AND `f`.`created_by`=:userId ORDER BY `c`.`created_on` DESC;"; $values = array( ':userId' => $user["id"], ':related_table' => "courses" ); return $this->db->Query($query, $values); } public function UserRecientlyPlayed($user) { $query = "SELECT `c`.`id`, `c`.`created_by`, `c`.`created_on`, `c`.`modified_by`, `c`.`modified_on`, `c`.`park_name`, `c`.`city`, `c`.`state`, `c`.`zip`, `c`.`latitude`, `c`.`longitude` FROM `Courses` AS `c` JOIN `Sessions` AS `sn` JOIN `Scores` AS `sc` WHERE `c`.`id`=`sn`.`course_id` AND `sn`.`id` = `sc`.`session_id` AND `sc`.`player_id` = :userId ORDER BY `c`.`created_on` DESC;"; $values = array( ':userId' => $user["id"] ); return $this->db->Query($query, $values); } } <file_sep>/src/assets/api/validationTest.php <?php printf ("Validation Test: <br>"); printf ("HTTP_REFERER: %s<br>", $_SERVER["HTTP_REFERER"]); printf ("HTTP_USER_AGENT: %s<br>", $_SERVER["HTTP_USER_AGENT"]); printf ("REMOTE_ADDR: %s<br>", $_SERVER["REMOTE_ADDR"]); printf ("REMOTE_HOST: %s<br>", $_SERVER["REMOTE_HOST"]); ?><file_sep>/src/assets/api/courses/search.php <?php session_start(); header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS'); header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token, Authorization, X-Requested-With'); header("Access-Control-Allow-Credentials: true"); header('Access-Control-Max-Age: 1000'); header('Content-Type: application/json,text/plain'); // Load Basic Functions :: For IP Grab require ($_SERVER['DOCUMENT_ROOT'] . '/api/disc/functions.php'); require ($_SERVER['DOCUMENT_ROOT'] . '/api/disc/sql.php'); $payload = json_decode(file_get_contents('php://input'), TRUE); $return = array(); // Get List of Leagues for User $query = "SELECT `c`.`ID`, `c`.`Name`, `f`.`Value` FROM `Courses` AS `c` JOIN `Flags` AS `f` ON `c`.`ID`=`f`.`Account ID` WHERE POSITION(:term IN CONCAT( `c`.`Name`, `c`.`ParkName`, `c`.`City`, `c`.`State`, `c`.`Zip`, `c`.`Difficulty` )) > 0 ORDER BY `f`.Value*1 DESC LIMIT 50"; // Set Values $values = array(":term"=>strtolower($payload["term"])); $sql = new SQL; $data = $sql->Query($query, $values); if (!isset($data)) { $return = array("status"=>"error", "msg"=>"No Courses Found"); } else { $return = array("status"=>"success", "data"=>$data); } printf(json_encode($return)); ?><file_sep>/src/assets/api/courses/detail.php <?php session_start(); header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS'); header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token, Authorization, X-Requested-With'); header("Access-Control-Allow-Credentials: true"); header('Access-Control-Max-Age: 1000'); header('Content-Type: application/json,text/plain'); // Load Basic Functions :: For IP Grab require ($_SERVER['DOCUMENT_ROOT'] . '/api/disc/functions.php'); require ($_SERVER['DOCUMENT_ROOT'] . '/api/disc/sql.php'); $sql = new SQL; $payload = json_decode(file_get_contents('php://input'), TRUE); $return = array(); /* Track Number of Views Reason: - Help drive the popularity section on the List view How: Set Flag to Increment Value on View Process: - Search for Popularity Key in Flag Table - If None Found -> Create; (For expansion of unknown amount of courses) - If Found -> Update with Incremented Value; */ // Check if entry already Exists to drive Update/Insert $query = "SELECT * FROM `Flags` WHERE `Account ID`=:course AND `Key`='CourseViews' LIMIT 1;"; $values = array(":course" => $payload['course']['id']); $data = $sql->Query($query, $values); if (count($data) == 0) { $query = "INSERT INTO `Flags` VALUES (:id, :course, 'CourseViews', '1');"; $values = array( ":id" => date("U") . rand(100000, 999999), ":course" => $payload['course']['id'] ); $sql->Query($query, $values); } else { $query = "UPDATE `Flags` SET `Value`=:value WHERE `ID`=:id"; $values = array( ":id" => $data[0]["ID"], ":value" => ($data[0]["Value"] + 1) ); $sql->Query($query, $values); } // Get List of Leagues for User $query = "SELECT * FROM `Courses` WHERE `ID`=:course;"; // Set Values $values = array( ":course" => $payload['course']['id'] ); $data = $sql->Query($query, $values); if (count($data) == 0) { $return = array( "status"=>"error", "msg"=>"Nothing Returned", "data" => array() ); } else { $return = array( "status"=>"success", "data"=> array( "course" => array( "id" => $data[0]['ID'], "locationKey" => $data[0]['LocationKey'], "parkName" => $data[0]['ParkName'], "name" => $data[0]['Name'], "img" => $data[0]['IMGPath'], "city" => $data[0]['City'], "state" => $data[0]['State'], "zip" => $data[0]['Zip'], "lat" => $data[0]['Latitude'], "lng" => $data[0]['Longitude'], "difficulty" => $data[0]['Difficulty'], "holeCount" => $data[0]['HoleCount'] ) ) ); } printf(json_encode($return)); // $googleMapHtml = require ($_SERVER['DOCUMENT_ROOT'] . '/disc/views/gmap.php'/*?lat="'.$lat.'"&?lng="'.$lng.'"'*/); // $weatherHtml = require ($_SERVER['DOCUMENT_ROOT'] . '/disc/views/weather-daily.php'); // $courseStatsHtml = require ($_SERVER['DOCUMENT_ROOT'] . '/disc/views/course-stats.php'); ?><file_sep>/src/assets/api/permissions/create.php <?php session_start(); header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS'); header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token, Authorization, X-Requested-With'); header("Access-Control-Allow-Credentials: true"); header('Access-Control-Max-Age: 1000'); header('Content-Type: application/json,text/plain'); // Load Basic Functions :: For IP Grab require ($_SERVER['DOCUMENT_ROOT'] . '/api/disc/functions.php'); require ($_SERVER['DOCUMENT_ROOT'] . '/api/disc/sql.php'); $sql = new SQL; $payload = json_decode(file_get_contents('php://input'), TRUE); $return = array(); // Prepare $query = "SELECT * FROM `Permissions` WHERE `LeagueID`=:league AND `UserID`=:user;"; // Set $values = array( ":league" => $payload["league"]["id"], ":user" => $payload["user"]["id"] ); // Run $data = $sql->Query($query, $values); if (count($data) != 0) { $return = array("status"=>"error", "msg"=>"There is another request pending"); } else { // Get List of Leagues for User $query = "INSERT INTO `Permissions` (`ID`, `LeagueID`, `UserID`, `Level`, `Status`) VALUES (:id, :league, :user, null, 'pending')"; // Set Values $values = array( ":id" => date("U") . rand(100000, 999999), ":league" => $payload["league"]["id"], ":user" => $payload["user"]["id"] ); $data = $sql->Query($query, $values); if (!isset($data)) { $return = array("status"=>"error", "msg"=>"Unable to submit request, please try again"); } else { $return = array("status"=>"success", "msg"=>"Request sent!"); } } printf(json_encode($return)); ?><file_sep>/src/app/modules/scores/components/team-list-item/team-list-item.component.ts import { Component, OnInit, Input } from '@angular/core'; import { MatDialog } from '@angular/material'; import { TeamSettingsComponent } from '../../dialogs/team-settings/team-settings.component'; import { SessionBackend } from 'src/app/modules/sessions/services/backend.service'; import { Team } from 'src/app/shared/types'; import { ScoresBackend } from '../../services/backend.service'; @Component({ selector: 'team-list-item', templateUrl: './team-list-item.component.html', styleUrls: ['./team-list-item.component.scss'] }) export class TeamListItemComponent implements OnInit { @Input() mode: Array<string> = []; @Input() team: Team; constructor( private dialog: MatDialog, private sessions_:SessionBackend, private _scores: ScoresBackend, ) { } ngOnInit() { } removeTeam(team) { this._scores.removeTeam(team); } openSettings() { this.dialog.open(TeamSettingsComponent, { data: this.team, }) } } <file_sep>/src/app/pipes/stroke-total.pipe.spec.ts import { StrokeTotalPipe } from './stroke-total.pipe'; describe('StrokeTotalPipe', () => { it('create an instance', () => { const pipe = new StrokeTotalPipe(); expect(pipe).toBeTruthy(); }); }); <file_sep>/src/assets/api_new/classes/players.php <?php class Player { // Properties public $id; public $created_by; public $created_on; public $modified_by; public $modified_on; public $first_name; public $last_name; public $email; public $token; public $token_expires_on; public $last_login; // DB public $db; public $con; // Init public function __construct($db) { $this->db = $db; $this->con = $db->getConnection(); } // DB Functions; /** * @param Player $item * @param string $type verify | forgot_password | login(session_id) */ public function generateToken($item, $type): string { $modifier = $type == 'login' ? session_id() : $type; $str = $item["id"] . $item["modified_on"] . 'DGC' . $item["email"] . $item["last_name"] . 'WAAAGH!!' . $modifier; $token = hash('sha512', $str); return $token; } /** * @param Player $player */ public function saltPassword($player): string { // Original; dn-new dataset; // $str = $payload["user"]["pass"]["current"] . "<PASSWORD>" . strtolower($payload["user"]["email"]); // $hash = hash("sha512", $str); return hash("sha512", $player["password"] . '<PASSWORD>' . strtolower($player["email"])); } /** * @return Date; ISO 8601: date("U") */ public function getTokenExpDate() { $expiration_date = mktime(date("H") + 1); return date("c", $expiration_date); } // DB Functions // Create public function registerPlayer($item) { // Format Query $query = "INSERT INTO `Players` ( `id`, `created_by`, `created_on`, `modified_by`, `modified_on`, `first_name`, `last_name`, `email`, `password`, `token`, `token_expires_on`, `last_login` ) VALUES ( :id, :created_by, :created_on, :modified_by, :modified_on, :first_name, :last_name, :email, :password, :token, :token_expires_on, :last_login );"; // Bind Data $values = array( ":id" => $this->db->generateGUID(), ":created_by" => null, ":created_on" => date("c"), ":modified_by" => null, ":modified_on" => null, ":first_name" => $item["first_name"], ":last_name" => $item["last_name"], ":email" => $item["email"], ":password" => <PASSWORD>), ":token" => $this->generateToken($item, "verify"), ":token_expires_on" => $this->getTokenExpDate(), ":last_login" => null ); // Insert return $this->db->Query($query, $values); } // Read public function getDetails($id) { $query = "SELECT `id`, `created_by`, `created_on`, `modified_by`, `modified_on`, `first_name`, `last_name`, `email`, `token`, FROM `Players` WHERE `id`=:id LIMIT 1"; $values = array( ":id" => $id ); return $this->db->Query($query, $values); } /** * @param string $email Email to search for */ public function getPlayerByEmail($email) { $query = "SELECT `id`, `created_by`, `created_on`, `modified_by`, `modified_on`, `first_name`, `last_name`, `email`, `password`, `token`, `token_expires_on`, `last_login` FROM `Players` WHERE `email`=:email LIMIT 1"; $values = array( ":email" => strtolower($email) ); return $this->db->Query($query, $values); } /** * @param string $term * Used to Search for Friends, makes adding people to a session simplified; */ public function searchPlayers($term) { $query = "SELECT `id` AS `scores.player.id`, `first_name` AS `scores.player.first_name`, `last_name` AS `scores.player.last_name`, `email` AS `scores.player.email` FROM `Players` WHERE POSITION(:term IN CONCAT( `first_name`, `last_name`, `email` )) > 0 ORDER BY `modified_on` DESC LIMIT 10"; $values = array( ":term" => $term ); return $this->db->Query($query, $values); } /** * Update * @param Player $item; * Object of columns to update. id, modified_by, and modified_on are * set automatically. Other fields can be missing to not be included * in the update, or included to be updated. */ public function updatePlayer($item) { // Verify Player Valid? // Check ID? // Base Values on each update; $values = array( ":id" => $item["id"] ); // Insert Modified Information $item['modified_by'] = null; $item['modified_on'] = date("c"); // Init Query $query = "UPDATE `Players` SET "; // Update query and values foreach ($item as $key => $value) { if ($key != "id" && $key != "access") { $query .= "`" . $key . "`=:" . $key . ", "; $values[":" . $key] = $value; } }; // Remove Trailing ", " $query = substr($query, 0, -2); // Finalize Query; $query .= " WHERE `id`=:id LIMIT 1"; return $this->db->Query($query, $values); } // Delete public function removePlayer($id) { $query = "DELETE FROM `Players` WHERE `id`=:id"; $values = array( ":id" => $id ); return $this->db->Query($query, $values); } /** * @param string $item */ public function verifyToken($token) { $query = "SELECT * FROM `Players` WHERE `token`=:token LIMIT 1"; $values = array( ":token" => $token ); return $this->db->Query($query, $values); } } <file_sep>/src/app/modules/sessions/pages/detail/detail.component.ts import { Component, OnInit } from '@angular/core'; import { flyIn } from 'src/app/animations'; import { FormGroup } from '@angular/forms'; import { SessionFormService } from '../../services/form.service'; import { SessionBackend } from '../../services/backend.service'; import { Router, ActivatedRoute, ParamMap } from '@angular/router'; import { ScoresBackend } from 'src/app/modules/scores/services/backend.service'; import { MatDialog } from '@angular/material'; import { SelectCourseComponent } from '../../dialogs/select-course/select-course.component'; import { SelectFormatComponent } from '../../dialogs/select-format/select-format.component'; import { SelectTimeComponent } from '../../dialogs/select-time/select-time.component'; import { SelectPlayersComponent } from '../../dialogs/select-players/select-players.component'; import { Session } from 'src/app/shared/types'; import { Observable } from 'rxjs/internal/Observable'; import { switchMap } from 'rxjs/operators'; @Component({ selector: 'app-detail', templateUrl: './detail.component.html', styleUrls: ['./detail.component.css'], animations: [flyIn] }) export class DetailComponent implements OnInit { session$: Observable<Session> = this._sessions.detail$; form: FormGroup; playerModes = ["full", "admin"]; confirmDelete: boolean = false; constructor( private _sessionsForm: SessionFormService, private _sessions: SessionBackend, private _scores: ScoresBackend, private route: ActivatedRoute, private dialog: MatDialog, ) { } ngOnInit() { // Upon Router Change; Update Details if neccessary; this.route.paramMap.subscribe((res)=>{ let session_id = res.get("session"); if (session_id != 'create') { this._sessionsForm.Setup("edit"); this._sessions.findDetails(session_id); } else { this._sessionsForm.Setup("create"); this._sessions.resetDetails(); } this._sessions.admin(); }); } // Popups selectCourse() { var dialogRef = this.dialog.open(SelectCourseComponent, { minWidth: "400px", }); dialogRef.afterClosed().subscribe((d) => { console.log("dialog.closed: ", d); }); } selectFormat() { var dialogRef = this.dialog.open(SelectFormatComponent, { minWidth: "400px", }); dialogRef.afterClosed().subscribe((d) => { console.log("dialog.closed: ", d); }); } selectTime() { var dialogRef = this.dialog.open(SelectTimeComponent, { }); dialogRef.afterClosed().subscribe((d) => { console.log("dialog.closed: ", d); }); } selectPlayers() { var dialogRef = this.dialog.open(SelectPlayersComponent, { minWidth: "400px", }); dialogRef.afterClosed().subscribe((d) => { console.log("dialog.closed: ", d); }); } scoreAction($event) { console.log("scoreAction.$event: ", $event); } toggleDelete() { this.confirmDelete = !this.confirmDelete; } }
34968ea36f46247e1f8fa82efbf8bd4762e33766
[ "TypeScript", "PHP" ]
111
TypeScript
bslotty/dg
6355e364c384bd7ee4d81385c32a27d65c587af5
f806cae18ee024b026774132f182e330c4463847
refs/heads/master
<repo_name>luan-css/ApiCasaShow<file_sep>/eventos/Data/ApplicationDbContext.cs using System; using System.Collections.Generic; using System.Text; using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; using eventos.Models; namespace eventos.Data { public class ApplicationDbContext : IdentityDbContext { public DbSet<Genero> Generos {get; set;} public DbSet<Casa> Casas {get; set;} public DbSet<Evento> Eventos{get; set;} public DbSet<Estoque> Estoques{get; set;} public DbSet<Saida> Saidas{get; set;} public DbSet<Venda> Vendas{get; set;} public DbSet<Compra> Compra{get; set;} public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { } } } <file_sep>/eventos/Models/Venda.cs using System; namespace eventos.Models { public class Venda { public int Id{get; set;} public DateTime Data{get; set;} public float Total {get; set;} } }<file_sep>/eventos/Models/Evento.cs using System; namespace eventos.Models { public class Evento { public int Id { get; set; } public string Nome{get; set;} public int capacidade{get; set;} public DateTime Data{get; set;} public float ValorIngresso { get; set; } public Casa Casa{get; set;} public Genero Genero{get; set;} public bool Status{get; set;} public int Quantidade{get; set;} public string imagem{get; set;} } }<file_sep>/eventos/Models/Estoque.cs namespace eventos.Models { public class Estoque { public int Id {get; set;} public Evento Evento {get; set;} public int Quantidade{get; set;} } }<file_sep>/eventos/Controllers/GenerosController.cs using eventos.Data; using eventos.DTO; using eventos.Models; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using System; using System.ComponentModel.DataAnnotations; using System.Linq; namespace eventos.Controllers { [Authorize(Policy = "Poli")] public class GenerosController : Controller { private readonly ApplicationDbContext database; public GenerosController(ApplicationDbContext database){ this.database = database; } [HttpPost] public IActionResult Salvar(GeneroDTO generoTemporario){ if(ModelState.IsValid){ Genero genero = new Genero(); genero.Nome = generoTemporario.Nome; genero.Status = true; database.Generos.Add(genero); database.SaveChanges(); return RedirectToAction("Generos", "Gestao"); }else{ return View("../Gestao/NovoGenero"); } } [HttpPost] public IActionResult Atualizar(GeneroDTO generoTemporario){ if(ModelState.IsValid){ var genero = database.Generos.First(p => p.Id == generoTemporario.Id); genero.Nome = generoTemporario.Nome; database.SaveChanges(); return RedirectToAction("Generos","Gestao"); }else{ return RedirectToAction("Generos","Gestao"); } } [HttpPost] public IActionResult Deletar(int id){ if(id > 0){ var genero = database.Generos.First(gene => gene.Id == id); genero.Status = false; database.SaveChanges(); } return RedirectToAction("Generos","Gestao"); } } }<file_sep>/eventos/Controllers/ApiVendaController.cs using System; using System.ComponentModel.DataAnnotations; using System.Linq; using eventos.Data; using eventos.Models; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; namespace eventos.Controllers { [Route("api/v1/vendas")] [ApiController] public class ApiVendaController : ControllerBase { private readonly ApplicationDbContext database; public ApiVendaController(ApplicationDbContext database) { this.database = database; } [HttpGet] public IActionResult Compras() { var compra = database.Compra.ToList(); return Ok(compra); } [HttpGet("id")] public IActionResult compraID(int id){ var compra = database.Compra.ToList().Where(c => c.Id == id); return Ok(compra); } } }<file_sep>/eventos/wwwroot/js/site.js // Please see documentation at https://docs.microsoft.com/aspnet/core/client-side/bundling-and-minification // for details on configuring this project to bundle and minify static web assets. // Write your JavaScript code. const encontrar = () =>{ } //const url='https://localhost:5001/api/v1/casas/'; // fetch(url).then(res => res.json()).then(res => console.log(res));<file_sep>/eventos/DTO/CasaDTO.cs using System.ComponentModel.DataAnnotations; namespace eventos.DTO { public class CasaDTO { [Required] public int Id { get; set; } [Required(ErrorMessage="Nome obrigatório")] [StringLength(100, ErrorMessage="Nome da casa muito grande, tente um menor!")] [MinLength(2, ErrorMessage="Nome muito curto, tente com mais de 2 caracteres.")] public string Nome{get; set;} [Required(ErrorMessage="Endereço obrigatório")] [StringLength(250, ErrorMessage="Nome do endereço muito grande, tente um menor!")] [MinLength(2, ErrorMessage="Endereço muito curto, tente com mais de 2 caracteres.")] public string Endereco{get; set;} } }<file_sep>/eventos/Controllers/ApiEventosController.cs using System; using System.ComponentModel.DataAnnotations; using System.Linq; using eventos.Data; using eventos.Models; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; namespace eventos.Controllers { [Route("api/v1/eventos")] [ApiController] public class ApiEventosController : ControllerBase { private readonly ApplicationDbContext database; public ApiEventosController(ApplicationDbContext database) { this.database = database; } [HttpGet] public IActionResult Get() { var produtos = database.Eventos.Include(p => p.Genero).Include(p => p.Casa).ToList(); return Ok(produtos); } [HttpGet("{id}")] public IActionResult Get(int id) { var produtos = database.Eventos.Include(p => p.Genero).Include(p => p.Casa).First(p => p.Id == id); return Ok(produtos); } [HttpDelete("{id}")] public IActionResult Delete(int id) { try { Evento eventos = database.Eventos.First(p => p.Id == id); database.Remove(eventos); database.SaveChanges(); return Ok("Deletado com sucesso"); } catch (Exception e) { Response.StatusCode = 404; return new ObjectResult(""); } } [HttpPost] public IActionResult Post([FromBody] EventoTemp etemp) { if (etemp.Nome.Length <= 1) { Response.StatusCode = 400; return new ObjectResult(new { msg = "O nome da casa precisa ter mais de um caracter." }); } if (etemp.Nome == null) { Response.StatusCode = 400; return new ObjectResult(new { msg = "O nome da casa é obrigatorio." }); } Evento p = new Evento(); p.Nome = etemp.Nome; p.capacidade = etemp.capacidade; p.imagem = etemp.Imagem; p.Data = etemp.Data; p.ValorIngresso = etemp.ValorIngresso; p.Genero = database.Generos.First(genero => genero.Id == etemp.GeneroID); p.Casa = database.Casas.First(casa => casa.Id == etemp.CasaID); p.Status = etemp.Status; database.Eventos.Add(p); database.SaveChanges(); Response.StatusCode = 201; return new ObjectResult("Criado com sucesso"); } [HttpGet("capacidade/asc")] public IActionResult GetAsc() { try { var evento = database.Eventos.ToList().OrderBy(e => e.capacidade); return Ok(evento); } catch { Response.StatusCode = 404; return new ObjectResult("Não encontrado"); } } [HttpGet("capacidade/desc")] public IActionResult Getcap() { try { var evento = database.Eventos.ToList().OrderByDescending(e => e.capacidade); return Ok(evento); } catch { Response.StatusCode = 404; return new ObjectResult("Não encontrado"); } } [HttpGet("data/asc")] public IActionResult Dataasc() { try { var evento = database.Eventos.ToList().OrderBy(e => e.Data); return Ok(evento); } catch { Response.StatusCode = 404; return new ObjectResult("Não encontrado"); } } [HttpGet("data/desc")] public IActionResult Datadesc() { try { var evento = database.Eventos.ToList().OrderByDescending(e => e.Data); return Ok(evento); } catch { Response.StatusCode = 404; return new ObjectResult("Não encontrado"); } } [HttpGet("nome/asc")] public IActionResult Nomeasc() { var casa = database.Casas.ToList(); var genero = database.Generos.ToList(); try { var evento = database.Eventos.ToList().OrderBy(e => e.Nome); return Ok(evento); } catch { Response.StatusCode = 404; return new ObjectResult("Não encontrado"); } } [HttpGet("nome/desc")] public IActionResult Nomedesc() { var casa = database.Casas.ToList(); var genero = database.Generos.ToList(); try { var evento = database.Eventos.ToList().OrderByDescending(e => e.Nome); return Ok(evento); } catch { Response.StatusCode = 404; return new ObjectResult("Não encontrado"); } } [HttpGet("preco/asc")] public IActionResult Precoasc() { try { var evento = database.Eventos.ToList().OrderBy(e => e.ValorIngresso); return Ok(evento); } catch { Response.StatusCode = 404; return new ObjectResult("Não encontrado"); } } [HttpGet("preco/desc")] public IActionResult Precodesc() { try { var evento = database.Eventos.ToList().OrderByDescending(e => e.ValorIngresso); return Ok(evento); } catch { Response.StatusCode = 404; return new ObjectResult("Não encontrado"); } } [HttpPatch] public IActionResult Patch([FromBody] EventoTemp eventoTemp) { if (eventoTemp.Id > 0) { var evento = database.Eventos.First(ctemp => ctemp.Id == eventoTemp.Id); if (evento != null) { evento.Nome = eventoTemp.Nome != null ? eventoTemp.Nome : evento.Nome; evento.capacidade = eventoTemp.capacidade != 0 ? eventoTemp.capacidade : evento.capacidade; if(eventoTemp.CasaID != 0){ evento.Casa = database.Casas.First(c => c.Id == eventoTemp.CasaID); }else{ evento.Casa = evento.Casa; } evento.Data = eventoTemp.Data != null ? eventoTemp.Data : evento.Data; evento.ValorIngresso = eventoTemp.ValorIngresso != 0 ? eventoTemp.ValorIngresso : evento.ValorIngresso; evento.imagem = eventoTemp.Imagem != null ? eventoTemp.Imagem : evento.imagem; if(eventoTemp.GeneroID != 0){ evento.Genero = database.Generos.First(c => c.Id == eventoTemp.GeneroID); }else{ evento.Genero = evento.Genero; } database.SaveChanges(); return Ok(); } else { Response.StatusCode = 400; return new ObjectResult(new { msg = "1O id do produto é invalido" }); } } else { Response.StatusCode = 400; return new ObjectResult(new { msg = "3O id do produto é invalido" }); } } public class EventoTemp { public int Id { get; set; } public string Nome { get; set; } [Required(ErrorMessage = "Digite a capacidade do local")] public int capacidade { get; set; } [Required(ErrorMessage = "Digite a data e a hora do local")] public DateTime Data { get; set; } [Required(ErrorMessage = "Digite o valor do ingresso")] public float ValorIngresso { get; set; } [Required(ErrorMessage = "Escolha a casa de show")] public int CasaID { get; set; } [Required(ErrorMessage = "Escolha o genero")] public int GeneroID { get; set; } public string Imagem { get; set; } [Required] public bool Status { get; set; } } } }<file_sep>/eventos/Controllers/ApiCasaController.cs using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Threading.Tasks; using eventos.Data; using eventos.Models; using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; namespace eventos.Controllers { [Route("api/v1/casas")] [ApiController] public class ApiCasaController : ControllerBase { private readonly ApplicationDbContext database; public ApiCasaController(ApplicationDbContext database){ this.database = database; } [HttpGet] public IActionResult Getcasa(){ var casa = database.Casas.ToList(); return Ok(casa); } [HttpDelete("{id}")] public IActionResult delete(int id){ try{ var casa = database.Casas.First(c => c.Id == id); database.Remove(casa); database.SaveChanges(); return Ok("Deletado com sucesso"); }catch(Exception e){ Response.StatusCode = 404; return new ObjectResult(""); } } [HttpGet("{id}")] public IActionResult Getcasa(int id){ try{ var casa = database.Casas.First(c => c.Id == id); return Ok(casa); }catch{ Response.StatusCode = 404; return new ObjectResult(""); } } [HttpGet("nome/{nome}")] public IActionResult GetcasaNome(string nome){ try{ var casa = database.Casas.Where(c => c.Nome == nome).First(); return Ok(casa); }catch(Exception e){ Response.StatusCode = 404; return new ObjectResult(""); } } [HttpGet("Asc")] public IActionResult Asc(){ var casa = database.Casas.ToList().OrderBy(c => c.Nome); return Ok(casa); } [HttpGet("Desc")] public IActionResult Desc(){ var casa = database.Casas.ToList().OrderByDescending(c => c.Nome); return Ok(casa); } [HttpPost] public IActionResult Post([FromBody] CasaTemp ctemp){ if(ctemp.Nome.Length <= 1){ Response.StatusCode = 400; return new ObjectResult(new {msg = "O nome da casa precisa ter mais de um caracter."}); } if(ctemp.Nome == null){ Response.StatusCode = 400; return new ObjectResult(new {msg = "O nome da casa é obrigatorio."}); } Casa p = new Casa(); p.Nome = ctemp.Nome; p.Endereco = ctemp.Endereco; p.Status = ctemp.status; database.Casas.Add(p); database.SaveChanges(); Response.StatusCode = 201; return new ObjectResult(""); } [HttpPatch] public IActionResult Patch([FromBody] Casa casa){ if(casa.Id > 0){ try{ var p = database.Casas.First(ctemp => ctemp.Id == casa.Id); if(p != null){ p.Nome = casa.Nome != null ? casa.Nome : p.Nome; p.Endereco = casa.Endereco != null ? casa.Endereco : p.Endereco; p.Status = casa.Status != true ? casa.Status : p.Status; database.SaveChanges(); return Ok(); }else{ Response.StatusCode = 400; return new ObjectResult(new {msg = "O id do produto é invalido"}); } }catch{ Response.StatusCode = 400; return new ObjectResult(new {msg = "O id do produto é invalido"}); } }else{ Response.StatusCode = 400; return new ObjectResult(new {msg = "O id do produto é invalido"}); } } public class CasaTemp{ public String Nome{get;set;} public string Endereco{get;set;} public bool status{get;set;} } } }<file_sep>/eventos/Controllers/EventosController.cs using System.ComponentModel.DataAnnotations; using System.Linq; using eventos.Data; using eventos.DTO; using eventos.Models; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; namespace eventos.Controllers { [Authorize] public class EventosController : Controller { private readonly ApplicationDbContext database; public EventosController(ApplicationDbContext database){ this.database = database; } [Authorize(Policy = "Poli")] [HttpPost] public IActionResult Salvar(EventoDTO eventoTemporario){ if(ModelState.IsValid){ Evento evento = new Evento(); evento.Nome = eventoTemporario.Nome; evento.capacidade = eventoTemporario.capacidade; evento.Genero = database.Generos.First(genero => genero.Id == eventoTemporario.GeneroID); evento.Casa = database.Casas.First(casa => casa.Id == eventoTemporario.CasaID); evento.ValorIngresso = eventoTemporario.ValorIngresso; evento.Data = eventoTemporario.Data; evento.Quantidade = eventoTemporario.Quantidade; evento.imagem = eventoTemporario.Imagem; evento.Status = true; database.Eventos.Add(evento); database.SaveChanges(); return RedirectToAction("Eventos" , "Gestao"); }else{ ViewBag.Generos = database.Generos.ToList(); ViewBag.Casas = database.Casas.ToList(); return View("../Gestao/NovoEvento"); } } [Authorize(Policy = "Poli")] [HttpPost] public IActionResult Atualizar(EventoDTO eventoTemporario, CompraDTO compratemporaria){ if(ModelState.IsValid){ var evento = database.Eventos.First(eve => eve.Id == eventoTemporario.Id); Compra compra = new Compra(); evento.Nome = eventoTemporario.Nome; evento.Casa = database.Casas.First(casa => casa.Id == eventoTemporario.CasaID); evento.Genero = database.Generos.First(gene => gene.Id == eventoTemporario.GeneroID); evento.imagem = eventoTemporario.Imagem; evento.ValorIngresso = eventoTemporario.ValorIngresso; evento.Data = eventoTemporario.Data; evento.capacidade = eventoTemporario.capacidade; compra.Quantidade = compratemporaria.Quantidade; if(compra.Quantidade > 0){ evento.capacidade -= compratemporaria.Quantidade; } database.SaveChanges(); return RedirectToAction("Eventos","Gestao"); }else{ return RedirectToAction("Produtos","Gestao"); } } [Authorize(Policy = "Poli")] [HttpPost] public IActionResult Deletar(int id){ if(id > 0){ var evento = database.Eventos.First(eve => eve.Id == id); evento.Status = false; database.SaveChanges(); } return RedirectToAction("Eventos", "Gestao"); } [Authorize(Policy = "Poli")] [HttpPost] public IActionResult AtualizarEstoque(CompraDTO compratemporaria){ if(ModelState.IsValid){ Compra compra = new Compra(); compra.Nome = compratemporaria.Nome; compra.ValorIngresso = compratemporaria.ValorIngresso; compra.capacidade = compratemporaria.capacidade; compra.Quantidade = compratemporaria.Quantidade; compra.usuario = compratemporaria.usuario; compra.total = compratemporaria.total; return RedirectToAction("Index","Home"); }else{ return RedirectToAction("Index","Home"); } } [HttpPost] public IActionResult SalvarEstoque(CompraDTO compratemporaria, EventoDTO eventoTemporario){ if(ModelState.IsValid){ Compra compra = new Compra(); var evento = database.Eventos.First(eve => eve.Id == eventoTemporario.Id); compra.Nome = compratemporaria.Nome; compra.ValorIngresso = compratemporaria.ValorIngresso; compra.capacidade = compratemporaria.capacidade; compra.Quantidade = compratemporaria.Quantidade; compra.usuario = compratemporaria.usuario; compra.total = compratemporaria.total; compra.imagem = compratemporaria.imagem; evento.capacidade = eventoTemporario.capacidade; compra.usuario = User.Identity.Name; database.Compra.Add(compra); database.SaveChanges(); if(compra.Quantidade > 0 && compra.Quantidade <= compra.capacidade){ compra.total = (compra.Quantidade*compra.ValorIngresso); evento.capacidade = compra.capacidade -= compra.Quantidade; database.SaveChanges(); } database.Update(evento); return RedirectToAction("Index","Home"); }else{ return RedirectToAction("Index","Home"); } } } }<file_sep>/eventos/DTO/CompraDTO.cs using System.ComponentModel.DataAnnotations; namespace eventos.DTO { public class CompraDTO { public int Id { get; set; } public string Nome{get; set;} public int capacidade{get; set;} public float ValorIngresso { get; set; } public float total{get; set;} public bool Status{get; set;} public int Quantidade{get; set;} public string usuario{get; set;} public string imagem{get;set;} } }<file_sep>/eventos/Controllers/ApiUserController.cs using System.Linq; using eventos.Data; using Microsoft.AspNetCore.Mvc; namespace eventos.Controllers { [Route("api/v1/user")] [ApiController] public class ApiUserController : ControllerBase { private readonly ApplicationDbContext database; public ApiUserController(ApplicationDbContext database) { this.database = database; } [HttpGet] public IActionResult getUser(){ var user = database.Users.Select(p => p.UserName).ToList(); return Ok (user); } [HttpGet("id")] public IActionResult getUser(string id){ var user = database.Users.First(p => p.Id == id).UserName; return Ok (user); } [HttpGet("nome/{name}")] public IActionResult getName(string name){ var user = database.Users.First(p => p.UserName == name); return Ok(user); } } }<file_sep>/eventos/Controllers/GestaoController.cs using eventos.Data; using eventos.DTO; using eventos.Models; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using System; using System.Linq; namespace eventos.Controllers { public class GestaoController : Controller { private readonly ApplicationDbContext database; public GestaoController(ApplicationDbContext database){ this.database = database; } public IActionResult Index(){ var eventos = database.Eventos.Include(p => p.Genero).Include(p => p.Casa).Where(P => P.Status == true).ToList(); return View(eventos); } [Authorize(Policy = "Poli")] public IActionResult Generos(){ var generos = database.Generos.Where(gene => gene.Status == true).ToList(); return View(generos); } [Authorize(Policy = "Poli")] public IActionResult NovoGenero(){ return View(); } [Authorize(Policy = "Poli")] public IActionResult EditarGenero(int id){ var genero = database.Generos.First(gene => gene.Id == id); GeneroDTO generoView = new GeneroDTO(); generoView.Id = genero.Id; generoView.Nome = genero.Nome; return View(generoView); } [Authorize(Policy = "Poli")] public IActionResult Casas(){ var casas = database.Casas.Where(casa => casa.Status == true).ToList(); return View(casas); } [Authorize(Policy = "Poli")] public IActionResult NovaCasa(){ return View(); } [Authorize(Policy = "Poli")] public IActionResult EditarCasa(int id){ var casa = database.Casas.First(casa => casa.Id == id); CasaDTO casaView = new CasaDTO(); casaView.Id = casa.Id; casaView.Nome = casa.Nome; casaView.Endereco = casa.Endereco; return View(casaView); } [Authorize(Policy = "Poli")] public IActionResult Eventos(){ var eventos = database.Eventos.Include(p => p.Genero).Include(p => p.Casa).Where(P => P.Status == true).Where(c => c.Casa.Status == true).Where(g => g.Genero.Status == true).ToList(); return View(eventos); } [Authorize(Policy = "Poli")] public IActionResult NovoEvento(){ ViewBag.Generos = database.Generos.Where(genero => genero.Status == true).ToList(); ViewBag.Casas = database.Casas.Where(casa => casa.Status == true).ToList(); var casas = database.Casas.FirstOrDefault(c => c.Status); var generos = database.Generos.FirstOrDefault(g => g.Status); if(casas == null || generos == null){ return View("ErroCad"); } return View(); } [Authorize(Policy = "Poli")] public IActionResult EditarEvento(int id){ var evento = database.Eventos.Include(eve => eve.Genero).Include(eve => eve.Casa).First(eve => eve.Id == id); EventoDTO eventoView = new EventoDTO(); eventoView.Id = evento.Id; eventoView.Nome = evento.Nome; eventoView.capacidade = evento.capacidade; eventoView.Data = evento.Data; eventoView.CasaID = evento.Casa.Id; eventoView.GeneroID = evento.Genero.Id; eventoView.ValorIngresso = evento.ValorIngresso; eventoView.Imagem = evento.imagem; ViewBag.Generos = database.Generos.ToList(); ViewBag.Casas = database.Casas.ToList(); return View(eventoView); } [Authorize] public IActionResult ComprarEvento(int id){ var evento = database.Eventos.Include(eve => eve.Genero).Include(eve => eve.Casa).First(eve => eve.Id == id); EventoDTO eventoView = new EventoDTO(); eventoView.Id = evento.Id; eventoView.Nome = evento.Nome; eventoView.capacidade = evento.capacidade; eventoView.Data = evento.Data; eventoView.CasaID = evento.Casa.Id; eventoView.GeneroID = evento.Genero.Id; eventoView.ValorIngresso = evento.ValorIngresso; eventoView.Quantidade = evento.Quantidade; eventoView.Imagem = evento.imagem.ToString(); ViewBag.Generos = database.Generos.ToList(); ViewBag.Casas = database.Casas.ToList(); return View(eventoView); } [Authorize] public IActionResult Historico(){ var compra = database.Compra.ToList(); return View(compra); } } }<file_sep>/eventos/Controllers/CasasController.cs using System; using System.ComponentModel.DataAnnotations; using System.Linq; using eventos.Data; using eventos.DTO; using eventos.Models; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; namespace eventos.Controllers { [Authorize(Policy = "Poli")] public class CasasController : Controller { private readonly ApplicationDbContext database; public CasasController(ApplicationDbContext database){ this.database = database; } [HttpPost] public IActionResult Salvar(CasaDTO casatemporaria){ if(ModelState.IsValid){ Casa casa = new Casa(); casa.Nome = casatemporaria.Nome; casa.Endereco = casatemporaria.Endereco; casa.Status = true; database.Casas.Add(casa); database.SaveChanges(); return RedirectToAction("Casas", "Gestao"); }else{ return View("../Gestao/NovaCasa"); } } [HttpPost] public IActionResult Atualizar(CasaDTO casatemporaria){ if(ModelState.IsValid){ var casa = database.Casas.First(c => c.Id == casatemporaria.Id); casa.Nome = casatemporaria.Nome; casa.Endereco = casatemporaria.Endereco; database.SaveChanges(); return RedirectToAction("Casas","Gestao"); }else{ return RedirectToAction("Casas","Gestao"); } } [HttpPost] public IActionResult Deletar(int id){ if(id > 0){ var casa = database.Casas.First(casa => casa.Id == id); casa.Status = false; database.SaveChanges(); } return RedirectToAction("Casas" , "Gestao"); } } }<file_sep>/eventos/Models/Genero.cs namespace eventos.Models { public class Genero { public int Id { get; set; } public string Nome { get; set; } public bool Status{get; set;} } }<file_sep>/eventos/DTO/GeneroDTO.cs using System.ComponentModel.DataAnnotations; namespace eventos.DTO { public class GeneroDTO { [Required] public int Id { get; set; } [Required] [StringLength(100, ErrorMessage="Nome de genero muito grande, tente um menor!")] [MinLength(2, ErrorMessage="Nome muito curto, tente com mais de 2 caracteres.")] public string Nome { get; set; } } }<file_sep>/eventos/Models/Casa.cs namespace eventos.Models { public class Casa { public int Id { get; set; } public string Nome{get; set;} public string Endereco{get; set;} public bool Status{get; set;} } }<file_sep>/eventos/Models/Saida.cs using System; namespace eventos.Models { public class Saida { public int Id { get; set; } public Evento Evento{ get; set; } public float ValorDaVenda{get; set;} public DateTime Data{get; set;} } }<file_sep>/eventos/DTO/EventoDTO.cs using System; using System.ComponentModel.DataAnnotations; namespace eventos.DTO { public class EventoDTO { [Required] public int Id { get; set; } [Required(ErrorMessage="Nome do evento obrigatório")] [StringLength(100, ErrorMessage="Nome do evento muito grande, tente um menor!")] [MinLength(3, ErrorMessage="Nome muito curto, tente com mais de 2 caracteres.")] public string Nome{get; set;} [Required(ErrorMessage="Digite a capacidade do local")] public int capacidade{get; set;} [Required(ErrorMessage="Digite a data e a hora do local")] public DateTime Data{get; set;} [Required(ErrorMessage="Digite o valor do ingresso")] public float ValorIngresso { get; set; } [Required(ErrorMessage="Escolha a casa de show")] public int CasaID{get; set;} [Required(ErrorMessage="Escolha o genero")] public int GeneroID{get; set;} [Required(ErrorMessage="Coloque o link de uma imagem")] public string Imagem{get; set;} public int Quantidade{get; set;} public string usuario{get; set;} } }<file_sep>/eventos/Models/Compra.cs namespace eventos.Models { public class Compra { public int Id { get; set; } public string Nome{get; set;} public int capacidade{get; set;} public float ValorIngresso { get; set; } public float total{get; set;} public int Quantidade{get; set;} public string usuario{get; set;} public string imagem{get; set;} } }
f631faa86eea686b54938924089393da885378d8
[ "JavaScript", "C#" ]
21
C#
luan-css/ApiCasaShow
cf8ef8e9ba5585b34ab957e1de2de66218f3d9fd
b2497e834243a0c5b29ae767124c88ee0e7f103a
refs/heads/master
<repo_name>JuanMarioSastre27/SchoolManager<file_sep>/SchoolManager/src/respaldos/PersonaRespaldo.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package respaldos; /** * * @author Usuario */ public class PersonaRespaldo { protected String name; protected String surnameF; protected String surnameM; public PersonaRespaldo(String name, String surnameF, String surnameM) { this.name = name; this.surnameF = surnameF; this.surnameM = surnameM; } @Override public String toString(){ return "\nNombre: " + name + "\nApellido Paterno: " + surnameF + "\nApellido Materno: " + surnameM; } } <file_sep>/SchoolManager/src/prueba/PruebaUno.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package prueba; import modelos.*; /** * * @author mario */ public class PruebaUno { public static void main(String[] args) { //Creamos el profesor Teacher teacher1 = new Teacher("Jose", "Lopez", "Hernandez", "Matematicas", " Dr. Matematicas"); //Creamos la uea Uea uea = new Uea("Calculo integral", "1213314"); //Limite de estudiantes int limit = 6; //Creamos la clave del grupo String groupKey = "CTG01"; Manager manager = new Manager(uea, teacher1, limit, groupKey); //Agregamos a los alumnos al grupo manager.addStudent(new Student("Mario", "Sastre", "Cuahutle", "ING Computacion")); manager.addStudent(new Student("Juan", "Martinez", "Perez", "ING Fisica")); manager.addStudent(new Student("Carlos", "Hernandez", "Juarez", "ING Ambiental")); manager.addStudent(new Student("Karla", "Samperio", "Leon", "ING Electronica")); manager.addStudent(new Student("Luis", "Flores", "Cortes", "ING Computacion")); manager.addStudent(new Student("Monserrat", "Olivos", "Martinez", "ING Electrica")); manager.addStudent(new Student("Jorge", "Perez", "Solis", "ING Quimica")); manager.addStudent(new Student("Brenda", "Leon", "Solis", "ING Computacion")); manager.addGroup(); manager.showGroups(); } } <file_sep>/SchoolManager/src/modelos/Manager.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package modelos; import java.util.ArrayList; /** * * @author mario */ public class Manager { private Group group; private ArrayList <Group> groups; //Gestion del grupo directo private Uea uea; private ArrayList <Student> students ; private Teacher teacher; private int studentsLimit; private String groupKey; public Manager(Uea uea, Teacher teacher, int studentsLimit, String groupKey) { this.uea = uea; this.students = students; this.teacher = teacher; this.studentsLimit = studentsLimit; this.groupKey = groupKey; group = new Group(uea, teacher, studentsLimit, groupKey); groups = new ArrayList <>(); } public void addStudent(Student student){ group.addStudent(student); } public void addGroup(){ groups.add(group); } public void showGroups(){ System.out.println("############## Grupos registrados #############"); ArrayList <Student> students = new ArrayList<>(); ArrayList <Student> studentsRejected = new ArrayList<>(); for(Group group : groups){ System.out.println("######################################"); System.out.println("######################################"); System.out.println(group.toString()); students = group.getStudents(); studentsRejected = group.getStudentsRejected(); showStudents(students, studentsRejected); /* System.out.println("--------------------- ALUMNOS INSCRITOS -------------------"); for(Student student : students){ System.out.println("----------------------------------------------------"); System.out.println(student.toString()); } */ } } public void showStudents(ArrayList <Student> students, ArrayList <Student> studentsRejected){ System.out.println("***************************************************************"); System.out.println("--------------------- ALUMNOS INSCRITOS -------------------"); for(Student student : students){ System.out.println("----------------------------------------------------"); System.out.println(student.toString()); } if(studentsRejected.size() > 0){ System.out.println("***************************************************************"); System.out.println("------------------ ALUMNOS RECHAZADOS POR CUPO ----------------"); for(Student studentRejected : studentsRejected){ System.out.println("----------------------------------------------------"); System.out.println(studentRejected.toString()); } } } @Override public String toString(){ return null; } }
50fddd159e6a891008d30c6c4dd147493141938f
[ "Java" ]
3
Java
JuanMarioSastre27/SchoolManager
90a8eff863713126208502a4c358cc3d352143e1
2135adf2718040692224cc1704d2200913f58c7f
refs/heads/master
<file_sep># Simon-Game-Project-jQuery- Simon was an electronic game of memory skill invented by <NAME> and <NAME>.This game uses the same logic of that electronic game and has been developed using Javascript and Jquery. ## How to play? There are four colored buttons, each producing a particular tone when it is pressed or activated. A round in the game consists of the bot lighting up one random button, after which the player must reproduce that same order/sequence by pressing the buttons. As the game progresses,it get tougher to remember the sequence. In order to move forward in the game the player must press all the buttons in the same sequence as they were pressed by the bot. ## Author > <NAME> ## Screenshots 📷 ![Game Screenshot Beginning](screenshots/1.png) ![Game Screenshot Lost](screenshots/3.png) ## Live Demo [https://nishkarsh01.github.io/Simon-Game-Project-jQuery-/](https://nishkarsh01.github.io/Simon-Game-Project-jQuery-/) ## Developed Using 💻 + [Html](https://developer.mozilla.org/en-US/docs/Web/HTML) + [Css](https://developer.mozilla.org/en-US/docs/Web/CSS) + [Javascript](https://developer.mozilla.org/en-US/docs/Web/javascript) + [jQuery](https://jquery.com/) ## Installation or Getting Started Run the following command in the terminal: git clone https://github.com/Nishkarsh01/Simon-Game-Project-jQuery-.git or download the zip file from github. ## Usage After extracting the files, cd Simon-Game-Project-jQuery- and simply, open the index.html file ## Collaborate To collaborate, reach me on [<EMAIL>]() ## Further help/Reference + [MDN Web Docs](https://developer.mozilla.org/en-US/) + [w3schools.com](https://www.w3schools.com/) + [jquery.com/](https://jquery.com/) <file_sep>/******starting the game******** */ var started=false; $("body").on("keyup", function () { if(!started){ botColorSequence = []; level=0; $("body").removeClass("game-over"); $("h1").text("level " + level); nextSequence(); started=true; } }); /*the color array*/ var colors = ["red", "green", "blue", "yellow"] /********levels */ var level = 0; /*arrays that include real color pattern and user clicked pattern*/ var botColorSequence = []; var clickPattern = []; var lastNumber = (clickPattern.length) - 1; var lastNumber1 = (botColorSequence.length) - 1; /*generating a sequence*/ function nextSequence() { level++; $("h1").text("level " + level); var randomNumber = Math.floor(Math.random() * 4); var botChosenColor = colors[randomNumber]; //console.log(botChosenColor); botColorSequence.push(botChosenColor); $("#" + botChosenColor).fadeIn(100).fadeOut(100).fadeIn(100); makeSound(botChosenColor); clickPattern = []; console.log(botColorSequence); } /****sequence on user click*/ $(".btn").on("click", function () { var clickedColor = this.id; clickPattern.push(clickedColor); //console.log(clickPattern); makeSound(clickedColor); visualEffects(clickedColor); checkAnswer(clickPattern.length-1); }); function checkAnswer(currentLevel) { if(clickPattern[currentLevel] === botColorSequence[currentLevel]){ if(clickPattern.length===botColorSequence.length ){ setTimeout(() => { nextSequence(); }, 1000); } } else{ makeSound("wrong"); $("h1").text("You lost,Press Any Key To Start Again."); $("body").addClass("game-over"); started=false; } /* var clickIndex = clickPattern.indexOf(clickedColor); console.log(clickedColor); console.log(clickPattern); if (clickPattern[clickIndex] == botColorSequence[clickIndex]) { console.log("right"); if (clickPattern[lastNumber] == botColorSequence[lastNumber1]) { setTimeout(() => { nextSequence(); }, 1000); } else { console.log("you lost"); } } else { console.log("lost"); }*/ } /**making sound on clicks or bot seq generation */ function makeSound(colorSound) { var audio = new Audio("sounds/" + colorSound + ".mp3"); audio.play(); } /***visual effects on clicks */ function visualEffects(a) { $("#" + a).addClass("pressed"); setTimeout(() => { $("#" + a).removeClass("pressed"); }, 100); }
93dc60a4d3858991c94431815317338f0e1dbe61
[ "Markdown", "JavaScript" ]
2
Markdown
Nishkarsh01/Simon-Game-Project-jQuery-
5986083c2ab5d6191a5a0b0c80c56f9c79fa7b8e
be01fff0fd4727a9273d17ee1240c26c46a8fb51
refs/heads/master
<repo_name>Thomaz-Peres/SQLite-studio<file_sep>/Form1.cs using SQLite.BancoDados; using SQLite.Components; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace SQLite { public partial class Form1 : Form { public Form1() { InitializeComponent(); F_Login f_Login = new F_Login(this); f_Login.ShowDialog(); } private void btn_logout_Click(object sender, EventArgs e) { lb_acesso.Text = "0"; lb_nomeUsuario.Text = "---"; pb_ledLogado.Image = Properties.Resources.led_vermelho; Globais.nivel = 0; Globais.logado = false; } private void btn_login_Click(object sender, EventArgs e) { F_Login f_Login = new F_Login(this); f_Login.ShowDialog(); } private void bancoDeDadosToolStripMenuItem_Click(object sender, EventArgs e) { if(Globais.logado == true) { if(Globais.nivel >= 2) { //Procedimentos da janela } else { MessageBox.Show("Nivel de acesso não permitido"); } } else { MessageBox.Show("É necessario ter um usuario logado."); } } private void novoUsuarioToolStripMenuItem_Click(object sender, EventArgs e) { if (Globais.logado == true) { if (Globais.nivel >= 1) { F_NovoUsuario f_NovoUsuario = new F_NovoUsuario(); f_NovoUsuario.ShowDialog(); } else { MessageBox.Show("Nivel de acesso não permitido"); } } else { MessageBox.Show("É necessario ter um usuario logado."); } } private void gestãoDeUsuariosToolStripMenuItem_Click(object sender, EventArgs e) { if (Globais.logado == true) { if (Globais.nivel >= 2) { F_GestaoUsuarios f_GestaoUsuarios = new F_GestaoUsuarios(); f_GestaoUsuarios.ShowDialog(); } else { MessageBox.Show("Nivel de acesso não permitido"); } } else { MessageBox.Show("É necessario ter um usuario logado."); } } private void novoAlunoToolStripMenuItem_Click(object sender, EventArgs e) { if (Globais.logado == true) { //procedimentos } else { MessageBox.Show("É necessario ter um usuario logado."); } } } } <file_sep>/F_GestaoUsuarios.cs using SQLite.BancoDados; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace SQLite { public partial class F_GestaoUsuarios : Form { public F_GestaoUsuarios() { InitializeComponent(); } private void btn_fechar_Click(object sender, EventArgs e) { Close(); } private void F_GestaoUsuarios_Load(object sender, EventArgs e) { dgv_usuarios.DataSource = Banco.ObterUsuariosIdNome(); dgv_usuarios.Columns[0].Width = 85; dgv_usuarios.Columns[1].Width = 250; } private void dgv_usuarios_SelectionChanged(object sender, EventArgs e) { DataGridView dgv = (DataGridView)sender; int contLinhas = dgv.SelectedRows.Count; if(contLinhas > 0) { DataTable dt = new DataTable(); string vID = dgv.SelectedRows[0].Cells[0].Value.ToString(); dt = Banco.ObterDadosUsuario(vID); tb_id.Text = dt.Rows[0].Field<Int64>("N_IDUSUARIAO").ToString(); tb_nome.Text = dt.Rows[0].Field<string>("T_NOMEUSUARIO").ToString(); tb_username.Text = dt.Rows[0].Field<string>("T_USERNAME").ToString(); tb_senha.Text = dt.Rows[0].Field<string>("T_STATUSUSUARIO").ToString(); cb_status.Text = dt.Rows[0].Field<string>("T_SENHAUSUARIO").ToString(); n_nivel.Value = dt.Rows[0].Field<Int64>("N_NIVELUSUARIO"); } } private void btn_novo_Click(object sender, EventArgs e) { F_NovoUsuario f_NovoUsuario = new F_NovoUsuario(); f_NovoUsuario.ShowDialog(); dgv_usuarios.DataSource = Banco.ObterUsuariosIdNome(); } private void btn_salvar_Click(object sender, EventArgs e) { int linha = dgv_usuarios.SelectedRows[0].Index; Usuario usuario = new Usuario(); usuario.id = Convert.ToInt32(tb_id.Text); usuario.nome = tb_nome.Text; usuario.username = tb_username.Text; usuario.senha = tb_senha.Text; usuario.status = cb_status.Text; usuario.nivel = Convert.ToInt32(Math.Round(n_nivel.Value, 0)); Banco.AtualizarUsuario(usuario); //dgv_usuarios.DataSource = Banco.ObterUsuariosIdNome(); //dgv_usuarios.CurrentCell = dgv_usuarios[0, linha]; //dgv_usuarios[0, linha].Value = tb_id.Text; dgv_usuarios[1, linha].Value = tb_nome.Text; } private void btn_excluir_Click(object sender, EventArgs e) { DialogResult res = MessageBox.Show("Confirma exclusão ?", "Excluir ?", MessageBoxButtons.YesNo); if(res == DialogResult.Yes) { Banco.ExcluirUsuario(tb_id.Text); dgv_usuarios.Rows.Remove(dgv_usuarios.CurrentRow); } } } } <file_sep>/README.MD # ENTENDENDO O BANCO DE DADOS SQLite ### todos projetos que utilizarem o SQLite, é necessario adicionar o NUGET ### aprendendo criando uma classe, e dentro dela, implementar as rotinas principais para a utilização do banco de dados ### e diretamente dentro da janela. ### aqui estou aprendendo as duas, CLASSE DE BANCO DE DADOS, E ACESSO DIRETO DENTRO DA JANELA SEM UTILIZAÇÃO DA CLASSE #### importe de dados na classe using System.Data; #### using System.Data.SQLite; #### criando a variavel e o metodo de conexão private static SQLiteConnection conexao; // variavel - metodo que faz a conexao com o banco - private static SQLiteConnection ConexaoBanco() // metodo - { - conexao = new SQLiteConnection("Data Source = C:\\Users\\AlphaPaiN\\Documents\\dev\\Notes\\Visual Studio\\SQLite\\Banco de Dados\\Banco_academia.db"); - conexao.Open(); - return conexao; - } ## o using engloba todo conteudo dentro do comando <file_sep>/Components/Globais.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SQLite.Components { class Globais { public static string versao = "1.0"; public static Boolean logado = false; public static int nivel = 0; // 0 - Básico - 1 Gerente - 2 Master /* N_IDUSUARIAO, T_NOMEUSUARIO, T_USERNAME, T_SENHAUSUARIO, T_STATUSUSUARIO, N_NIVELUSUARIO, */ } } <file_sep>/BancoDados/Banco.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data; using System.Data.SQLite; using System.Windows.Forms; namespace SQLite.BancoDados { class Banco { private static SQLiteConnection conexao; private static SQLiteConnection ConexaoBanco() { conexao = new SQLiteConnection("Data Source = C:\\Users\\AlphaPaiN\\Documents\\dev\\Notes\\Visual Studio\\SQLite\\Banco de Dados\\Banco_academia.db"); conexao.Open(); return conexao; } public static DataTable ObterTodosUsuarios() { SQLiteDataAdapter da = null; DataTable dt = new DataTable(); try { var vcon = ConexaoBanco(); var cmd = vcon.CreateCommand(); cmd.CommandText = "SELECT * FROM tb_usuarios"; da = new SQLiteDataAdapter(cmd.CommandText, vcon); da.Fill(dt); vcon.Close(); return dt; } catch (Exception ex) { throw ex; } } public static DataTable Consulta(string sql) { SQLiteDataAdapter da = null; DataTable dt = new DataTable(); try { var vcon = ConexaoBanco(); var cmd = vcon.CreateCommand(); cmd.CommandText = sql; da = new SQLiteDataAdapter(cmd.CommandText, vcon); da.Fill(dt); vcon.Close(); return dt; } catch (Exception ex) { throw ex; } } public static DataTable ObterUsuariosIdNome() { SQLiteDataAdapter da = null; DataTable dt = new DataTable(); try { var vcon = ConexaoBanco(); var cmd = vcon.CreateCommand(); cmd.CommandText = "SELECT N_IDUSUARIAO as 'ID Usuario', T_NOMEUSUARIO as 'Nome Usuario' FROM tb_usuarios"; da = new SQLiteDataAdapter(cmd.CommandText, vcon); da.Fill(dt); vcon.Close(); return dt; } catch (Exception ex) { throw ex; } } public static DataTable ObterDadosUsuario(string id) { SQLiteDataAdapter da = null; DataTable dt = new DataTable(); try { var vcon = ConexaoBanco(); var cmd = vcon.CreateCommand(); cmd.CommandText = "SELECT * FROM tb_usuarios WHERE N_IDUSUARIAO = " + id; da = new SQLiteDataAdapter(cmd.CommandText, vcon); da.Fill(dt); vcon.Close(); return dt; } catch (Exception ex) { throw ex; } } public static void AtualizarUsuario(Usuario u) { SQLiteDataAdapter da = null; DataTable dt = new DataTable(); try { var vcon = ConexaoBanco(); var cmd = vcon.CreateCommand(); cmd.CommandText = "UPDATE tb_usuarios SET T_NOMEUSUARIO = '" + u.nome + "', T_USERNAME = '" + u.username + "', T_SENHAUSUARIO = '" + u.senha + "', T_STATUSUSUARIO = '" + u.status + "', N_NIVELUSUARIO = " + u.nivel + " WHERE N_IDUSUARIAO= " + u.id; da = new SQLiteDataAdapter(cmd.CommandText, vcon); cmd.ExecuteNonQuery(); vcon.Close(); } catch (Exception ex) { throw ex; } } public static void ExcluirUsuario(string id) { SQLiteDataAdapter da = null; DataTable dt = new DataTable(); try { var vcon = ConexaoBanco(); var cmd = vcon.CreateCommand(); cmd.CommandText = "DELETE FROM tb_usuarios WHERE N_IDUSUARIAO= " + id; da = new SQLiteDataAdapter(cmd.CommandText, vcon); cmd.ExecuteNonQuery(); vcon.Close(); } catch (Exception ex) { throw ex; } } public static void NovoUsuario(Usuario usuario) { if(existeUsername(usuario)) { MessageBox.Show("Username ja existe"); return; } try { var vcon = ConexaoBanco(); var cmd = vcon.CreateCommand(); cmd.CommandText = "INSERT INTO tb_usuarios " + "(T_NOMEUSUARIO," + " T_USERNAME," + " T_SENHAUSUARIO," + " T_STATUSUSUARIO," + " N_NIVELUSUARIO)" + " VALUES (@nome, @username, @senha, @status, @nivel)"; cmd.Parameters.AddWithValue("@nome", usuario.nome); cmd.Parameters.AddWithValue("@username", usuario.username); cmd.Parameters.AddWithValue("@senha", usuario.senha); cmd.Parameters.AddWithValue("@status", usuario.status); cmd.Parameters.AddWithValue("@nivel", usuario.nivel); cmd.ExecuteNonQuery(); MessageBox.Show("Novo usuario inserido"); vcon.Close(); } catch (Exception ex) { MessageBox.Show("Erro ao gravar novo usuario" + ex); } } public static bool existeUsername(Usuario u) { bool res; SQLiteDataAdapter da = null; DataTable dt = new DataTable(); var vcon = ConexaoBanco(); var cmd = vcon.CreateCommand(); cmd.CommandText = "SELECT T_USERNAME FROM tb_usuarios WHERE T_USERNAME='"+u.username+"' "; da = new SQLiteDataAdapter(cmd.CommandText, vcon); da.Fill(dt); if(dt.Rows.Count > 0) { res = true; } else { res = false; } vcon.Close(); return res; } } }
c06bce57386eeb7c86f5680bbf8593a7331acaf1
[ "Markdown", "C#" ]
5
C#
Thomaz-Peres/SQLite-studio
8ec75c9d299d3094aa959350780c38ccc32725ae
62e2a3e781145fc952e4d6b9ec3fcd4cffaebcea
refs/heads/master
<file_sep>#!/bin/bash sudo su mkdir /tmp/jenkins pushd /tmp/jenkins wget --no-check-certificate --no-cookies \ --header "Cookie: oraclelicense=accept-securebackup-cookie" \ http: //download.oracle.com/otn-pub/java/jdk/8u131-b11/d54c1d3a095b4ff2b6607d096fa80163/jdk-8u131-linux-x64. rpm –i jdk-8u131-linux-x64.rpm alternatives --install /usr/bin/java java /usr/java/latest/bin/java 200000 alternatives --install /usr/bin/javac javac /usr/java/latest/bin/javac 200000 alternatives --install /usr/bin/jar jar /usr/java/latest/bin/jar 200000 echo "export JAVA_HOME="/usr/java/latest"" >> /etc/rc.local popd <file_sep># -*- mode: ruby -*- # vi: set ft=ruby : Vagrant.configure(2) do |config| config.vm.define :ops do |ops| ops.vm.box ='geerlingguy/centos7' ops.vm.hostname ='ops.lab.com' ops.vm.network :private_network, ip: "192.168.1.2" end config.vm.define :jenkins do |jenkins| jenkins.vm.box = 'geerlingguy/centos7' jenkins.vm.hostname = 'jenkins.lab.com' jenkins.vm.network :private_network, ip: "192.168.1.3" end config.vm.define :prod do |prod| prod.vm.box = 'geerlingguy/centos7' prod.vm.hostname = 'prod.lab.com' prod.vm.network :private_network, ip: "192.168.1.4" end end
cb33a579d6f16388b5fd3cc10da0d1cdfb26975f
[ "Ruby", "Shell" ]
2
Shell
DanielaZacarias/superintento
4875c55ca93831d2192e9ff279ff65defe4fa658
717708c12c6cd592e6d66319f0911c98fdcd546b
refs/heads/master
<repo_name>Cheshihin/optimal_group_test_right<file_sep>/currency/add-currency.php <? require($_SERVER["DOCUMENT_ROOT"]."/bitrix/header.php"); $APPLICATION->SetTitle("Добавление курсов валют в базу"); ?> Добавление курсов валют в базу. <? $fill_from_record_number = isset($_GET['fill_from_record_number'])?$_GET['fill_from_record_number']:1; $currency_add = new CurrencyActions('eurofxref-hist.xml'); //$currency_add->fill_date_from = '2018-05-01'; $currency_add->fill_from_record_number = isset($_GET['fill_from_record_number'])?$_GET['fill_from_record_number']:1; $currency_add->fill_record_count = 15; $currency_add->addCurrencyRates(); echo '</br>'; echo 'Валюты добавлены!'; ?> <script type="text/javascript"> $(document).ready(function(){ var fill_from_record_number = parseInt(<?=$fill_from_record_number;?>); fill_from_record_number += 15; setTimeout(function(){ window.location = '/currency/add-currency.php?fill_from_record_number='+fill_from_record_number; }, 2000); }); </script> <?require($_SERVER["DOCUMENT_ROOT"]."/bitrix/footer.php");?><file_sep>/bitrix/license_key.php <? $LICENSE_KEY = "<KEY>"; ?><file_sep>/currency/.section.php <? $sSectionName="Курсы валют"; ?><file_sep>/bitrix/modules/main/admin/define.php <?define("TEMPORARY_CACHE", "ARtvdgYHb2MMdwgebRtkG2cA");?><file_sep>/bitrix/php_interface/init.php <? CModule::IncludeModule("iblock"); class CurrencyActions{ public $fill_date_from; public $fill_date_to; public $fill_from_record_number; public $fill_record_count; public $currency_XML_url; public $update_mode; private $xml_data; private $all_xml_data_parsed; private $XML; private $created_count; public $xml_data_count; public $partialPageCount; function __construct($currency_XML_url="https://www.ecb.europa.eu/stats/eurofxref/eurofxref-hist.xml", $need_parse_xml_data=false){ if($currency_XML_url && $currency_XML_url != ''){ $this->currency_XML_url = $currency_XML_url; } else { $this->currency_XML_url = "https://www.ecb.europa.eu/stats/eurofxref/eurofxref-hist.xml"; } $this->fill_date_from = null; $this->fill_date_to = null; $this->fill_from_record_number = 1; $this->fill_record_count = null; $this->update_mode = false; $this->created_count = 0; $this->XML = simplexml_load_file($this->currency_XML_url); $this->partialPageCount = 100; if($need_parse_xml_data){ $this->xml_data = array(); foreach($this->XML->Cube->Cube as $time){ $curr_date = $this->getRightDateString1($time['time']); $this->xml_data[$curr_date] = array(); foreach($time->Cube as $cube){ $this->xml_data[$curr_date][] = array('CURRENCY'=>$cube['currency'],'VALUE'=>$cube['rate']); } } $this->all_xml_data_parsed = true; } else { $this->xml_data = null; $this->all_xml_data_parsed = false; } } private function parse_xml_data(){ $this->xml_data = array(); $this->xml_data_count = 0; if($this->fill_from_record_number !== null){ $curr_record_number = 1; $curr_count = 0; } else { $curr_date = null; } $no_parsed_data_exists = false; if($this->fill_from_record_number !== null){ $itter_count = 0; foreach($this->XML->Cube->Cube as $time){ if(($this->fill_from_record_number !== null && $curr_record_number < $this->fill_from_record_number) || ($this->fill_record_count !== null && $curr_count > $this->fill_record_count)){ if($this->fill_record_count !== null && $curr_count > $this->fill_record_count){ $no_parsed_data_exists = true; break; } else { $no_parsed_data_exists = true; $curr_record_number++; continue; } } $curr_date = $this->getRightDateString1($time['time']); $this->xml_data[$curr_date] = array(); foreach($time->Cube as $cube){ $this->xml_data[$curr_date][] = array('CURRENCY'=>$cube['currency'],'DATE_UNIX'=>strtotime($this->getRightDateString3($time['time'])),'VALUE'=>$cube['rate']); $this->xml_data_count++; } $curr_count++; $curr_record_number++; $itter_count++; } } else if($this->fill_date_from !== null || $this->fill_date_to !== null){ if($this->fill_date_to !== null){ $date_to = strtotime($this->getRightDateString3($this->fill_date_to)); } else { $date_to = null; } if($this->fill_date_from !== null){ $date_from = strtotime($this->getRightDateString3($this->fill_date_from)); } else { $date_from = null; } foreach($this->XML->Cube->Cube as $time){ if($this->fill_date_to !== null && strtotime($this->getRightDateString3($time['time']))>$date_to){ $no_parsed_data_exists = true; break; } if(($this->fill_date_from === null || strtotime($this->getRightDateString3($time['time']))>=$date_from) && ($this->fill_date_to === null || strtotime($this->getRightDateString3($time['time']))<=$date_to)){ $curr_date = $this->getRightDateString1($time['time']); $this->xml_data[$curr_date] = array(); foreach($time->Cube as $cube){ $this->xml_data[$curr_date][] = array('CURRENCY'=>$cube['currency'],'DATE_UNIX'=>strtotime($this->getRightDateString3($time['time'])),'VALUE'=>$cube['rate']); $this->xml_data_count++; } } else { $no_parsed_data_exists = true; } } } else { //foreach($this->XML->Cube->Cube as $time){ foreach($this->XML->Cube->Cube as $time){ $curr_date = $this->getRightDateString1($time['time']); $this->xml_data[$curr_date] = array(); foreach($time->Cube as $cube){ $this->xml_data[$curr_date][] = array('CURRENCY'=>$cube['currency'],'DATE_UNIX'=>strtotime($this->getRightDateString3($time['time'])),'VALUE'=>$cube['rate']); $this->xml_data_count++; } } //} } if(!$no_parsed_data_exists){ $this->all_xml_data_parsed = true; } else { $this->all_xml_data_parsed = false; } } private function getDataPage($page_number){ $fromXML = array(); $start_number = ($page_number - 1) * $this->partialPageCount + 1; $end_number = $start_number + $this->partialPageCount - 1; $curr_number = 1; $min_date = 0; $max_date = $min_date; $curr_number = 1; $total_count = 0; $records_are_over = false; $first_entering = true; foreach($this->xml_data as $date=>$date_item){ //$fromXML[$date] = array(); foreach($date_item as $data_item){ if($curr_number > $end_number){ break; } if($curr_number < $start_number){ $curr_number++; continue; } if($first_entering){ $min_date = $date_item['UNIX_DATE']; $max_date = $date_item['UNIX_DATE']; $first_entering = false; } else { if($date_item['UNIX_DATE'] < $min_date){ $min_date = $date_item['UNIX_DATE']; } if($date_item['UNIX_DATE'] > $max_date){ $max_date = $date_item['UNIX_DATE']; } } if(!isset($fromXML[$date])){ $fromXML[$date] = array(); $fromXML[$date][] = $data_item; } else { $fromXML[$date][] = $data_item; } $curr_number++; $total_count++; } } if($curr_number > $this->partialPageCount){ $records_are_over = true; } $max_date += 86399; $min_date_str = $this->getRightDateStringFromUnixDate($min_date,'Y-m-d H:i:s'); $max_date_str = $this->getRightDateStringFromUnixDate($max_date,'Y-m-d H:i:s'); $arFilter = Array( "IBLOCK_ID"=>6, //">DATE_ACTIVE_FROM"=>date($DB->DateFormatToPHP(CLang::GetDateFormat("SHORT")), mktime(0,0,0,1,1,2003)), "ACTIVE"=>"Y", ">=PROPERTY_DATE_VALUE"=>$min_date_str, "<=PROPERTY_DATE_VALUE"=>$max_date_str, ); $res = CIBlockElement::GetList(array(), $arFilter, false, false, Array("IBLOCK_ID",'ID','PROPERTY_DATE')); $dates = array(); while($ob = $res->GetNextElement()) { $arProps = $ob->GetProperties(); $dates[$arProps["DATE"]['VALUE']] = true; } $dates = array_keys($dates); //var_dump('DATES_COUNT:'.count($dates)); $toUpdate = array(); foreach($dates as $date){ if(isset($fromXML[$date])){ if(!isset($toUpdate[$date])){ var_dump('to_update'.$date); $toUpdate[$date] = $fromXML[$date]; } } } foreach($toUpdate as $k=>$item){ unset($fromXML[$k]); } return array( 'ADDED'=>$fromXML, 'UPDATED'=>$toUpdate, 'TOTAL_COUNT'=>$total_count, 'END'=>$records_are_over ); } private function getDateArray($date_string){ $exp = explode('-',$date_string); return array( 'YEAR'=>$exp[0], 'MONTH'=>$exp[1], 'DAY'=>$exp[2] ); } private function getDateArray1($date_string){ $exp = explode('.',$date_string); return array( 'DAY'=>$exp[0], 'MONTH'=>$exp[1], 'YEAR'=>$exp[2] ); } private function getFromDate($date_string){ $date_array = $this->getDateArray1($date_string); $date_unix = strtotime($date_array['YEAR'].'-'.$date_array['MONTH'].'-'.$date_array['DAY']) - 1; $str = $this->getRightDateStringFromUnixDate($date_unix, 'Y-m-d H:i:s'); return $str; } private function getToDate($date_string){ $date_array = $this->getDateArray1($date_string); $str = $date_array['YEAR'].'-'.$date_array['MONTH'].'-'.$date_array['DAY'].' 23:59:59'; return $str; } private function getRightDateStringFromUnixDate($unix_date, $format='d.m.Y'){ $date = date_create(); date_timestamp_set($date, $unix_date); return date_format($date, $format); } private function getRightDateString1($date_string){ $date_array = $this->getDateArray($date_string); return $date_array['DAY'].'.'.$date_array['MONTH'].'.'.$date_array['YEAR']; } private function getRightDateString2($date_string){ $date_array = $this->getDateArray($date_string); return $date_array['DAY'].'-'.$date_array['MONTH'].'-'.$date_array['YEAR']; } private function getRightDateString3($date_string){ $date_array = $this->getDateArray($date_string); return $date_array['MONTH'].'/'.$date_array['DAY'].'/'.$date_array['YEAR']; } private function getRightDateString4($date_string){ $date_array = $this->getDateArray1($date_string); return $date_array['YEAR'].'-'.$date_array['MONTH'].'-'.$date_array['DAY']; } private function addCurrencyOnDate($date,$currency_name,$currency_value){ $fields = array( 'IBLOCK_ID' => 6, 'NAME'=>$currency_name, 'ACTIVE'=>'Y', 'CODE'=>$currency_name.'-'.$date ); $fields['PROPERTY_VALUES'] = array( 'DATE' => $date, 'VALUE' => $currency_value ); $el = new CIBlockElement; if($ELEMENT_ID = $el->Add($fields)){ $this->created_count++; //echo "New ID: ".$ELEMENT_ID.'</br>'; }else echo "Error: ".$el->LAST_ERROR.'</br>'; } public function addCurrencyRates(){ $this->created_count = 0; $this->parse_xml_data(); $min_date_unix = 0; $max_date_unix = 0; $first_entering = true; foreach($this->xml_data as $date=>$items){ foreach($items as $item){ if($first_entering){ $min_date_unix = $item['DATE_UNIX']; $max_date_unix = $min_date_unix; $first_entering = false; } else { if($item['DATE_UNIX'] < $min_date_unix){ $min_date_unix = $item['DATE_UNIX']; } if($item['DATE_UNIX'] > $max_date_unix){ $max_date_unix = $item['DATE_UNIX']; } } } } $min_date_str = $this->getRightDateStringFromUnixDate($min_date_unix - 1,'Y-m-d H:i:s'); $max_date_str = $this->getRightDateStringFromUnixDate($max_date_unix + 86399,'Y-m-d H:i:s'); $arFilter = Array( "IBLOCK_ID"=>6, //">DATE_ACTIVE_FROM"=>date($DB->DateFormatToPHP(CLang::GetDateFormat("SHORT")), mktime(0,0,0,1,1,2003)), "ACTIVE"=>"Y", ">=PROPERTY_DATE"=>$min_date_str, "<=PROPERTY_DATE"=>$max_date_str, ); $res = CIBlockElement::GetList(array(), $arFilter, false, false, Array("IBLOCK_ID",'ID','PROPERTY_DATE')); $dates = array(); while($ob = $res->GetNextElement()) { $arProps = $ob->GetProperties(); $dates[$arProps["DATE"]['VALUE']] = true; } $dates = array_keys($dates); $result_xml_data = $this->xml_data; foreach($dates as $date){ if(isset($result_xml_data[$date])){ unset($result_xml_data[$date]); //var_dump($date); } } foreach($result_xml_data as $date=>$items){ foreach($items as $item){ $this->addCurrencyOnDate($date,$item['CURRENCY'],$item['VALUE']); } } $created_count = $this->created_count; echo "</br>СОЗДАНО: $created_count элементов"; } public function getCurrencyRateData($date_from, $date_to, $page_number=1, $page_count=200){ $arFilter = Array( "IBLOCK_ID"=>6, //">DATE_ACTIVE_FROM"=>date($DB->DateFormatToPHP(CLang::GetDateFormat("SHORT")), mktime(0,0,0,1,1,2003)), "ACTIVE"=>"Y", ">=PROPERTY_DATE"=>$this->getFromDate($date_from), "<=PROPERTY_DATE"=>$this->getToDate($date_to), ); $res = CIBlockElement::GetList(array('PROPERTY_DATE'=>'ASC','NAME'=>'ASC'), $arFilter, false, /*array('iNumPage'=>$page_number, 'nPageSize'=>$page_count)*/false, Array("IBLOCK_ID",'ID','NAME','PROPERTY_DATE_VALUE','PROPERTY_VALUE_VALUE')); $records = array(); $names_array = array(); $dates_array = array(); while($ob = $res->GetNextElement()) { $arFields = $ob->GetFields(); $arProps = $ob->GetProperties(); $records[] = array('CURRENCY'=>$arFields['NAME'], 'DATE'=>$arProps['DATE']['VALUE'], 'VALUE'=>$arProps['VALUE']['VALUE']); $names_array[$arFields['NAME']] = true; $dates_array[$arProps['DATE']['VALUE']] = true; } //var_dump($records); $result_table = array(); foreach($names_array as $name=>$name_value){ foreach($dates_array as $date=>$date_value){ if(!isset($result_table[$date])){ $result_table[$date] = array(); $value = null; foreach($records as $record){ if($record['CURRENCY'] == $name && $record['DATE'] == $date){ $value = $record['VALUE']; } } $result_table[$date][$name] = $value; } else { $value = null; foreach($records as $record){ if($record['CURRENCY'] == $name && $record['DATE'] == $date){ $value = $record['VALUE']; } } $result_table[$date][$name] = $value; } } } return array('COLUMNS'=>array_keys($names_array), 'ROWS'=>array_keys($dates_array), 'RESULT'=>$result_table); } public function displayCurrencyRateData($date_from, $date_to, $page_number=1, $page_count=200){ $rate_data = $this->getCurrencyRateData($date_from, $date_to, $page_number=1, $page_count=200); $html_str = '<div class="display-currency-rates" style="display:block;width:100%;">'; $html_str .= '<div style="display:inline-block;width:10%;height:410px;overflow-y:scroll;">'; $html_str .= '<table style="width:100%;">'; $html_str .= '<tr style="display:inline-block;width:100%;"><td style="font-style:bold;font-size:8px;text-align:center;padding:10px;">'.'ДАТА'.'</td></tr>'; foreach($rate_data['ROWS'] as $k=>$row){ if($k < count($rate_data['ROWS']) - 1){ $html_str .= '<tr style="display:inline-block;margin-top:-1px;"><td style="font-style:italic;font-size:8px;text-align:center;width:100%;">'.$row.'</td></tr>'; } else { $html_str .= '<tr style="display:inline-block;margin-top:-1px;"><td style="font-style:italic;font-size:8px;text-align:center;width:100%;">'.$row.'</td></tr>'; } } $html_str .= '</table>'; $html_str .= '</div>'; $html_str .= '<div style="width:90%;max-width:100%;display:inline-block;height:400px;overflow-x:scroll;overflow-y:scroll;"><table><tr>'; foreach($rate_data['COLUMNS'] as $column){ $html_str .= '<td style="font-style:bold;font-size:10px;padding:3px;text-align:center;">'.$column.'</td>'; } $html_str .= '</tr>'; //$html_str .= '<tbody style="display: block;height: 400px;background: pink;">'; foreach($rate_data['RESULT'] as $date=>$result_row){ //$html_str .= '<tr><td style="font-style:bold;font-size:8px;padding:3px;">'.$date.'</td>'; $html_str .= '<tr>'; foreach($result_row as $item){ $html_str .= '<td style="font-style:italic;font-size:8px;padding:4.2px;">'.$item.'</td>'; } $html_str .= '</tr>'; } //$html_str .= '</tr>'; //$html_str .= '</tbody>'; $html_str .= '</table></div>'; $html_str .= '</div>'; return $html_str; } } ?><file_sep>/currency/display-currency.php <? require($_SERVER["DOCUMENT_ROOT"]."/bitrix/header.php"); $APPLICATION->SetTitle("Отображение курсов валют"); ?> Отображение курсов валют <? $date_from = isset($_GET['date_from'])?$_GET['date_from']:'24.06.2018'; $date_to = isset($_GET['date_to'])?$_GET['date_to']:'24.07.2018'; $currency_display = new CurrencyActions('eurofxref-hist.xml'); //$currency_add->fill_date_from = '2018-05-01'; echo '</br>'.$currency_display->displayCurrencyRateData($date_from, $date_to, 1,5000); ?> <script type="text/javascript"> $('.display-currency-rates>div').eq(1).scroll(function(){ var self = this; $('.display-currency-rates>div').eq(0).scrollTop($(self).scrollTop()); }); $('.display-currency-rates>div').eq(0).scroll(function(){ var self = this; $('.display-currency-rates>div').eq(1).scrollTop($(self).scrollTop()); }); //$('.display-currency-rates thead').eq(0).css('position','absolute').css('overflow-x','hidden').css('width',$('.display-currency-rates>div').eq(1).width()); </script> <?require($_SERVER["DOCUMENT_ROOT"]."/bitrix/footer.php");?>
bc12f6f16f2871e1dab4b4347970d284d900841d
[ "PHP" ]
6
PHP
Cheshihin/optimal_group_test_right
e93dce8399cc916124328f9db6a224b3b216c09e
6ce50bc669fec453a24de8ea0945375c583fe556
refs/heads/main
<file_sep>using System.Collections; using System.Globalization; using System.Runtime.InteropServices; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI; using System.Collections.Generic; public class HomeCanvasManager : MonoBehaviour { public GameObject homeOptionsMenu; public GameObject homeMenu; private string currentScene; public Toggle toggle; private string leftHandedPref; private bool isLeftHanded; void Start() { currentScene = SceneManager.GetActiveScene().name; print(currentScene); //Add listener for when the state of the Toggle changes, to take action if (currentScene != "LvlSelect" || currentScene != "Customize" || currentScene != "LvlTransition") { StartCheckLeftHanded(); toggle.onValueChanged.AddListener(delegate { ToggleValueChanged(toggle); }); } } private void StartCheckLeftHanded() { leftHandedPref = PlayerPrefs.GetString("LeftHanded"); print(leftHandedPref); if (leftHandedPref == "") { PlayerPrefs.SetString("LeftHanded", "false"); toggle.isOn = false; isLeftHanded = false; } SwitchControls(leftHandedPref); } private void ToggleValueChanged(Toggle change) { isLeftHanded = toggle.isOn; leftHandedPref = isLeftHanded.ToString(); PlayerPrefs.SetString("LeftHanded", leftHandedPref); SwitchControls(leftHandedPref); } private void SwitchControls(string hand) { switch (hand) { case "True": toggle.isOn = true; isLeftHanded = true; break; case "False": toggle.isOn = false; isLeftHanded = false; break; default: break; } } public void HomeOptionsMenu() { homeMenu.SetActive(false); homeOptionsMenu.SetActive(true); } public void HomeOptionsBack() { homeMenu.SetActive(true); homeOptionsMenu.SetActive(false); } public void LoadSceneByName(string sceneName) { if (sceneName == "Home" || sceneName == "LvlSelect") { PlayerPrefs.SetInt("Score", 0); } SceneManager.LoadScene(sceneName); Time.timeScale = 1f; SceneSettings(sceneName); } private void SceneSettings(string s) { switch (s) { case "Home": Cursor.lockState = CursorLockMode.None; Cursor.visible = true; break; case "Level Select": Cursor.lockState = CursorLockMode.None; Cursor.visible = true; break; default: break; } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; namespace Player { public class SoundManager : MonoBehaviour { public static SoundManager instance; public AudioSource[] audioSources; public Slider volumeSlider; [HideInInspector] public float masterVolume = 1f; private string currentScene; private void Awake() { instance = this; } void Start() { currentScene = SceneManager.GetActiveScene().name; if (volumeSlider == null) { volumeSlider = GameObject.Find("Slider").GetComponent<Slider>(); } volumeSlider.onValueChanged.AddListener(delegate { UpdateMasterVolume(); }); masterVolume = PlayerPrefs.GetFloat("MasterVolume"); volumeSlider.value = masterVolume; PlaySceneMusic(); } private void UpdateMasterVolume() { masterVolume = volumeSlider.value; for (int i = 0; i < audioSources.Length; i++) { audioSources[i].volume = masterVolume; } PlayerPrefs.SetFloat("MasterVolume", masterVolume); } private void PlaySceneMusic() { switch (currentScene) { case "Home": audioSources[0].Play(); break; case "Level 1": audioSources[0].Play(); break; case "Level 2": audioSources[0].Play(); break; case "Level 3": audioSources[0].Play(); break; case "Level 4 Endless": audioSources[0].Play(); break; default: break; } } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class SkinUpdate : MonoBehaviour { public GameObject VariableHolder; public GameObject original; public GameObject tophat; public GameObject swimsuit; public int skinType; // Start is called before the first frame update void Start() { original = GameObject.Find("Sprite_Original"); tophat = GameObject.Find("Sprite_TopHat"); swimsuit = GameObject.Find("Sprite_Swim"); if (original == null) { Debug.Log("Cannot find Original Skin"); } if (tophat == null) { Debug.Log("Cannot find TopHat Skin"); } if (swimsuit == null) { Debug.Log("Cannot find Swimsuit Skin"); } } void OnEnable() { VariableHolder = GameObject.Find("VariableHolder"); if (VariableHolder == null) { Debug.Log("Cannot find VariableHolder"); } if (VariableHolder != null) { skinType = VariableHolder.GetComponent<Variables>().skinType; } } void Update() { if (skinType == 1) //original { original.SetActive(true); tophat.SetActive(false); swimsuit.SetActive(false); } if (skinType == 2) //tophat { original.SetActive(false); tophat.SetActive(true); swimsuit.SetActive(false); } if (skinType == 3) //swim { original.SetActive(false); tophat.SetActive(false); swimsuit.SetActive(true); } } public void SkinOriginal() { skinType = 1; } public void SkinTopHat() { skinType = 2; } public void SkinSwim() { skinType = 3; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI; namespace Player { public class NextLevel : MonoBehaviour { public static NextLevel instance; private string nextScene; [HideInInspector] public int score; [HideInInspector] public int highScore; public Text nextSceneText; public Text highScoreText; public Text scoreText; public GameObject homeBackground; public GameObject lvl1Background; public GameObject lvl2Background; public GameObject lvl3Background; public GameObject lvl4Background; private Button continueBtn; public float continueBtnPause = 1f; private void Awake() { instance = this; } void Start() { continueBtn = GameObject.Find("ContinueBTN").GetComponent<Button>(); nextScene = PlayerPrefs.GetString("NextScene"); score = PlayerPrefs.GetInt("Score"); highScore = PlayerPrefs.GetInt("HighScore"); StartCoroutine(EnableContinueBtn()); switch (nextScene) { case "Home": homeBackground.SetActive(true); break; case "Level 1": lvl1Background.SetActive(true); break; case "Level 2": lvl2Background.SetActive(true); break; case "Level 3": lvl3Background.SetActive(true); break; case "Level 4 Endless": lvl4Background.SetActive(true); break; default: break; } SetText(); } private void SetText() { nextSceneText.text = nextScene; highScoreText.text = "High Score: " + highScore; scoreText.text = "Current Score: " + score; } public void GoToNextLevel() { if (nextScene == "Home") { GameController.instance.ScoreTextAvailable(); GameController.instance.ClearScore(); } CanvasManager.instance.LoadSceneByName(nextScene); } IEnumerator EnableContinueBtn() { continueBtn.interactable = false; yield return new WaitForSeconds(continueBtnPause); continueBtn.interactable = true; } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using System.Runtime.InteropServices; using System.Diagnostics; namespace Player { public class DestroyByContact : MonoBehaviour { public Animator animator; //private Rigidbody2D rigid; public int scoreValue; private GameController gameController; void Start() { //rigid = GetComponent<Rigidbody2D>(); GameObject gameControllerObject = GameObject.FindWithTag("GameController"); //This section is to detect if the object that collides with this script also has the 'GameController' script if (gameControllerObject != null) //And apply the values associated with that script. { //Debug.Log("CONTROLLER FOUND"); gameController = gameControllerObject.GetComponent<GameController>(); } if (gameControllerObject == null) { //Debug.Log("Cannot find 'GameController' script"); } } void Awake() { } void Update() { } void OnTriggerEnter(Collider other) { if (other.tag == "Player") { StartCoroutine(DeathAnimation()); PlayerHealth.instance.TakeDamage(0.1f); } else if (other.tag == "Boundary") { return; } else if (other.tag == "Enemy") { return; } else if (other.tag == "Collectible") { return; } else if (other.tag == "Boundary") { return; } else if (other.tag == "GameController") { return; } else if (other.tag == "Projectile") { StartCoroutine(DeathAnimation()); gameController.AddScore(scoreValue); //add score when hitting this object Destroy(other.gameObject); //destroys projectile return; } } IEnumerator DeathAnimation() { SoundManager.instance.audioSources[2].Play(); animator.SetBool("DeathState", true); // go into death animation this.GetComponent<BoxCollider>().enabled = false; yield return new WaitForSeconds(0.3f); // time of animation Destroy(gameObject); } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; namespace Player { public class PlayerHealth : MonoBehaviour { public static PlayerHealth instance; private float counterTimer; [HideInInspector] public float maxHealth = 1f; [HideInInspector] public float currentHealth; public float healthDepletionSpeed = 0.005f; //Amount that the health declines public float counterTimerMax = 0.1f; public Slider healthBar; private float previousHealthDivided; private float newHealthDivided; private float healthGainCheck; private float newHealthGainAmount; public bool takeDamage = true; private void Awake() { instance = this; } private void Start() { counterTimer = counterTimerMax; currentHealth = maxHealth; healthBar.value = maxHealth; } private void Update() { counterTimer -= Time.fixedDeltaTime; if (counterTimer <= 0) { TakeDamageOvertime(healthDepletionSpeed); counterTimer = counterTimerMax; } } public void TakeDamageToggle() { takeDamage = !takeDamage; } public void TakeDamageOvertime(float damage) { if (takeDamage) { previousHealthDivided = currentHealth / maxHealth; currentHealth -= damage; newHealthDivided = currentHealth / maxHealth; healthBar.value = currentHealth; if (healthBar.value <= 0) { SoundManager.instance.audioSources[3].Play(); CanvasManager.instance.Death(); } healthBar.value = Mathf.Lerp(previousHealthDivided, newHealthDivided, 0.1f); } } public void TakeDamage(float take) { if (healthBar.value > 0) { currentHealth -= take; healthBar.value = currentHealth; } } public void GainHealth(float gain) { // Checks to see if the amount depleted on the health bar is smaller than the gain amount and changes the amount accordingly healthGainCheck = maxHealth - currentHealth; if (healthBar.value < maxHealth) { if (healthGainCheck < gain) { newHealthGainAmount = healthGainCheck; currentHealth += newHealthGainAmount; } else { currentHealth += gain; } healthBar.value = currentHealth; } } } } <file_sep>using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.IO; using UnityEngine; using UnityEngine.Experimental.XR; namespace Player { [System.Serializable] public class Boundary //This is the section where you would set the boundary in the scene { public float xMin, xMax, zMin, zMax; //These are the values you will set for the boundary in the Inspector Pane } public class PlayerController : MonoBehaviour { public static PlayerController instance; public float speed; public Boundary boundary; public GameObject shot; public Transform shotSpawn; public float fireRate; public VirtualJoystick moveJoystick; private float nextFire; AudioSource audioData; public GameObject[] enemy; public GameObject[] enemyFollow; public bool splitShot; public float splitShotOnTimer = 5; private void Awake() { instance = this; splitShot = false; } private void Update() { moveJoystick = GameObject.Find("VirtualJoystickContainer").GetComponent<VirtualJoystick>(); } void FixedUpdate() { float moveHorizontal = Input.GetAxis("Horizontal"); float moveVertical = Input.GetAxis("Vertical"); Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical); GetComponent<Rigidbody>().velocity = movement * speed; GetComponent<Rigidbody>().position = new Vector3 ( Mathf.Clamp(GetComponent<Rigidbody>().position.x, boundary.xMin, boundary.xMax), 0.0f, Mathf.Clamp(GetComponent<Rigidbody>().position.z, boundary.zMin, boundary.zMax) ); if (moveJoystick.InputDirection != Vector3.zero) { GetComponent<Rigidbody>().velocity = moveJoystick.InputDirection * speed; } } public void FireWeapon() { if (Time.time > nextFire) //fireRate value adjusts shots per second { nextFire = Time.time + fireRate; Instantiate(shot, shotSpawn.position, Quaternion.identity); //instantiates a Shot in front of the player on button press SoundManager.instance.audioSources[1].Play(); if (splitShot == true) { Instantiate(shot, shotSpawn.position, Quaternion.Euler(new Vector3(0, 40, 0))); Instantiate(shot, shotSpawn.position, Quaternion.Euler(new Vector3(0, -40, 0))); } } } public void OnTriggerEnter(Collider other) { if (other.gameObject.CompareTag("Nuke")) { other.gameObject.SetActive(false); GameObject[] enemy = GameObject.FindGameObjectsWithTag("Enemy"); for (var i = 0; i < enemy.Length; i++) { Destroy(enemy[i]); } other.gameObject.SetActive(false); GameObject[] enemyFollow = GameObject.FindGameObjectsWithTag("EnemyFollow"); for (var i = 0; i < enemy.Length; i++) { Destroy(enemyFollow[i]); } } if (other.gameObject.CompareTag("Split")) { other.gameObject.SetActive(false); StartCoroutine(SplitShotTimer()); } IEnumerator SplitShotTimer() { splitShot = true; yield return new WaitForSeconds(splitShotOnTimer); splitShot = false; } } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; namespace Player { public class Collectable : MonoBehaviour { private string tagName; [SerializeField] private Animator anim; public static Collectable instance; public float foodHealthGain = 0.03f; public int foodPointGain = 1; private GameController gameController; public int scoreValue; private void Awake() { instance = this; } // Start is called before the first frame update void Start() { tagName = this.gameObject.tag; // Use this to determine if this is food or other tag GameObject gameControllerObject = GameObject.FindWithTag("GameController"); //This section is to detect if the object that collides with this script also has the 'GameController' script if (gameControllerObject != null) //And apply the values associated with that script. { //Debug.Log("CONTROLLER FOUND"); gameController = gameControllerObject.GetComponent<GameController>(); } if (gameControllerObject == null) { //Debug.Log("Cannot find 'GameController' script"); } } private void OnTriggerEnter(Collider other) { if (other.tag == "Player") { switch (tagName) { case "Collectible": SoundManager.instance.audioSources[4].Play(); break; case "Double": SoundManager.instance.audioSources[7].Play(); break; case "Nuke": SoundManager.instance.audioSources[6].Play(); break; case "PowerUp": SoundManager.instance.audioSources[7].Play(); break; case "Rapid": SoundManager.instance.audioSources[7].Play(); break; case "Shield": SoundManager.instance.audioSources[7].Play(); break; case "Shot": SoundManager.instance.audioSources[7].Play(); break; case "Split": SoundManager.instance.audioSources[7].Play(); break; default: break; } gameController.AddScore(scoreValue); PlayerHealth.instance.GainHealth(foodHealthGain); Destroy(gameObject); } } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Variables : MonoBehaviour { private static Variables objectInstance; public int skinType; public GameObject skinUpdate; void Awake() { DontDestroyOnLoad(this.gameObject); if (objectInstance == null) { objectInstance = this; } else { DestroyObject(gameObject); } } void Start() { } void Update() { skinUpdate = GameObject.Find("SkinUpdater"); if (skinUpdate == null) { Debug.Log("Cannot find Skin Updater (should only find in home menu)"); } if (skinUpdate != null) { skinType = skinUpdate.GetComponent<SkinUpdate>().skinType; } } } <file_sep>using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using UnityEngine; using Random = UnityEngine.Random; public class FoodSpawn : MonoBehaviour { public GameObject food; public Transform foodSpawnPos; public float spawnRate; public float negValue; public float posValue; private float nextSpawn; // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { if (Time.time > nextSpawn) { nextSpawn = Time.time + spawnRate; Vector3 position = new Vector3(foodSpawnPos.position.x + Random.Range(negValue, posValue), 0, foodSpawnPos.position.z); Instantiate(food, position, Quaternion.identity); } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; using System.Runtime.InteropServices; namespace Player { public class GameController : MonoBehaviour { public static GameController instance; public GameObject enemy; public GameObject food; public GameObject nuke; public GameObject split; public GameObject enemyTwo; public Vector3 enemySpawnValues; public Vector3 foodSpawnValues; public Vector3 nukeSpawnValues; public Vector3 splitSpawnValues; public Vector3 enemyTwoSpawnValues; public int enemyCount; public int foodCount; public int nukeCount; public int splitCount; public int enemyTwoCount; public float enemySpawnWait; public float enemyStartWait; public float enemyWaveWait; public float foodSpawnWait; public float foodStartWait; public float foodWaveWait; public float nukeSpawnWait; public float nukeStartWait; public float nukeWaveWait; public float splitSpawnWait; public float splitStartWait; public float splitWaveWait; public float enemyTwoSpawnWait; public float enemyTwoStartWait; public float enemyTwoWaveWait; private string currentScene; public bool isScoreTextAvailable = true; public Text scoreText; public int score; public int highScore; public int neededPointsLvl1 = 100; public int neededPointsLvl2 = 120; public int neededPointsLvl3 = 300; private void Awake() { instance = this; } void Start() { score = PlayerPrefs.GetInt("Score"); highScore = PlayerPrefs.GetInt("HighScore"); currentScene = SceneManager.GetActiveScene().name; UpdateScore(); SetNextScene(); StartCoroutine(SpawnEnemyWaves()); StartCoroutine(SpawnFoodWaves()); StartCoroutine(SpawnnukeWaves()); StartCoroutine(SpawnsplitWaves()); StartCoroutine(SpawnEnemyTwoWaves()); } void Update() { if (Input.GetKeyDown(KeyCode.C)) { ClearScore(); ClearHighScore(); } } IEnumerator SpawnEnemyWaves() { yield return new WaitForSeconds(enemyStartWait); while (true) { for (int i = 0, j = 0; i < enemyCount; i++) { Vector3 spawnPosition = new Vector3(Random.Range(-enemySpawnValues.x, enemySpawnValues.x), enemySpawnValues.y, enemySpawnValues.z); //For 'x' the script will chose random numbers between x and -x Quaternion spawnRotation = Quaternion.identity; Instantiate(enemy, spawnPosition, spawnRotation); yield return new WaitForSeconds(enemySpawnWait); } //Spawn Enemy yield return new WaitForSeconds(enemyWaveWait); //Wait } } IEnumerator SpawnFoodWaves() { yield return new WaitForSeconds(foodStartWait); while (true) { for (int i = 0, j = 0; i < foodCount; i++) { Vector3 foodspawnPosition = new Vector3(Random.Range(-foodSpawnValues.x, foodSpawnValues.x), foodSpawnValues.y, foodSpawnValues.z); Quaternion foodspawnRotation = Quaternion.identity; Instantiate(food, foodspawnPosition, foodspawnRotation); yield return new WaitForSeconds(foodSpawnWait); } //Spawn Food yield return new WaitForSeconds(foodWaveWait); //Wait } } IEnumerator SpawnnukeWaves() { yield return new WaitForSeconds(nukeStartWait); while (true) { for (int i = 0, j = 0; i < nukeCount; i++) { Vector3 nukespawnPosition = new Vector3(Random.Range(-nukeSpawnValues.x, nukeSpawnValues.x), nukeSpawnValues.y, nukeSpawnValues.z); Quaternion nukespawnRotation = Quaternion.identity; Instantiate(nuke, nukespawnPosition, nukespawnRotation); yield return new WaitForSeconds(nukeSpawnWait); } //Spawn Nuke Pickup yield return new WaitForSeconds(nukeWaveWait); //Wait } } IEnumerator SpawnsplitWaves() { yield return new WaitForSeconds(splitStartWait); while (true) { for (int i = 0, j = 0; i < splitCount; i++) { Vector3 splitspawnPosition = new Vector3(Random.Range(-splitSpawnValues.x, splitSpawnValues.x), splitSpawnValues.y, splitSpawnValues.z); Quaternion splitspawnRotation = Quaternion.identity; Instantiate(split, splitspawnPosition, splitspawnRotation); yield return new WaitForSeconds(splitSpawnWait); } //Spawn Split Pickup yield return new WaitForSeconds(splitWaveWait); //Wait } } IEnumerator SpawnEnemyTwoWaves() { yield return new WaitForSeconds(enemyTwoStartWait); while (true) { for (int i = 0, j = 0; i < enemyCount; i++) { Vector3 spawnPosition = new Vector3(Random.Range(-enemyTwoSpawnValues.x, enemyTwoSpawnValues.x), enemyTwoSpawnValues.y, enemyTwoSpawnValues.z); //For 'x' the script will chose random numbers between x and -x Quaternion spawnRotation = Quaternion.identity; Instantiate(enemyTwo, spawnPosition, spawnRotation); yield return new WaitForSeconds(enemyTwoSpawnWait); } //Spawn Enemy Two yield return new WaitForSeconds(enemyTwoWaveWait); //Wait } } public void AddScore(int newScoreValue) { score += newScoreValue; UpdateScore(); NextLevelCheck(); SetHighScore(); } private void UpdateScore() { scoreText.text = "Score: " + score; } private void NextLevelCheck() { if (score >= neededPointsLvl1 && currentScene == "Level 1") { PlayerPrefs.SetInt("Score", score); CanvasManager.instance.LoadSceneByName("LvlTransition"); } else if (score >= neededPointsLvl2 && currentScene == "Level 2") { PlayerPrefs.SetInt("Score", score); CanvasManager.instance.LoadSceneByName("LvlTransition"); } else if (score >= neededPointsLvl3 && currentScene == "Level 3") { PlayerPrefs.SetInt("Score", score); CanvasManager.instance.LoadSceneByName("LvlTransition"); } else if (currentScene == "Level 4 Endless") { PlayerPrefs.SetInt("Score", score); } } public void ClearScore() { PlayerPrefs.SetInt("Score", 0); score = 0; if (isScoreTextAvailable) { scoreText.text = "Score: " + score; } } public void ClearHighScore() { PlayerPrefs.SetInt("HighScore", 0); } public void ScoreTextAvailable() // Prevents Error when going to LvlTransition scene to Home screen { isScoreTextAvailable = false; } public void SetNextScene() { switch (currentScene) { case "Level 1": PlayerPrefs.SetString("NextScene", "Level 2"); break; case "Level 2": PlayerPrefs.SetString("NextScene", "Level 3"); break; case "Level 3": PlayerPrefs.SetString("NextScene", "Level 4 Endless"); break; case "Level 4 Endless": PlayerPrefs.SetString("NextScene", "Home"); break; default: break; } } public void SetHighScore() { if (score >= highScore) { PlayerPrefs.SetInt("HighScore", score); } } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; namespace Player { public class PlayerRespawn : MonoBehaviour { public static PlayerRespawn instance; private string currentScene; private string playerPrefsScene; private void Awake() { instance = this; } void Start() { currentScene = SceneManager.GetActiveScene().name; PlayerPrefs.SetString("Scene", currentScene); } void Update() { /*if (Input.GetKeyDown("space")) { print("space key was pressed"); Respawn(); }*/ } public void Respawn() { playerPrefsScene = PlayerPrefs.GetString("Scene"); CanvasManager.instance.LoadSceneByName(playerPrefsScene); } } } <file_sep>using System.Collections; using System.Collections.Generic; using System.Diagnostics; using UnityEngine; public class MainMenuAnimator : MonoBehaviour { public GameObject Menu; Animator animator; void Start() { Animator animator = Menu.GetComponent<Animator>(); if (animator != null); } public void OptionsButton() { UnityEngine.Debug.Log("transition"); animator.SetBool("MenuToOptions", true); } // Update is called once per frame void Update() { } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; namespace Player { public class OnAppPause : MonoBehaviour { void OnApplicationPause() { Debug.Log("Paused"); // CanvasManager.instance.Pause(); Time.timeScale = 0f; } } } <file_sep>using System.Collections; using System.Globalization; using System.Runtime.InteropServices; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI; using System.Collections.Generic; namespace Player { public class CanvasManager : MonoBehaviour { public static CanvasManager instance; public GameObject pauseMenu; public GameObject deathMenu; public GameObject optionsMenu; public GameObject homeOptionsMenu; public GameObject homeMenu; public GameObject bugBearHealth; public GameObject joystick; public GameObject fire; private string currentScene; [HideInInspector] public static string nextScene; [HideInInspector] public bool gameIsPaused; public Toggle toggle; private string leftHandedPref; private bool isLeftHanded; public Animator bearAnimator; public GameObject bearSkin; public GameObject bearSkin2; public GameObject bearSkin3; private Button pauseBtn; private void Awake() { instance = this; } void Start() { currentScene = SceneManager.GetActiveScene().name; gameIsPaused = false; pauseBtn = GameObject.Find("PauseBTN").GetComponent<Button>(); if (currentScene != "LvlSelect") { StartCheckLeftHanded(); toggle.onValueChanged.AddListener(delegate { ToggleValueChanged(toggle); }); } } void Update() { /*if (Input.GetKeyDown("space")) { }*/ } private void StartCheckLeftHanded() { leftHandedPref = PlayerPrefs.GetString("LeftHanded"); //print(leftHandedPref); if (leftHandedPref == "") { PlayerPrefs.SetString("LeftHanded", "false"); toggle.isOn = false; isLeftHanded = false; } SwitchControls(leftHandedPref); } private void ToggleValueChanged(Toggle change) { isLeftHanded = toggle.isOn; leftHandedPref = isLeftHanded.ToString(); PlayerPrefs.SetString("LeftHanded", leftHandedPref); SwitchControls(leftHandedPref); } private void SwitchControls(string hand) { switch (hand) { case "True": toggle.isOn = true; isLeftHanded = true; BottomRight(fire); BottomLeft(joystick); break; case "False": toggle.isOn = false; isLeftHanded = false; BottomRight(joystick); BottomLeft(fire); break; default: break; } } private void BottomRight(GameObject uiObject) { RectTransform uitransform = uiObject.GetComponent<RectTransform>(); uitransform.anchorMin = new Vector2(1, 0); uitransform.anchorMax = new Vector2(1, 0); uitransform.pivot = new Vector2(1, 0); } private void BottomLeft(GameObject uiObject) { RectTransform uitransform = uiObject.GetComponent<RectTransform>(); uitransform.anchorMin = new Vector2(0, 0); uitransform.anchorMax = new Vector2(0, 0); uitransform.pivot = new Vector2(0, 0); } public void LockScreen() { Cursor.lockState = CursorLockMode.None; Cursor.visible = true; Time.timeScale = 0f; PlayerHealth.instance.TakeDamageToggle(); } public void UnlockScreen() { Time.timeScale = 1f; PlayerHealth.instance.TakeDamageToggle(); } public void Pause() { if (gameIsPaused) { gameIsPaused = false; pauseMenu.SetActive(false); UnlockScreen(); } else { gameIsPaused = true; pauseMenu.SetActive(true); LockScreen(); } } public void Death() { StartCoroutine(BearDeath()); } public void ReplayLevel() { PlayerRespawn.instance.Respawn(); } public void Resume() { Pause(); } public void Fire() { PlayerController.instance.FireWeapon(); } public void OptionsMenu() { pauseMenu.SetActive(false); optionsMenu.SetActive(true); pauseBtn.interactable = false; } public void Back() { pauseMenu.SetActive(true); optionsMenu.SetActive(false); pauseBtn.interactable = true; } public void LoadSceneByName(string sceneName) { if (sceneName == "Home" || sceneName == "LvlSelect") { PlayerPrefs.SetInt("Score", 0); } SceneManager.LoadScene(sceneName); Time.timeScale = 1f; SceneSettings(sceneName); } private void SceneSettings(string s) { switch (s) { case "Home": Cursor.lockState = CursorLockMode.None; Cursor.visible = true; break; case "Level Select": Cursor.lockState = CursorLockMode.None; Cursor.visible = true; break; case "Level 1": break; case "Level 2": break; default: break; } } IEnumerator BearDeath() { bearSkin = GameObject.Find("Sprite_Original");// Get Original Sprite bearSkin2 = GameObject.Find("Sprite_TopHat");// Get TopHat Sprite bearSkin3 = GameObject.Find("Sprite_Swim");// Get Swim Sprite if (bearSkin != null) { bearAnimator = bearSkin.GetComponent<Animator>(); } if (bearSkin2 != null) { bearAnimator = bearSkin2.GetComponent<Animator>(); } if (bearSkin3 != null) { bearAnimator = bearSkin3.GetComponent<Animator>(); } bearAnimator.SetInteger("AnimState", 1); // go into death animation yield return new WaitForSeconds(.5f); // time of animation deathMenu.SetActive(true); Pause(); } } } <file_sep>using System; using System.Collections; using System.Collections.Generic; using System.Runtime.CompilerServices; using UnityEngine; public class HomeAnimation : MonoBehaviour { public Animator animator; public GameObject options; public GameObject main; public GameObject customize; void Start() { //main = GameObject.Find("Main"); //options = GameObject.Find("OptionsMenu"); //customize = GameObject.Find("CustomizeMenu"); } public void MenuToOptions() { StartCoroutine(MenuToOptionsAnimation()); } public void OptionsToMenu() { StartCoroutine(OptionsToMenuAnimation()); } public void MenuToCustomize() { StartCoroutine(MenuToCustomizeAnimation()); } public void CustomizeToMenu() { StartCoroutine(CustomizeToMenuAnimation()); } IEnumerator MenuToOptionsAnimation() { animator.SetBool("MenuToOptions", true); // go into transition animation customize.SetActive(false); options.SetActive(false); main.SetActive(false); yield return new WaitForSeconds(0.3f); // time of animation options.SetActive(true); } IEnumerator OptionsToMenuAnimation() { animator.SetBool("MenuToOptions", false); // go into transition animation customize.SetActive(false); options.SetActive(false); main.SetActive(false); yield return new WaitForSeconds(0.3f); // time of animation main.SetActive(true); } IEnumerator MenuToCustomizeAnimation() { animator.SetBool("MenuToCustomize", true); // go into transition animation customize.SetActive(false); options.SetActive(false); main.SetActive(false); yield return new WaitForSeconds(0.3f); // time of animation customize.SetActive(true); } IEnumerator CustomizeToMenuAnimation() { animator.SetBool("MenuToCustomize", false); // go into transition animation customize.SetActive(false); options.SetActive(false); main.SetActive(false); yield return new WaitForSeconds(0.3f); // time of animation main.SetActive(true); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; namespace Player { public class SoundManagerMin : MonoBehaviour { public static SoundManagerMin instance; public AudioSource[] audioSources; private string currentScene; private float masterVolume; private void Awake() { instance = this; } void Start() { masterVolume = PlayerPrefs.GetFloat("MasterVolume"); print(masterVolume); currentScene = SceneManager.GetActiveScene().name; PlaySceneMusic(); UpdateMasterVolume(); } private void UpdateMasterVolume() { for (int i = 0; i < audioSources.Length; i++) { audioSources[i].volume = masterVolume; } } private void PlaySceneMusic() { switch (currentScene) { case "LvlSelect": audioSources[0].Play(); break; case "LvlTransition": audioSources[1].Play(); break; default: break; } } } } <file_sep>using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using UnityEngine; using Random = UnityEngine.Random; public class PowerUpSpawn : MonoBehaviour { public GameObject powerUp; public Transform powerUpPos; public float spawnRate; public float negValue; public float posValue; private float nextSpawn; // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { if (Time.time > nextSpawn) { nextSpawn = Time.time + spawnRate; Vector3 position = new Vector3(powerUpPos.position.x + Random.Range(negValue, posValue), 0, powerUpPos.position.z); Instantiate(powerUp, position, Quaternion.identity); } } }
4d022e9279f747c87a75e4ce49c1c4140629b49c
[ "C#" ]
18
C#
rnfisher/BugBear
9ae9182d16e3aa0bc6a2e3ba77095acdabfa5892
84e958c7fd9b16104e6a7e0697b9916a9cd0c149
refs/heads/master
<repo_name>HugoAndCat/sassdoc<file_sep>/Gruntfile.js /*global module:false*/ module.exports = function(grunt) { 'use strict'; grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), config: { // Configurable paths app: 'app', dist: 'dist' }, // The actual grunt server settings connect: { options: { port: 9000, livereload: 35729, // Change this to '0.0.0.0' to access the server from outside hostname: 'localhost' }, livereload: { options: { open: true, base: 'sassdoc' // remove this to livereload the main INDEX FILE } }, }, watch: { options: { livereload: true }, sass: { files: ['scss/{,*/}*.{scss,sass}'], tasks: 'sass' }, sassdoc: { files: ['scss/{,*/}*.{scss,sass}'], tasks: 'sassdoc' } }, sass: { dev: { files: { 'css/global.css': 'scss/global.scss' } }, }, 'sassdoc': { 'default': { 'src': 'scss/', 'dest': 'sassdoc', 'options': { 'groups': { 'colors': 'Colours', 'helpers': 'Helpers', 'fonts': 'Fonts', 'units': 'Units', 'utils': 'Utilities', 'elems': 'Elements', 'hacks': 'Dirty Hacks & Fixes', 'undefined': 'General' } } } } }); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-contrib-sass'); grunt.loadNpmTasks('grunt-sassdoc'); grunt.loadNpmTasks('grunt-contrib-connect'); grunt.registerTask('serve', function() { grunt.task.run([ 'connect:livereload', 'watch' ]); }); grunt.registerTask('docsass', ['sassdoc']); grunt.registerTask('default', ['sass:dev']); };<file_sep>/README.md # Sassdoc / SASS structure example This is a test to see how useful SASSDoc will be in future projects. Read about SASSdoc here: http://sassdoc.com/ Sassdoc currently only documents mixins, variables and functions. Ideally it would also document modules and maybe even elements too. ## Setup: Run `npm install` in root directory Run `grunt sassdoc` to compile create the SASSdoc documentation folder Run `grunt serve` to compile sass and build the sassdoc on the fly. This will open the sass documentation in a server on your local machine.
f802457450d8fc21bc848528fd79a274c55127e6
[ "JavaScript", "Markdown" ]
2
JavaScript
HugoAndCat/sassdoc
7b107256324921a4e75a3d0f6e2aae4ae1b3b251
979b4d0b4b19b56b5e983632e3e019e99425ce45
refs/heads/master
<file_sep>package com; import java.util.Scanner; public class Email { private String firstName; private String lastName; private String department; private String emailDomain = "company.com"; private String password; private int defaultPwLength = 8; private String altEmail; private int mailboxCapacity = 500; //in MB private String email; //constructor for firstname and lastname public Email(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; //System.out.println("Email created for " + firstName + " " + lastName); //call method asking for department and return the department this.department = setDepartment(); //System.out.println("Department: " + this.department); //call method for return random password this.password = randomPassword(defaultPwLength); System.out.println("\nYour randomly generated password is: " + this.password + "\n"); //concatenate the email elements this.email = firstName.toLowerCase() + "." + lastName.toLowerCase() + "@" + department.toLowerCase() + "." + emailDomain; //System.out.println("Your email is: " + email); } //get department private String setDepartment() { System.out.print(" DEPARTMENT CODES AS FOLLOWED:\n1 for Sales\n2 for Development\n3 for accounting\n0 for none\nEnter the department code: "); Scanner input = new Scanner(System.in); int deptCode = input.nextInt(); if(deptCode == 1) {return "Sales";} else if(deptCode == 2) {return "Development";} else if(deptCode == 3) {return "Accounting";} else{return "";} } //generate random password public String randomPassword(int length) { String pwSet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%"; char[] password = new char[length]; for(int i = 0; i < length; i++) { int rand = (int) (Math.random() * pwSet.length()); password[i] = pwSet.charAt(rand); } return new String(password); } //set method for changing the password public void setNewPassword(String password) { this.password = password; } //set mailbox capacity public void setMailboxCapacity(int capacity) { this.mailboxCapacity = capacity; } //set alt email public void setAltEmail(String altEmail) { this.altEmail = altEmail; } //get methods to initialize new values public int getMailboxCapacity() {return mailboxCapacity;} public String getAltEmail() {return altEmail;} public String getPassword() {return password;} //show all the info public String showInfo() { return "DISPLAY NAME: " + firstName + " " + lastName + "\nCOMPANY EMAIL: " + email + "\nMAILBOX CAPACITY: " + mailboxCapacity + "mb"; } } <file_sep>package com; public class EmailApp { public static void main(String[] args) { // TODO Auto-generated method stub Email em1 = new Email("Devin", "Cohen"); /* test for setters and getters * em1.setAltEmail("<EMAIL>"); System.out.println(em1.getAltEmail()); */ System.out.println(em1.showInfo()); } }
7ea06f468a9e578124f7cb6943960d608143e30e
[ "Java" ]
2
Java
Jo4nnyRico/EmailApp
1de2af412025032c85a50162345f4883fd15a068
25650aa9b3eeacf3726e6bf9eab787e5afae7e40
refs/heads/main
<file_sep><!DOCTYPE html> <html> <body style="background-color:grey;"> <img alt="hawamahal"src="hawamahal.jpg" width="330px" height="300px"> <img alt="redfort"src="redfort.jpg" width="330px" height="300px"> <img alt="tajmahal"src="tajmahal.jpg" width="330px" height="300px"> <img alt="amerfort"src="amerfort.jpg" width="330px" height="300px"> <br> <p><h4>IMAGE1:-</h4>The structure was built in 1799 by<b style="background-color:red"><i>Maharaja sawai pratap singh</i></b> , the grandson of <NAME>, who was the founder of Jaipur. He was so inspired by the unique structure of Khetri Mahal that he built this grand and historical palace. <p><h4>IMAGE2:-</h4>The <b style="background-color:red"><i>Red fort</i></b> is a historic fort in the city of Delhi (in Old Delhi) in India that served as the main residence of the Mughal Emperors. Emperor <NAME> commissioned construction of the Red Fort on 12 May 1638, when he decided to shift his capital from Agra to Delhi. Originally red and white, its painting is credited to architect <NAME>, who also constructed the Taj Mahal.</p> <p><h4>IMAGE3:-</h4>It was commissioned in 1632 by the Mughal emperor <b style="background-color:red"><i>shah jahan</i></b> (reigned from 1628 to 1658) to house the tomb of his favourite wife, <NAME>; it also houses the tomb of Shah Jahan himself.</p> <p><h4>IMAGE4:-</h4>Amer Fort or Amber Fort is a fort located in Amer,<b style="background-color:red"><i>Rajasthan</i></b>, India. Amer is a town with an area of 4 square kilometres (1.5 sq mi)[1] located 11 kilometres (6.8 mi) from Jaipur, the capital of Rajasthan.</p> </body> </html> <file_sep>const express = require('express'); const app = express(); const bodyParser = require('body-parser'); const userRoutes = require('./routes/user-routes'); const adminRoutes = require('./routes/admin-routes'); //const HttpError = require('./utils/http-error'); const port = 3000; app.use(bodyParser.json()); // Routing app.use('/api/v1/user', userRoutes); app.use('/api/v1/admin', adminRoutes) app.listen(port, () => { console.log(`App running on http://localhost:${port}`) });<file_sep># full-stack fullstacklearn
ba1a3ad0d4362452f8e5e0ac2cf721302c71beef
[ "JavaScript", "HTML", "Markdown" ]
3
HTML
himanshi7236/full-stack
79d62651ed7db1ac45bac583390f0853acfc5b77
77b3011dfb734684004960f5fe239bad7fcbba32
refs/heads/master
<repo_name>zeschi/GotoClass<file_sep>/bundle/src/main/java/com/zes/bundle/app/MyApplication.java package com.zes.bundle.app; import android.app.Application; import android.content.Context; /** * Created by zhy on 15/8/25. */ public class MyApplication extends Application { private static MyApplication sInstance; @Override public void onCreate() { super.onCreate(); sInstance = this; } /** * @return application instance */ public static /*synchronized*/ MyApplication getInstance() { return sInstance; } /** * @return applicationContext */ public static Context getAppContext() { return getInstance().getApplicationContext(); } } <file_sep>/app/src/main/java/com/app/zes/gotoclass/api/ApiFactory.java package com.app.zes.gotoclass.api; import com.app.zes.gotoclass.model.Course; import com.app.zes.gotoclass.model.CourseAttendance; import com.app.zes.gotoclass.model.CourseByCode; import com.app.zes.gotoclass.model.CourseComment; import com.app.zes.gotoclass.model.CourseFeedback; import com.app.zes.gotoclass.model.CourseGPAReport; import com.app.zes.gotoclass.model.CourseLeaving; import com.app.zes.gotoclass.model.CourseLesson; import com.app.zes.gotoclass.model.CourseOutline; import com.app.zes.gotoclass.model.GPAReport; import com.app.zes.gotoclass.model.Login; import com.app.zes.gotoclass.model.SimpleResult; import com.app.zes.gotoclass.model.User; import com.app.zes.gotoclass.utils.RxSchedulers; import com.zes.bundle.utils.GsonUtil; import com.zes.bundle.utils.Utils; import java.util.List; import okhttp3.MediaType; import okhttp3.RequestBody; import rx.Observable; /** * Created by zes on 17-3-19 11:04 */ public class ApiFactory { /** * 登录 * * @param user * @return */ public static Observable<Login> login(User user) { return Api.getInstance().service.login(getBody(user)).compose(RxSchedulers.io_main()); } /** * 注册 * * @param user * @return */ public static Observable<Login> register(User user) { return Api.getInstance().service.register(getBody(user)).compose(RxSchedulers.io_main()); } /** * 查询用户所有的课程 * * @param page * @param pageSize * @return */ public static Observable<List<Course>> findUserCourses(int page, int pageSize) { return Api.getInstance().service.findUserCourses(Utils.getSpUtils().getString("token"), page, pageSize).compose(RxSchedulers.io_main()); } /** * 根据课程码查找课程 * * @param coursecode * @return */ public static Observable<CourseByCode> findCourseByCode(String coursecode) { return Api.getInstance().service.findCourseByCode(Utils.getSpUtils().getString("token"), coursecode).compose(RxSchedulers.io_main()); } /** * 根据查询得到的课程id添加课程 * * @param courseId * @return */ public static Observable<SimpleResult> addCourse(int courseId) { return Api.getInstance().service.addCourse(Utils.getSpUtils().getString("token"), courseId).compose(RxSchedulers.io_main()); } /** * 查看课堂小节 * * @param lessonId * @return */ public static Observable<CourseLesson> findCourseLesson(int lessonId) { return Api.getInstance().service.findCourseLesson(Utils.getSpUtils().getString("token"), lessonId).compose(RxSchedulers.io_main()); } /** * 查看课程预备(大纲) * * @param courseId * @param page * @param pageSize * @return */ public static Observable<List<CourseOutline>> findCourseOutline(int courseId, int page, int pageSize) { return Api.getInstance().service.findCourseOutline(Utils.getSpUtils().getString("token"), courseId, page, pageSize).compose(RxSchedulers.io_main()); } /** * 查看课堂公告 * * @param courseId * @param page * @param pageSize * @return */ public static Observable<List<CourseComment>> findCourseComment(int courseId, int page, int pageSize) { return Api.getInstance().service.findCourseComment(Utils.getSpUtils().getString("token"), courseId, page, pageSize).compose(RxSchedulers.io_main()); } /** * 查看反馈 * * @param courseId * @param page * @param pageSize * @return */ public static Observable<List<CourseFeedback>> findCourseFeedback(int courseId, int page, int pageSize) { return Api.getInstance().service.findCourseFeedback(Utils.getSpUtils().getString("token"), courseId, page, pageSize).compose(RxSchedulers.io_main()); } /** * 查看课程签到 * * @param courseId * @param page * @param pageSize * @return */ public static Observable<CourseAttendance> findCourseAttendance(int courseId, int page, int pageSize) { return Api.getInstance().service.findCourseAttendance(Utils.getSpUtils().getString("token"), courseId, page, pageSize).compose(RxSchedulers.io_main()); } /** * 查看请假 * * @param courseId * @param page * @param pageSize * @return */ public static Observable<CourseLeaving> findCourseLeaving(int courseId, int page, int pageSize) { return Api.getInstance().service.findCourseLeaving(Utils.getSpUtils().getString("token"), courseId, page, pageSize).compose(RxSchedulers.io_main()); } /** * 填写反馈 * * @param courseId * @param content * @param anonymous * @return */ public static Observable<SimpleResult> fillInFeedback(int courseId, String content, String anonymous) { return Api.getInstance().service.fillInFeedback(Utils.getSpUtils().getString("token"), courseId, content, anonymous).compose(RxSchedulers.io_main()); } /** * 签到 * * @param code * @return */ public static Observable<SimpleResult> attendance(String code, String longitude, String latitude) { return Api.getInstance().service.attendance(Utils.getSpUtils().getString("token"), code, longitude, latitude).compose(RxSchedulers.io_main()); } /** * 请假 * * @param courseId * @param lessonId * @param reason * @return */ public static Observable<SimpleResult> askForLeave(int courseId, int lessonId, String reason) { return Api.getInstance().service.askForLeave(Utils.getSpUtils().getString("token"), courseId, lessonId, reason).compose(RxSchedulers.io_main()); } /** * 查看平时分 * * @param courseId * @return */ public static Observable<GPAReport> getGPAReport(int courseId) { return Api.getInstance().service.getGPAReport(Utils.getSpUtils().getString("token"), courseId).compose(RxSchedulers.io_main()); } /** * 查看平时成绩总览 * * @return */ public static Observable<CourseGPAReport> getCourseGPAReport() { return Api.getInstance().service.getCourseGPAReport(Utils.getSpUtils().getString("token")).compose(RxSchedulers.io_main()); } private static RequestBody getBody(Object t) { RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), GsonUtil.getGson().toJson(t)); return body; } } /** *         ┏┓   ┏┓ *        ┏┛┻━━━┛┻┓ *        ┃       ┃ *        ┃   ━   ┃ *        ┃ >   < ┃ *        ┃       ┃ *        ┃... ⌒ ... ┃ *        ┃       ┃ *        ┗━┓   ┏━┛ *          ┃   ┃ Code is far away from bug with the animal protecting *          ┃   ┃ 神兽保佑,代码无bug *          ┃   ┃ *          ┃   ┃ *          ┃   ┃ *          ┃   ┃ *          ┃   ┗━━━┓ *          ┃       ┣┓ *          ┃       ┏┛ *          ┗┓┓┏━┳┓┏┛ *           ┃┫┫ ┃┫┫ *           ┗┻┛ ┗┻┛ */ <file_sep>/app/src/main/java/com/app/zes/gotoclass/activity/GpaReportActivity.java package com.app.zes.gotoclass.activity; import android.os.Bundle; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.widget.ImageView; import com.app.zes.gotoclass.R; import com.app.zes.gotoclass.adapter.ScoreAdapter; import com.app.zes.gotoclass.api.ApiFactory; import com.app.zes.gotoclass.model.CourseGPAReport; import com.zes.bundle.activity.BaseActivity; import com.zes.bundle.view.DividerGridItemDecoration; import java.util.ArrayList; import java.util.List; import butterknife.Bind; import butterknife.ButterKnife; /** * Created by zes on 17-4-15 11:10 */ public class GpaReportActivity extends BaseActivity { @Bind(R.id.toolbar) Toolbar toolbar; @Bind(R.id.gpa_report_rv) RecyclerView gpaReportRv; @Bind(R.id.iv_back) ImageView ivBack; private List<String> mDatas; private ScoreAdapter adapter; @Override protected int getContentViewId() { return R.layout.activity_gpa_report; } /** * 初始化数据 * * @param savedInstanceState */ @Override protected void initData(Bundle savedInstanceState) { } /** * 初始化视图 */ @Override protected void initView() { mDatas = new ArrayList<>(); ApiFactory.getCourseGPAReport().subscribe(courseGPAReport -> { if (courseGPAReport != null) { List<CourseGPAReport.ScoreEntity> scoreEntities = courseGPAReport.getScore(); if (scoreEntities != null) { mDatas.add("课程名称"); mDatas.add("考勤得分"); mDatas.add("互动得分"); mDatas.add("总分"); for (int i = 0; i < scoreEntities.size(); i++) { mDatas.add(scoreEntities.get(i).getCourseName()); mDatas.add(scoreEntities.get(i).getAttendanceScore() + ""); mDatas.add(scoreEntities.get(i).getInteractScore() + ""); mDatas.add(scoreEntities.get(i).getTotalScore() + ""); } adapter = new ScoreAdapter(this, mDatas, R.layout.item_score); gpaReportRv.setLayoutManager(new GridLayoutManager(this, 4)); gpaReportRv.addItemDecoration(new DividerGridItemDecoration(this)); gpaReportRv.setAdapter(adapter); } } }, throwable -> { throwable.toString(); }); toolbar.setTitle(""); setSupportActionBar(toolbar); ivBack.setOnClickListener(view -> finish()); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // TODO: add setContentView(...) invocation ButterKnife.bind(this); } } /** *         ┏┓   ┏┓ *        ┏┛┻━━━┛┻┓ *        ┃       ┃ *        ┃   ━   ┃ *        ┃ >   < ┃ *        ┃       ┃ *        ┃... ⌒ ... ┃ *        ┃       ┃ *        ┗━┓   ┏━┛ *          ┃   ┃ Code is far away from bug with the animal protecting *          ┃   ┃ 神兽保佑,代码无bug *          ┃   ┃ *          ┃   ┃ *          ┃   ┃ *          ┃   ┃ *          ┃   ┗━━━┓ *          ┃       ┣┓ *          ┃       ┏┛ *          ┗┓┓┏━┳┓┏┛ *           ┃┫┫ ┃┫┫ *           ┗┻┛ ┗┻┛ */ <file_sep>/app/src/main/java/com/app/zes/gotoclass/api/ApiService.java package com.app.zes.gotoclass.api; import com.app.zes.gotoclass.model.Course; import com.app.zes.gotoclass.model.CourseAttendance; import com.app.zes.gotoclass.model.CourseByCode; import com.app.zes.gotoclass.model.CourseComment; import com.app.zes.gotoclass.model.CourseFeedback; import com.app.zes.gotoclass.model.CourseGPAReport; import com.app.zes.gotoclass.model.CourseLeaving; import com.app.zes.gotoclass.model.CourseLesson; import com.app.zes.gotoclass.model.CourseOutline; import com.app.zes.gotoclass.model.GPAReport; import com.app.zes.gotoclass.model.Login; import com.app.zes.gotoclass.model.Phone; import com.app.zes.gotoclass.model.SimpleResult; import java.util.List; import okhttp3.RequestBody; import retrofit2.Call; import retrofit2.http.Body; import retrofit2.http.GET; import retrofit2.http.Header; import retrofit2.http.POST; import retrofit2.http.Query; import rx.Observable; /** * Created by zes on 17-3-18 21:28 */ public interface ApiService { // @POST("login") // Call<Login> login(@Body RequestBody requestBody); @GET("get") Call<Phone> phone(@Query("phone") String phone, @Query("key") String key); /** * 登录 * * @param requestBody * @return */ @POST("login") Observable<Login> login(@Body RequestBody requestBody); /** * 注册 * * @param requestBody * @return */ @POST("register") Observable<Login> register(@Body RequestBody requestBody); /** * 查询用户所有的课程 * * @param token * @param page * @param pageSize * @return */ @GET("findUserCourses") Observable<List<Course>> findUserCourses(@Header("Authorization") String token, @Query("page") int page, @Query("pageSize") int pageSize); /** * 根据课程码查找课程 * * @param token * @param coursecode * @return */ @GET("findCourseByCode") Observable<CourseByCode> findCourseByCode(@Header("Authorization") String token, @Query("coursecode") String coursecode); /** * 根据查询得到的课程id添加课程 * * @param token * @param courseId * @return */ @GET("addCourse") Observable<SimpleResult> addCourse(@Header("Authorization") String token, @Query("courseId") int courseId); /** * 查看课堂小节 * * @param token * @param lessonId * @return */ @GET("findCourseLesson") Observable<CourseLesson> findCourseLesson(@Header("Authorization") String token, @Query("lessonId") int lessonId); /** * 查看课程预备(大纲) * * @param token * @param courseId * @param page * @param pageSize * @return */ @GET("findCourseOutline") Observable<List<CourseOutline>> findCourseOutline(@Header("Authorization") String token, @Query("courseId") int courseId, @Query("page") int page, @Query("pageSize") int pageSize); /** * 查看课堂公告 * * @param token * @param courseId * @param page * @param pageSize * @return */ @GET("findCourseComment") Observable<List<CourseComment>> findCourseComment(@Header("Authorization") String token, @Query("courseId") int courseId, @Query("page") int page, @Query("pageSize") int pageSize); /** * 查看反馈 * * @param token * @param courseId * @param page * @param pageSize * @return */ @GET("findCourseFeedback") Observable<List<CourseFeedback>> findCourseFeedback(@Header("Authorization") String token, @Query("courseId") int courseId, @Query("page") int page, @Query("pageSize") int pageSize); /** * 查看课程签到 * * @param token * @param courseId * @param page * @param pageSize * @return */ @GET("findCourseAttendance") Observable<CourseAttendance> findCourseAttendance(@Header("Authorization") String token, @Query("courseId") int courseId, @Query("page") int page, @Query("pageSize") int pageSize); /** * 查看请假 * * @param token * @param courseId * @param page * @param pageSize * @return */ @GET("findCourseLeaving") Observable<CourseLeaving> findCourseLeaving(@Header("Authorization") String token, @Query("courseId") int courseId, @Query("page") int page, @Query("pageSize") int pageSize); /** * 填写反馈 * * @param token * @param courseId * @param content * @param anonymous * @return */ @GET("fillInFeedback") Observable<SimpleResult> fillInFeedback(@Header("Authorization") String token, @Query("courseId") int courseId, @Query("content") String content, @Query("anonymous") String anonymous); /** * 签到 * * @param token * @param code * @return */ @GET("attendance") Observable<SimpleResult> attendance(@Header("Authorization") String token, @Query("code") String code, @Query("longitude") String longitude, @Query("latitude") String latitude); /** * 请假 * * @param token * @param courseId * @param lessonId * @param reason * @return */ @GET("askForLeave") Observable<SimpleResult> askForLeave(@Header("Authorization") String token, @Query("courseId") int courseId, @Query("lessonId") int lessonId, @Query("reason") String reason); /** * 查看平时分 * * @param token * @param courseId * @return */ @GET("student/getGPAReport") Observable<GPAReport> getGPAReport(@Header("Authorization") String token, @Query("courseId") int courseId); /** * 查看平时成绩总览 * * @param token * @return */ @GET("student/getCourseGPAReport") Observable<CourseGPAReport> getCourseGPAReport(@Header("Authorization") String token); } /** *         ┏┓   ┏┓ *        ┏┛┻━━━┛┻┓ *        ┃       ┃ *        ┃   ━   ┃ *        ┃ >   < ┃ *        ┃       ┃ *        ┃... ⌒ ... ┃ *        ┃       ┃ *        ┗━┓   ┏━┛ *          ┃   ┃ Code is far away from bug with the animal protecting *          ┃   ┃ 神兽保佑,代码无bug *          ┃   ┃ *          ┃   ┃ *          ┃   ┃ *          ┃   ┃ *          ┃   ┗━━━┓ *          ┃       ┣┓ *          ┃       ┏┛ *          ┗┓┓┏━┳┓┏┛ *           ┃┫┫ ┃┫┫ *           ┗┻┛ ┗┻┛ */ <file_sep>/app/src/main/java/com/app/zes/gotoclass/activity/ClassFeedbackActivity.java package com.app.zes.gotoclass.activity; import android.os.Bundle; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.Toolbar; import android.text.TextUtils; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import com.app.zes.gotoclass.R; import com.app.zes.gotoclass.adapter.FeedbackAdapter; import com.app.zes.gotoclass.api.ApiFactory; import com.app.zes.gotoclass.view.RefreshRecyclerView; import com.zes.bundle.activity.BaseActivity; import com.zes.bundle.utils.MKToast; import com.zes.bundle.view.DividerItemDecoration; import butterknife.Bind; import butterknife.ButterKnife; /** * Created by zes on 17-3-18 11:03 */ public class ClassFeedbackActivity extends BaseActivity { @Bind(R.id.toolbar) Toolbar toolbar; @Bind(R.id.rv_feedback) RefreshRecyclerView rvFeedback; @Bind(R.id.btn_feedback_send) Button btnFeedbackSend; @Bind(R.id.et_feedback_content) EditText etFeedbackContent; @Bind(R.id.cb_feedback_anonymous) CheckBox cbFeedbackAnonymous; @Bind(R.id.srl) SwipeRefreshLayout swipeRefreshLayout; @Bind(R.id.iv_back) ImageView ivBack; @Bind(R.id.ll_send_feedback) LinearLayout llSendFeedback; private int couresId; private FeedbackAdapter feedbackAdapter; private int currentPage = 2; @Override protected int getContentViewId() { return R.layout.activity_class_feedback; } /** * 初始化数据 * * @param savedInstanceState */ @Override protected void initData(Bundle savedInstanceState) { } /** * 初始化视图 */ @Override protected void initView() { swipeRefreshLayout.setColorSchemeResources(android.R.color.holo_red_light, android.R.color.holo_blue_light, android.R.color.holo_green_light); couresId = getIntent().getIntExtra("courseId", 0); rvFeedback.setLayoutManager(new LinearLayoutManager(this)); rvFeedback.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST)); rvFeedback.setLoadMoreEnable(true); rvFeedback.setFooterResource(R.layout.item_footer); toolbar.setTitle(""); setSupportActionBar(toolbar); ApiFactory.findCourseFeedback(couresId, 1, 10).subscribe(courseFeedbacks -> { if (courseFeedbacks != null) { feedbackAdapter = new FeedbackAdapter(this, courseFeedbacks, R.layout.item_feedback); rvFeedback.setAdapter(feedbackAdapter); } }); btnFeedbackSend.setOnClickListener(view -> { sendFeedBack(); }); initListener(); ivBack.setOnClickListener(view -> finish()); } /** * 提交反馈 */ private void sendFeedBack() { String anonymous = "N"; if (!cbFeedbackAnonymous.isChecked()) { anonymous = "Y"; } String content; content = etFeedbackContent.getText().toString(); if (TextUtils.isEmpty(content)) { MKToast.showToast(this, "请输入您的意见"); return; } ApiFactory.fillInFeedback(couresId, content, anonymous).subscribe(simpleResult -> { if (simpleResult != null) { ApiFactory.findCourseFeedback(couresId, 1, 10).subscribe(courseFeedbacks -> { if (courseFeedbacks != null && feedbackAdapter != null) { feedbackAdapter.setData(courseFeedbacks); rvFeedback.notifyData(); } }); } }); } private void initListener() { rvFeedback.setOnLoadMoreListener(() -> ApiFactory.findCourseFeedback(couresId, currentPage, 10).subscribe(courseFeedbacks -> { currentPage++; if (courseFeedbacks != null) { if (courseFeedbacks.size() == 0) { MKToast.showToast(this, "暂无更多数据"); } else { feedbackAdapter.addAll(courseFeedbacks); } rvFeedback.notifyData(); } })); swipeRefreshLayout.setOnRefreshListener(() -> { swipeRefreshLayout.setRefreshing(false); ApiFactory.findCourseFeedback(couresId, 1, 10).subscribe(courseFeedbacks -> { if (courseFeedbacks != null) { feedbackAdapter.clear(); currentPage = 2; feedbackAdapter.setData(courseFeedbacks); rvFeedback.notifyData(); } }); }); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // TODO: add setContentView(...) invocation ButterKnife.bind(this); } } /** *         ┏┓   ┏┓ *        ┏┛┻━━━┛┻┓ *        ┃       ┃ *        ┃   ━   ┃ *        ┃ >   < ┃ *        ┃       ┃ *        ┃... ⌒ ... ┃ *        ┃       ┃ *        ┗━┓   ┏━┛ *          ┃   ┃ Code is far away from bug with the animal protecting *          ┃   ┃ 神兽保佑,代码无bug *          ┃   ┃ *          ┃   ┃ *          ┃   ┃ *          ┃   ┃ *          ┃   ┗━━━┓ *          ┃       ┣┓ *          ┃       ┏┛ *          ┗┓┓┏━┳┓┏┛ *           ┃┫┫ ┃┫┫ *           ┗┻┛ ┗┻┛ */ <file_sep>/app/src/main/java/com/app/zes/gotoclass/model/CourseGPAReport.java package com.app.zes.gotoclass.model; import java.util.List; /** * Created by zes on 17-4-15 10:30 */ public class CourseGPAReport { /** * result : success * score : [{"interactCount":0,"courseName":"WEB开发","attendanceCount":1,"attendanceScore":10,"interactScore":0,"totalScore":10},{"interactCount":4,"courseName":"JAVA开发","attendanceCount":2,"attendanceScore":20,"interactScore":12.5,"totalScore":32.5},{"interactCount":0,"courseName":"XML开发","attendanceCount":1,"attendanceScore":10,"interactScore":0,"totalScore":10},{"interactCount":0,"courseName":"JAVASCRIPT","attendanceCount":2,"attendanceScore":13.333333333333334,"interactScore":0,"totalScore":13.333333333333334},{"interactCount":0,"courseName":"HTML开发","attendanceCount":0,"attendanceScore":0,"interactScore":0,"totalScore":0}] */ private String result; /** * interactCount : 0 * courseName : WEB开发 * attendanceCount : 1 * attendanceScore : 10 * interactScore : 0 * totalScore : 10 */ private List<ScoreEntity> score; public void setResult(String result) { this.result = result; } public void setScore(List<ScoreEntity> score) { this.score = score; } public String getResult() { return result; } public List<ScoreEntity> getScore() { return score; } public static class ScoreEntity { private int interactCount; private String courseName; private int attendanceCount; private double attendanceScore; private double interactScore; private double totalScore; public void setInteractCount(int interactCount) { this.interactCount = interactCount; } public void setCourseName(String courseName) { this.courseName = courseName; } public void setAttendanceCount(int attendanceCount) { this.attendanceCount = attendanceCount; } public void setAttendanceScore(double attendanceScore) { this.attendanceScore = attendanceScore; } public void setInteractScore(double interactScore) { this.interactScore = interactScore; } public void setTotalScore(double totalScore) { this.totalScore = totalScore; } public int getInteractCount() { return interactCount; } public String getCourseName() { return courseName; } public int getAttendanceCount() { return attendanceCount; } public double getAttendanceScore() { return attendanceScore; } public double getInteractScore() { return interactScore; } public double getTotalScore() { return totalScore; } } } /** *         ┏┓   ┏┓ *        ┏┛┻━━━┛┻┓ *        ┃       ┃ *        ┃   ━   ┃ *        ┃ >   < ┃ *        ┃       ┃ *        ┃... ⌒ ... ┃ *        ┃       ┃ *        ┗━┓   ┏━┛ *          ┃   ┃ Code is far away from bug with the animal protecting *          ┃   ┃ 神兽保佑,代码无bug *          ┃   ┃ *          ┃   ┃ *          ┃   ┃ *          ┃   ┃ *          ┃   ┗━━━┓ *          ┃       ┣┓ *          ┃       ┏┛ *          ┗┓┓┏━┳┓┏┛ *           ┃┫┫ ┃┫┫ *           ┗┻┛ ┗┻┛ */ <file_sep>/app/src/main/java/com/app/zes/gotoclass/adapter/FeedbackAdapter.java package com.app.zes.gotoclass.adapter; import android.content.Context; import com.app.zes.gotoclass.R; import com.app.zes.gotoclass.model.CourseFeedback; import com.zes.bundle.adapter.BaseRecycleAdapter; import com.zes.bundle.bean.RecycleViewHolder; import java.util.List; /** * Created by zes on 17-3-18 11:07 */ public class FeedbackAdapter extends BaseRecycleAdapter<CourseFeedback> { public FeedbackAdapter(Context context, List<CourseFeedback> datas, int layoutId) { super(context, datas, layoutId); } /** * 所有子类的逻辑代码的实现 * * @param holder * @param data * @param position */ @Override protected void convertView(RecycleViewHolder holder, CourseFeedback data, int position) { holder.setText(R.id.tv_item_feedback_user_name, data.getUsername()); holder.setText(R.id.tv_item_feedback_time, data.getTime()); holder.setText(R.id.tv_item_feedback_content, data.getContent()); } } /** *         ┏┓   ┏┓ *        ┏┛┻━━━┛┻┓ *        ┃       ┃ *        ┃   ━   ┃ *        ┃ >   < ┃ *        ┃       ┃ *        ┃... ⌒ ... ┃ *        ┃       ┃ *        ┗━┓   ┏━┛ *          ┃   ┃ Code is far away from bug with the animal protecting *          ┃   ┃ 神兽保佑,代码无bug *          ┃   ┃ *          ┃   ┃ *          ┃   ┃ *          ┃   ┃ *          ┃   ┗━━━┓ *          ┃       ┣┓ *          ┃       ┏┛ *          ┗┓┓┏━┳┓┏┛ *           ┃┫┫ ┃┫┫ *           ┗┻┛ ┗┻┛ */ <file_sep>/bundle/src/main/java/com/zes/bundle/activity/BaseActivity.java package com.zes.bundle.activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.EditText; import android.widget.Toast; import butterknife.ButterKnife; /** * BaseActivity */ public abstract class BaseActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(getContentViewId()); ButterKnife.bind(this); initView(); initData(savedInstanceState); } protected abstract int getContentViewId(); /** * 初始化数据 */ protected abstract void initData(Bundle savedInstanceState); /** * 初始化视图 */ protected abstract void initView(); public void setContentViewWithoutInject(int layoutResId) { super.setContentView(layoutResId); } protected int[] getStartingLocation(View view) { int[] startingLocation = new int[2]; view.getLocationOnScreen(startingLocation); startingLocation[0] += view.getWidth() / 2; return startingLocation; } /** * @param text */ protected void showToast(String text) { Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show(); } /** * Activity跳转 * * @param context * @param targetActivity * @param bundle */ public void redictToActivity(Context context, Class<?> targetActivity, Bundle bundle) { Intent intent = new Intent(context, targetActivity); if (null != bundle) { intent.putExtras(bundle); } startActivity(intent); } /** * Activity跳转 * * @param context * @param targetActivity */ public void redictToActivity(Context context, Class<?> targetActivity) { Intent intent = new Intent(context, targetActivity); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); } /** * 获取EditText的输入 如果不是EditText类型,返回null * * @param view * @return */ public String getEditTextString(View view) { if (view instanceof EditText) { return ((EditText) view).getText().toString(); } return null; } } <file_sep>/bundle/src/main/java/com/zes/bundle/fragment/BaseFragment.java package com.zes.bundle.fragment; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import butterknife.ButterKnife; /** * Created by zes on 16-1-15. */ public abstract class BaseFragment extends Fragment { private View rootView; @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { rootView = inflater.inflate(getContentViewId(), container, false); ButterKnife.bind(this, rootView); initView(); return rootView; } protected abstract int getContentViewId(); /** * 初始化视图 */ protected abstract void initView(); protected View getRootView() { return rootView; } protected void redirectActivity(Activity activity, Class c) { Intent intent = new Intent(activity, c); startActivity(intent); } } <file_sep>/bundle/src/main/java/com/zes/bundle/bean/RecycleViewHolder.java package com.zes.bundle.bean; import android.content.Context; import android.graphics.Bitmap; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.text.TextUtils; import android.util.SparseArray; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.zes.bundle.R; import com.zes.bundle.adapter.BaseRecycleAdapter; import com.zes.bundle.view.RecycleImageView; import java.io.File; /** * Created by zes on 15-10-12. */ public class RecycleViewHolder extends RecyclerView.ViewHolder { private SparseArray<View> mViews; private Context mContext; protected View mConvertView; public RecycleViewHolder(View itemView, Context context) { super(itemView); mConvertView = itemView; mContext = context; this.mViews = new SparseArray<View>(); } /** * 获取根视图 * * @return */ public View getRootView() { return mConvertView; } /** * 根据输入的viewId,初始化view,将初始化后的view存入SparseArray类型的mViews中 * * @param viewId * @return */ @SuppressWarnings("unchecked") public <T extends View> T getView(int viewId) { View view = mViews.get(viewId); if (view == null) { view = mConvertView.findViewById(viewId); mViews.put(viewId, view); } return (T) view; } /** * TextView中设置text值,可调用此方法,也可以链式编程。 * * @param viewId * @param text * @return */ public RecycleViewHolder setText(int viewId, String text) { TextView tv = getView(viewId); tv.setText(text); return this; } public RecycleViewHolder setText(int viewId, Number num) { return setText(viewId, String.valueOf(num)); } public RecycleViewHolder appendText(int viewId, String text) { if (!TextUtils.isEmpty(text)) { TextView tv = getView(viewId); tv.append(text); } return this; } public RecycleViewHolder appendText(int viewId, Number num) { return appendText(viewId, String.valueOf(num)); } /** * 设置TextView的text颜色 * * @param viewId * @param textColor * @return */ public RecycleViewHolder setTextColor(int viewId, int textColor) { TextView view = getView(viewId); view.setTextColor(textColor); return this; } public RecycleViewHolder setTextColorResource(int viewId, int textColorRes) { TextView view = getView(viewId); view.setTextColor(mContext.getResources().getColor(textColorRes)); return this; } /** * 只适用于imageview及其子类 * * @param viewId * @param bm * @return */ public RecycleViewHolder setImageBitmap(int viewId, Bitmap bm) { ImageView iv = getView(viewId); iv.setImageBitmap(bm); return this; } public RecycleViewHolder setImageResource(int viewId, int resId) { ImageView iv = getView(viewId); iv.setImageResource(resId); return this; } public RecycleViewHolder setRecycleAdapter(int viewId, Context context, BaseRecycleAdapter adapter) { RecyclerView recyclerView = getView(viewId); // recyclerView.addItemDecoration(new DividerGridItemDecoration(context)); recyclerView.setLayoutManager(new GridLayoutManager(context, 3)); recyclerView.setAdapter(adapter); return this; } /** * ImageView设置为本地图片 * * @param viewId viewId * @param filePath 本地图片地址 * @param errorResId error图片,0则不设置 * @param placeholderResId 占位图,0则不设置 * @return */ public RecycleViewHolder setImageByFilePath(int viewId, String filePath, int placeholderResId, int errorResId) { RecycleImageView iv = getView(viewId); // Picasso.with(mContext).load(new File(filePath)) // .error(R.drawable.pictures_no). // config(Bitmap.Config.RGB_565).transform(new CropSquareTransformation()) .memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE).into(iv); Glide.with(mContext).load(new File(filePath)).error(R.drawable.pictures_no).into(iv); return this; } /** * 网络图片 * * @param viewId * @param url * @return */ public RecycleViewHolder setImageByUrl(int viewId, String url) { ImageView iv = getView(viewId); Glide.with(mContext).load(url).into(iv); return this; } /** * 设置图片文件路径 * * @param viewId * @param filePath * @return */ public RecycleViewHolder setImageByFilePath(int viewId, String filePath) { setImageByFilePath(viewId, filePath, 0, 0); return this; } } <file_sep>/app/src/main/java/com/app/zes/gotoclass/model/CourseFeedback.java package com.app.zes.gotoclass.model; /** * Created by zes on 17-3-19 23:19 */ public class CourseFeedback { /** * id : 10 * username : Lucas * content : 滚蛋 * time : 2017-03-19 11:19 */ private int id; private String username; private String content; private String time; public void setId(int id) { this.id = id; } public void setUsername(String username) { this.username = username; } public void setContent(String content) { this.content = content; } public void setTime(String time) { this.time = time; } public int getId() { return id; } public String getUsername() { return username == null ? "" : username; } public String getContent() { return content == null ? "" : content; } public String getTime() { return time == null ? "" : time; } } /** *         ┏┓   ┏┓ *        ┏┛┻━━━┛┻┓ *        ┃       ┃ *        ┃   ━   ┃ *        ┃ >   < ┃ *        ┃       ┃ *        ┃... ⌒ ... ┃ *        ┃       ┃ *        ┗━┓   ┏━┛ *          ┃   ┃ Code is far away from bug with the animal protecting *          ┃   ┃ 神兽保佑,代码无bug *          ┃   ┃ *          ┃   ┃ *          ┃   ┃ *          ┃   ┃ *          ┃   ┗━━━┓ *          ┃       ┣┓ *          ┃       ┏┛ *          ┗┓┓┏━┳┓┏┛ *           ┃┫┫ ┃┫┫ *           ┗┻┛ ┗┻┛ */ <file_sep>/app/src/main/java/com/app/zes/gotoclass/C.java package com.app.zes.gotoclass; /** * Created by zes on 17-3-18 21:11 */ public class C { // public static final String BASE_URL = "http://apis.juhe.cn/mobile/"; public static final String BASE_URL = "http://119.29.186.230/studygo-student/"; } /** *         ┏┓   ┏┓ *        ┏┛┻━━━┛┻┓ *        ┃       ┃ *        ┃   ━   ┃ *        ┃ >   < ┃ *        ┃       ┃ *        ┃... ⌒ ... ┃ *        ┃       ┃ *        ┗━┓   ┏━┛ *          ┃   ┃ Code is far away from bug with the animal protecting *          ┃   ┃ 神兽保佑,代码无bug *          ┃   ┃ *          ┃   ┃ *          ┃   ┃ *          ┃   ┃ *          ┃   ┗━━━┓ *          ┃       ┣┓ *          ┃       ┏┛ *          ┗┓┓┏━┳┓┏┛ *           ┃┫┫ ┃┫┫ *           ┗┻┛ ┗┻┛ */ <file_sep>/bundle/src/main/java/com/zes/bundle/bean/ViewHolder.java package com.zes.bundle.bean; import android.content.Context; import android.graphics.Bitmap; import android.graphics.drawable.Drawable; import android.os.Build; import android.text.TextUtils; import android.util.SparseArray; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.animation.AlphaAnimation; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; import com.zes.bundle.R; import com.zes.bundle.utils.GlideCircleTransform; /** * ViewHolder 后期可以根据开发添加一些方法 * * @author zes and hyman */ public class ViewHolder { private SparseArray<View> mViews; private Context mContext; private View mConvertView; private int mPosition; // public ViewHolder(View itemView) { // super(itemView); // } public ViewHolder(Context context, ViewGroup parent, int layoutId, int position) { this.mPosition = position; this.mContext = context; this.mViews = new SparseArray<View>(); this.mConvertView = LayoutInflater.from(mContext).inflate(layoutId, parent, false); this.mConvertView.setTag(R.id.viewholder, this); } public ViewHolder(Context context, ViewGroup parent, int layoutId) { this(context, parent, layoutId, -1); } /** * 创建ViewHolder * * @param context * @param convertView * @param parent * @param layoutId * @param position * @return */ public static ViewHolder getViewHolder(Context context, View convertView, ViewGroup parent, int layoutId, int position) { if (null == convertView || null == convertView.getTag(R.id.viewholder)) { return new ViewHolder(context, parent, layoutId, position); } else { return (ViewHolder) convertView.getTag(R.id.viewholder); } } /** * 创建ViewHolder,position默认为-1 * * @param context * @param convertView * @param parent * @param layoutId * @return */ public static ViewHolder getViewHolder(Context context, View convertView, ViewGroup parent, int layoutId) { return getViewHolder(context, convertView, parent, layoutId, -1); } /** * 获取viewholder对应的position * * @return */ public int getPosition() { return mPosition; } public View getConvertView() { return mConvertView; } /** * 根据输入的viewId,初始化view,将初始化后的view存入SparseArray类型的mViews中 * * @param viewId * @return */ @SuppressWarnings("unchecked") public <T extends View> T getView(int viewId) { View view = mViews.get(viewId); if (view == null) { view = mConvertView.findViewById(viewId); mViews.put(viewId, view); } return (T) view; } /** * TextView中设置text值,可调用此方法,也可以链式编程。 * * @param viewId * @param text * @return */ public ViewHolder setText(int viewId, String text) { TextView tv = getView(viewId); tv.setText(text); return this; } public ViewHolder setText(int viewId, Number num) { return setText(viewId, String.valueOf(num)); } public ViewHolder appendText(int viewId, String text) { if (!TextUtils.isEmpty(text)) { TextView tv = getView(viewId); tv.append(text); } return this; } public ViewHolder appendText(int viewId, Number num) { return appendText(viewId, String.valueOf(num)); } /** * 设置TextView的text颜色 * * @param viewId * @param textColor * @return */ public ViewHolder setTextColor(int viewId, int textColor) { TextView view = getView(viewId); view.setTextColor(textColor); return this; } public ViewHolder setTextColorResource(int viewId, int textColorRes) { TextView view = getView(viewId); view.setTextColor(mContext.getResources().getColor(textColorRes)); return this; } /** * 只适用于imageview及其子类 * * @param viewId * @param bm * @return */ public ViewHolder setImageBitmap(int viewId, Bitmap bm) { ImageView iv = getView(viewId); iv.setImageBitmap(bm); return this; } // /** * ImageView设置为网络图片 * * @param viewId * @param url * @return */ public ViewHolder setImageByUrl(int viewId, String url) { return setImageByUrl(viewId, url, 0, 0); } public ViewHolder setImageByUrl(int viewId, String url, int placeholderResId) { return setImageByUrl(viewId, url, placeholderResId, 0); } public ViewHolder setImageByUrl(int viewId, String url, int placeholderResId, int errorResId) { ImageView iv = getView(viewId); Glide.with(mContext).load(url).placeholder(placeholderResId).error(errorResId).into(iv); // ImageLoader.load(mContext, iv, url, placeholderResId, errorResId); return this; } public ViewHolder setCircleImageByUrl(int viewId, String url, int placeholderResId) { return setCircleImageByUrl(viewId, url, placeholderResId, 0); } /** * 加载圆形图片 * * @param viewId * @param url * @param placeholderResId * @param errorResId * @return */ public ViewHolder setCircleImageByUrl(int viewId, String url, int placeholderResId, int errorResId) { ImageView iv = getView(viewId); Glide.with(mContext).load(url).transform(new GlideCircleTransform(mContext)).placeholder(placeholderResId).error(errorResId).into(iv); return this; } // public ViewHolder setCropImageByUrl(int viewId, String url, int placeholderResId, int errorResId) { // CropImageView iv = getView(viewId); // Glide.with(mContext).load(url).placeholder(placeholderResId).error(errorResId).into(iv); // // ImageLoader.load(mContext, iv, url, placeholderResId, errorResId); // return this; // } // // /** // * ImageView设置为本地图片 // * // * @param viewId viewId // * @param filePath 本地图片地址 // * @param errorResId error图片,0则不设置 // * @param placeholderResId 占位图,0则不设置 // * @return // */ // public ViewHolder setImageByFilePath(int viewId, String filePath, int placeholderResId, int errorResId) { // ImageView iv = getView(viewId); // ImageLoader.load(mContext, iv, filePath, placeholderResId, errorResId); // return this; // } // // public ViewHolder setImageByFilePath(int viewId, String filePath) { // setImageByFilePath(viewId, filePath, 0, 0); // return this; // } /** * 设置ImageView的Image * * @param viewId * @param resId * @return */ public ViewHolder setImageResource(int viewId, int resId) { ImageView iv = getView(viewId); iv.setImageResource(resId); return this; } /** * 设置ImageView的drawable * * @param viewId * @param drawable * @return */ public ViewHolder setImageDrawable(int viewId, Drawable drawable) { ImageView iv = getView(viewId); iv.setImageDrawable(drawable); return this; } /** * 设置背景颜色 * * @param viewId * @param color * @return */ public ViewHolder setBackgroundColor(int viewId, int color) { View view = getView(viewId); view.setBackgroundColor(color); return this; } /** * 适用于所有view设置背景图片 * * @param viewId * @param resId 图片资源的ID * @return */ public ViewHolder setBackgroundResource(int viewId, int resId) { View iv = getView(viewId); iv.setBackgroundResource(resId); return this; } /** * 设置View的可见性 * * @param viewId * @param visible true,可见 * @return */ public ViewHolder setVisible(int viewId, boolean visible) { View view = getView(viewId); view.setVisibility(visible ? View.VISIBLE : View.GONE); return this; } /** * 设置View的监听器 * * @param viewId * @param listener * @return */ public ViewHolder setOnClickListener(int viewId, View.OnClickListener listener) { View view = getView(viewId); view.setOnClickListener(listener); return this; } /** * 设置View的透明度 * * @param viewId * @param value * @return */ public ViewHolder setAlpha(int viewId, float value) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { getView(viewId).setAlpha(value); } else { // Pre-honeycomb hack to set Alpha value AlphaAnimation alpha = new AlphaAnimation(value, value); alpha.setDuration(0); alpha.setFillAfter(true); getView(viewId).startAnimation(alpha); } return this; } } <file_sep>/app/src/main/java/com/app/zes/gotoclass/model/CourseLeaving.java package com.app.zes.gotoclass.model; import java.util.List; /** * Created by zes on 17-3-19 23:21 */ public class CourseLeaving { /** * id : 1 * lessonName : 第二课时 * lessonId : 2 * reason : ??? * permission : W * time : 2017-03-12 09:23 */ private List<LeavesEntity> leaves; public void setLeaves(List<LeavesEntity> leaves) { this.leaves = leaves; } public List<LeavesEntity> getLeaves() { return leaves; } public static class LeavesEntity { private int id; private String lessonName; private int lessonId; private String reason; private String permission; private String time; public void setId(int id) { this.id = id; } public void setLessonName(String lessonName) { this.lessonName = lessonName; } public void setLessonId(int lessonId) { this.lessonId = lessonId; } public void setReason(String reason) { this.reason = reason; } public void setPermission(String permission) { this.permission = permission; } public void setTime(String time) { this.time = time; } public int getId() { return id; } public String getLessonName() { return lessonName; } public int getLessonId() { return lessonId; } public String getReason() { return reason; } public String getPermission() { return permission; } public String getTime() { return time; } } } /** *         ┏┓   ┏┓ *        ┏┛┻━━━┛┻┓ *        ┃       ┃ *        ┃   ━   ┃ *        ┃ >   < ┃ *        ┃       ┃ *        ┃... ⌒ ... ┃ *        ┃       ┃ *        ┗━┓   ┏━┛ *          ┃   ┃ Code is far away from bug with the animal protecting *          ┃   ┃ 神兽保佑,代码无bug *          ┃   ┃ *          ┃   ┃ *          ┃   ┃ *          ┃   ┃ *          ┃   ┗━━━┓ *          ┃       ┣┓ *          ┃       ┏┛ *          ┗┓┓┏━┳┓┏┛ *           ┃┫┫ ┃┫┫ *           ┗┻┛ ┗┻┛ */ <file_sep>/app/src/main/java/com/app/zes/gotoclass/fragment/ClassFragment.java package com.app.zes.gotoclass.fragment; import android.content.Intent; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.LinearLayoutManager; import android.view.View; import com.app.zes.gotoclass.R; import com.app.zes.gotoclass.activity.ClassDetailActivity; import com.app.zes.gotoclass.adapter.ClassAdapter; import com.app.zes.gotoclass.api.ApiFactory; import com.app.zes.gotoclass.model.Course; import com.app.zes.gotoclass.utils.RxBus; import com.app.zes.gotoclass.view.RefreshRecyclerView; import com.zes.bundle.adapter.BaseRecycleAdapter; import com.zes.bundle.bean.RecycleViewHolder; import com.zes.bundle.fragment.BaseFragment; import com.zes.bundle.utils.MKToast; import com.zes.bundle.view.DividerItemDecoration; import java.util.List; import butterknife.Bind; import static com.app.zes.gotoclass.R.layout.fragment_class; /** * Created by zes on 17-3-5 22:01 */ public class ClassFragment extends BaseFragment implements BaseRecycleAdapter.OnItemClickListener { @Bind(R.id.class_recyclerview) protected RefreshRecyclerView classRecyclerView; @Bind(R.id.srl) protected SwipeRefreshLayout swipeRefreshLayout; private ClassAdapter classAdapter; private List<Course> courseList; private int currentPage; @Override protected int getContentViewId() { return fragment_class; } /** * 初始化视图 */ @Override protected void initView() { swipeRefreshLayout.setColorSchemeResources(android.R.color.holo_red_light, android.R.color.holo_blue_light, android.R.color.holo_green_light); classRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity())); classRecyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST)); classRecyclerView.setLoadMoreEnable(true); classRecyclerView.setFooterResource(R.layout.item_footer); initListener(); currentPage = 1; ApiFactory.findUserCourses(currentPage, 10).subscribe(courses -> { if (classRecyclerView != null && classAdapter == null) { classAdapter = new ClassAdapter(getActivity(), courses, R.layout.item_class); classRecyclerView.setAdapter(classAdapter); classAdapter.setOnItemClickLitener(this); } else { classAdapter.setData(courses); classRecyclerView.setAdapter(classAdapter); } currentPage++; }); RxBus.getInstance().toObserverable(Integer.class).subscribe(integer -> { ApiFactory.findUserCourses(1, 10).subscribe(courses -> { if (courses != null) { classAdapter.clear(); currentPage = 2; classAdapter.setData(courses); classRecyclerView.notifyData(); } }); }); } private void initListener() { classRecyclerView.setOnLoadMoreListener(() -> ApiFactory.findUserCourses(currentPage, 10).subscribe(courses -> { currentPage++; if (courses != null) { if (courses.size() == 0) { MKToast.showToast(getActivity(), "暂无更多数据"); } else { classAdapter.addAll(courses); } classRecyclerView.notifyData(); courseList = courses; } })); swipeRefreshLayout.setOnRefreshListener(() -> { swipeRefreshLayout.setRefreshing(false); ApiFactory.findUserCourses(1, 10).subscribe(courses -> { if (courses != null) { classAdapter.clear(); currentPage = 2; classAdapter.setData(courses); classRecyclerView.notifyData(); } }); }); } @Override public void onItemClick(RecycleViewHolder holder, View view, int position) { // redirectActivity(getActivity(), ClassDetailActivity.class); Intent intent = new Intent(getActivity(), ClassDetailActivity.class); intent.putExtra("lessonId", classAdapter.getData().get(position).getLessonId()); intent.putExtra("courseId", classAdapter.getData().get(position).getId()); startActivity(intent); } @Override public void onItemLongClick(View view, int position) { } } /** *         ┏┓   ┏┓ *        ┏┛┻━━━┛┻┓ *        ┃       ┃ *        ┃   ━   ┃ *        ┃ >   < ┃ *        ┃       ┃ *        ┃... ⌒ ... ┃ *        ┃       ┃ *        ┗━┓   ┏━┛ *          ┃   ┃ Code is far away from bug with the animal protecting *          ┃   ┃ 神兽保佑,代码无bug *          ┃   ┃ *          ┃   ┃ *          ┃   ┃ *          ┃   ┃ *          ┃   ┗━━━┓ *          ┃       ┣┓ *          ┃       ┏┛ *          ┗┓┓┏━┳┓┏┛ *           ┃┫┫ ┃┫┫ *           ┗┻┛ ┗┻┛ */ <file_sep>/app/src/main/java/com/app/zes/gotoclass/model/CourseByCode.java package com.app.zes.gotoclass.model; /** * Created by zes on 17-3-19 23:01 */ public class CourseByCode { /** * result : success * course : {"id":3,"name":"XML开发","teacher":"Mark","lessonName":"第一课时","lessonId":5,"classroom":"教506","time":"2017-3-22 10:00"} */ private String result; /** * id : 3 * name : XML开发 * teacher : Mark * lessonName : 第一课时 * lessonId : 5 * classroom : 教506 * time : 2017-3-22 10:00 */ private CourseEntity course; public void setResult(String result) { this.result = result; } public void setCourse(CourseEntity course) { this.course = course; } public String getResult() { return result; } public CourseEntity getCourse() { return course; } public static class CourseEntity { private int id; private String name; private String teacher; private String lessonName; private int lessonId; private String classroom; private String time; public void setId(int id) { this.id = id; } public void setName(String name) { this.name = name; } public void setTeacher(String teacher) { this.teacher = teacher; } public void setLessonName(String lessonName) { this.lessonName = lessonName; } public void setLessonId(int lessonId) { this.lessonId = lessonId; } public void setClassroom(String classroom) { this.classroom = classroom; } public void setTime(String time) { this.time = time; } public int getId() { return id; } public String getName() { return name; } public String getTeacher() { return teacher; } public String getLessonName() { return lessonName; } public int getLessonId() { return lessonId; } public String getClassroom() { return classroom; } public String getTime() { return time; } } } /** *         ┏┓   ┏┓ *        ┏┛┻━━━┛┻┓ *        ┃       ┃ *        ┃   ━   ┃ *        ┃ >   < ┃ *        ┃       ┃ *        ┃... ⌒ ... ┃ *        ┃       ┃ *        ┗━┓   ┏━┛ *          ┃   ┃ Code is far away from bug with the animal protecting *          ┃   ┃ 神兽保佑,代码无bug *          ┃   ┃ *          ┃   ┃ *          ┃   ┃ *          ┃   ┃ *          ┃   ┗━━━┓ *          ┃       ┣┓ *          ┃       ┏┛ *          ┗┓┓┏━┳┓┏┛ *           ┃┫┫ ┃┫┫ *           ┗┻┛ ┗┻┛ */ <file_sep>/app/src/main/java/com/app/zes/gotoclass/fragment/MineFragment.java package com.app.zes.gotoclass.fragment; import android.content.Intent; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import com.app.zes.gotoclass.R; import com.app.zes.gotoclass.activity.GpaReportActivity; import com.app.zes.gotoclass.activity.MainActivity; import com.zes.bundle.fragment.BaseFragment; import com.zes.bundle.utils.Utils; import butterknife.Bind; import butterknife.ButterKnife; import butterknife.OnClick; /** * Created by zes on 17-3-5 22:15 */ public class MineFragment extends BaseFragment { @Bind(R.id.tv_mine_user_name) TextView tvMineUserName; @Bind(R.id.ll_mine_score) LinearLayout llMineScore; @Bind(R.id.ll_mine_user_feedback) LinearLayout llMineUserFeedback; @Bind(R.id.ll_mine_setting) LinearLayout llMineSetting; @Override protected int getContentViewId() { return R.layout.fragement_mine; } /** * 初始化视图 */ @Override protected void initView() { } @OnClick({R.id.ll_mine_score, R.id.ll_mine_setting, R.id.ll_mine_user_feedback, R.id.ll_mine_logout}) protected void click(View view) { switch (view.getId()) { case R.id.ll_mine_score: redirectActivity(getActivity(), GpaReportActivity.class); break; case R.id.ll_mine_logout: Utils.getSpUtils().clear(); Intent intent = new Intent(getActivity(), MainActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(intent); break; } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // TODO: inflate a fragment view View rootView = super.onCreateView(inflater, container, savedInstanceState); ButterKnife.bind(this, rootView); return rootView; } @Override public void onDestroyView() { super.onDestroyView(); ButterKnife.unbind(this); } } /** *         ┏┓   ┏┓ *        ┏┛┻━━━┛┻┓ *        ┃       ┃ *        ┃   ━   ┃ *        ┃ >   < ┃ *        ┃       ┃ *        ┃... ⌒ ... ┃ *        ┃       ┃ *        ┗━┓   ┏━┛ *          ┃   ┃ Code is far away from bug with the animal protecting *          ┃   ┃ 神兽保佑,代码无bug *          ┃   ┃ *          ┃   ┃ *          ┃   ┃ *          ┃   ┃ *          ┃   ┗━━━┓ *          ┃       ┣┓ *          ┃       ┏┛ *          ┗┓┓┏━┳┓┏┛ *           ┃┫┫ ┃┫┫ *           ┗┻┛ ┗┻┛ */ <file_sep>/README.md # GotoClass 上课啦 <file_sep>/bundle/src/main/java/com/zes/bundle/view/DragMaskLayout.java package com.zes.bundle.view; import android.content.Context; import android.graphics.Point; import android.support.v4.widget.ViewDragHelper; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import android.widget.FrameLayout; /** * 拖动控件并显示遮罩 */ public class DragMaskLayout extends FrameLayout { private ViewDragHelper mDragger; private View mDragView; private View mMaskView; private Context mContext; private Point mDragViewOriginPos = new Point(); //初始化当前控件的位置 private int currentX = 0; private int currentY = 0; //记录上一次控件的位置 private int previousX = 0; private int previousY = 0; public DragMaskLayout(Context context, AttributeSet attrs) { super(context, attrs); mContext = context; mDragger = ViewDragHelper.create(this, 1.0f, new ViewDragHelper.Callback() { @Override public int getViewVerticalDragRange(View child) { return getMeasuredHeight() - child.getMeasuredHeight(); } @Override public boolean tryCaptureView(View child, int pointerId) { //mEdgeTrackerView禁止直接移动 return child == mDragView; } @Override public int clampViewPositionHorizontal(View child, int left, int dx) { return child.getLeft(); } @Override public int clampViewPositionVertical(View child, int top, int dy) { return top; } //手指释放的时候回调 @Override public void onViewReleased(View releasedChild, float xvel, float yvel) { //mAutoBackView手指释放时可以自动回去 // if (releasedChild == mAutoBackView) { // mDragger.settleCapturedViewAt(mAutoBackOriginPos.x, mAutoBackOriginPos.y); // invalidate(); // } if (releasedChild == mDragView) { if (yvel > 0 || mDragView.getTop() < 0) { mDragger.settleCapturedViewAt(mDragViewOriginPos.x, mDragViewOriginPos.y); mMaskView.setVisibility(INVISIBLE); invalidate(); } } } }); } @Override public boolean onInterceptTouchEvent(MotionEvent event) { return mDragger.shouldInterceptTouchEvent(event); } @Override public boolean onTouchEvent(MotionEvent event) { mDragger.processTouchEvent(event); currentX = (int) event.getX(); //获取当前X坐标 currentY = (int) event.getY(); //获取当前Y坐标 switch (event.getAction()) { case MotionEvent.ACTION_DOWN: //按下控件时 previousX = currentX; //记录上次X,Y坐标 previousY = currentY; break; case MotionEvent.ACTION_MOVE: //开始移动控件 int detelX = currentX - previousX; int detelY = currentY - previousY; if (detelY > 10) { mMaskView.setVisibility(VISIBLE); } previousX = currentX - detelX; //记录上一次的X,Y坐标 previousY = currentY - detelY; break; case MotionEvent.ACTION_UP: //触摸事件结束,触摸离开屏幕 break; case MotionEvent.ACTION_CANCEL: //取消触摸事件 break; } return true; } @Override public void computeScroll() { if (mDragger.continueSettling(true)) { invalidate(); } } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { super.onLayout(changed, l, t, r, b); mDragViewOriginPos.x = mDragView.getLeft(); mDragViewOriginPos.y = mDragView.getTop(); } @Override protected void onFinishInflate() { super.onFinishInflate(); if (getChildCount() >= 1) { mDragView = getChildAt(1); mMaskView = getChildAt(0); } } private boolean mIsDisallowIntercept = false; @Override public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) { // keep the info about if the innerViews do requestDisallowInterceptTouchEvent mIsDisallowIntercept = disallowIntercept; super.requestDisallowInterceptTouchEvent(disallowIntercept); } @Override public boolean dispatchTouchEvent(MotionEvent ev) { // the incorrect array size will only happen in the multi-touch scenario. if (ev.getPointerCount() > 1 && mIsDisallowIntercept) { requestDisallowInterceptTouchEvent(false); boolean handled = super.dispatchTouchEvent(ev); requestDisallowInterceptTouchEvent(true); return handled; } else { return super.dispatchTouchEvent(ev); } } } <file_sep>/app/src/main/java/com/app/zes/gotoclass/model/SimpleResult.java package com.app.zes.gotoclass.model; /** * Created by zes on 17-3-19 23:10 */ public class SimpleResult { /** * result : success */ private String result; public void setResult(String result) { this.result = result; } public String getResult() { return result; } } /** *         ┏┓   ┏┓ *        ┏┛┻━━━┛┻┓ *        ┃       ┃ *        ┃   ━   ┃ *        ┃ >   < ┃ *        ┃       ┃ *        ┃... ⌒ ... ┃ *        ┃       ┃ *        ┗━┓   ┏━┛ *          ┃   ┃ Code is far away from bug with the animal protecting *          ┃   ┃ 神兽保佑,代码无bug *          ┃   ┃ *          ┃   ┃ *          ┃   ┃ *          ┃   ┃ *          ┃   ┗━━━┓ *          ┃       ┣┓ *          ┃       ┏┛ *          ┗┓┓┏━┳┓┏┛ *           ┃┫┫ ┃┫┫ *           ┗┻┛ ┗┻┛ */ <file_sep>/app/src/main/java/com/app/zes/gotoclass/model/Course.java package com.app.zes.gotoclass.model; import java.io.Serializable; /** * Created by zes on 17-3-19 17:12 */ public class Course implements Serializable { /** * id : 2 * name : WEB开发 * teacher : Mark * lessonName : 第一课时 * lessonId : 3 * classroom : 教507 * time : 2017-3-22 08:00 */ private int id; private String name; private String teacher; private String lessonName; private int lessonId; private String classroom; private String time; public void setId(int id) { this.id = id; } public void setName(String name) { this.name = name; } public void setTeacher(String teacher) { this.teacher = teacher; } public void setLessonName(String lessonName) { this.lessonName = lessonName; } public void setLessonId(int lessonId) { this.lessonId = lessonId; } public void setClassroom(String classroom) { this.classroom = classroom; } public void setTime(String time) { this.time = time; } public int getId() { return id; } public String getName() { return name; } public String getTeacher() { return teacher; } public String getLessonName() { return lessonName; } public int getLessonId() { return lessonId; } public String getClassroom() { return classroom; } public String getTime() { return time; } } /** *         ┏┓   ┏┓ *        ┏┛┻━━━┛┻┓ *        ┃       ┃ *        ┃   ━   ┃ *        ┃ >   < ┃ *        ┃       ┃ *        ┃... ⌒ ... ┃ *        ┃       ┃ *        ┗━┓   ┏━┛ *          ┃   ┃ Code is far away from bug with the animal protecting *          ┃   ┃ 神兽保佑,代码无bug *          ┃   ┃ *          ┃   ┃ *          ┃   ┃ *          ┃   ┃ *          ┃   ┗━━━┓ *          ┃       ┣┓ *          ┃       ┏┛ *          ┗┓┓┏━┳┓┏┛ *           ┃┫┫ ┃┫┫ *           ┗┻┛ ┗┻┛ */ <file_sep>/app/src/main/java/com/app/zes/gotoclass/activity/ClassScoreActivity.java package com.app.zes.gotoclass.activity; import android.os.Bundle; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.widget.ImageView; import com.app.zes.gotoclass.R; import com.app.zes.gotoclass.adapter.ScoreAdapter; import com.app.zes.gotoclass.api.ApiFactory; import com.app.zes.gotoclass.model.GPAReport; import com.zes.bundle.activity.BaseActivity; import com.zes.bundle.view.DividerGridItemDecoration; import java.util.ArrayList; import java.util.List; import butterknife.Bind; import butterknife.ButterKnife; /** * Created by zes on 17-3-18 11:02 */ public class ClassScoreActivity extends BaseActivity { @Bind(R.id.toolbar) Toolbar toolbar; @Bind(R.id.score_rv) RecyclerView scoreRv; @Bind(R.id.iv_back) ImageView ivBack; private List<String> mDatas; private ScoreAdapter adapter; private int couresId; @Override protected int getContentViewId() { return R.layout.activity_class_score; } /** * 初始化数据 * * @param savedInstanceState */ @Override protected void initData(Bundle savedInstanceState) { } /** * 初始化视图 */ @Override protected void initView() { mDatas = new ArrayList<>(); // for (int i = 'A'; i < 'z'; i++) { // mDatas.add("" + (char) i); // } // ApiFactory.getGPAReport() couresId = getIntent().getIntExtra("courseId", 0); ApiFactory.getGPAReport(couresId).subscribe(gpaReport -> { if (gpaReport != null) { List<GPAReport.DetailEntity> detail = gpaReport.getDetail(); if (detail != null) { mDatas.add("课时"); mDatas.add("考勤"); mDatas.add("互动"); for (int i = 0; i < detail.size(); i++) { mDatas.add(detail.get(i).getLessonName()); mDatas.add(detail.get(i).getAttendance()); mDatas.add(detail.get(i).getInteract() + ""); } adapter = new ScoreAdapter(this, mDatas, R.layout.item_score); scoreRv.setLayoutManager(new GridLayoutManager(this, 3)); scoreRv.addItemDecoration(new DividerGridItemDecoration(this)); scoreRv.setAdapter(adapter); } } }, throwable -> { throwable.toString(); }); toolbar.setTitle(""); setSupportActionBar(toolbar); ivBack.setOnClickListener(view -> finish()); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // TODO: add setContentView(...) invocation ButterKnife.bind(this); } } /** *         ┏┓   ┏┓ *        ┏┛┻━━━┛┻┓ *        ┃       ┃ *        ┃   ━   ┃ *        ┃ >   < ┃ *        ┃       ┃ *        ┃... ⌒ ... ┃ *        ┃       ┃ *        ┗━┓   ┏━┛ *          ┃   ┃ Code is far away from bug with the animal protecting *          ┃   ┃ 神兽保佑,代码无bug *          ┃   ┃ *          ┃   ┃ *          ┃   ┃ *          ┃   ┃ *          ┃   ┗━━━┓ *          ┃       ┣┓ *          ┃       ┏┛ *          ┗┓┓┏━┳┓┏┛ *           ┃┫┫ ┃┫┫ *           ┗┻┛ ┗┻┛ */
a373314f693690c3c4564eaaaa96a0a08a6dfb05
[ "Markdown", "Java" ]
22
Java
zeschi/GotoClass
abe862be509a52b731d130160e1fe96208f53eea
538a05de08f785fdfae0a71b6ba180966e68b5e2
refs/heads/main
<repo_name>Rohith04MVK/Geolexa<file_sep>/Pipfile [[source]] # Here goes your package sources (where you are downloading your packages from). url = "https://pypi.python.org/simple" verify_ssl = true name = "pypi" [packages] # Here goes your package requirements for running the application and its versions (which packages you will use when running the application). requests = "*" youtube_dl = "*" [dev-packages] # Here goes your package requirements for developing the application and its versions (which packages you will use when developing the application) pylint = "*" [requires] # Here goes your required Python version. <file_sep>/code.py import os import youtube_dl import re import urllib.request import requests import time from random import randint def dad_joke(): data = requests.get("https://icanhazdadjoke.com/", headers={"Accept": "application/json"}) data = data.json() return(data["joke"]) def countdown(t): while t: mins, secs = divmod(t, 60) timer = '{:02d}:{:02d}'.format(mins, secs) print(timer, end="\r") time.sleep(1) t -= 1 print(f'your timer is up{home}') def play_music(name): name = list(name) name = ["+" if x == " " else x for x in name] vid_url = (f"https://www.youtube.com/results?search_query={''.join(name)}") html = urllib.request.urlopen(vid_url) video_ids = re.findall(r"watch\?v=(\S{11})", html.read().decode()) song_link = video_ids[0] path = os.getcwd() music_folder = os.path.join(path, "music") if os.path.exists(music_folder): music_folder = os.path.join(path, "music") else: os.mkdir(os.path.join(path, "music")) music_folder = os.path.join(path, "music") ydl_opts = { 'format': 'bestaudio/best', 'postprocessors': [{ 'key': 'FFmpegExtractAudio', 'preferredcodec': 'mp3', 'preferredquality': '192', }], 'outtmpl': os.path.join(music_folder, "music.mp3"), } if len(os.listdir(music_folder)) != 0: os.remove(os.path.join(music_folder, "music.mp3")) else: with youtube_dl.YoutubeDL(ydl_opts) as ydl: ydl.download([f'https://www.youtube.com/watch?v={song_link}']) print("DONE!") home = input("enter your name: ") want = input(f"{home} what do you want: ") if want == "riddle" or want == "Riddle" or want == "RIDDLE": riddle = ["what goes up when rain comes down ?", "How many months of the year have 28 days?", "What has hands and a face, but can’t hold anything or smile?", " If you don’t keep me, I’ll break. What am I?"] num = randint(0, 3) print(riddle[num]) solution = ["umbrella", "12", "clock", "promise."] answer = input("your answer pls ") if (answer == solution[num]): print(f"{home} your answer is correct") else: print(f"{home} your answer is wrong") elif want == "joke" or want == "JOKE" or want == "Joke": print(dad_joke()) elif want == "game" or want == "Game" or want == "GAME": game = input("rps or tictactoe: ") if game == "tictactoe": board = [' ' for x in range(10)] def insertLetter(letter, pos): board[pos] = letter def spaceIsFree(pos): return board[pos] == ' ' def printBoard(board): print(' | |') print(' ' + board[1] + ' | ' + board[2] + ' | ' + board[3]) print(' | |') print('-----------') print(' | |') print(' ' + board[4] + ' | ' + board[5] + ' | ' + board[6]) print(' | |') print('-----------') print(' | |') print(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9]) print(' | |') def isWinner(bo, le): return (bo[7] == le and bo[8] == le and bo[9] == le) or (bo[4] == le and bo[5] == le and bo[6] == le) or (bo[1] == le and bo[2] == le and bo[3] == le) or (bo[1] == le and bo[4] == le and bo[7] == le) or (bo[2] == le and bo[5] == le and bo[8] == le) or (bo[3] == le and bo[6] == le and bo[9] == le) or (bo[1] == le and bo[5] == le and bo[9] == le) or (bo[3] == le and bo[5] == le and bo[7] == le) def playerMove(): run = True while run: move = input( 'Please select a position to place an \'X\' (1-9): ') try: move = int(move) if move > 0 and move < 10: if spaceIsFree(move): run = False insertLetter('X', move) else: print('Sorry, this space is occupied!') else: print('Please type a number within the range!') except: print('Please type a number!') def compMove(): possibleMoves = [x for x, letter in enumerate( board) if letter == ' ' and x != 0] move = 0 for let in ['O', 'X']: for i in possibleMoves: boardCopy = board[:] boardCopy[i] = let if isWinner(boardCopy, let): move = i return move cornersOpen = [] for i in possibleMoves: if i in [1, 3, 7, 9]: cornersOpen.append(i) if len(cornersOpen) > 0: move = selectRandom(cornersOpen) return move if 5 in possibleMoves: move = 5 return move edgesOpen = [] for i in possibleMoves: if i in [2, 4, 6, 8]: edgesOpen.append(i) if len(edgesOpen) > 0: move = selectRandom(edgesOpen) return move def selectRandom(li): import random ln = len(li) r = random.randrange(0, ln) return li[r] def isBoardFull(board): if board.count(' ') > 1: return False else: return True def main(): print('Welcome to Tic Tac Toe!') printBoard(board) while not(isBoardFull(board)): if not(isWinner(board, 'O')): playerMove() printBoard(board) else: print('Sorry, O\'s won this time!') break if not(isWinner(board, 'X')): move = compMove() if move == 0: print('Tie Game!') else: insertLetter('O', move) print('Computer placed an \'O\' in position', move, ':') printBoard(board) else: print('X\'s won this time! Good Job!') break if isBoardFull(board): print('Tie Game!') while True: answer = input('Do you want to play again? (Y/N)') if answer.lower() == 'y' or answer.lower == 'yes': board = [' ' for x in range(10)] print('%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%') main() else: break if game == "rps": y = 'y' while y != 'n': x = randint(1, 3) print("1=rock,2=paper,3=sis") man = int(input("enter a number between 1 and 3 : ")) if man == 1: print("you choose rock") elif man == 2: print("you choose paper") else: print("you choose sis") if x == 1: print("computer choose rock") elif x == 2: print("computer choose paper") else: print("computer choose sis") if x == man: print("draw") elif man == 1 and x == 3: print("man won") elif man == 2 and x == 1: print("man won ") elif man == 3 and x == 2: print("man won") else: print("computer won") y = input("Would you like to play agian? y/n: ") elif want == "calculator" or want == "Calculator" or want == "CALCULATOR": x = float(input("enter a number: ")) y = input("enter a opration: ") z = float(input("enter a numder: ")) if y == "*": print("your answer is", x*z) elif y == "/": print("your answer is", x/z) elif y == "+": print("your answer is", x+z) elif y == "^": print("your answer is", x**z) else: print("your answer is", x-z) elif want == "timer" or want == "Timer" or want == "TIMER": t = input("Enter the time in seconds: ") countdown(int(t)) elif want.lower() == "nick name": name = input( f"would you like to change your nick name (enter y for yes and n for no):(your name is currently {home}) ") if name == "y": new_name = input("your new you nick name: ") if new_name == home: print("it is alredy your nick name") else: print(f"okay your new nick name is {new_name} ") if name == "n": print(f"okay I will keep calling you {home}") if want.lower() == "music": name_song = input("music name") play_music(f"{name_song}") else: print("sorry i can not do that ")
455d813f9e68fe388af6672680e1ee4c9ef25831
[ "TOML", "Python" ]
2
TOML
Rohith04MVK/Geolexa
878476b34c75c6ea276ac4ca0410db10842b62b7
3f44d56e82a601a1ab466723cfe73906ddd54fae
refs/heads/master
<file_sep>require 'rails_helper' RSpec.feature "AddTrips", type: :feature, js: true do before :each do @user = User.create( first_name: 'first', last_name: 'last', email: '<EMAIL>', password: '<PASSWORD>', password_confirmation: '<PASSWORD>' ) end scenario "user is able to add a trip" do visit '/users/sign_in' within 'form' do fill_in id: 'user_email', with: @user.email fill_in id: 'user_password', with: '<PASSWORD>' end find('input[name="commit"]').click visit '/trips/new' within 'form' do fill_in id: 'trip_name', with: 'My trip' fill_in id: 'trip_start_date', with: Time.now + 1.days fill_in id: 'trip_end_date', with: Time.now + 5.days end find('input[name="commit"]').click expect(page).to have_content('My trip') end end <file_sep>class TripsController < ApplicationController before_action :authenticate_user! def new @trip = Trip.new end def edit end def create @trip = Trip.new(trip_params) @trip.users << current_user if @trip.save create_itineraries(@trip) redirect_to trip_url(@trip.id) else render new_trip_path flash[:notice] = 'Woops. We\'ve had some problems with saving your trip.' end end def destroy tripId = params[:id] @trip = Trip.find(params[:id]) usertrip = UserTrip.where(trip_id: @trip) usertrip.each do |indTrip| if indTrip.user_id === current_user.id @trip.destroy! else flash[:notice] = 'Woops. Looks like you do not own that itinerary.' end end if @trip.destroy redirect_back fallback_location: user_trips_path(current_user.id) else flash[:notice] = 'Woops. Looks like we couldn\'t delete your trip.' end end def index @user = User.find params[:user_id] @trips = @user.trips @trip = Trip.new end def show @trip = Trip.includes(itineraries: :itinerary_items).find params[:id] @itinerary_item = ItineraryItem.new @selected_itinerary = @trip.itineraries.find_by(id: params[:selected_itinerary_id]) @selected_itinerary ||= @trip.itineraries.first @invite = Invite.new respond_to do |format| format.cable { render layout: false } end end private def create_itineraries(trip) (trip.start_date..trip.end_date).each do |date| Itinerary.create( name: "Day #{trip.itineraries.count + 1}", date: date, notes: "", trip_id: trip.id, public: false, featured: false ) end end def trip_params params.require(:trip).permit( :name, :start_date, :end_date, :public ) end end <file_sep>class RenameAttractionsCityColumn < ActiveRecord::Migration[5.2] def change change_table :attractions do |t| t.rename :city, :address_city t.rename :postcode, :address_postcode end end end <file_sep>Rails.application.routes.draw do resources :todos devise_for :users, controllers: { registrations: 'users/registrations' } root to: 'cities#index' get '/login' => 'sessions#new' post '/login' => 'sessions#create' get '/logout' => 'sessions#destroy' resources :users, only: [:new, :create, :edit] do resources :trips end resources :trips, except: [:index] do resources :invites, only: [:create, :new, :show] resources :user_trips, only: [:create, :new] resources :itineraries, only: [:new, :create, :destroy] end get 'itinerary_details/:id', to: 'itineraries#details', as: :itinerary_details resources :itineraries, except: [:index] do resources :itinerary_items, only: [:show] end resources :itinerary_items resources :cities, only: [:show, :index] resources :attractions, only: [:show] do resources :reviews, only: [:create] resources :itinerary_items, only: [:create, :new] end resources :reviews, only: [:destroy] namespace :admin do resources :attractions, except: [:show] resources :cities, except: [:show] end mount ActionCable.server => '/cable' end <file_sep>class InviteMailer < ApplicationMailer default from: '<EMAIL>' def register_invite(invite) @invite = invite mail(to:@invite.email, subject: "Join Traveller now to join my trip!") end def existing_user_invite(invite) @invite = invite mail(to:@invite.email, subject: "Join my trip!") end end <file_sep>class CreateItineraries < ActiveRecord::Migration[5.2] def change create_table :itineraries do |t| t.string :name, null: false t.date :date, null: false t.string :notes, null: false, default: "" t.boolean :public, null: false, default: false t.boolean :featured, null: false, default: false t.references :trip, foreign_key: true, null: false t.timestamps end end end <file_sep>class Itinerary < ApplicationRecord belongs_to :trip has_many :itinerary_items, -> { order(:start_time) }, dependent: :delete_all validates_presence_of :name attr_accessor :selected_item after_create -> { TripChannel.broadcast_to(self.trip, {created_itinerary: self.id}) ItineraryChannel.broadcast_to(self, {created: self.id}) } after_update -> { ItineraryChannel.broadcast_to(self, {updated: self.id}) } after_destroy -> { ItineraryChannel.broadcast_to(self, {destroyed: self.id}) } end <file_sep>class TripChannel < ApplicationCable::Channel def subscribed @trip = Trip.find(params[:id]) stream_for @trip end def unsubscribed # Any cleanup needed when channel is unsubscribed end def speak(data) itinerary_item = ItineraryItem.create(data) itinerary = Itinerary.find_by_id(itinerary_item.itinerary_id) TripChannel.broadcast_to('trip_channel', itinerary) end end <file_sep># ActionMailer::Base.register_interceptor(SendGrid::MailInterceptor)<file_sep>class CreateAttractions < ActiveRecord::Migration[5.2] def change create_table :attractions do |t| t.string :name, null: false t.string :address, null: false, default: "" t.string :city, null: false t.string :postcode, null: false, default: "" t.string :website, null: false, default: "" t.string :facebook, null: false, default: "" t.string :instagram, null: false, default: "" t.string :twitter, null: false, default: "" t.text :description, null: false t.string :monday_hours, null: false, default: "" t.string :tuesday_hours, null: false, default: "" t.string :wednesday_hours, null: false, default: "" t.string :thursday_hours, null: false, default: "" t.string :friday_hours, null: false, default: "" t.string :saturday_hours, null: false, default: "" t.string :sunday_hours, null: false, default: "" t.string :image, null: false t.string :categories, null: false, default: "" t.string :google_place, null: false, default: "" t.references :city, foreign_key: true, null: false t.boolean :public, null: false, default: false t.boolean :featured, null: false, default: false t.timestamps end end end <file_sep>class AddColumnsToInvites < ActiveRecord::Migration[5.2] def change add_reference :invites, :trip, foreign_key: true, null: false add_column :invites, :sender, :integer, null: false end end <file_sep>class Trip < ApplicationRecord has_many :user_trips, dependent: :delete_all has_many :users, through: :user_trips has_many :itineraries, dependent: :destroy has_many :invites, dependent: :delete_all validates_presence_of :start_date, :end_date, :name validate :end_after_start default_scope { order(start_date: :desc) } attr_accessor :selected_itinerary after_update -> { TripChannel.broadcast_to(self, {updated: self.id}) } after_destroy -> { TripChannel.broadcast_to(self, {destroyed: self.id}) } private def end_after_start return if end_date.blank? || start_date.blank? if end_date < start_date errors.add(:end_date, "must be after the start date") end end end <file_sep>class ItineraryItemsController < ApplicationController def new if params[:attraction_id] @attraction = Attraction.find params[:attraction_id] end @itinerary_item = ItineraryItem.new end def create @itinerary_item = ItineraryItem.new(itinerary_params) @trips = Trip.where("end_date > ?", 1.day.ago) if @itinerary_item.save flash[:notice] = 'Added to itinerary' else flash[:notice] = 'Woops something went wrong with adding your itinerary item.' end redirect_to trip_url(@itinerary_item.itinerary.trip_id) end def edit @itinerary_item = ItineraryItem.find(params[:id]) @itinerary = ItineraryItem.find_by(itinerary_id: @itinerary_item.itinerary_id) end def update @itinerary_item = ItineraryItem.find(params[:id]) @itinerary_item.update(itinerary_params) redirect_to trip_url(@itinerary_item.itinerary.trip_id) end def show @itinerary_item = ItineraryItem.find params[:id] @itinerary = ItineraryItem.find_by(itinerary_id: @itinerary_item.itinerary_id) end def destroy @itinerary_item = ItineraryItem.find(params[:id]) itinerary = @itinerary_item.itinerary trip = Trip.find_by_id(itinerary.trip_id) @itinerary_item.destroy! redirect_back fallback_location: trip_path(trip) end private def itinerary_params params.require(:itinerary_item).permit( :name, :notes, :start_time, :end_time, :itinerary_id, :attraction_id ) end end <file_sep>class ApplicationController < ActionController::Base # layout 'application' before_action :configure_permitted_parameters, if: :devise_controller? protect_from_forgery with: :exception before_action :detect_cable_guy protected def detect_cable_guy if params[:cable_guy] request.variant = :cable end end def configure_permitted_parameters devise_parameter_sanitizer.permit(:sign_up, keys: [:first_name, :last_name, :profile_pic, :invite_token]) devise_parameter_sanitizer.permit(:account_update, keys: [:first_name, :last_name, :profile_pic]) end end <file_sep>require 'test_helper' class ItinerariesControllerTest < ActionDispatch::IntegrationTest test "should get new" do get itineraries_new_url assert_response :success end test "should get create" do get itineraries_create_url assert_response :success end test "should get edit" do get itineraries_edit_url assert_response :success end test "should get destroy" do get itineraries_destroy_url assert_response :success end test "should get show" do get itineraries_show_url assert_response :success end test "should get update" do get itineraries_update_url assert_response :success end end <file_sep>require 'rails_helper' RSpec.feature "Visitor navigates to homepage", type: :feature, js: true do before :each do 10.times do |n| City.create!( name: Faker::HarryPotter.location, country: Faker::HarryPotter.location, description: Faker::HarryPotter.quote, language: 'English', currency: 'CAD', transit: 'www.translink.ca', emergency_phone: '911', time_zone: 'PST (UTC-8h)', tipping_custom: '18%', image: 'cities/city_vancouver1.jpg' ) end end scenario "They see all cities" do visit root_path expect(page).to have_css 'div.city-card', count: 10 end end <file_sep>require 'rails_helper' RSpec.feature "AttractionPages", type: :feature, js: true do before :each do @city = City.create( name: Faker::HarryPotter.location, country: Faker::HarryPotter.location, description: Faker::HarryPotter.quote, language: 'English', currency: 'CAD', transit: 'www.translink.ca', emergency_phone: '911', time_zone: 'PST (UTC-8h)', tipping_custom: '18%', image: 'cities/city_vancouver1.jpg' ) @attraction = Attraction.create( name: Faker::HarryPotter.spell, address: Faker::HarryPotter.spell, address_city: Faker::HarryPotter.location, city_id: @city.id, address_postcode: "SE1 9SG", website: "https://www.theviewfromtheshard.com/", facebook: "https://www.facebook.com/TheShardLondon/", instagram: "https://www.instagram.com/shardview/", twitter: "https://twitter.com/TheShardLondon", description: Faker::HarryPotter.quote, monday_hours: "10am - 8pm", tuesday_hours: "10am - 8pm", wednesday_hours: "10am - 8pm", thursday_hours: "10am - 10pm", friday_hours: "10am - 10pm", saturday_hours: "10am - 10pm", sunday_hours: "10am - 8pm", image: "attractions/london-the-shard.jpg", categories: ["viewpoint", "child-friendly"], google_place: "ChIJ03GSCloDdkgRe_s-p2vyvQA", public: true, featured: true ) end scenario "attractions page has relevant info" do visit root_path first('div.city-card').click click_on('All') sleep 3 first('.attraction-card').click expect(page).to have_content(@attraction.monday_hours) end end <file_sep>require 'rails_helper' RSpec.feature "CityPages", type: :feature, js: true do before :each do @city = City.create( name: Faker::HarryPotter.location, country: Faker::HarryPotter.location, description: Faker::HarryPotter.quote, language: 'English', currency: 'CAD', transit: 'www.translink.ca', emergency_phone: '911', time_zone: 'PST (UTC-8h)', tipping_custom: '18%', image: 'cities/city_vancouver1.jpg' ) end scenario "they see information about the city and attraactions" do visit root_path first('div.city-card').click expect(find('.all-city-info')).to have_content(@city.country) end end <file_sep>require 'rails_helper' RSpec.describe ItineraryItem, type: :model do before :each do @user = User.create( first_name: 'first', last_name: 'last', email: '<EMAIL>', password: '<PASSWORD>', password_confirmation: '<PASSWORD>' ) @trip = Trip.create( name: 'sometrip', start_date: Time.now + 1.days, end_date: Time.now + 3.days, public: 't', featured: 't' ) @user_trip = UserTrip.create( user_id: @user.id, trip_id: @trip.id, role: '' ) @itinerary = Itinerary.create( name: 'My itinerary', date: Time.now + 2.days, notes: 'Here are my notes', public: 't', featured: 't', trip_id: @trip.id ) @city = City.create( name: 'Vancouver', country: 'Canada', description: 'This is a description.', language: 'English', currency: 'CAD', transit: 'www.translink.ca', emergency_phone: '911', time_zone: 'PST (UTC-8h)', tipping_custom: '18%', image: 'cities/city_vancouver1.jpg' ) @attraction = Attraction.create( name: 'Some attraction', address: 'some address', address_city: 'Vancouver', address_postcode: 'V5X 3X9', website: 'www.google.com', facebook: 'myfacebook', instagram: 'asdfkj', twitter: 'tweeet', description: 'some description', monday_hours: '9:00 - 10:00', tuesday_hours: '9:00 - 10:00', wednesday_hours: '9:00 - 10:00', thursday_hours: '9:00 - 10:00', friday_hours: '9:00 - 10:00', saturday_hours: '9:00 - 10:00', sunday_hours: '9:00 - 10:00', image: 'attractions/vancouver-capilano.jpg', categories: ["nature", "child-friendly"], google_place: 'skljdflksjdfk', city_id: @city.id, public: 't', featured: 't' ) @itinerary_item = ItineraryItem.create( name: 'Item', notes: 'This is the first item', start_time: "08:25:00", end_time: "15:25:00", attraction_id: @attraction.id, itinerary_id: @itinerary.id ) end describe 'Validations' do it "is valid with all fields" do expect(@itinerary_item).to be_valid end it "is valid with no attraction id" do @itinerary_item.attraction_id = nil expect(@itinerary_item).to be_valid end it "is valid with no name" do @itinerary_item.name = nil expect(@itinerary_item).to be_valid end it "is valid with no notes" do @itinerary_item.notes = nil expect(@itinerary_item).to be_valid end it "is not valid with no start time" do @itinerary_item.start_time = nil expect(@itinerary_item).to_not be_valid end it "is not valid with no end time" do @itinerary_item.end_time = nil expect(@itinerary_item).to_not be_valid end it "is not valid with no itinerary" do @itinerary_item.itinerary_id = nil expect(@itinerary_item).to_not be_valid end it "is not valid with no itinerary" do @itinerary_item.itinerary_id = nil expect(@itinerary_item).to_not be_valid end it "is not valid if end time is before start time" do @itinerary_item.start_time = "15:25:00" @itinerary_item.end_time = "14:25:00" expect(@itinerary_item).to_not be_valid end end end <file_sep>class CreateItineraryItems < ActiveRecord::Migration[5.2] def change create_table :itinerary_items do |t| t.references :itinerary, foreign_key: true, null: false t.references :attraction, foreign_key: true t.string :name, null: false, default: "" t.text :notes, null: false, default: "" t.time :start_time, null: false t.time :end_time, null: false t.timestamps end end end <file_sep>class CitiesController < ApplicationController def show @city = City.find params[:id] @attractions = @city.attractions @categories = categories(@attractions) end def index @cities = City.all.order(:name) end def categories(attractions) allCategories = ['child-friendly', 'gallery', 'garden', 'historical', 'museum', 'nature', 'shopping', 'viewpoint'] categories = [] allCategories.each do |category| attractions.each do |attraction| if attraction.categories.include?(category) && !categories.include?(category) categories << category end end end categories end end <file_sep>class RemoveUserTripFromInvites < ActiveRecord::Migration[5.2] def change remove_reference :invites, :user_trip, foreign_key: true end end <file_sep>module Admin::AttractionsHelper end <file_sep>require 'test_helper' class ItineraryItemsControllerTest < ActionDispatch::IntegrationTest test "should get create" do get itinerary_items_create_url assert_response :success end test "should get edit" do get itinerary_items_edit_url assert_response :success end test "should get update" do get itinerary_items_update_url assert_response :success end test "should get show" do get itinerary_items_show_url assert_response :success end test "should get destroy" do get itinerary_items_destroy_url assert_response :success end end <file_sep>class AttractionsController < ApplicationController def show @attraction = Attraction.find params[:id] @reviews = @attraction.reviews @review = Review.new @itinerary_item = ItineraryItem.new end end <file_sep>class CreateCities < ActiveRecord::Migration[5.2] def change create_table :cities do |t| t.string :name, null: false t.string :country, null: false t.text :description, null: false t.string :language, null: false t.string :currency, null: false t.string :transit, null: false, default: "" t.string :emergency_phone, null: false t.string :time_zone, null: false t.string :tipping_custom, null: false, default: "" t.string :image, null: false t.timestamps end end end <file_sep>class UsersController < ApplicationController def new @token = params[:invite_token] end def create @newUser = User.new(user_params) @newUser.save @token = params[:invite_token] if @token != nil trip = Invite.find_by_token(@token).user_trip @newUser.user_trips.create({trip_id: trip.id, role: 'contributor'}) else # do normal registration things # end end private def user_params params.require(:user).permit( :first_name, :last_name, :email, :profile_pic, :password, :password_confirmation ) end end <file_sep>class UserChannel < ApplicationCable::Channel def subscribed @user = User.find(params[:id]) stream_for @user # stream_from "some_channel" end def unsubscribed # Any cleanup needed when channel is unsubscribed end end <file_sep>class AddPresenceToTripName < ActiveRecord::Migration[5.2] def change change_column :trips, :name, :string, presence: true end end <file_sep>class CreateInvites < ActiveRecord::Migration[5.2] def change create_table :invites do |t| t.references :user_trip, foreign_key: true, null: false t.integer :recipient, null: false t.string :email, null: false t.text :message, null: false t.string :token, null: false t.timestamps end end end <file_sep>class ItinerariesController < ApplicationController def new @itinerary = Itinerary.new end def create @itinerary = Itinerary.new(itinerary_params) respond_to do |format| if @itinerary.save format.html { redirect_to user_trips_path(current_user.id), notice: 'Itinerary was successfully created.' } format.json { render :show, status: :created, location: @itinerary } else format.html { render :new } format.json { render json: @itinerary.errors, status: :unprocessable_entity } end end end def edit @itinerary = Itinerary.find(params[:id]) end def update @itinerary = Itinerary.find(params[:id]) @itinerary.update(itinerary_params) redirect_to trip_url(@itinerary.trip_id) end def destroy @itinerary = Itinerary.find(params[:id]) trip = @itinerary.trip_id usertrip = UserTrip.where(trip_id: trip) usertrip.each do |indTrip| if indTrip.user_id === current_user.id @itinerary.destroy! else flash[:notice] = 'Woops. Looks like you do not own that itinerary.' end end if @itinerary.destroy redirect_to trip_path(trip) else flash[:notice] = 'Woops. Looks like we couldn\'t delete your trip.' end end def show @itinerary_item = ItineraryItem.new @itinerary = Itinerary.find params[:id] end def details @itinerary_item = ItineraryItem.new @itinerary = Itinerary.find params[:id] @trip = @itinerary.trip end private def itinerary_params params.require(:itinerary).permit( :name, :date, :notes, :trip_id, :public, :featured ) end end <file_sep>class Invite < ApplicationRecord belongs_to :trip before_create :generate_token before_save :check_user_existence def generate_token self.token = Digest::SHA1.hexdigest([self.trip_id, Time.now, rand].join) end def check_user_existence recipient = User.find_by_email(email) if recipient self.recipient = recipient.id end end end <file_sep>class UserTrip < ApplicationRecord belongs_to :user, touch: true belongs_to :trip, touch: true after_create -> { UserChannel.broadcast_to(self.user, {created_trip: self.trip_id}) TripChannel.broadcast_to(self.trip, {created: self.trip_id}) } end <file_sep>class ReviewsController < ApplicationController before_action :authenticate_user! def new @review = Review.new end def create @review = Review.new(review_params) @review.user = current_user if @review.save! flash[:notice] = 'Thanks for your review!' else flash[:notice] = `Woops something went wrong with your review. Please ensure you're logged in` end redirect_to attraction_path(@review.attraction_id) end def destroy @review = Review.find(params[:id]) attraction = @review.attraction @review.destroy! redirect_to attraction_path(attraction) end private def review_params params.require(:review).permit( :review, :rating, :attraction_id ) end end <file_sep>require 'rails_helper' RSpec.describe Trip, type: :model do before :each do @user = User.create( first_name: 'first', last_name: 'last', email: '<EMAIL>', password: '<PASSWORD>', password_confirmation: '<PASSWORD>' ) current_user = @user @trip = Trip.create( name: 'sometrip', start_date: Time.now + 1.days, end_date: Time.now + 3.days, public: 't', featured: 't' ) end describe 'Trip:Validations' do it "is valid with valid fields" do expect(@trip).to be_valid end it "is not valid without a trip name" do @trip.name = nil expect(@trip).to_not be_valid end it "is not valid without a start date" do @trip.start_date = nil expect(@trip).to_not be_valid end it "is not valid without a end date" do @trip.end_date = nil expect(@trip).to_not be_valid end it "is not valid if start date is later than end date" do @trip.end_date = Time.now @trip.start_date = Time.now + 3.days expect(@trip).to_not be_valid end end end <file_sep>require 'rails_helper' RSpec.describe User, type: :model do before :each do @user = User.create( first_name: 'first', last_name: 'last', email: '<EMAIL>', password: '<PASSWORD>', password_confirmation: '<PASSWORD>' ) end describe 'Validations' do it "is valid with valid fields" do expect(@user).to be_valid end it "is not valid without an email address" do @user.email = nil expect(@user).to_not be_valid end it "is not valid when passwords don't match" do @user.password_confirmation = "<PASSWORD>" expect(@user).to_not be_valid end it "is not valid with an empty pasword" do @user.password = nil @user.password_confirmation = nil expect(@user).to_not be_valid end it "is valid with no first name" do @user.first_name = nil expect(@user).to be_valid end it "is valid with no last name" do @user.last_name = nil expect(@user).to be_valid end end end <file_sep>class City < ApplicationRecord has_many :attractions end <file_sep>Traveller (LHL Bootcamp Final Project) ================================ By <NAME>, <NAME> & <NAME> Traveller is a collaborative trip-planning web application. It allows users to create trips, invite their friends to join and dynamically add itineraries and then attractions or notes to each itinerary. Users can also amend and delete intineraries or trips too. ## Screenshots Invite a friend to collaborate on your trip: If they're already a user, they will be automatically added and sent an email. Otherwise, they'll receive an email to tell them to join. !["Invite a friend"](https://github.com/ratofkryll/tripper/blob/master/public/invite-friend.gif?raw=true) Add an item to the itinerary and it will be automatically visible to anyone who's on the trip !["Add an itinerary item"](https://github.com/ratofkryll/tripper/blob/master/public/add-item-to-trip.gif?raw=true) ## Getting Started 1. Install dependencies using the `bundle install` command. 2. Create PostgreSQL database manually. 3. Apply data into the application using `rails db:create`, `rails db:migrate` and `rails db:seed`. 4. Start the web server using the `rails s` command. The app will be served at <http://localhost:3000/>. 5. Go to <http://localhost:3000/> in your browser. ## Dependencies * Ruby 2.6.0 * Rails 5.2.2 * PostgreSQL * Faker * JQuery Rails * Sass * Uglifier * Coffee * Jbuilder * Redis * Bcrypt * Fontawesome * Bootsnap * Devise * Formtastic * Sendgrid API * Google Map API <file_sep>require 'rails_helper' RSpec.describe Itinerary, type: :model do before :each do @user = User.create( first_name: 'first', last_name: 'last', email: '<EMAIL>', password: '<PASSWORD>', password_confirmation: '<PASSWORD>' ) @trip = Trip.create( name: 'sometrip', start_date: Time.now + 1.days, end_date: Time.now + 3.days, public: 't', featured: 't' ) @user_trip = UserTrip.create( user_id: @user.id, trip_id: @trip.id, role: '' ) @itinerary = Itinerary.create( name: 'My itinerary', date: Time.now + 2.days, notes: 'Here are my notes', public: 't', featured: 't', trip_id: @trip.id ) end describe 'Itinerary:Validations' do it "is valid with valid fields" do expect(@itinerary).to be_valid end it "is not valid with no name" do @itinerary.name = nil expect(@itinerary).to_not be_valid end it "is valid with no notes" do @itinerary.notes = nil expect(@itinerary).to be_valid end it "is valid with no date" do @itinerary.date = nil expect(@itinerary).to be_valid end end end <file_sep># This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: "Star Wars" }, { name: "Lord of the Rings" }]) # Character.create(name: "Luke", movie: movies.first) require "faker" puts "Starting seed..." # Delete existing data puts "Deleting existing data..." Itinerary.destroy_all UserTrip.destroy_all Trip.destroy_all Review.destroy_all User.destroy_all Attraction.destroy_all City.destroy_all # Reset primary key sequences puts "Resetting keys..." ActiveRecord::Base.connection.tables.each do |t| ActiveRecord::Base.connection.reset_pk_sequence!(t) end # CITIES puts "Finding or creating cities..." city1 = City.create!({ name: "Vancouver", country: "Canada", description: "Vancouver, a bustling west coast seaport in British Columbia, is among Canada’s densest, most ethnically diverse cities. A popular filming location, it’s surrounded by mountains, and also has thriving art, theatre and music scenes. Vancouver Art Gallery is known for its works by regional artists, while the Museum of Anthropology houses preeminent First Nations collections.", language: "English", currency: "CAD", transit: "https://www.translink.ca/", emergency_phone: "911", time_zone: "PST (UTC-8h)", tipping_custom: "15-18%", image: "cities/city_vancouver1.jpg" }) city2 = City.create!({ name: "Montreal", country: "Canada", description: "Montréal is the largest city in Canada's Québec province. It’s set on an island in the Saint Lawrence River and named after <NAME>, the triple-peaked hill at its heart. Its boroughs, many of which were once independent cities, include neighbourhoods ranging from cobblestoned, French colonial Vieux-Montréal – with the Gothic Revival Notre-Dame Basilica at its centre – to bohemian Plateau.", language: "French/English", currency: "CAD", transit: "http://www.stm.info/en", emergency_phone: "911", time_zone: "EST (UTC-5h)", tipping_custom: "15-18%", image: "cities/city_montreal.jpg" }) city3 = City.create!({ name: "London", country: "United Kingdom", description: "London, the capital of England and the United Kingdom, is a 21st-century city with history stretching back to Roman times. At its centre stand the imposing Houses of Parliament, the iconic ‘Big Ben’ clock tower and Westminster Abbey, site of British monarch coronations. Across the Thames River, the London Eye observation wheel provides panoramic views of the South Bank cultural complex, and the entire city.", language: "English", currency: "GBP", transit: "https://tfl.gov.uk/", emergency_phone: "999", time_zone: "GMT (UTC+0h)", tipping_custom: "Usually 12.75% added to your bill.", image: "cities/city_london.jpg" }) city4 = City.create!({ name: "Boston", country: "U.S.A.", description: "Boston is Massachusetts’ capital and largest city. Founded in 1630, it’s one of the oldest cities in the U.S. The key role it played in the American Revolution is highlighted on the Freedom Trail, a 2.5-mile walking route of historic sites that tells the story of the nation’s founding. One stop, former meeting house Faneuil Hall, is a popular marketplace.", language: "English", currency: "USD", transit: "https://www.mbta.com/", emergency_phone: "911", time_zone: "EST (UTC-5h)", tipping_custom: "15-20%", image: "cities/city_boston.jpg" }) city5 = City.create!({ name: "<NAME>", country: "U.S.A.", description: "Los Angeles is a sprawling Southern California city and the center of the nation’s film and television industry. Near its iconic Hollywood sign, studios such as Paramount Pictures, Universal and Warner Brothers offer behind-the-scenes tours. On Hollywood Boulevard, TCL Chinese Theatre displays celebrities’ hand- and footprints, the Walk of Fame honors thousands of luminaries and vendors sell maps to stars’ homes.", language: "English", currency: "USD", transit: "https://www.metro.net/", emergency_phone: "911", time_zone: "EST (UTC-8h)", tipping_custom: "15-20%", image: "cities/city_losangeles.jpg" }) city6 = City.create!({ name: "Toronto", country: "Canada", description: "Toronto, the capital of the province of Ontario, is a major Canadian city along Lake Ontario’s northwestern shore. It's a dynamic metropolis with a core of soaring skyscrapers, all dwarfed by the iconic, free-standing CN Tower. Toronto also has many green spaces, from the orderly oval of Queen’s Park to 400-acre High Park and its trails, sports facilities and zoo.", language: "English", currency: "CAD", transit: "http://www.ttc.ca/", emergency_phone: "911", time_zone: "EST (UTC-5h)", tipping_custom: "15-18%", image: "cities/city_toronto.jpg" }) city7 = City.create!({ name: "Chicago", country: "U.S.A.", description: "Chicago, on Lake Michigan in Illinois, is among the largest cities in the U.S. Famed for its bold architecture, it has a skyline punctuated by skyscrapers such as the iconic John Hancock Center, 1,451-ft. Willis Tower (formerly the Sears Tower) and the neo-Gothic Tribune Tower. The city is also renowned for its museums, including the Art Institute of Chicago with its noted Impressionist and Post-Impressionist works.", language: "English", currency: "USD", transit: "https://www.transitchicago.com/", emergency_phone: "911", time_zone: "EST (UTC-6h)", tipping_custom: "15-20%", image: "cities/city_chicago.jpg" }) city8 = City.create!({ name: "Paris", country: "France", description: "Paris, France's capital, is a major European city and a global center for art, fashion, gastronomy and culture. Its 19th-century cityscape is crisscrossed by wide boulevards and the River Seine. Beyond such landmarks as the Eiffel Tower and the 12th-century, Gothic Notre-Dame cathedral, the city is known for its cafe culture and designer boutiques along the Rue du Faubourg Saint-Honoré.", language: "French", currency: "EUR", transit: "https://www.ratp.fr/en", emergency_phone: "112", time_zone: "CEST (UTC+1h)", tipping_custom: "Suggested 10-15%", image: "cities/city_paris.jpg" }) city9 = City.create!({ name: "Sydney", country: "Australia", description: "Sydney, capital of New South Wales and one of Australia's largest cities, is best known for its harbourfront Sydney Opera House, with a distinctive sail-like design. Massive Darling Harbour and the smaller Circular Quay port are hubs of waterside life, with the arched Harbour Bridge and esteemed Royal Botanic Garden nearby. Sydney Tower’s outdoor platform, the Skywalk, offers 360-degree views of the city and suburbs.", language: "English", currency: "AUD", transit: "https://transportnsw.info/", emergency_phone: "000", time_zone: "AET (UTC+11h)", tipping_custom: "Suggested 10-15%", image: "cities/city_sydney.jpg" }) # ATTRACTIONS puts "Creating attractions..." ## Vancouver Attraction Data city1.attractions.create!({ name: "<NAME>", address: "3735 Capilano Rd", address_city: "North Vancouver", address_postcode: "V7R 4J1", website: "https://www.capbridge.com/", facebook: "https://www.facebook.com/capilanosuspensionbridgepark/", instagram: "https://www.instagram.com/capilanosuspensionbridge/?hl=en", twitter: "https://twitter.com/capsuspbridge", description: "Explore one of the most popular visitor attractions in Vancouver today! Experience Cliffwalk, Treetops Adventure, and the legendary Suspension Bridge. Kids under 6 free. Canyon Lights On Now. Destinations: Suspension Bridge, Cliffwalk, Treetop Adventures, Story Centre, The Living Forest.", monday_hours: "9am - 6pm", tuesday_hours: "9am - 6pm", wednesday_hours: "9am - 6pm", thursday_hours: "9am - 6pm", friday_hours: "9am - 6pm", saturday_hours: "9am - 6pm", sunday_hours: "9am - 6pm", image: "attractions/vancouver-capilano.jpg", categories: ["nature", "child-friendly"], google_place: "<KEY> <KEY>", public: true, featured: true }) city1.attractions.create!({ name: "<NAME>", address: "845 Avison Way", address_city: "Vancouver", address_postcode: "V6G 3E2", website: "https://www.vanaqua.org/", facebook: "https://www.facebook.com/vanaqua/", instagram: "https://www.instagram.com/vanaqua/", twitter: "https://twitter.com/vanaqua", description: "With a worldwide reputation as a leading marine science centre, the Vancouver Aquarium was the country’s first public aquarium when it opened in 1956, and is Canada’s largest. It is home to more than 70,000 animals, more than 60,000 children take advantage of its school programs each year, and each year it welcomes more than 1 million visitors from around the world.", monday_hours: "10am - 5pm", tuesday_hours: "10am - 5pm", wednesday_hours: "10am - 5pm", thursday_hours: "10am - 5pm", friday_hours: "10am - 5pm", saturday_hours: "10am - 5pm", sunday_hours: "10am - 5pm", image: "attractions/vancouver-aqua.jpg", categories: ["nature", "child-friendly"], google_place: "<KEY>", public: true, featured: true }) city1.attractions.create!({ name: "<NAME>", address: "6400 Nancy Greene Way", address_city: "North Vancouver", address_postcode: "V7R 4K9", website: "https://www.grousemountain.com/", facebook: "https://www.facebook.com/grousemountain", instagram: "https://www.instagram.com/grousemountain/", twitter: "https://twitter.com/grousemountain", description: "Rising 1,250 metres (4,100 feet) above Vancouver and just 15 minutes from the city’s downtown core, is the vast alpine playground of Grouse Mountain. The iconic Red Skyride gives visitors and locals alike the opportunity to see the jaw-dropping majestic nature of B.C. unfold in front of them during the 8 minute ride from the Valley Station to the summit.", monday_hours: "9am - 10pm", tuesday_hours: "9am - 10pm", wednesday_hours: "9am - 10pm", thursday_hours: "9am - 10pm", friday_hours: "9am - 10pm", saturday_hours: "9am - 10pm", sunday_hours: "9am - 10pm", image: "attractions/vancouver-grouse.jpg", categories: ["nature", "child-friendly", "viewpoint"], google_place: "ChIJNz7rZoVvhlQR9kZL6IxEY00", public: true, featured: true }) city1.attractions.create!({ name: "<NAME>", address: "5251 Oak St", address_city: "Vancouver", address_postcode: "V6M 4H1", website: "http://vandusengarden.org/", facebook: "https://www.facebook.com/vandusenbotanicalgarden", instagram: "https://www.instagram.com/vandusengarden/?hl=ense", twitter: "https://twitter.com/vandusengdn", description: " View across one of the ponds, to the mountains north of Vancouver Autumn colours at VanDusen Botanical Garden, 2011 In 1970 the Vancouver Foundation, the British Columbia provincial government, and the city of Vancouver signed an agreement to provide the funding to develop a public garden on part of the old Shaughnessy Golf Course.", monday_hours: "10am - 3pm", tuesday_hours: "10am - 3pm", wednesday_hours: "10am - 3pm", thursday_hours: "10am - 3pm", friday_hours: "10am - 3pm", saturday_hours: "10am - 3pm", sunday_hours: "10am - 3pm", image: "attractions/vancouver-vandusen.jpg", categories: ["nature", "child-friendly", "garden"], google_place: "ChIJwW3HeIZzhlQRVxJgWI8VjAg", public: true, featured: true }) city1.attractions.create!({ name: "<NAME>", address: "201 - 999 Canada Place", address_city: "Vancouver", address_postcode: "V6C 3E1", website: "https://www.flyovercanada.com/", facebook: "https://www.facebook.com/flyovercanada/", instagram: "https://www.instagram.com/flyovercanada/?hl=en", twitter: "https://twitter.com/FlyOverCanada", description: "FlyOver Canada utilizes state-of-the-art technology to give you the feeling of flight. You will hang suspended, feet dangling, before a 20-metre spherical screen while our film whisks you away on an exhilarating 8-minute journey across Canada, from east to west. Special effects, including wind, mist and scents, combine with the ride’s motion to create an unforgettable experience.", monday_hours: "10am - 9pm", tuesday_hours: "10am - 9pm", wednesday_hours: "10am - 9pm", thursday_hours: "10am - 9pm", friday_hours: "10am - 9pm", saturday_hours: "10am - 9pm", sunday_hours: "10am - 9pm", image: "attractions/vancouver-fly-over.jpg", categories: ["child-friendly"], google_place: "ChIJA4o63IJxhlQRw62GaRizNKQ", public: true, featured: true }) city1.attractions.create!({ name: "<NAME>", address: "555 W Hastings St", address_city: "Vancouver", address_postcode: "V6B 4N6", website: "http://vancouverlookout.com/", facebook: "http://www.facebook.com/Vancouverlookout", instagram: "https://www.instagram.com/vancouverlookout/", twitter: "http://twitter.com/VanLookout", description: "Harbour Centre and the Vancouver Lookout are part of the fabric of the city, a staple of Vancouver’s skyline since 1977 and the tallest, solely commercial building in Vancouver. The iconic ‘flying saucer’ shaped observation deck lights up at night, and during the holidays, it becomes a Christmas tree decorating the Vancouver skyline.", monday_hours: "9am - 9pm", tuesday_hours: "9am - 9pm", wednesday_hours: "9am - 9pm", thursday_hours: "9am - 9pm", friday_hours: "9am - 9pm", saturday_hours: "9am - 9pm", sunday_hours: "9am - 9pm", image: "attractions/vancouver-lookout.jpg", categories: ["child-friendly"], google_place: "Ch<KEY>", public: true, featured: true }) city1.attractions.create!({ name: "Dr. Sun Yat-Sen Classical Chinese Garden", address: "578 Carrall St", address_city: "Vancouver", address_postcode: "V6B 5K2", website: "https://vancouverchinesegarden.com/", facebook: "https://www.facebook.com/vancouverchinesegarden/", instagram: "https://www.instagram.com/vancouverchinesegarden/", twitter: "https://twitter.com/vangarden?lang=en", description: "Situated in the heart of Vancouver’s historic Chinatown neighbourhood, Dr. Sun Yat-Sen Classical Chinese Garden is an oasis of tranquility and reflection amid the bustle of urban life. Modeled after the Ming Dynasty scholars’ gardens in the city of Suzhou, it became the first authentic full-scale Chinese garden built outside of China upon its completion in April 1986.", monday_hours: "Closed", tuesday_hours: "10am - 4:30pm", wednesday_hours: "10am - 4:30pm", thursday_hours: "10am - 4:30pm", friday_hours: "10am - 4:30pm", saturday_hours: "10am - 4:30pm", sunday_hours: "10am - 4:30pm", image: "attractions/vancouver-sun-yet.jpg", categories: ["child-friendly", "garden"], google_place: "ChIJ8<KEY>", public: true, featured: true }) city1.attractions.create!({ name: "Vancouver Art Gallery", address: "750 Hornby St", address_city: "Vancouver", address_postcode: "V6Z 2H7", website: "http://www.vanartgallery.bc.ca/", facebook: "http://www.facebook.com/VancouverArtGallery", instagram: "https://instagram.com/vanartgallery", twitter: "http://twitter.com/VanArtGallery", description: "The Vancouver Art Gallery (VAG) is the fifth-largest art gallery in Canada, and the largest in Western Canada[citation needed. It is located at 750 Hornby Street in Vancouver, British Columbia. Its permanent collection of about 11,000 artworks includes more than 200 major works by <NAME>, the Group of Seven, <NAME>, <NAME> and <NAME>.", monday_hours: "10am - 5pm", tuesday_hours: "10am - 9pm", wednesday_hours: "10am - 5pm", thursday_hours: "10am - 5pm", friday_hours: "10am - 5pm", saturday_hours: "10am - 5pm", sunday_hours: "10am - 5pm", image: "attractions/vancouver-vag.jpg", categories: ["gallery"], google_place: "ChIJwXz9f39xhlQRT3qxXAPDlbU", public: true, featured: true }) city1.attractions.create!({ name: "Science World", address: "1455 Quebec St", address_city: "Vancouver", address_postcode: "V6A 3Z7", website: "https://scienceworld.ca/", facebook: "https://www.facebook.com/scienceworldca", instagram: "https://instagram.com/scienceworldca", twitter: "https://twitter.com/scienceworldca", description: "Science World at Telus World of Science, Vancouver is a science centre run by a not-for-profit organization in Vancouver, British Columbia, Canada. It is located at the end of False Creek, and features many permanent interactive exhibits and displays, as well as areas with varying topics throughout the years.", monday_hours: "Closed", tuesday_hours: "10am - 5pm", wednesday_hours: "10am - 5pm", thursday_hours: "10am - 5pm", friday_hours: "10am - 5pm", saturday_hours: "10am - 6pm", sunday_hours: "10am - 6pm", image: "attractions/vancouver-science-world.jpg", categories: ["child-friendly"], google_place: "ChIJnZHwi2NxhlQRN3CYHzc3giE", public: true, featured: true }) ## Montreal Attraction Data city2.attractions.create!({ name: "Notre-Dame Basilica of Montreal", address: "110 Notre-Dame St W", address_city: "Montreal", address_postcode: "H2Y 1T2", website: "https://www.basiliquenotredame.ca/en/", facebook: "https://www.facebook.com/Basilique-Notre-Dame-de-Montr%C3%A9al-1894117630829404/", instagram: "https://www.instagram.com/basiliquenddm/", twitter: "https://twitter.com/BasiliqueD", description: "Notre-Dame Basilica is a basilica in the historic district of Old Montreal, in Montreal, Quebec, Canada. The church is located at 110 Notre-Dame Street West, at the corner of Saint Sulpice Street. It is located next to the Saint-Sulpice Seminary and faces the Place d'Armes square.", monday_hours: "N/A", tuesday_hours: "N/A", wednesday_hours: "N/A", thursday_hours: "N/A", friday_hours: "N/A", saturday_hours: "N/A", sunday_hours: "N/A", image: "attractions/montreal_notre_dame.jpg", categories: ["historical", "museum"], google_place: "ChIJPXGXWFcayUwRqpYNHZ_v_B8", public: true, featured: true }) city2.attractions.create!({ name: "<NAME>", address: "4101 Rue Sherbrooke E", address_city: "Montreal", address_postcode: "H1X 2B2", website: "http://espacepourlavie.ca/en/botanical-garden", facebook: "https://www.facebook.com/Espacepourlavie", instagram: "https://www.instagram.com/espacepourlavie/", twitter: "https://twitter.com/espacepourlavie", description: "The Montreal Botanical Garden is a large botanical garden in Montreal, Quebec, Canada comprising 75 hectares of thematic gardens and greenhouses.", monday_hours: "Closed", tuesday_hours: "9am - 5pm", wednesday_hours: "9am - 5pm", thursday_hours: "9am - 5pm", friday_hours: "9am - 5pm", saturday_hours: "9am - 5pm", sunday_hours: "9am - 5pm", image: "attractions/montreal_botanical_garden.jpg", categories: ["garden"], google_place: "ChIJx4O-WgkcyUwRc3W0WQK-oUI", public: true, featured: true }) city2.attractions.create!({ name: "The Montreal Museum of Fine Arts", address: "1380 Rue Sherbrooke W", address_city: "Montreal", address_postcode: "H3G 1J5", website: "https://www.mbam.qc.ca/en/", facebook: "https://www.facebook.com/mbamtl", instagram: "https://www.instagram.com/mbamtl/", twitter: "https://twitter.com/mbamtl", description: "The Montreal Museum of Fine Arts is an art museum in Montreal, Quebec, Canada. It is the city's largest museum and is amongst the most prominent in Canada. The museum is located on the historic Golden Square Mile stretch of Sherbrooke Street.", monday_hours: "Closed", tuesday_hours: "10am - 5pm", wednesday_hours: "10am - 9pm", thursday_hours: "10am - 5pm", friday_hours: "10am - 5pm", saturday_hours: "10am - 5pm", sunday_hours: "10am - 5pm", image: "attractions/montreal_museum_of_fine_arts.jpg", categories: ["museum"], google_place: "ChIJZcCSF0AayUwRsDVrEHZsydY", public: true, featured: true }) city2.attractions.create!({ name: "Saint Joseph's Oratory of Mount Royal", address: "3800 Queen Mary Rd", address_city: "Montreal", address_postcode: "H3V 1H6", website: "https://www.saint-joseph.org/en/", facebook: "https://www.facebook.com/osaintjoseph/", instagram: "https://www.instagram.com/osjmr/", twitter: "https://twitter.com/osjmr", description: "Saint Joseph's Oratory of Mount Royal is a Roman Catholic minor basilica and national shrine on Mount Royal's Westmount Summit in Montreal, Quebec. It is Canada's largest church and claims to have one of the largest domes in the world.", monday_hours: "N/A", tuesday_hours: "N/A", wednesday_hours: "N/A", thursday_hours: "N/A", friday_hours: "N/A", saturday_hours: "N/A", sunday_hours: "N/A", image: "attractions/montreal-st-joesephs.jpg", categories: ["historical", "museum"], google_place: "ChIJad-yd_oZyUwRQ20Rv84PQ0o", public: true, featured: true }) city2.attractions.create!({ name: "Biosphere Environmental Museum", address: "160 Chemin du Tour de l'isle", address_city: "Montreal", address_postcode: "H3C 4G8", website: "https://www.canada.ca/en/environment-climate-change/services/biosphere.html", facebook: "https://www.facebook.com/biospheremtl/", instagram: "https://www.instagram.com/parcjeandrapeau/", twitter: "https://twitter.com/biospheremtl", description: "The Biosphere is a museum dedicated to the environment. It is located at <NAME>, on Saint Helen's Island in the former pavilion of the United States for the 1967 World Fair, Expo 67 in Montreal, Quebec, Canada. The museum's geodesic dome was designed by <NAME>.", monday_hours: "Closed", tuesday_hours: "Closed", wednesday_hours: "10am - 5pm", thursday_hours: "10am - 5pm", friday_hours: "10am - 5pm", saturday_hours: "10am - 5pm", sunday_hours: "10am - 5pm", image: "attractions/montreal-biosphere.jpg", categories: ["museum", "garden"], google_place: "ChIJscEBsAgbyUwRKVqf-G_mDi0", public: true, featured: true }) city2.attractions.create!({ name: "<NAME>", address: "859 Sherbrooke St W", address_city: "Montreal", address_postcode: "H3A 0C4", website: "https://www.mcgill.ca/redpath/", facebook: "https://www.facebook.com/RedpathMuseum/", instagram: "https://www.instagram.com/explore/locations/171558/musee-redpath-museum/", twitter: "https://twitter.com/redpathmuseum", description: "The Redpath Museum is a museum of natural history belonging to McGill University and located on the university's campus at 859 Sherbrooke Street West in Montreal, Quebec. It was built in 1882 as a gift from the sugar baron <NAME>.", monday_hours: "9am - 5pm", tuesday_hours: "9am - 5pm", wednesday_hours: "9am - 5pm", thursday_hours: "9am - 5pm", friday_hours: "9am - 5pm", saturday_hours: "11am - 5pm", sunday_hours: "11am - 5pm", image: "attractions/montreal-red-path.jpg", categories: ["museum"], google_place: "ChIJewCbJ0cayUwRkk-dMZ99ir4", public: true, featured: true }) city2.attractions.create!({ name: "<NAME>", address: "4141 Pierre-de Coubertin Ave", address_city: "Montreal", address_postcode: "H1V 3N7", website: "https://parcolympique.qc.ca/en/what-to-do/olympic-stadium/", facebook: "https://www.facebook.com/parcolympiquemontreal/", instagram: "https://www.instagram.com/parcolympique/", twitter: "https://twitter.com/parcolympique", description: "The Olympic Park is a district in Montreal, Quebec, Canada, which was home to many of the venues from the 1976 Summer Olympics. It is bound by Sherbrooke Street to the west, Viau Street to the north, Pierre de Coubertin Avenue to the east, and Pie-IX Boulevard to the south.", monday_hours: "N/A", tuesday_hours: "N/A", wednesday_hours: "N/A", thursday_hours: "N/A", friday_hours: "N/A", saturday_hours: "N/A", sunday_hours: "N/A", image: "attractions/montreal-parc-olympique.jpg", categories: ["viewpoint"], google_place: "ChIJW7Yg-QocyUwRz9D3Is02NQ4", public: true, featured: true }) city2.attractions.create!({ name: "Underground City", address: "747 Rue du Square-Victoria", address_city: "Montreal", address_postcode: "H2Y 3Y9", website: "https://montrealundergroundcity.com/", facebook: "https://www.facebook.com/MontrealUndergroundCity/", instagram: "https://www.instagram.com/explore/tags/montrealundergroundcity/?hl=en", twitter: "https://twitter.com/mtl_souterrain?lang=en", description: "RÉSO, commonly referred to as The Underground City (French: La ville souterraine), is the name applied to a series of interconnected office towers, hotels, shopping centres, residential and commercial complexes, convention halls, universities and performing arts venues that form the heart of Montreal's central business district.", monday_hours: "10am - 9pm", tuesday_hours: "10am - 9pm", wednesday_hours: "10am - 9pm", thursday_hours: "10am - 9pm", friday_hours: "10am - 9pm", saturday_hours: "10am - 6pm", sunday_hours: "10am - 5pm", image: "attractions/montreal-RESO.jpg", categories: ["shopping"], google_place: "ChIJZcWSvUQayUwRXr2czLB1oEA", public: true, featured: true }) city2.attractions.create!({ name: "<NAME>", address: "138 Atwater Ave", address_city: "Montreal", address_postcode: "H4C 2H6", website: "https://www.marchespublics-mtl.com/en/marches/atwater-market/", facebook: "https://www.facebook.com/mpmontreal", instagram: "https://www.instagram.com/marchespublicsmtl/", twitter: "https://twitter.com/MarchePublicMtl", description: "Atwater Market is a market hall located in the Saint-Henri area of Montreal, Quebec, Canada. It opened in 1933. The interior market is home to many butchers and the Première Moisson bakery and restaurant.", monday_hours: "8am - 6pm", tuesday_hours: "8am - 6pm", wednesday_hours: "8am - 6pm", thursday_hours: "8am - 7pm", friday_hours: "8am - 8pm", saturday_hours: "8am - 5pm", sunday_hours: "8am - 5pm", image: "attractions/montreal-atwater.jpg", categories: ["shopping"], google_place: "ChIJD9akWHgayUwRy9872P6KvJA", public: true, featured: true }) ## London Attraction Data city3.attractions.create!({ name: "<NAME>", address: "Westminster", address_city: "London", address_postcode: "SW1A 0AA", website: "https://www.parliament.uk/bigben", facebook: "https://www.facebook.com/ukparliament/", instagram: "https://www.instagram.com/ukparliament/", twitter: "https://twitter.com/ukparliament?lang=en", description: " <NAME> is the nickname for the Great Bell of the clock at the north end of the Palace of Westminster in London and is usually extended to refer to both the clock and the clock tower. The official name of the tower in which <NAME> is located was originally the Clock Tower, but it was renamed Elizabeth Tower in 2012 to mark the Diamond Jubilee of Elizabeth II.", monday_hours: "N/A", tuesday_hours: "N/A", wednesday_hours: "N/A", thursday_hours: "N/A", friday_hours: "N/A", saturday_hours: "N/A", sunday_hours: "N/A", image: "attractions/London-BigBen.jpg", categories: ["historical", "monument", "child-friendly"], google_place: "ChIJ2dGMjMMEdkgRqVqkuXQkj7c", public: true, featured: true }) city3.attractions.create!({ name: "<NAME>", address: "Westminster", address_city: "London", address_postcode: "SW1A 1AA", website: "https://www.rct.uk/visit/the-state-rooms-buckingham-palace", facebook: "https://www.facebook.com/royalcollectiontrust/", instagram: "https://www.instagram.com/royalcollectiontrust/?hl=en", twitter: "https://twitter.com/rct?lang=en", description: "Buckingham Palace is the London residence and administrative headquarters of the monarch of the United Kingdom. Located in the City of Westminster, the palace is often at the centre of state occasions and royal hospitality. It has been a focal point for the British people at times of national rejoicing and mourning.", monday_hours: "9am - 7.30pm", tuesday_hours: "9am - 7.30pm", wednesday_hours: "9am - 7.30pm", thursday_hours: "9am - 7.30pm", friday_hours: "9am - 7.30pm", saturday_hours: "9am - 7.30pm", sunday_hours: "9am - 7.30pm", image: "attractions/london-buck-palace.jpg", categories: ["historical", "child-friendly"], google_place: "ChIJtV5bzSAFdkgRpwLZFPWrJgo", public: true, featured: true }) city3.attractions.create!({ name: "<NAME>", address: "Lambeth", address_city: "London", address_postcode: "SE1 7PB", website: "https://www.londoneye.com/", facebook: "https://www.facebook.com/OfficialLondonEye/", instagram: "https://www.instagram.com/londoneye/", twitter: "https://twitter.com/TheLondonEye", description: "The structure is 135 metres (443 ft) tall and the wheel has a diameter of 120 metres (394 ft). When it opened to the public in 2000 it was the world's tallest Ferris wheel. Supported by an A-frame on one side only, the Eye is described by its operators as the world's tallest cantilevered observation wheel.", monday_hours: "10am - 7.30pm", tuesday_hours: "10am - 7.30pm", wednesday_hours: "10am - 7.30pm", thursday_hours: "10am - 7.30pm", friday_hours: "10am - 7.30pm", saturday_hours: "10am - 7.30pm", sunday_hours: "10am - 7.30pm", image: "attractions/london-eye.jpg", categories: ["viewpoint", "child-friendly"], google_place: "ChIJc2nSALkEdkgRkuoJJBfzkUI", public: true, featured: true }) city3.attractions.create!({ name: "<NAME>", address: "St Katharine's & Wapping", address_city: "London", address_postcode: "EX3N 4AB", website: "https://www.hrp.org.uk/tower-of-london/", facebook: "https://www.facebook.com/toweroflondon/", instagram: "https://www.instagram.com/historicroyalpalaces/", twitter: "https://twitter.com/TowerOfLondon", description: "The Tower of London, officially Her Majesty's Royal Palace and Fortress of the Tower of London, is a historic castle located on the north bank of the River Thames in central London.", monday_hours: "10am - 4:30pm", tuesday_hours: "9am - 4:30pm", wednesday_hours: "9am - 4:30pm", thursday_hours: "9am - 4:30pm", friday_hours: "9am - 4:30pm", saturday_hours: "9am - 4:30pm", sunday_hours: "10am - 4:30pm", image: "attractions/london-tower-of-london.jpg", categories: ["historical", "child-friendly"], google_place: "ChIJ3TgfM0kDdkgRZ2TV4d1Jv6g", public: true, featured: true }) city3.attractions.create!({ name: "<NAME>", address: "Tower Bridge Road", address_city: "London", address_postcode: "SE1 2UP", website: "https://www.towerbridge.org.uk/", facebook: "https://www.facebook.com/towerbridge/", instagram: "https://www.instagram.com/towerbridge/?hl=en", twitter: "https://twitter.com/TowerBridge?ref_src=twsrc%5Egoogle%7Ctwcamp%5Eserp%7Ctwgr%5Eauthor", description: "Tower Bridge is a combined bascule and suspension bridge in London built between 1886 and 1894. The bridge crosses the River Thames close to the Tower of London and has become an iconic symbol of London. Because of this, Tower Bridge is sometimes confused with London Bridge.", monday_hours: "9am - 5pm", tuesday_hours: "9am - 5pm", wednesday_hours: "9am - 5pm", thursday_hours: "9am - 5pm", friday_hours: "9am - 5pm", saturday_hours: "9am - 5pm", sunday_hours: "10am - 4:30pm", image: "attractions/london-tower-bridge.jpg", categories: ["historical", "viewpoint", "child-friendly"], google_place: "<KEY>", public: true, featured: true }) city3.attractions.create!({ name: "<NAME>", address: "Great Russell Street, Bloomsbury", address_city: "London", address_postcode: "WC1B 3DG", website: "https://www.britishmuseum.org/", facebook: "https://www.facebook.com/britishmuseum/", instagram: "https://www.instagram.com/britishmuseum/", twitter: "https://twitter.com/britishmuseum", description: "The British Museum, located in the Bloomsbury area of London, in the United Kingdom, is a public institution dedicated to human history, art and culture. Its permanent collection numbers some 8 million works, and is among the largest and most comprehensive in existence having been widely sourced during the era of the British Empire.", monday_hours: "10am - 5:30pm", tuesday_hours: "10am - 5:30pm", wednesday_hours: "10am - 5:30pm", thursday_hours: "10am - 5:30pm", friday_hours: "10am - 8:30pm", saturday_hours: "10am - 5:30pm", sunday_hours: "10am - 5:30pm", image: "attractions/london-british-musuem.jpg", categories: ["historical", "child-friendly", "museum"], google_place: "ChIJB9OTMDIbdkgRp0JWbQGZsS8", public: true, featured: true }) city3.attractions.create!({ name: "<NAME>", address: "20 Deans Yard, Westminster", address_city: "London", address_postcode: "SW1P 3PA", website: "https://www.westminster-abbey.org/", facebook: "https://www.facebook.com/WestminsterAbbeyLondon/", instagram: "https://www.instagram.com/westminsterabbeylondon/", twitter: "https://twitter.com/wabbey", description: "Westminster Abbey, formally titled the Collegiate Church of St Peter at Westminster, is a large, mainly Gothic abbey church in the City of Westminster, London, England, just to the west of the Palace of Westminster.", monday_hours: "9am - 3:30pm", tuesday_hours: "9am - 3:30pm", wednesday_hours: "9am - 6pm", thursday_hours: "9am - 3:30pm", friday_hours: "10am - 8:30pm", saturday_hours: "9am - 1:30pm", sunday_hours: "Closed", image: "attractions/london-westminster-abbey.jpg", categories: ["historical", "child-friendly"], google_place: "ChIJRUeRWcMEdkgRAO7ZzLCgDXA", public: true, featured: true }) city3.attractions.create!({ name: "<NAME>", address: "St. Paul's Churchyard", address_city: "London", address_postcode: "EC4M 8AD", website: "https://www.stpauls.co.uk/", facebook: "https://www.facebook.com/stpaulscathedral", instagram: "https://www.instagram.com/stpaulscathedrallondon/", twitter: "https://twitter.com/StPaulsLondon", description: "St Paul's Cathedral, London, is an Anglican cathedral, the seat of the Bishop of London and the mother church of the Diocese of London. It sits on Ludgate Hill at the highest point of the City of London and is a Grade I listed building.", monday_hours: "8:30am - 4:30pm", tuesday_hours: "8:30am - 4:30pm", wednesday_hours: "8:30am - 4:30pm", thursday_hours: "8:30am - 4:30pm", friday_hours: "8:30am - 4:30pm", saturday_hours: "8:30am - 4:30pm", sunday_hours: "Closed", image: "attractions/london-st-pauls.jpg", categories: ["historical", "viewpoint", "child-friendly", "monument"], google_place: "ChIJh7wHoqwEdkgR3l-vqQE1HTo", public: true, featured: true }) city3.attractions.create!({ name: "The Shard (The View)", address: "32 London Bridge Street", address_city: "London", address_postcode: "SE1 9SG", website: "https://www.theviewfromtheshard.com/", facebook: "https://www.facebook.com/TheShardLondon/", instagram: "https://www.instagram.com/shardview/", twitter: "https://twitter.com/TheShardLondon", description: "The Shard, also infrequently referred to as the Shard of Glass, Shard London Bridge and formerly London Bridge Tower, is a 95-story supertall skyscraper, designed by the Italian architect Renzo Piano, in Southwark, London, that forms part of the Shard Quarter development.", monday_hours: "10am - 8pm", tuesday_hours: "10am - 8pm", wednesday_hours: "10am - 8pm", thursday_hours: "10am - 10pm", friday_hours: "10am - 10pm", saturday_hours: "10am - 10pm", sunday_hours: "10am - 8pm", image: "attractions/london-the-shard.jpg", categories: ["viewpoint", "child-friendly"], google_place: "ChIJ03GSCloDdkgRe_s-p2vyvQA", public: true, featured: true }) # USERS puts "Creating users..." 60.times do |i| User.create({ first_name: Faker::Name.first_name, last_name: Faker::Name.last_name, email: Faker::Internet.email, password: '<PASSWORD>', password_confirmation: '<PASSWORD>' }) end User.create({ first_name: 'Gio', last_name: 'R', email: '<EMAIL>', password: '<PASSWORD>', password_confirmation: '<PASSWORD>' }) # REVIEWS puts "Creating reviews..." 100.times do |i| Review.create({ user_id: rand(1..61), attraction_id: rand(1..27), review: Faker::VentureBros.quote, rating: rand(1..5) }) end # TRIPS puts "Creating trips..." 5.times do |i| Trip.create({ name: Faker::VentureBros.organization, start_date: Faker::Date.between(60.days.ago, 30.days.ago), end_date: Faker::Date.between(29.days.ago, Date.today), public: true, featured: true }) end # USER_TRIPS puts "Linking trips to test user..." 5.times do |i| UserTrip.create({ user_id: 61, trip_id: rand(1..5), role: 'creator' }) end # ITINERARIES puts "Creating itineraries..." 15.times do |i| Itinerary.create({ name: Faker::HeyArnold.location, date: Faker::Date.between(60.days.ago, 30.days.ago), notes: Faker::HeyArnold.quote, public: true, featured: false, trip_id: rand(1..5) }) end puts "Seed complete." <file_sep>class Attraction < ApplicationRecord belongs_to :city has_many :reviews end <file_sep>class InvitesController < ApplicationController def create @invite = Invite.new(invite_params) if @invite.save redirect_to trip_path(@invite.trip_id) if @invite.recipient != nil InviteMailer.existing_user_invite(@invite).deliver UserTrip.create({user_id: @invite.recipient, trip_id: @invite.trip_id, role: 'contributor'}) else InviteMailer.register_invite(@invite).deliver end else # oh no, creating an new invitation failed end end def new @invite = Invite.new @trip = Trip.find_by_id(params[:id]) end def show end private def invite_params params.require(:invite).permit( :recipient, :email, :message, :trip_id, :sender, :token ) end end <file_sep>GOOGLE_API: "" SENDGRID_API_KEY: ""<file_sep>class ItineraryItem < ApplicationRecord belongs_to :itinerary belongs_to :attraction, optional: true validates_presence_of :start_time, :end_time validate :end_after_start after_create -> { ItineraryChannel.broadcast_to(self.itinerary, {created_itinerary_item: self.id}) ItineraryItemChannel.broadcast_to(self, {created: self.id}) } after_update -> { ItineraryItemChannel.broadcast_to(self, {updated: self.id}) } after_destroy -> { ItineraryItemChannel.broadcast_to(self, {destroyed: self.id}) } private def end_after_start return if end_time.blank? || start_time.blank? if end_time < start_time errors.add(:end_time, "must be after the start date") end end end
768baf8aadadb83dd0321bf2acac620e31015505
[ "Markdown", "Ruby" ]
44
Ruby
ratofkryll/tripper
0358a3b435f19c4969255d4b857865247d0e59be
09011b16551bd7e1906493adee6a575f116e364f
refs/heads/master
<repo_name>ChrBlaes/Impr<file_sep>/opgave 11 s 125 pythagoras.c #include <stdio.h> #include <stdlib.h> #include <math.h> int main(void){ double n = 0.0; double m = 0.0; double side1 = 0.0; double side2 = 0.0; double hypo = 0.0; int res; printf("please enter value\n"); res = scanf("%lf, %lf\n", &m, &n); printf("%d\n",res); side1 = (m * m) - (n * n); side2 = 2 * m * n; hypo = (m * m) + (n * n); printf("side1 is equal to %lf\n, side2 is equal to %lf\n, hypo is equal to %lf\n",side1, side2, hypo); return EXIT_SUCCESS; } <file_sep>/græsslåning.c #include <stdio.h> #include <stdlib.h> #define SPEED 2 #define SEC_PR_HOUR 3600 int main(void){ double lenght_garden = 0.0; double wide_garden = 0.0; double lenght_house = 0.0; double wide_house = 0.0; /*Tid taget fra tid aflevering*/ int sec, min, hours, days, weeks; double square_meter_garden = 0.0; double square_meter_house = 0.0; double square_meter_grass = 0.0; int time_to_cut = 0.0; printf("Please inset lenght and wide of garden\n"); scanf(" %lf, %lf",&lenght_garden, &wide_garden); printf("Please inset lenght and wide of house\n"); scanf(" %lf, %lf",&lenght_house, &wide_house); square_meter_garden = (lenght_garden*wide_garden); square_meter_house = (lenght_house*wide_house); square_meter_grass = ((square_meter_garden)-(square_meter_house)); time_to_cut = (square_meter_grass)/(SPEED); sec = time_to_cut; weeks = sec / (SEC_PR_HOUR*24*7); /*restværdien af sec samt den nye sec bliver beregnet såles*/ sec = sec % (SEC_PR_HOUR*24*7); /*hvor mange gange går sec op i day*/ days = sec / (SEC_PR_HOUR*24); /*restværdien af sec samt den nye sec bliver beregnet såles*/ sec = sec % (SEC_PR_HOUR*24); /*hvor mange gange går sec op i Hours*/ hours = sec / (SEC_PR_HOUR); /*restværdien af sec samt den nye sec bliver beregnet såles*/ sec = sec % (SEC_PR_HOUR); /*hvor mange gange går sec op i min*/ min = sec / 60; /*restværdien af sec samt den nye sec bliver beregnet såles*/ sec = sec % 60; printf("%f square_meter_garden,\n%f square_meter_house,\n%f square_meter_grass\n%d time_to_cut,\n%d weeks,%d days, %d hours, %d min, %d sec",square_meter_garden, square_meter_house, square_meter_grass, time_to_cut, weeks, days, hours, min, sec); return EXIT_SUCCESS; } <file_sep>/inde_ude_cirkel.c #include <stdio.h> #include <stdlib.h> #include <math.h> #define PI 3.141592 int main(void){ double r = 0; double x = 0; double y = 0; double circumference = (r*r*PI); printf("Please insert radius of circle\n"); scanf(" %lf", &r); printf("Please insert x and y kordinates\n"); scanf("%lf, %lf",&x,&y); if (((x*x)+(y*y))==(r*r)){ printf("The point is on the circumference\n");} else if (((x*x)+(y*y))<(r*r)) { printf("The point in inside the circle\n"); } else if (((x*x)+(y*y))>(r*r)) { printf("The point is outside the circle\n");} return EXIT_SUCCESS; } <file_sep>/phværdi.c #include <stdio.h> #include <stdlib.h> int main(void){ int yes = 1; int yes_<12; int no_<12; int user_responce = 0; printf("Is pH>7?\n 1=yes\n 0=no"); scanf("%d",user_responce); if (user_responce) { printf("Is pH<12?\n");} else (!user_responce){ printf("awesomeness\n"); } } <file_sep>/trekant.c #include <stdio.h> #include <stdlib.h> #include <math.h> #define CONSTANT_IMPUT 1 #define DELTA 0.0000001 int main(void){ double p1_x = 0.0, p1_y = 0.0; double p2_x = 0.0, p2_y = 0.0; double p3_x = 0.0, p3_y = 0.0; double circumference = 0.0; double hc = 0.0, area = 0.0; double length_p1_p2 = 0.0; double length_p2_p3 = 0.0; double length_p3_p1 = 0.0; int choice = 0, Iís_triangle = 0; if (CONSTANT_IMPUT){ p1_x = 0; p1_y = 0; p2_x = 5; p2_y = 0; p3_x = 0; p3_y = 5; } else { printf("%s\n", "please enter a point: (x,y)\n" ); scanf(" (%lf , %lf)", &p1_x, &p1_y); printf("point: (%lf, %lf)\n\n", p1_x, p1_y) ; printf("%s\n", "please enter a point: (x,y)\n" ); scanf(" (%lf , %lf)", &p2_x, &p2_y); printf("point: (%lf, %lf)\n\n", p2_x, p2_y) ; printf("%s\n", "please enter a point: (x,y)\n" ); scanf(" (%lf , %lf)", &p3_x, &p3_y); printf("point: (%lf, %lf)\n\n", p3_x, p3_y) ; p1_p2_equals = fabs(p1_x - p2_x) < Delta && fabs(p1_y - p2_y) < DELTA; p1_p2p1_p2_different = !p1_p2_equals; all_points_different = p1_p2_different && p2_p3_different && p3_p1 different; is_triangle = all_points_different && !vertically_aligned && !horizontally_aligned && !aligned if (Iís_triangle){ /* circumference */ length_p1_p2 = sqrt((p1_x - p2_x) * (p1_x - p2_x) + (p1_y - p2_y) * (p1_y - p2_y)); length_p2_p3 = sqrt((p2_x - p3_x) * (p2_x - p3_x) + (p2_y - p3_y) * (p2_y - p3_y)); length_p3_p1 = sqrt((p3_x - p1_x) * (p3_x - p1_x) + (p3_y - p1_y) * (p3_y - p1_y)); /*Precalculations: */ printf("Your choice: Area (1), circumference (2), Equilateral? (3)\n", ); scanf(" &d", &choice ); switch(choice) { case 1: { hc = circumference / 2; area = sqrt(hc * (hc - length_p1_p2) * (hc - length_p2_p3) * (hc - length_p3_p1)); printf("area: %lf\n", area ); break; } case 2: { printf("circumference: %lf/n", circumference); break; } case 3: { int Equilateral = length_p1_p2 == length_p2_p3 && length_p2_p3 == length_p3_p1; printf("The triangle is %s equilateral\n", Equilateral ? "" : "NOT" ); break; } default: { printf("Should not happen. Bye bye\n"); exit(EXIT_FAILURE) } } } else { printf("Not a triangle\n"); exit(EXIT_FAILURE); } return EXIT_SUCCESS; }
32036e808dbae1574c86269d37e9357115fdfcca
[ "C" ]
5
C
ChrBlaes/Impr
3d77e018ea93804161149915062e0b82ed5d2d63
3adb6a45dbd27eeea400976dc797ff26f90e3e18
refs/heads/master
<repo_name>seasonJIE/react-test<file_sep>/src/container/register/register.js import React from 'react' import {connect} from 'react-redux' class Register extends React.Component { constructor(props) { super(props) this.state = { username: '', password: '', other: '' } } login() { this.props.history.push('/login') } handleChange(key, val) { this.setState({ [key]: val.target.value }) } handleClick() { console.log(this.props) } componentDidMount() { console.log(this.props) } render() { return ( <div> <h2>注册页{this.props.count}and{this.props.match.params.id}</h2> 用户名:<input onChange={v => this.handleChange('username', v)} /> 密码:<input /> 备注:<input /> <button onClick={() => { this.login() }}>登陆</button> <button onClick={() => { this.handleClick()}}>注册</button> </div> ) } } Register =connect(state=>state.userinfo)(Register) export default Register<file_sep>/src/redux/reducers/user.js import * as types from '../actions_type/userAction_type' const initState = { count: 10, list: [ { num: 1 }, { num: 11 }, { num: 13 }, { num: 61 }, { num: 17 } ] } export function userinfo(state = initState, action) { switch (action.type) { case types.ADD: return { ...state, count: state.count + 1 } case types.ADDLIST: let newList = [] newList.push(...state.list) newList.push({ num: action.username }) return { ...state, list: newList } default: return state } }<file_sep>/src/container/login/login.js import React from 'react' import { connect } from 'react-redux' import { add,addList } from '../../redux/actions/userAction' import '../../style.css' class Login extends React.Component { constructor(props) { super(props) this.state = { checked: null, selected: null, } } componentWillMount() { this.setState({ list: this.props.list }) } enter() { this.props.add(this.state.username, this.state.password) // console.log(this.props.store) } register() { this.props.history.push('/register') } handleChange(key, val) { this.setState({ [key]: val.target.value }) } addList() { this.props.addList(this.state.username) } selected(index) { this.setState({ 'checked': index }) } checked(value) { if (typeof (value.checked) === undefined) { value.checked = true } else { value.checked = !value.checked } this.setState({}) console.log(this.state) } render() { const count = this.props.count const list = this.state.list return ( <div> <h2>登陆页{count}</h2> <input type='text' onChange={e => { this.handleChange('username', e) }} /> <input type='password' onChange={e => { this.handleChange('password', e) }} /> <button onClick={() => { this.enter() }} >登陆</button> <button onClick={() => { this.register() }}>注册</button> <button onClick={this.props.add}>add</button> <button onClick={() => this.addList()}>addList</button> <div> {this.props.list.map((value, index) => <p key={index} className={`select ${this.state.checked === index ? 'checked' : ''}`} onClick={() => this.selected(index)} >{value.num}</p> )} <hr /> {list.map((value, index) => <p key={index} className={`select ${value.checked === true ? 'checked' : ''}`} onClick={() => this.checked(value)} >{value.num}</p> )} <hr /> <p className={`select ${this.state.selected === 1 ? 'checked' : ''}`} onClick={() => this.setState({ selected: 1 })}>12</p> <p className={`select ${this.state.selected === 2 ? 'checked' : ''}`} onClick={() => this.setState({ selected: 2 })}>132</p> <p className={`select ${this.state.selected === 3 ? 'checked' : ''}`} onClick={() => this.setState({ selected: 3 })}>142</p> <hr /> </div> </div> ) } } Login = connect(state => state.userinfo, { add, addList })(Login) export default Login<file_sep>/src/redux/reducers.js import { combineReducers } from 'redux' // import { userinfo } from './user.redux' import {userinfo} from './reducers/user' export default combineReducers({ userinfo })<file_sep>/src/index.js import React from 'react' import ReactDOM from 'react-dom' import { createStore } from 'redux' import { Provider } from 'react-redux' import { BrowserRouter, Route, Redirect, Switch } from 'react-router-dom' import Register from './container/register/register'; import Login from './container/login/login'; import reducers from './redux/reducers' const store = createStore(reducers) ReactDOM.render( (<Provider store={store}> <BrowserRouter> <div> <Switch> <Route path='/login' exact component={Login} > </Route> <Route path='/register' exact component={Register} ></Route> <Route path='/register/:id' component={Register} ></Route> <Redirect to='/login' exact ></Redirect> </Switch> </div> </BrowserRouter> </Provider>), document.getElementById('root') ); // function render() { // ReactDOM.render( // (<Login store={store} add={add}></Login>), // document.getElementById('root') // ); // } // render() // store.subscribe(render)
896fbaa66dc20655de316114291b8c8a2607eed8
[ "JavaScript" ]
5
JavaScript
seasonJIE/react-test
7554047a2394f9b5c481f844f0f0bb19a9bc052c
b04635fa378026040217151807863d91199b4265
refs/heads/main
<repo_name>purkonuddin/restfullApi-kampus<file_sep>/src/controllers/dosenControllers.js require('dotenv').config() const dosenModel = require('../models/dosenModel') const jwt = require('jsonwebtoken') const async = require('async') const helpers = require('../helpers/response') const GetDataDosen = async (req, res, next) => { try { const userId = req.userData.user_id const [results] = await Promise.all([ dosenModel.getProfile(userId) ]) console.log('GetDataDosen',results[0]); req.body.object = 'user' req.body.action = 'get my profile data' req.dosenProfile = results[0] next() } catch (error) { console.log(error) } } module.exports = { getDataDosen: GetDataDosen }<file_sep>/src/models/dosenModel.js require('dotenv').config() const db = require('../configs/db') const GetProfile = (data) => { return new Promise((resolve, reject) => { const qry1 = `SELECT * FROM kampus.dosen WHERE nidn = '${data}'`; db.query(`${qry1}`, (error, result) => { if (!error) { resolve(result) } else { reject(new Error(error)) } }) }) } module.exports = { getProfile: GetProfile }<file_sep>/src/models/usersModel.js require('dotenv').config() const db = require('../configs/db') const Insertuser = (data) => { return new Promise((resolve, reject) => { db.query(`INSERT INTO kampus.users (user_id, email, password, role) VALUES ('${data.user_id}','${data.email}', '${data.password}', '${data.role}')`, (error, result) => { if (!error) { resolve(result) } else { reject(new Error(error)) } }) }) } const Insertdosen = (data) => { return new Promise((resolve, reject) => { db.query(`INSERT INTO kampus.dosen (nidn, nama) VALUES ('${data.user_id}', '${data.nama}')`, (error, result) => { if (!error) { resolve(result) } else { reject(new Error(error)) } }) }) } const Insertmhs = (data) => { return new Promise((resolve, reject) => { db.query(`INSERT INTO kampus.mahasiswa (nim, nama, alamat, tanggal_lahir, jurusan) VALUES ('${data.user_id}', '${data.nama}', '${data.alamat}', '${data.tanggal_lahir}', '${data.jurusan}')`, (error, result) => { if (!error) { resolve(result) } else { reject(new Error(error)) } }) }) } const Insertuserdosen = (data) => { return new Promise((resolve, reject) => { db.query(`BEGIN; INSERT INTO kampus.users (user_id, email, password, role) VALUES ('${data.user_id}','${data.email}', '${data.password}', '${data.role}'); INSERT INTO kampus.dosen (nidn, nama) VALUES ('${data.user_id}', '${data.name}'); COMMIT;`, (error, result) => { if (!error) { resolve(result) } else { reject(new Error(error)) } }) }) } const Insertusermhs = (data) => { return new Promise((resolve, reject) => { const qry1 = 'BEGIN'; const qry2 = ` INSERT INTO kampus.users (user_id, email, password, role) VALUES ('${data.user_id}','${data.email}', '${data.password}', '${data.role}')` const qry3 = ` INSERT INTO kampus.mahasiswa (nim, nama, alamat, tanggal_lahir, jurusan) VALUES ('${data.user_id}', '${data.nama}', '${data.alamat}', '${data.tanggal_lahir}', '${data.jurusan}')` const qry4 = ' COMMIT'; db.query(`${qry1} ${qry2} ${qry3} ${qry4}`, (error, result) => { if (!error) { resolve(result) } else { reject(new Error(error)) } }) }) } const Login = (email, role) => { if(role === 'dosen') { return new Promise((resolve, reject) => { db.query(`Select u.user_id, u.email, u.password, u.role, d.nama, d.nidn from users u inner join dosen d on u.user_id = d.nidn WHERE u.email = '${email}'`, (error, result) => { if (!error) { resolve(result) } else { reject(new Error(error)) } }) }) } if (role === 'mahasiswa') { return new Promise((resolve, reject) => { db.query(`Select u.user_id, u.email, u.password, u.role, m.nama, m.alamat, m.tanggal_lahir, m.jurusan, m.nim, Date_format( From_Days( To_Days(Curdate()) - To_Days(m.tanggal_lahir) ), '%Y' ) + 0 AS umur from users u inner join mahasiswa m on u.user_id = m.nim WHERE u.email = '${email}'`, (error, result) => { if (!error) { resolve(result) } else { reject(new Error(error)) } }) }) } } module.exports = { insertuser: Insertuser, insertmhs: Insertmhs, insertdosen: Insertdosen, insertusermhs: Insertusermhs, insertuserdosen: Insertuserdosen, login: Login }<file_sep>/src/helpers/usersMidleware.js const response = require('./response') const jwt = require('jsonwebtoken') const regexEmail = /^\w+([.-]?\w+)*@\w+([.-]?\w+)*(\.\w{2,3})+$/ const regexPassword = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{5,}$/ const regexField = /^\w+([ ]?\w+)+$/ const ValidateRegister = (req, res, next) => { const validateEmailReg = regexEmail.test(req.body.email) const validateStringReg = regexField.test(req.body.nama) const validatePasswordReg = regexPassword.test(req.body.password) const {password, email, nama, role, alamat, tanggal_lahir, jurusan} = req.body if (!nama || nama.length < 3 || !validateStringReg) { response.customErrorResponse(res, 400, 'Please enter a name with min. 3 chars without single quote') } else if (!email || !validateEmailReg) { response.customErrorResponse(res, 400, 'Please enter a valid email') } else if (!password || !validatePasswordReg) { response.customErrorResponse(res, 400, 'gunakan alpha numeric, 1 uppercase, 1 lowercase, min 6 character') } else if (!role) { response.customErrorResponse(res, 400, 'role "dosen/mahasiswa"') } else if (role === 'mahasiswa' && (!alamat || alamat.length < 5 || alamat.length > 255)) { response.customErrorResponse(res, 400, 'Please enter valid alamat') } else if (role === 'mahasiswa' && (!tanggal_lahir && tanggal_lahir instanceof Date && !isNaN(tanggal_lahir.valueOf()))) { response.customErrorResponse(res, 400, 'Please enter a valid birth date') } else if (role === 'mahasiswa' && (!jurusan)) { response.customErrorResponse(res, 400, 'this fiel is required') } else { next() } }; const ValidateLogin = (req, res, next) => { const {email, password} = req.body const validateEmailReg = regexEmail.test(email) if (!email || !validateEmailReg) { response.customErrorResponse(res, 400, 'Please enter a valid email') } if (!password) { response.customErrorResponse(res, 400, 'Please enter a valid password') } next() }; module.exports = { validateRegister: ValidateRegister, validateLogin: ValidateLogin }<file_sep>/src/models/nilaiModel.js require('dotenv').config() const db = require('../configs/db') const Insertnilai = (data) => { return new Promise((resolve, reject) => { const qry1 = `INSERT INTO kampus.nilai (nim, id_matkul, nidn, nilai, keterangan) VALUES ('${data.nim}', '${data.id_matkul}', '${data.nidn}', '${data.nilai}', '${data.keterangan}')`; db.query(`${qry1}`, (error, result) => { if (!error) { resolve(result) } else { reject(new Error(error)) } }) }) } const Updatenilai = (data, params) => { return new Promise((resolve, reject) => { const qry1 = `UPDATE kampus.nilai SET nilai = '${data.nilai}' WHERE nilai.id = '${params.id}' && nilai.nidn = '${params.nidn}'`; db.query(`${qry1}`, (error, result) => { if (!error) { resolve(result) } else { reject(new Error(error)) } }) }) } const Deletenilai = (params) => { return new Promise((resolve, reject) => { const qry1 = `DELETE FROM kampus.nilai WHERE nilai.id = '${params.id}' && nilai.nidn = '${params.nidn}'`; db.query(`${qry1}`, (error, result) => { if (!error) { resolve(result) } else { reject(new Error(error)) } }) }) } const Getnilai = () => { return new Promise((resolve, reject) => { const qry1 = `SELECT n.nim, m.nama, m.jurusan, Date_format( From_Days( To_Days(Curdate()) - To_Days(m.tanggal_lahir) ), '%Y' ) + 0 AS umur, d.nama AS dosen, mk.nama AS nama_matkul, n.nilai, n.keterangan FROM nilai n INNER JOIN mahasiswa m ON n.nim = m.nim INNER JOIN dosen d ON d.nidn = n.nidn INNER JOIN mata_kuliah mk ON mk.id_matkul = n.id_matkul WHERE n.nilai >= '65' ORDER BY n.id_matkul, n.nim DESC`; db.query(`${qry1}`, (error, result) => { if (!error) { resolve(result) } else { reject(new Error(error)) } }) }) } const AverageScoreMahasiswa = ()=>{ return new Promise((resolve, reject)=>{ const qry = 'SELECT n.nim, m.nama, m.jurusan, AVG(n.nilai) AS average_score FROM nilai n INNER JOIN mahasiswa m ON n.nim = m.nim GROUP BY n.nim ORDER BY n.id_matkul' db.query(`${qry}`, (error, result) => { if (!error) { resolve(result) } else { reject(new Error(error)) } }) }) } const AverageScoreJurusan = ()=>{ return new Promise((resolve, reject)=>{ const qry = 'SELECT @no:=@no+1 AS nomor, m.jurusan AS nama_jurusan, AVG(n.nilai) AS average_score FROM nilai n INNER JOIN mahasiswa m ON n.nim = m.nim ,(SELECT @no:= 0) AS no GROUP BY m.jurusan ORDER BY m.jurusan' db.query(`${qry}`, (error, result) => { if (!error) { resolve(result) } else { reject(new Error(error)) } }) }) } module.exports = { insertNilai: Insertnilai, updateNilai: Updatenilai, deleteNilai: Deletenilai, getNilai: Getnilai, averageScoreMahasiswa: AverageScoreMahasiswa, averageScoreJurusan: AverageScoreJurusan }<file_sep>/src/helpers/uploadMidleware.js const multer = require('multer'); const response = require('./response'); const SingleFile = (req, res, next) => { global.__basedir = __dirname; const storage = multer.diskStorage({ destination: (req, file, cb) => { cb(null, 'src/assets') }, filename: (req, file, cb) => { cb(null, file.fieldname + "-" + Date.now() + "-" + file.originalname) } }); const multerFilter = (req, file, cb) => { let allowedExtensions = new RegExp(/.(xlsx|xls|csv)$/gi) const ext = allowedExtensions.test(file.originalname) console.log('ext ***',ext); if (ext===false) { response.customErrorResponse(res, 400, `only xlsx|xls|csv are alowed`) } else { cb(null, true) } } const upload = multer({storage: storage, fileFilter: multerFilter}); try { const uploadXls= upload.single("uploadfile"); uploadXls(req, res, err => { if (err) { return res.send(err) } let xlsFile = '' if (req.file === undefined) { xlsFile = "" } else { xlsFile = `${req.file.filename}` } req.body.file = xlsFile next() }) } catch (error) { throw error } } module.exports = { uploadMidleware: SingleFile }<file_sep>/src/routers/mahasiswa.js const express = require('express') const router = express.Router() const {uploadMidleware} = require('../helpers/uploadMidleware') const {isLoggedIn, isDosen} = require('../helpers/authMidleware') const {uploadController}= require('../controllers/mahasiswaController') router.route('/').post(isLoggedIn, isDosen, uploadMidleware, uploadController); module.exports = router <file_sep>/src/controllers/mahasiswaController.js // uploadController require('dotenv').config() const dosenModel = require('../models/dosenModel') const jwt = require('jsonwebtoken') const async = require('async') const helpers = require('../helpers/response') const UploadController = async (req, res, next) => { try { const respData = { object: 'mahasiswa', action: 'upload file', message:`upload success`, result: req.body, file: req.body.file } helpers.response(res, 200, respData) } catch (error) { console.log(error) } } module.exports = { uploadController: UploadController }<file_sep>/src/controllers/nilaiController.js const nilaiModel = require('../models/nilaiModel') const jwt = require('jsonwebtoken') const async = require('async') const helpers = require('../helpers/response') const GetArgJurusan = async(req, res)=>{ try { const avrgJurusan = nilaiModel.averageScoreJurusan() avrgJurusan.then((respon)=>{ if (respon.length >= 0) { const data = { object: 'nilai', action: 'get average mahasiswa perjurusan ', message:`success`, result:respon } helpers.response(res, 200, data) } helpers.customErrorResponse(res, 400, 'gagal delete') }).catch(err=> new Error(err)) } catch (error) { throw error } } const GetArgMhsiswa = async(req, res)=>{ try { const avrgMhs = nilaiModel.averageScoreMahasiswa() avrgMhs.then((respon)=>{ if (respon.length >= 0) { const data = { object: 'nilai', action: 'get average mahasiswa perjurusan ', message:`success`, result:respon } helpers.response(res, 200, data) } helpers.customErrorResponse(res, 400, 'gagal delete') }).catch(err=> new Error(err)) } catch (error) { throw error } } const InsertNilai = async(req, res)=>{ try { const dataNilai = { nim: req.body.nim, id_matkul: req.body.id_matkul, nidn: req.userData.user_id, nilai: req.body.nilai, keterangan: req.body.keterangan } const simpan = nilaiModel.insertNilai(dataNilai) simpan.then((respon)=>{ if (respon.affectedRows === 1) { const data = { object: 'nilai', action: 'insert', message:`success`, result:respon } helpers.response(res, 200, data) } helpers.customErrorResponse(res, 400, 'gagal menyimpan') }).catch(err=> new Error(err)) } catch (error) { throw error } } const UpdateNilai = async(req, res)=>{ try { const paramsSet = { id: req.query.id, nidn: req.userData.user_id } const dataNilai = { nilai: req.body.nilai } const simpan = nilaiModel.updateNilai(dataNilai, paramsSet) simpan.then((respon)=>{ if (respon.affectedRows === 1 && respon.changedRows === 1) { const data = { object: 'nilai', action: 'update', message:`success`, result:respon } helpers.response(res, 200, data) } helpers.customErrorResponse(res, 400, 'gagal update') }).catch(err=> new Error(err)) } catch (error) { throw error } } const DeleteNilai = async(req, res)=>{ try { const paramsSet = { id: req.query.id, nidn: req.userData.user_id } const simpan = nilaiModel.deleteNilai(paramsSet) simpan.then((respon)=>{ if (respon.affectedRows === 1) { const data = { object: 'nilai', action: 'delete', message:`success`, result:respon } helpers.response(res, 200, data) } helpers.customErrorResponse(res, 400, 'gagal delete') }).catch(err=> new Error(err)) } catch (error) { throw error } } const GetNilai = async(req, res)=>{ try { const simpan = nilaiModel.getNilai() simpan.then((respon)=>{ // console.log(respon); if (respon.length >= 1) { const data = { object: 'nilai', action: 'get nilai ', message:`success`, result:respon } helpers.response(res, 200, data) } helpers.customErrorResponse(res, 400, 'gagal delete') }).catch(err=> new Error(err)) } catch (error) { throw error } } module.exports = { getArgJurusan: GetArgJurusan, getArgMhsiswa: GetArgMhsiswa, insertNilai: InsertNilai, updateNilai: UpdateNilai, deleteNilai: DeleteNilai, getNilai: GetNilai }<file_sep>/README.md # restfullApi-kampus # postman collection https://www.getpostman.com/collections/46decaf5fd16f1be11a7 # end point ## register http://localhost:8000/api/v1/users/register <code> { "role": "mahasiswa", "nama": "abdul", "email": "<EMAIL>", "password": "<PASSWORD>", "alamat": "bogor, leuwiliang, cibeber 2", "tanggal_lahir": "2011-06-05", "jurusan": "Ipa" } </code> ## Post Login http://localhost:8000/api/v1/users/login <code> { "email": "<EMAIL>", "password": "<PASSWORD>", "role": "dosen" } </code> ## Post Nilai http://localhost:8000/api/v1/nilai <code> headers: { Authorization: Bearer Token } body:{ "nim": "21622666873", "id_matkul": "Bad", "nilai": "79", "keterangan": "lulus" } </code> ## Patch Nilai http://localhost:8000/api/v1/nilai?id=9 <code> headers: { Authorization: Bearer Token } body:{ "nilai": "100" } </code> ## Delete Nilai http://localhost:8000/api/v1/nilai?id=8 <code> headers: { Authorization: Bearer Token } </code> ## Get Nilai http://localhost:8000/api/v1/nilai <code><div> response status 200: { { "status": 200, "result": { "object": "nilai", "action": "get nilai ", "message": "success", "result": [ { "nim": "12119617", "nama": "Mita", "jurusan": "IPA", "umur": 9, "dosen": "purkon", "nama_matkul": "Agama", "nilai": 76, "keterangan": "lulus" }, { "nim": "12119617", "nama": "Mita", "jurusan": "IPA", "umur": 9, "dosen": "purkon", "nama_matkul": "Agama", "nilai": 76, "keterangan": "lulus" }, { "nim": "12119617", "nama": "Mita", "jurusan": "IPA", "umur": 9, "dosen": "purkon", "nama_matkul": "Agama", "nilai": 76, "keterangan": "lulus" }, dll... }</div> </code> ## Get Average http://localhost:8000/api/v1/nilai/average-mahasiswa <code> response status 200: { { "status": 200, "result": { "object": "nilai", "action": "get average mahasiswa perjurusan ", "message": "success", "result": [ { "nim": "21622666873", "nama": "abdul", "jurusan": "Ipa", "average_score": 64.2 }, { "nim": "21622666788", "nama": "alex", "jurusan": "Komputer", "average_score": 71.6 }, { "nim": "21622666818", "nama": "rahmat", "jurusan": "Komputer", "average_score": 66.2 }, { "nim": "21622666844", "nama": "rahma", "jurusan": "Ipa", "average_score": 86.6 }, { "nim": "12119617", "nama": "Mita", "jurusan": "Ipa", "average_score": 84.8 }, { "nim": "21622651591", "nama": "jklm", "jurusan": "Komputer", "average_score": 82.25 } ] } } } </code> ## Get Average http://localhost:8000/api/v1/nilai/average-jurusan <code> response 200: { { "status": 200, "result": { "object": "nilai", "action": "get average mahasiswa perjurusan ", "message": "success", "result": [ { "nomor": 1, "nama_jurusan": "Ipa", "average_score": 78.5333 }, { "nomor": 2, "nama_jurusan": "Komputer", "average_score": 72.7143 } ] } } } </code> ## post Upload file http://localhost:8000/api/v1/mahasiswa <code> response 200: { "status": 200, "result": { "object": "mahasiswa", "action": "upload file", "message": "upload success", "result": { "file": "uploadfile-1622676709544-penutup_final.xls" }, "file": "uploadfile-1622676709544-penutup_final.xls" } } </code> <br/> <code> response 400: { "status": 400, "message": "only xlsx|xls|csv are alowed" } </code> <file_sep>/chalenges/A-dan-B.js function convertInt(params) { // return 9 jam 60 menit 60 detik const date = new Date(null); date.setSeconds(params); const arrWaktu = date.toISOString().substr(11, 8); const convert = arrWaktu.split(":"); return `${convert[0]} jam ${convert[1]} menit ${convert[2]} detik` } /** * A. convert int to time */ const data = convertInt(10000); console.log(data); //02 jam 46 menit 40 detik /** * B. database mysql, * buat database * * */ const qryB1 = 'CREATE DATABASE kampus'; /** * buat tabel serta ERD (type data, key, relasi one to many, relasi many to many, dsb) * * tabel { * users {id, email, password, role(mahasiswa/dosen)} * mahasiswa {nim, nama, alamat, tanggal_lahir, jurusan} * dosen {nidn, nama} * mata_kuliah {id, nama} * nilai {id, nim, id_matkul, nidn, nilai, keterangan(lulus/belum lulus)} * } * * b.1. buat syntax sql create database, dan table * */ const qryB11 = "CREATE TABLE `kampus`.`users` ( `id` INT NOT NULL AUTO_INCREMENT , `user_id` VARCHAR(255), `email` VARCHAR(255) NOT NULL , `password` VARCHAR(255) NOT NULL , `role` ENUM('mahasiswa','dosen','','') NOT NULL , PRIMARY KEY (`id`), UNIQUE (`email`))"; const qryB12 = "CREATE TABLE `kampus`.`mahasiswa` ( `id` INT NOT NULL AUTO_INCREMENT , `nim` VARCHAR(255) NOT NULL , `nama` VARCHAR(255) NOT NULL , `alamat` TEXT NOT NULL , `tanggal_lahir` DATE NOT NULL , `jurusan` VARCHAR(255) NOT NULL , PRIMARY KEY (`id`), UNIQUE (`nim`))"; const qryB13 = "CREATE TABLE `kampus`.`dosen` ( `id` INT NOT NULL AUTO_INCREMENT , `nidn` VARCHAR(255) NOT NULL , `nama` VARCHAR(255) NOT NULL , PRIMARY KEY (`id`), UNIQUE (`nidn`))"; const qryB14 = "CREATE TABLE `kampus`.`mata_kuliah` ( `id` INT NOT NULL AUTO_INCREMENT , `id_matkul` VARCHAR(255) NOT NULL , `nama` VARCHAR(255) NOT NULL , PRIMARY KEY (`id`), UNIQUE (`nama`))"; const qryB15 = "CREATE TABLE `kampus`.`nilai` ( `id` INT NOT NULL AUTO_INCREMENT , `nim` VARCHAR(255) NOT NULL , `id_matkul` INT NOT NULL , `nidn` VARCHAR(255) NOT NULL , `nilai` INT NOT NULL , `keterangan` ENUM('lulus','belum lulus','','') NOT NULL , PRIMARY KEY (`id`))"; /** b.2. buat syntax sql insert */ const b21 = "dibawah ini sintak untuk insert data user dan dosen"; /* BEGIN; INSERT INTO `users` (`user_id`, `email`, `password`, `role`) VALUES ('20210601','<EMAIL>', '<PASSWORD>', 'dosen'); INSERT INTO `dosen` (`nidn`, `nama`) VALUES ('20210601', 'purkon'); COMMIT; */ const b22 = "dibawah ini sintak untuk insert data user dan mahasiswa"; /* BEGIN; INSERT INTO `users` (`user_id`, `email`, `password`, `role`) VALUES ('1<PASSWORD>','<EMAIL>', '<PASSWORD>', 'mahasiswa'); INSERT INTO `mahasiswa` (`nim`, `nama`, `alamat`, `tanggal_lahir`, `jurusan`) VALUES ('12119617', 'Mita', 'Kp. pasir desa konoha', '2011-06-05', 'IPA'); COMMIT; */ const b23 = "INSERT INTO `mata_kuliah` (`id_matkul`,`nama`) VALUES ('Aga', 'Agama'), ('Bad', 'Basis Data')"; const b24 = "INSERT INTO `nilai` (`nim`, `id_matkul`, `nidn`, `nilai`, `keterangan`) VALUES ('12119617', 'Aga', '20210601', '75', 'lulus')"; /** b.3.1 buat syntaq sql select {*, umur*} data mahasiswa (*umur dari tanggal_lahir) */ const b31 = "SELECT `nim`,`nama`,`alamat`,`tanggal_lahir`,`jurusan`, Date_format( From_Days( To_Days(Curdate()) - To_Days(tanggal_lahir) ), '%Y' ) + 0 AS umur FROM `mahasiswa`"; /** b.3.3 buat syntaq sql select {*} data dosen*/ const b33 = "SELECT * FROM `dosen`" /** b.3.4 buat syntaq sql select {*} data matakuliah*/ const b34 = "SELECT * FROM `mahasiswa`"; /** b.3.5 buat syntaq sql select {*} data nilai (dengan filter nilai >= 75, sort besar ke kecil)*/ const b35 = "SELECT * FROM `nilai` WHERE `nilai` >= 65 ORDER BY id_matkul, nim DESC"; /** * C. rest API * 1.1. register/, post(, ()=>{ * if email tdk terdaftar * data di input ke tbl user dan mahasiswa/dosen * return success * return denied * }) * * 1.2. login/, post(, ()=>{ * return token JWT * }) * * 2.1.1 nilai/, .post((if users.role === dosen ? next), validasi body, req,res)=>{ * data = { * nilai: req.body.nilai * mahasiswa: req.body.mahasiswa * dosen: req.body.dosen * matakuliah: req.body.matakuliah * } * insert data nilai * if(insert) return 200 : return * 2.1.2 nilai/, .patch((if users.role === dosen ? next), validasi body, req,res)=>{ * idnilai = req.query.idnilai * data = { * nilai: req.body.nilai * } * update nilai * if(update) return 200 : return * * 2.1.3 nilai/,.delete( (if users.role === dosen ? next), validasi body, (req,res)=>{ * idnilai = req.query.idnilai * delete nilai * if(delete) return 200 : return * * 3.1. nilai/,.get(()=>{ * return {nim, nama, jurusan, umur, dosen, nama_matkul, nlai, keterangan} * }) * * 4.1. nilai_rata_rata_tiap_mahasiswa/, .get(()=>{ * return {nim, nama, jurusan, average_score} * }) * * 5.1. nilai rata-rata tiap jurusan/, .get(()=>{ * return {id, nama_jurusan, average_score} * }) * * 6.1. mahasiswa/, .post((if users.role === dosen ? next), upload file xlsx/xls/csv, ()=>{ * simpan file * }) * */<file_sep>/index.js require('dotenv').config() const express = require('express') const cors = require('cors') const cookieParser = require('cookie-parser') const compress = require('compression') const helmet = require('helmet') const logger = require('morgan') const app = express() const port = process.env.PORT || 8000 const IP = process.env.IP app.use(helmet()) app.use(compress()) app.use(cors()) app.listen(port, () => console.log(`\n This server is running on port ${port}, and use IP ${IP}`)) app.use(logger('dev')) app.use(express.urlencoded({extended: true})); app.use(express.json()) app.use(cookieParser()) app.get('/', (req, res) => res.send('halo...!')) const apiRouter = require('./src/routers') app.use('/api/v1/', apiRouter) <file_sep>/src/routers/nilai.js const express = require('express'); const router = express.Router(); const {getArgJurusan, getArgMhsiswa, insertNilai, updateNilai, deleteNilai, getNilai} = require('../controllers/nilaiController'); const {validateNilai, validateUpdtNilai} = require('../helpers/nilaiMidleware'); const {isLoggedIn, isDosen} = require('../helpers/authMidleware'); const {getDataDosen} = require('../controllers/dosenControllers'); router.route('/') .post(isLoggedIn, isDosen, getDataDosen, validateNilai, insertNilai) .patch(isLoggedIn, isDosen, validateUpdtNilai, updateNilai) .delete(isLoggedIn, isDosen, deleteNilai) .get(getNilai); router.route('/average-mahasiswa').get(getArgMhsiswa); router.route('/average-jurusan').get(getArgJurusan); module.exports = router <file_sep>/src/routers/index.js const express = require('express') const router = express.Router() const users = require('./users') const nilai = require('./nilai') const mahasiswa = require('./mahasiswa') router.get('/', function (req, res) { res.json({ status: 'API its works', message: 'Welcome ...!' }) }) router.use('/users', users) router.use('/nilai', nilai) router.use('/mahasiswa', mahasiswa) module.exports = router
0471181332218883f123de8f6b5175cb9d04b55c
[ "JavaScript", "Markdown" ]
14
JavaScript
purkonuddin/restfullApi-kampus
52cb96d0a142f34b216dba9ca0638a73105e67aa
9d7e426dd44d4769ca1f739bf8fd1d492fb3baff
refs/heads/master
<repo_name>wangcc57/sql-utils<file_sep>/src/main/java/tool/sql/SqlBuildTool.java package tool.sql; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; /** * Hello world! * */ public class SqlBuildTool { private static final String FILE_PATH = "/Users/wangchaochao/data/eclipse/workspace-bailian/sql/source/sqlTemp.xlsx"; private static final String PK_MARK = "pk"; public void buildSql(String path) throws IOException { List<String> lines = new ArrayList<String>(); List<String> comms = new ArrayList<String>(); InputStream inp = new FileInputStream(path); XSSFWorkbook workbook = new XSSFWorkbook(inp); XSSFSheet st = workbook.getSheetAt(0); XSSFRow row0 = st.getRow(0); XSSFCell row0cell1 = row0.getCell(1); String tableName = row0cell1.getStringCellValue(); lines.add("-- Create table"); lines.add("create table " + tableName); lines.add("("); XSSFRow row4 = st.getRow(4); XSSFCell row4cell1 = row4.getCell(1); String tableDesc = row4cell1.getStringCellValue(); comms.add("-- Add comments to the table"); comms.add("comment on table TABLE_TEST is '" + tableDesc + "';"); comms.add(""); comms.add("-- Add comments to the columns"); int lastRowNum = st.getLastRowNum(); String pk = null; for (int i = 7; i < lastRowNum; i++) { String line = ""; XSSFRow row = st.getRow(i); XSSFCell rowcell0 = row.getCell(0); String colDesc = null; if (rowcell0 != null) { colDesc = rowcell0.getStringCellValue(); comms.add("comment on column TABLE_TEST.USERID is '" + colDesc + "';"); } XSSFCell rowcell1 = row.getCell(1); String colName = null; if (rowcell1 != null) { colName = rowcell1.getStringCellValue(); } line = " " + line + colName + " "; XSSFCell rowcell2 = row.getCell(2); String colType = null; if (rowcell2 != null) { colType = rowcell2.getStringCellValue(); } line = line + colType; XSSFCell rowcell3 = row.getCell(3); String colLen = null; if (rowcell3 != null) { colLen = (int)rowcell3.getNumericCellValue() + ""; } XSSFCell rowcell4 = row.getCell(4); String colDou = null; if (rowcell4 != null) { colDou = (int)rowcell4.getNumericCellValue() + ""; } if (colDou != null) { line = line + "(" + colLen + "," + colDou + "),"; } else { line = line + "(" + colLen + "),"; } XSSFCell rowcell5 = row.getCell(5); String colpk = null; if (rowcell5 != null) { colpk = rowcell5.getStringCellValue(); if (PK_MARK.equals(colpk)) { pk = colName; } } lines.add(line); } int index = lines.size() - 1; String lastLine = lines.get(index); String newLine = lastLine.substring(0, lastLine.length() - 1); lines.set(index, newLine); lines.add(")"); lines.add("tablespace " + tableName); lines.add(" pctfree 10"); lines.add(" initrans 1"); lines.add(" maxtrans 255"); lines.add(" storage"); lines.add(" ("); lines.add(" initial 64K"); lines.add(" minextents 1"); lines.add(" maxextents unlimited"); lines.add(" );"); lines.add(""); lines.addAll(comms); lines.add(""); lines.add("-- Create/Recreate primary, unique and foreign key constraints"); lines.add("alter table " + tableName); lines.add(" add primary key (" + pk + ")"); lines.add(" using index"); lines.add(" tablespace " + tableName); lines.add(" pctfree 10"); lines.add(" initrans 2"); lines.add(" maxtrans 255"); lines.add(" storage"); lines.add(" ("); lines.add(" initial 64K"); lines.add(" minextents 1"); lines.add(" maxextents unlimited"); lines.add(" );"); for (String li : lines) { System.out.println(li); } } public static void main(String[] args) throws IOException { SqlBuildTool tool = new SqlBuildTool(); tool.buildSql(FILE_PATH); } }
6256012788d2a2e8698d1add4bba9dd24ad6e9d8
[ "Java" ]
1
Java
wangcc57/sql-utils
6be3b345203f54f1361f1af0f06cb513cc8f9a2f
8b9e580a0fe7bcfc262237540bbc21b92a7034aa
refs/heads/master
<file_sep>(function () { 'use strict'; angular .module('iigame.check') .controller('CheckCtrl', CheckCtrl); /** @ngInject */ function CheckCtrl($timeout, $cookies, AuthService, AlertsService, FirebaseService, SessionService, md5, gettextCatalog, MODULE) { AuthService.checkAccess(MODULE.CHECK); var vm = this; var CHECK_LOGIN_COOKIE = 'iigame.check_login'; // template types vm.templates = { login: 0, result: 1 }; // fields vm.success = false; vm.passwordText = ''; vm.check = {}; // methods vm.isTemplateVisible = isTemplateVisible; vm.changeTemplate = changeTemplate; vm.checkPassword = checkPassword; vm.hasAlerts = hasAlerts; vm.getResultMsg = getResultMsg; changeTemplate(vm.templates.login, true); //////////// function isTemplateVisible(template) { return template === vm.template; } function changeTemplate(template, init) { __clear(); __loadCookie(); vm.template = template; if (!init) { AlertsService.cleanAlerts(); __fakeLoadPage(); } } function checkPassword() { if (vm.checkForm.$invalid) { return; } if (!FirebaseService.getLogins().hasOwnProperty(vm.check.login)) { AlertsService.addAlert('alert', gettextCatalog.getString('Employer {{user}} doesn\'t exist.', {user: vm.check.login})); __clearLogin(); __fakeLoadPage(); return; } $cookies.put(CHECK_LOGIN_COOKIE, vm.rememberCheckLogin ? vm.check.login : ''); var passwords = FirebaseService.getEncryptedPasswords(); var encryptedPassword = md5.createHash(vm.check.password); if (!passwords.hasOwnProperty(encryptedPassword)) { AlertsService.addAlert('alert', gettextCatalog.getString('Password {{password}} doesn\'t exist.', {password: vm.check.password})); __fakeLoadPage(); return; } vm.success = passwords[encryptedPassword].type === 'real'; vm.passwordText = passwords[encryptedPassword].text; changeTemplate(vm.templates.result); } function hasAlerts() { return AlertsService.getAlerts().length !== 0; } function getResultMsg() { return vm.success ? gettextCatalog.getString('SUCCESS') : gettextCatalog.getString('FAILURE'); } //////////// function __loadCookie() { vm.check.login = $cookies.get(CHECK_LOGIN_COOKIE); vm.rememberCheckLogin = (!vm.check.login || vm.check.login === '') ? null : true; } function __clear() { vm.check = {}; if (angular.isDefined(vm.checkForm)) { vm.checkForm.$setPristine(); } } function __clearLogin() { vm.rememberCheckLogin = null; $cookies.put(CHECK_LOGIN_COOKIE, ''); } function __fakeLoadPage() { SessionService.setPageLoaded(false); $timeout(function () { SessionService.setPageLoaded(true); }, 500); } } })(); <file_sep>(function () { 'use strict'; angular .module('iigame.constants') .constant('PASSWORD_TYPE', { FAKE: 'fake', REAL: 'real', getAll: function() { return [this.FAKE, this.REAL]; } }); })(); <file_sep>(function () { 'use strict'; angular .module('iigame.login', []) .config(config); /** @ngInject */ function config($stateProvider) { $stateProvider.state('login', { url: '/login', templateUrl: 'login.html', controller: 'LoginCtrl', controllerAs: 'vm' }); } })(); <file_sep>(function () { 'use strict'; angular .module('iigame.check', []) .config(config); /** @ngInject */ function config($stateProvider) { $stateProvider.state('check', { url: '/home', templateUrl: 'check.html', controller: 'CheckCtrl', controllerAs: 'vm' }); } })(); <file_sep>(function () { 'use strict'; angular .module('iigame.constants') .constant('ROLE', { DOM: 'dom', SUB: 'sub', getAll: function() { return [this.DOM, this.SUB]; } }); })(); <file_sep>(function () { 'use strict'; angular.module('iigame.alerts', []); })(); <file_sep>(function () { 'use strict'; angular .module('iigame.passwords', []) .config(config); /** @ngInject */ function config($stateProvider) { $stateProvider.state('passwords', { url: '/passwords', templateUrl: 'passwords.html', controller: 'PasswordsCtrl', controllerAs: 'vm' }); } })(); <file_sep>(function () { 'use strict'; angular .module('iigame.constants') .constant('MODULE', { CHECK: 'check', PASSWORDS: '<PASSWORD>', LOGIN: 'login', USERS: 'users', SETTINGS: 'settings', ABOUT: 'about' }); })(); <file_sep>(function () { 'use strict'; angular .module('template/alert/alert.html', []) .run(run); function run($templateCache) { $templateCache.put('template/alert/alert.html', '<div class="alert-box" ng-class="(type || \'\')">\n' + ' <span ng-transclude></span>\n' + ' <a ng-show="closeable" class="close" ng-click="close()"><span class="fi-x"></span></a>\n' + '</div>\n' + ''); } })();<file_sep>(function () { 'use strict'; angular .module('iigame.core') .controller('CoreCtrl', CoreCtrl); /** @ngInject */ function CoreCtrl($q, FirebaseService, SecurityRulesService, AlertsService, SessionService) { var vm = this; var appLoaded = false; vm.isAppLoaded = isAppLoaded; vm.isPageLoaded = SessionService.isPageLoaded; __init(); //////////// function isAppLoaded() { return appLoaded; } //////////// function __init() { $q.all([ AlertsService.getLoadedPromise(), FirebaseService.getLoadedPromise(), SecurityRulesService.getLoadedPromise() ]).then(function () { appLoaded = true; }); } } }());<file_sep>(function () { 'use strict'; angular .module('iigame.menu') .controller('MenuCtrl', MenuCtrl); /** @ngInject */ function MenuCtrl($rootScope, AuthService, MODULE) { var vm = this; $rootScope.$on('userUpdated', function () { load(); }); load(); //////////// function load() { vm.isHomeVisible = AuthService.canAccess(MODULE.CHECK); vm.isPasswordsVisible = AuthService.canAccess(MODULE.PASSWORDS); vm.isLoginVisible = AuthService.canAccess(MODULE.LOGIN) && !AuthService.getUser(); vm.isLogoutVisible = AuthService.canAccess(MODULE.LOGIN) && AuthService.getUser(); vm.isSettingsVisible = AuthService.canAccess(MODULE.SETTINGS); vm.isUsersVisible = AuthService.canAccess(MODULE.USERS); vm.isAboutVisible = AuthService.canAccess(MODULE.ABOUT); } } })(); <file_sep>(function () { 'use strict'; angular .module('iigame.users', []) .config(config); /** @ngInject */ function config($stateProvider) { $stateProvider.state('users', { url: '/users', templateUrl: 'users.html', controller: 'UsersCtrl', controllerAs: 'vm' }); } })(); <file_sep>(function () { 'use strict'; angular.module('iigame.modal', []); })(); <file_sep>(function () { 'use strict'; angular .module('iigame.core') .service('SecurityRulesService', SecurityRulesService); /** @ngInject */ function SecurityRulesService($q, $http) { var ALLOWED_FILE = '.security_allowed.json'; var DISABLED_FILE = '.security_disabled.json'; var loadedPromise = $q.defer(); var data = {}; var service = { getLoadedPromise: getLoadedPromise, getAllowedRules: getAllowedRules, getDisabledRules: getDisabledRules }; __init(); return service; //////////// function getLoadedPromise() { return loadedPromise.promise; } function getAllowedRules() { return data.allowed; } function getDisabledRules() { return data.disabled; } //////////// function __loadData() { return $q.all([ $http.get(ALLOWED_FILE).then(function (response) { data.allowed = response.data; }), $http.get(DISABLED_FILE).then(function (response) { data.disabled = response.data; }) ]); } function __init() { __loadData() .then(function () { loadedPromise.resolve(); }); } } })(); <file_sep>(function () { 'use strict'; angular .module('iigame.error', []) .config(config); /** @ngInject */ function config($stateProvider) { $stateProvider .state('403', { url: '/error/403', templateUrl: 'error.html', controller: 'ErrorCtrl', controllerAs: 'vm' }) .state('404', { url: '/error/404', templateUrl: 'error.html', controller: 'ErrorCtrl', controllerAs: 'vm' }); } })(); <file_sep>(function () { 'use strict'; angular .module('iigame.modal') .controller('ModalCtrl', ModalCtrl); /** @ngInject */ function ModalCtrl($modalInstance, data) { var vm = this; // fields vm.data = data; // methods vm.close = close; vm.ok = ok; vm.nok = nok; //////////// function close() { $modalInstance.close(false); } function ok() { $modalInstance.close(true); } function nok() { $modalInstance.close(false); } } }());<file_sep>(function () { 'use strict'; angular .module('iigame.error') .controller('ErrorCtrl', ErrorCtrl); /** @ngInject */ function ErrorCtrl($location, SessionService, gettextCatalog) { SessionService.setPageLoaded(true); var vm = this; var url = $location.url().split('/'); var errors = { 404: { code: '404', /// error 404 title name: gettextCatalog.getString('Not Found'), msg: gettextCatalog.getString('The page you requested cannot be found. Please try again later.') }, 403: { code: '403', /// error 403 title name: gettextCatalog.getString('Forbidden'), msg: gettextCatalog.getString('You don\'t have permission to access this folder/file on this server.') } }; vm.error = errors[url[url.length - 1]]; } })(); <file_sep>(function () { 'use strict'; angular .module('iigame.core') .service('FirebaseService', FirebaseService); /** @ngInject */ function FirebaseService($q, $log, $firebaseAuth, $firebaseObject, ConfigService) { var loadedPromise = $q.defer(); var data = { areUsersDisabled: false }; var service = { getLoadedPromise: getLoadedPromise, getAuth: getAuth, getUsers: getUsers, getLogins: getLogins, getEncryptedPasswords: getEncryptedPasswords, getDecryptedPasswords: getDecryptedPasswords, getSecurityUrl: getSecurityUrl, areUsersDisabled: areUsersDisabled, reloadData: reloadData }; __init(); return service; //////////// function getLoadedPromise() { return loadedPromise.promise; } function getAuth() { return data.auth; } function getUsers() { return data.users; } function getLogins() { return data.logins; } function getEncryptedPasswords() { return data.encryptedPasswords; } function getDecryptedPasswords() { return data.decryptedPasswords; } function areUsersDisabled() { return data.areUsersDisabled; } function getSecurityUrl() { return data.fireBaseUrl + '/?page=Security'; } function reloadData() { data = { areUsersDisabled: false }; loadedPromise = $q.defer(); __init(); } //////////// function __getRef() { return ConfigService.getFireBaseAppName().then(function (fireBaseAppName) { data.fireBaseUrl = 'https://' + fireBaseAppName + '.firebaseio.com'; return new Firebase(data.fireBaseUrl); }); } function __getFirebaseObject(path) { return __getRef().then(function (ref) { var deffered = $q.defer(); ref.child(path).on('value', function () { deffered.resolve($firebaseObject(ref.child(path))); }, function () { $log.debug('FirebaseService.getFirebaseObject() - The read on path "' + path + '" failed.'); deffered.resolve(null); }); return deffered.promise; }); } function __loadAuth() { return __getRef().then(function (ref) { return $firebaseAuth(ref).$waitForAuth().then(function () { return data.auth = $firebaseAuth(ref); }); }) } function __loadData() { return $q.all([ __getFirebaseObject('accounts/logins').then(function (logins) { data.logins = logins; }), __getFirebaseObject('accounts/users').then(function (users) { data.users = users; }), __getFirebaseObject('passwords/encrypted').then(function (passwords) { data.encryptedPasswords = passwords; }), __getFirebaseObject('passwords/decrypted').then(function (passwords) { data.decryptedPasswords = passwords; }) ]); } function __areDataLoaded() { return $q.all([ data.users && data.users.$loaded(), data.logins && data.logins.$loaded(), data.encryptedPasswords && data.encryptedPasswords.$loaded(), data.decryptedPasswords && data.decryptedPasswords.$loaded() ]) } function __postLoadData() { return $q.all([ __disableUsers() ]); } function __disableUsers() { if (!data.users) { data.areUsersDisabled = true; return true; } return data.users.$save().catch(function () { data.areUsersDisabled = true; }); } function __init() { __loadAuth() .then(__loadData) .then(__areDataLoaded) .then(__postLoadData) .then(function () { loadedPromise.resolve(); }); } } })(); <file_sep># I&I Game #### Table of Contents 1. [About](#about) 1. [Connection with Manna](#connection-with-manna) 1. [Disclaimer](#disclaimer) 1. [Use Cases](#use-cases) 1. [Demo](#demo) 1. [Installation](#installation) 1. [Usage Howto](#usage-howto) 1. [Initial Startup](#initial-startup) 1. [Passwords Setup](#passwords-setup) 1. [Passwords Check](#passwords-check) 1. [Forgotten Password](#forgotten-password) 1. [Changing Password](#changing-password) 1. [Changing E-mail](#changing-e-mail) 1. [Account Deletion](#account-deletion) 1. [Re-enabling and Re-disabling Users Creation](#re-enabling-and-re-disabling-users-creation) 1. [What's in Plan](#whats-in-plan) 1. [Changelog](#changelog) 1. [License](#license) ## About Everyone needs relaxing sometimes, almost everyone loves sex and most of us like playing games. This app is here to connect all these three things together and improve your sexual experiences. ### Connection with Manna [<NAME>](http://www.mannazone.org/) wrote a great fiction called The Administration and this app is loosely inspired by it. However, if you haven't read it it doesn't matter - I can highly recommend it but it doesn't affort usage of this app. Only name of Investigation & Interrogation division was taken from the fiction and this is exactly what this app is about. Of course, if you are fan of Manna's work, feel free to name your accounts after Toreth and Warrick :-) ### Disclaimer **Warning:** If you know nothing about BDSM or don't like it, this app probably isn't for you. The same thing is when you are under 18 or simply under law in your country. Anyway, author doesn't take any consequences for possible injury got by usaging this app. ### Use Cases #### ...if your are dom (top) Your partner knows a secret password. He/she thinks that he/she will never ever tell you even if you do whatever you are able to, whatever you can or whatever you want to do. Do you think he/she is right? #### ...if you are sub (bottom) You know a secret password and your partner really wants to know. He/she can do whatever is able to, whatever he/she can and whatever he/she wants to do. Oh, really? God be with you. This app is here to help you realize this scenario. It helds the passwords and is able to validate them. No cheats, no mistakes, simply setup, short preparation - just you, your partner and your investigation and interrogation game. And computer or mobile phone, of course. ## Demo Demo of this app can be found [here](https://iigame-demo.firebaseapp.com). **The demo isn't set for your game** so don't use it that way. Everybody can delete your passwords or accounts anytime there. You can see the app and try it there. If you like the app and want to have your own copy please see the installation section. ## Installation Installation is simple and doesn't require any technical knowledge or payment. Everyone can deploy and use their own copy absolutely free. If you are interested please follow the steps below. 1. You need a Firebase account. If you don't have one you can create it for free [here](https://www.firebase.com/signup) (Google account is required). 1. Create new Firebase app on your [dashboard](https://www.firebase.com/account). You can use whatever name or URL you wish. If you see some error, please try another URL - it has to be unique worldwidely. You will use your Firebase URL again during the installation. 1. Go to **Dashboard > Login & Auth** of your new Firebase app and check an option **Enable Email & Password Authentication**. 1. If you don't have installed [Node.js](https://nodejs.org) yet, do it now. Don't forget to add `npm` on `PATH` during the installation if you are using Windows. 1. Open your terminal or command line and install Firebase Tools by command `npm install -g firebase-tools`. It can take some time to start installation. If you see the error saying that command npm hasn't been found you probably didn't add `npm` on the system `PATH`. Fix it or reinstall Node.js in this case. 1. Download I&I Game files. All of them are placed in `dist` folder on this web and on [releases page](https://github.com/akarienta/iigame/releases) ([download the last release now](https://github.com/akarienta/iigame/releases/download/1.0.0/iigame.zip)). 1. Open file `firebase.json` in some text editor and: * Change variable named `firebase` to your own Firebase URL from the step 2. * *[Optional]* If you are interested you can also change the app language here - it is done by variable `language`. Supported languages are **en** (English) and **cs** (Czech) for now. If you wish to translate the app into another language please write me an e-mail on <<EMAIL>>. * *[Optional]* You can also setup behaviour of alerts here. If you wish to keep relevant alerts visible until you close them, set a variable `alertsHistory` to `true`. If you keep it as `false`, every new alert overwrites the old one and you see one alert only everytime. 1. You are almost done. Before you continue please doublecheck your `firebase.json` file. You should see something like this (this is a conf file of the demo app): ``` { "firebase": "iigame-demo", "language": "en", "alertsHistory": false, "public": ".", "rules": ".security_allowed.json" } ``` 1. If you wish to deploy the app now type this command into your terminal or command line. You have to run this command from the folder where are I&I Game files including `firebase.json` file: `firebase deploy`. If you are asked for authorization run command `firebase login` firstly. 1. You can open your app by command `firebase open` or by visiting site `https://<your-firebase-app-name>.firebaseapp.com`. * *[Optional]* App can be removed from internet anytime by command `firebase disable:hosting`. 1. Please check Usage Howto section to learn how to use the app and perform initial startup steps. ## Usage Howto App has two menus, the left menu contains game items, the right menu contains settings items. Once you have installed your own copy you are required to make **initial startup** steps. Then you can perform **passwords setup** steps and **password checking** whenever you want. There are also some other use cases, please read the doc bellow to discover them. #### Initial Startup 1. Go to **Right Menu > Users** and create user accounts there. You need at least one account for dom/top and one account for sub/bottom. 1. Disable creation of new accounts by instructions given. #### Passwords Setup 1. Log in in with your sub/bottom account on page **Right Menu > Log In**. 1. Go to **Left Menu > Passwords** and setup your passwords here. You can setup as many passwords as you want. Every password can be set as real or fake - it depends what behaviour you want to set up for the password phrase. You can use fake passwords to provoke your dom/top partner and real passwords to end the game. 1. If you want to delete some passwords use trash icon on the end of the line of the password you want to delete. 1. Don't forget to log out on page **Right Menu > Log Out**. #### Passwords Check 1. This action doesn't require to be logged in into the app. 1. Go to **Left Menu > Home** (this is also the app homepage). 1. Every user account (user role doesn't matter) can be used as an employer username. This is here only for fun to improve the feeling from role playing. 1. Both real and fake passwords can be used as an employer password. This is not connected with real user account passwords - you can log in there only with passwords from **Left Menu > Passwords** section. 1. If you don't know any password, don't waste your time with this app and try to ask your sub/bottom partner. If he/she knows, he/she must tell, get it done. :-) 1. You can be pissed off with fake password. Whenever you enter some of the fake passwords a derisive message is shown and you have to try again better. 1. Whenever you enter some of the real passwords the game is over, uh, at least within the scope of this app. :-) #### Forgotten Password 1. Go to **Right Menu > Log In**. 1. There is a link placed to password reset on the bottom of Log In Form - use it. 1. Fill in the given form. You will recieve an e-mail with temporary password. 1. Temporary password can be used to log in and then you can change your password as it is described bellow. This temporary password is valid for 24 hours and then is destroyed. Your old password is still valid throughout this time until you change it. 1. Once you change the password the old one as well as the temporary one are destroyed immediately. #### Changing Password 1. Log in on page **Right Menu > Log In**. 1. Go to **Right Menu > Settings** and select option **Change Password**. 1. You can log out on page **Right Menu > Log Out**. #### Changing E-mail 1. Log in on page **Right Menu > Log In**. 1. Go to **Right Menu > Settings** and select option **Change E-mail**. 1. You can log out on page **Right Menu > Log Out**. #### Account Deletion 1. Only user himself/herself can delete his/her account. There is no option how to do it as admin without knowing the user password. 1. Log in on page **Right Menu > Log In**. 1. Go to **Right Menu > Settings** and select option **Change Password**. 1. You can log out on page **Right Menu > Log Out**. #### Re-enabling and Re-disabling Users Creation 1. To perform this action you need to have access into Firebase where the app is installed. 1. Log in on page **Right Menu > Log In**. 1. Go to **Right Menu > Users**. Follow the instructions. 1. Don't forget to log out on page **Right Menu > Log Out**. ## What's in Plan * more translations * countdown timer ## Changelog * 1.0.0 - The First Release ## License [The MIT License](https://github.com/akarienta/iigame/blob/master/LICENSE.md) <file_sep>(function () { 'use strict'; angular .module('iigame.core') .service('ConfigService', ConfigService); /** @ngInject */ function ConfigService($http) { var CONFIG_FILE = 'firebase.json'; var service = { getLanguage: getLanguage, getFireBaseAppName: getFireBaseAppName, getAlertsHistory: getAlertsHistory, getFile: getFile }; return service; //////////// function getLanguage() { return __getParam('language'); } function getFireBaseAppName() { return __getParam('firebase'); } function getAlertsHistory() { return __getParam('alertsHistory'); } function getFile() { return $http.get(CONFIG_FILE).then(function (response) { return response.data; }); } //////////// function __getParam(paramName) { return $http.get(CONFIG_FILE).then(function (response) { return response.data[paramName]; }); } } })(); <file_sep>(function () { 'use strict'; angular .module('iigame.users') .controller('UsersCtrl', UsersCtrl); /** @ngInject */ function UsersCtrl($log, FirebaseService, AuthService, AlertsService, SessionService, SecurityRulesService, gettextCatalog, ROLE, MODULE) { AuthService.checkAccess(MODULE.USERS); var vm = this; // fields vm.users = FirebaseService.getUsers(); vm.logins = FirebaseService.getLogins(); vm.areUsersDisabled = FirebaseService.areUsersDisabled(); vm.addingUser = false; vm.newUser = {}; vm.newUser.password = {}; vm.newUser.role = null; vm.data = {}; vm.areRulesShown = false; // methods vm.createUser = createUser; vm.createUserCancel = createUserCancel; vm.addUser = addUser; vm.getFirebaseSecurityUrl = getFirebaseSecurityUrl; vm.getAllowedJSON = getAllowedJSON; vm.getDisabledJSON = getDisabledJSON; vm.changeRulesVisibility = changeRulesVisibility; vm.getSnippetMsg = getSnippetMsg; //////////// function createUser() { if (vm.userForm.$invalid) { return; } SessionService.setPageLoaded(false); FirebaseService.getAuth().$createUser({ email: vm.newUser.mail, password: <PASSWORD> }).then(function (userData) { AlertsService.addAlert('success', gettextCatalog.getString('User {{login}} was created.', {login: vm.newUser.login})); __saveUser(userData); __saveLogin(); }).catch(function (error) { $log.error('Error while adding user:', error); AlertsService.addAlert('alert', gettextCatalog.getString('Something is wrong. Maybe user with e-mail {{mail}} exists already?', {mail: vm.newUser.mail})); }).finally(function () { __clearForm(); addUser(false); SessionService.setPageLoaded(true); }); } function createUserCancel() { addUser(false); __clearForm(); } function addUser(value) { vm.addingUser = value; } function getFirebaseSecurityUrl() { return FirebaseService.getSecurityUrl(); } function getAllowedJSON() { return __objectToJSON(SecurityRulesService.getAllowedRules()); } function getDisabledJSON() { return __objectToJSON(SecurityRulesService.getDisabledRules()); } function changeRulesVisibility() { vm.areRulesShown = !vm.areRulesShown; } function getSnippetMsg() { return vm.areRulesShown ? gettextCatalog.getString('Hide code snippet') : gettextCatalog.getString('Show code snippet'); } //////////// function __saveUser(userData) { vm.users[userData.uid] = { login: vm.newUser.login, role: ROLE.getAll()[vm.newUser.role] }; vm.users.$save(); } function __saveLogin() { vm.logins[vm.newUser.login] = { mail: vm.newUser.mail }; vm.logins.$save(); } function __clearForm() { vm.newUser.login = ''; vm.newUser.role = null; vm.newUser.mail = ''; vm.newUser.password.new = ''; vm.newUser.password.confirm = ''; vm.userForm.$setPristine(); } function __objectToJSON(object) { return JSON.stringify(object, null, 2); } } })(); <file_sep>(function() { 'use strict'; angular .module('iigame.alerts') .controller('AlertsCtrl', AlertsCtrl); /** @ngInject */ function AlertsCtrl(AlertsService) { var vm = this; vm.getAlerts = AlertsService.getAlerts; vm.closeAlert = closeAlert; //////////// function closeAlert(index) { AlertsService.removeAlert(index); } } }());
57b0acd2383d07808e48f74c68f32c6a0b392795
[ "JavaScript", "Markdown" ]
22
JavaScript
Akarienta/iigame
6d773142d8342ca706ef7c865e77bb6d0d5f2e91
b126591678aff30f553a2f36db65e177c2012186
refs/heads/master
<repo_name>ren2040/Robotgame<file_sep>/C++ Coursework/robot.cpp #include "robot.h" #include <iostream> #include <string> #include <tuple> #include <list> #include <algorithm> #include <map> #include <vector> using namespace std; robot::robot(const string &n) { robotName = n; x = 0; y = 0; _travelled = 0; } void robot::move_north() { y++; _travelled++; } void robot::move_east() { x++; _travelled++; } void robot::move_south() { y--; _travelled++; } void robot::move_west() { x--; _travelled++; } int robot::north() const { return y; } int robot::east() const { return x; } const std::string &robot::name() { return robotName; } int robot::travelled() const { return _travelled; } int robot::distance(const robot& r) { return abs(r.x) + abs(r.y); } <file_sep>/C++ Coursework/robot.h #ifndef ROBOT_H #define ROBOT_H #include <iostream> #include <string> #include <tuple> #include <vector> class robot { std::string robotName; int x; int y; int _travelled; public: explicit robot(const std::string &n); void move_north(); void move_east(); void move_south(); void move_west(); const std::string & name(); int north() const; int east() const; int travelled() const; int distance(const robot& r); }; #endif<file_sep>/C++ Coursework/game.cpp #include "pch.h" #include "robot.h" #include <iostream> #include <string> #include <tuple> #include <list> #include <algorithm> #include <map> #include <vector> using namespace std; class game { map<string, robot> robots; public: int num_robots() const { return robots.size(); } void move(const string &name, int dir) { if (robots.count(name) == 0) { robot rob = robot(name); robots.emplace(name, rob); switch (dir) { case 0: robots.find(name)->second.move_north(); break; case 1: robots.find(name)->second.move_east(); break; case 2: robots.find(name)->second.move_south(); break; case 3: robots.find(name)->second.move_west(); break; } } else { switch (dir) { case 0: robots.find(name)->second.move_north(); break; case 1: robots.find(name)->second.move_east(); break; case 2: robots.find(name)->second.move_south(); break; case 3: robots.find(name)->second.move_west(); break; } } } int num_close() const { int count = 0; robot localRobot("LocalRobot"); typedef map<string, robot>::const_iterator iter; for (iter r = robots.cbegin(); r != robots.cend(); ++r ) { if (localRobot.distance(r->second) <= 10) { count++; } } return count; } int max_distance() const { int max = 0; typedef map<string, robot>::const_iterator iter; for (iter r = robots.cbegin(); r != robots.cend(); ++r) { robot localRobot("LocalRobot"); if (localRobot.distance(r->second) > max) { max = localRobot.distance(r->second); } } return max; } string furthest() const { int max = 0; string name; typedef map<string, robot>::const_iterator iter; for (iter r = robots.cbegin(); r != robots.cend(); ++r) { if (distance(r->second) > max) { max = distance(r->second); name = r->first; } } return name; } struct pred { inline bool operator() (robot& rob1, robot& rob2) { return rob1.travelled() > rob2.travelled(); } }; vector<robot> robots_by_travelled() const { vector<robot> robotsList = vector<robot>(); typedef map<string, robot>::const_iterator iter; for (iter r = robots.cbegin(); r != robots.cend(); ++r) { robotsList.push_back(r->second); } sort(robotsList.begin(), robotsList.end(), pred()); return robotsList; } };
a70f2645ac5a8baff41b169ed2bf92eede7a52aa
[ "C++" ]
3
C++
ren2040/Robotgame
6d63c13270e2b1664d99ed3dd5869ef9d928f431
3c49cf9c914fd22b76f8d6a7e7d69798909ed59a
refs/heads/main
<repo_name>iliaspsi/assesment_13062021<file_sep>/part1.sql -- sum customer basket for all cuisine_parent -- having at least one order with Breakfast cuisine with totalBasket as ( select SUM(basket) as userbasket,city from `bi-2019-test.ad_hoc.orders_jan2021` t where exists (select * from `bi-2019-test.ad_hoc.orders_jan2021` where cuisine_parent = 'Breakfast' and user_id = t.user_id ) group by city ) -- calculate number of breakfast orders per city -- distinct users that ordered per city (one user may order in different cities) -- get sum of all user baskets from the cte and divide by distinct users to get average select count(order_id) as Breakfast_Orders ,count(distinct a.user_id) as Breakfast_Users ,a.city ,ROUND(MAX(b.userbasket)/ count(distinct a.user_id),2) as Avg_Basket from `bi-2019-test.ad_hoc.orders_jan2021` a inner join totalBasket b on b.city = a.city where cuisine_parent = 'Breakfast' group by a.city having count(order_id)>500 order by 1 desc; <file_sep>/main.py import pandas as pd import json from datetime import datetime import datetime from scipy import stats import numpy as np from sklearn.preprocessing import StandardScaler from sklearn.cluster import KMeans import plotly import chart_studio.plotly as py import plotly.graph_objects as go import plotly.offline as pltoff import plotly_express as px import matplotlib.pyplot as plt import seaborn as sns from seaborn import pointplot from seaborn import lineplot # please note no exception handling was added since this is a once off analysis and not # a production application def data_preparation(): df = pd.read_json('/Users/iliaspsi/PycharmProjects/efood_assesment/exports/bq-results-orders.json',lines=True) df['submit_dt'] = df['submit_dt'].str.replace(r'UTC', '') #regular exp, remove UTC string df['submit_dt'] = pd.to_datetime(df['submit_dt'], format='%Y-%m-%d %H:%M:%S') df["submit_dt"] = df["submit_dt"].dt.date snapshot_date = max(df.submit_dt) + datetime.timedelta(days=1) print(snapshot_date); customers = df.groupby(['user_id']).agg({ 'submit_dt': lambda x: (snapshot_date - x.max()).days, 'order_id': 'count', 'basket': 'sum'}) customers.rename(columns = {'submit_dt': 'Recency', 'order_id': 'Frequency', 'basket': 'MonetaryValue'}, inplace=True) return customers def normalize_data(customers): scaler = StandardScaler(); scaler.fit(customers) customers_normalized = scaler.transform(customers) print(np.shape(customers_normalized)[0]) return customers_normalized def decide_numof_clusters(customers_normalized): sse = {} for k in range(1, 11): kmeans = KMeans(n_clusters=k, random_state=42) kmeans.fit(customers_normalized) sse[k] = kmeans.inertia_ # SSE to closest cluster centroid trace1 = { "name": "Elbow curve for k means mini-batch clustering", "type": "scatter", "x": list(sse.keys()), "y": list(sse.values()) } data = [trace1] layout = { "title": "Elbow curve for k means mini-batch clustering", "xaxis": { "title": "K value", "titlefont": { "size": 18, "color": "#7f7f7f", "family": "Courier New, monospace" } }, "yaxis": { "title": "sum of squared errors", "titlefont": { "size": 18, "color": "#7f7f7f", "family": "Courier New, monospace" } } } fig = dict(data=data, layout=layout) pltoff.offline.plot(fig,filename='elbow_curve') def apply_kmeans(customers_normalized, customers): model = KMeans(n_clusters=3, random_state=42) model.fit(customers_normalized) model.labels_.shape customers["Cluster"] = model.labels_ segments = customers.groupby('Cluster').agg({ 'Cluster': 'max', 'Recency':'mean', 'Frequency':'mean', 'MonetaryValue':['mean', 'count']}).round(2) print(segments) fig = go.Figure(data=[go.Table( header=dict(values=list(segments.columns), fill_color='paleturquoise', align='left'), cells=dict(values=[segments.Cluster,segments.Recency, segments.Frequency, segments.MonetaryValue['mean'], segments.MonetaryValue['count']], fill_color='lavender', align='left')) ]) fig.show() return model def present_data(customers_normalized,model): # Create the dataframe df_normalized = pd.DataFrame(customers_normalized, columns=['Recency', 'Frequency', 'MonetaryValue']) df_normalized['ID'] = customers.index df_normalized['Cluster'] = model.labels_ # Melt The Data df_nor_melt = pd.melt(df_normalized.reset_index(), id_vars=['ID', 'Cluster'], value_vars=['Frequency','MonetaryValue','Recency'], var_name='Attribute', value_name='Value') df_nor_melt.head() # Visualize it lineplot(x='Attribute', y='Value', hue='Cluster', data=df_nor_melt) plt.show() def scatter_plot3d(customers_normalized,model): df_normalized = pd.DataFrame(customers_normalized, columns=['Recency', 'Frequency', 'MonetaryValue']) df_normalized['ID'] = customers.index df_normalized['Cluster'] = model.labels_ fig = px.scatter_3d(df_normalized, x='Recency', y='Frequency', z='MonetaryValue', color='Cluster', title="3D Scatter Plot") fig.show() if __name__ == "__main__": # execute only if run as a script customers = data_preparation() customers_normalized = normalize_data(customers) decide_numof_clusters(customers_normalized) model = apply_kmeans(customers_normalized, customers) present_data(customers_normalized,model) scatter_plot3d(customers_normalized,model) <file_sep>/README.md assesment_Part_1 please open Bigquery link https://console.cloud.google.com/bigquery?project=bi-2019-test&authuser=0&p=bi-2019-test&d=ad_hoc&t=orders_jan2021&page=table to run the sql code attached use your personal google account for Part 2 set up a python venv with 3.7 interpreter and add all imported libs to your repository you will also need to download orders_jan2021 from the bigquery project in part 1 and modify the json file path at line 24
7849927be152e7150b42f2b231f02225237dddf5
[ "Markdown", "SQL", "Python" ]
3
SQL
iliaspsi/assesment_13062021
25309b3744639f753c5faf10b5ca164f4ea07d21
58128a28d99fef8d2ff99d5f795eed2fdce52294
refs/heads/master
<file_sep><?php session_start(); if(!isset($_SESSION['username'])) header('location:http://localhost/quiz/login.html'); $con=mysqli_connect('localhost','root'); mysqli_select_db($con,'quizdb'); ?> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <style type="text/css"> #demo{text-align: center; font-size: 30px; margin-top: 0px;} #VIP{margin-left:6px; color:blue; float:left;} #IP{margin-left:600px;color:blue;float:left;} a{text-decoration:none;} #z{background-color:orange;font-style:italic;margin-top:10px;width=100%;height=70px;padding-right=200px;} .a{width:100%;height:250px;background-color:pink;padding:50px; padding-left:300px;} h1{color:green;} .b{width:100%;height:250px;background-color:pink;padding:50px; padding-left:300px;} .c{width:100%;height:250px;background-color:pink;padding:50px; padding-left:300px;} .e{width:100%;height:250px;background-color:pink;padding:50px; padding-left:300px;} .f{width:100%;height:250px;background-color:pink;padding:50px; padding-left:300px;} #button { background-color: #4CAF50; /* Green */ border: none; color: white; padding: 15px 32px; text-align: center; text-decoration: none; display: inline-block; font-size: 16px; margin-left:600px; } h2{color:red;} </style> </head> <body> <p id="demo"> </div> <script> var time=new Date(new Date().getTime() + 0.033*60*60*1000).toLocaleTimeString(); var today = new Date(); var dd = today.getDate(); var mm = today.getMonth() + 1; //January is 0! var yyyy = today.getFullYear(); if (dd < 10) { dd = '0' + dd; } if (mm < 10) { mm = '0' + mm; } today = mm + '/' + dd + '/' + yyyy; // Set the date we're counting down to var countDownDate = new Date(today+" "+time).getTime(); // Update the count down every 1 second var x = setInterval(function() { // Get todays date and time var now = new Date().getTime(); // Find the distance between now and the count down date var distance = countDownDate - now; // Time calculations for days, hours, minutes and seconds var days = Math.floor(distance / (1000 * 60 * 60 * 24)); var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)); var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60)); var seconds = Math.floor((distance % (1000 * 60)) / 1000); // Display the result in the element with id="demo" document.getElementById("demo").innerHTML = days + "d " + hours + "h " + minutes + "m " + seconds + "s "; // If the count down is finished, write some text if (distance < 0) { clearInterval(x); window.location.replace("http://localhost/quiz/result.php"); } }, 1000); </script> <br/> <br/> <br/> <div id="d"> <h1 id="z" align="center">WELCOME TO QUIZ-MANIA </h1> </div> <h1 id="VIP"> <?php echo "welcome"." " .$_SESSION['username']; ?></h1> <h1 id="IP"> <a href="logout.php"> Logout</a></h1> <br/> </br> <marquee> <h2>all questions are carrying 1 marks each. there is no negative marking....all the best</h2></marquee> <form id="f" action="result.php" method="post"> <div class="a"> <h1>1.<?php $res=mysqli_query($con,'select * from question where qid=1');$r=mysqli_fetch_array($res); echo $r['question'];?></h1> <table> <tr><td><h2>a. <?php $res=mysqli_query($con,'select * from answer where aid=1');$r=mysqli_fetch_array($res); echo $r['answer'];?></h2></td> <td><input type="radio" name="1" value="1"></td> </tr> <tr> <td><h2>b. <?php $res=mysqli_query($con,'select * from answer where aid=2');$r=mysqli_fetch_array($res); echo $r['answer'];?></h2></td> <td><input type="radio" name="1" value="2"></td> </tr> <tr> <td><h2>c. <?php $res=mysqli_query($con,'select * from answer where aid=3');$r=mysqli_fetch_array($res); echo $r['answer'];?></h2></td><td><input type="radio" name="1" value="3"></td> </tr> <tr> <td><h2>d. <?php $res=mysqli_query($con,'select * from answer where aid=4');$r=mysqli_fetch_array($res); echo $r['answer'];?></h2></td> <td><input type="radio" name="1" value="4"></td> </tr> </table> <br/> <br/> </div> <br/> <br/> <div class="b"> <h1>2. <?php $res=mysqli_query($con,'select * from question where qid=2');$r=mysqli_fetch_array($res); echo $r['question'];?></h1> <table> <tr> <td><h2>a. <?php $res=mysqli_query($con,'select * from answer where aid=5');$r=mysqli_fetch_array($res); echo $r['answer'];?></h2></td> <td><input type="radio" name="2" value="5"></td> </tr> <tr> <td><h2>b. <?php $res=mysqli_query($con,'select * from answer where aid=6');$r=mysqli_fetch_array($res); echo $r['answer'];?></h2></td> <td><input type="radio" name="2" value="6"></td> </tr> <tr> <td><h2>c. <?php $res=mysqli_query($con,'select * from answer where aid=7');$r=mysqli_fetch_array($res); echo $r['answer'];?></h2></td> <td><input type="radio" name="2" value="7"></td> </tr> <tr> <td><h2>d. <?php $res=mysqli_query($con,'select * from answer where aid=8');$r=mysqli_fetch_array($res); echo $r['answer'];?></h2></td> <td><input type="radio" name="2" value="8"></td> </tr> </table> <br/> <br/> </div> <br/> <br/> <div class="c"> <h1>3. <?php $res=mysqli_query($con,'select * from question where qid=3');$r=mysqli_fetch_array($res); echo $r['question'];?></h1> <table> <tr> <td><h2>a. <?php $res=mysqli_query($con,'select * from answer where aid=9'); $r=mysqli_fetch_array($res);echo $r['answer'];?></h2></td> <td><input type="radio" name="3" value="9"></td> </tr> <tr> <td><h2>b. <?php $res=mysqli_query($con,'select * from answer where aid=10');$r=mysqli_fetch_array($res); echo $r['answer'];?></h2></td> <td><input type="radio" name="3" value="10"></td> </tr> <tr> <td><h2>c. <?php $res=mysqli_query($con,'select * from answer where aid=11'); $r=mysqli_fetch_array($res);echo $r['answer'];?></h2></td> <td><input type="radio" name="3" value="11"></td> </tr> <tr> <td><h2>d. <?php $res=mysqli_query($con,'select * from answer where aid=12');$r=mysqli_fetch_array($res); echo $r['answer'];?></h2></td> <td><input type="radio" name="3" value="12"></td> </tr> </table> <br/> <br/> </div> <br/> <br/> <div class="e"> <h1>4. <?php $res=mysqli_query($con,'select * from question where qid=4');$r=mysqli_fetch_array($res); echo $r['question'];?></h1> <table> <tr> <td><h2>a. <?php $res=mysqli_query($con,'select * from answer where aid=13');$r=mysqli_fetch_array($res); echo $r['answer'];?></h2></td> <td><input type="radio" name="4" value="13"></td> </tr> <tr> <td><h2>b. <?php $res=mysqli_query($con,'select * from answer where aid=14');$r=mysqli_fetch_array($res); echo $r['answer'];?></h2></td> <td><input type="radio" name="4" value="14"></td> </tr> <tr> <td><h2>c. <?php $res=mysqli_query($con,'select * from answer where aid=15');$r=mysqli_fetch_array($res); echo $r['answer'];?></h2></td> <td><input type="radio" name="4" value="15"></td> </tr> <tr> <td><h2>d. <?php $res=mysqli_query($con,'select * from answer where aid=16');$r=mysqli_fetch_array($res); echo $r['answer'];?></h2></td> <td><input type="radio" name="4" value="16"></td> </tr> </table> <br/> <br/> </div> <br/> <br/> <div class="f"> <h1>5. <?php $res=mysqli_query($con,'select * from question where qid=5');$r=mysqli_fetch_array($res); echo $r['question'];?></h1> <table> <tr> <td><h2>a. <?php $res=mysqli_query($con,'select * from answer where aid=17');$r=mysqli_fetch_array($res); echo $r['answer'];?></h2></td> <td><input type="radio" name="5" value="17"></td> </tr> <tr> <td><h2>b. <?php $res=mysqli_query($con,'select * from answer where aid=18');$r=mysqli_fetch_array($res); echo $r['answer'];?></h2></td> <td><input type="radio" name="5" value="18"></td> </tr> <tr> <td><h2>c. <?php $res=mysqli_query($con,'select * from answer where aid=19');$r=mysqli_fetch_array($res); echo $r['answer'];?></h2></td> <td><input type="radio" name="5" value="19"></td> </tr> <tr> <td><h2>d. <?php $res=mysqli_query($con,'select * from answer where aid=20'); $r=mysqli_fetch_array($res);echo $r['answer'];?></h2></td> <td><input type="radio" name="5" value="20"></td> </tr> </table> </div> <br/> <br/> <input type="submit" value="submit" id="button" > <form> </body> </html> <file_sep><?php $email=$_POST['email']; $user=$_POST['username']; $pass=$_POST['<PASSWORD>']; // PHPMailer classes into the global namespace use PHPMailer\PHPMailer\PHPMailer; use PHPMailer\PHPMailer\Exception; // Base files require 'PHPMailer/src/Exception.php'; require 'PHPMailer/src/PHPMailer.php'; require 'PHPMailer/src/SMTP.php'; // create object of PHPMailer class with boolean parameter which sets/unsets exception. $mail = new PHPMailer(true); try { $mail->isSMTP(); // using SMTP protocol $mail->Host = 'smtp.gmail.com'; // SMTP host as gmail $mail->SMTPAuth = true; // enable smtp authentication $mail->Username = '<EMAIL>'; // sender gmail host $mail->Password = '<PASSWORD>'; // sender gmail host password $mail->SMTPSecure = 'tls'; // for encrypted connection $mail->Port = 587; // port for SMTP $mail->setFrom('<EMAIL>', "ratnesh"); // sender's email and name $mail->addAddress($email,$user ); // receiver's email and name $mail->Subject = 'registration'; $mail->Body = 'Successfully registered on quiz mania'; $mail->send(); header('location:http://localhost/quiz/Validation.php'); } catch (Exception $e) { // handle error. echo 'Message could not be sent. Mailer Error: ', $mail->ErrorInfo; } ?> <file_sep><?php session_start(); if(!isset($_SESSION['username'])) header('location:http://localhost/quiz/login.html'); ?> <html> <head> <link rel="stylesheet" href="style.css"> </head> <body> <div> <h1 id="d1" align="center">QUIZ-RESULT </h1> </div> <br/> <br/> <h1 id="heading"><a href='logout.php' >Logout</a></h1> <?php $con=mysqli_connect('localhost','root'); mysqli_select_db($con,'quizdb'); $counter= count($_POST); $marks=0; for($i=1;$i<=5;$i++) { $q="select * from question where qid=$i"; $t=mysqli_query($con,$q); $a=mysqli_fetch_array($t); if(isset($_POST["$i"])) { if($a['ansid']==$_POST["$i"]) $marks++; } } ?> <table> <tr> <td colspan="5"><h1><?php echo "Questions attempted by you :"." $counter ";?> </h1></td> </tr> <tr> <td colspan="5"> <h1><?php echo "Total marks="." $marks"; ?></h1></td> </tr> </table> <br/> </br> </br> </body> </html><file_sep><?php session_start(); $con = mysqli_connect('localhost','root'); mysqli_select_db($con,'quizdb'); $username = $_POST['username']; $password = $_POST['password']; $_SESSION['username']=$username; + // echo $username; // echo $password; $check = "select * from user where username='$username' && password='$<PASSWORD>' "; $resultcheck = mysqli_query($con,$check); $row = mysqli_num_rows($resultcheck); if($row == 1){ header('location:http://localhost/quiz/test.php'); } else header('location:http://localhost/quiz/login.html'); ?>
ab7def153190eb96e7d1d9c9a45ee301293e9d08
[ "PHP" ]
4
PHP
nik-hil27/MyProject
c11f055d69d0c0130f2717eb416470b2e3708811
91917cbf378debc2a58952f52e8abc9053ef0513
refs/heads/master
<file_sep>package cli import ( "testing" "github.com/stretchr/testify/require" ) func TestNormalize(t *testing.T) { cases := []struct { opts func(*Cmd) input []string output []string }{ {func(cmd *Cmd) { }, []string{}, []string{}}, {func(cmd *Cmd) { cmd.Bool(BoolOpt{Name: "a", Value: true, Desc: ""}) }, []string{"ab"}, []string{"ab"}}, {func(cmd *Cmd) { cmd.Bool(BoolOpt{Name: "a", Value: true, Desc: ""}) }, []string{"-a"}, []string{"-a", "true"}}, {func(cmd *Cmd) { cmd.Bool(BoolOpt{Name: "a", Value: true, Desc: ""}) }, []string{"-a=false"}, []string{"-a", "false"}}, {func(cmd *Cmd) { cmd.Bool(BoolOpt{Name: "a", Value: true, Desc: ""}) cmd.Bool(BoolOpt{Name: "b", Value: true, Desc: ""}) }, []string{"-ab"}, []string{"-a", "true", "-b", "true"}}, {func(cmd *Cmd) { cmd.Bool(BoolOpt{Name: "a", Value: true, Desc: ""}) cmd.Bool(BoolOpt{Name: "b", Value: true, Desc: ""}) cmd.String(StringOpt{Name: "c", Value: "", Desc: ""}) }, []string{"-abc", "hello"}, []string{"-a", "true", "-b", "true", "-c", "hello"}}, {func(cmd *Cmd) { cmd.String(StringOpt{Name: "s", Value: "", Desc: ""}) }, []string{"-shello"}, []string{"-s", "hello"}}, {func(cmd *Cmd) { cmd.Bool(BoolOpt{Name: "a", Value: true, Desc: ""}) cmd.String(StringOpt{Name: "b", Value: "", Desc: ""}) }, []string{"-ab", "test"}, []string{"-a", "true", "-b", "test"}}, } for _, cas := range cases { cmd := &Cmd{optionsIdx: map[string]*opt{}} cas.opts(cmd) nz, cons, err := cmd.normalize(cas.input) require.Nil(t, err, "Unexpected error %v", err) t.Logf("%v %v", nz, cons) require.Equal(t, cas.output, nz) } }
b40b95cf0aef57b5f0596e81cda119b72f42b2dc
[ "Go" ]
1
Go
apackeer/mow.cli
b72ecdcb48454d9860626129c2b535e28832f53a
1905f3b90dc3effca26a35499daa920b13c16bdc
refs/heads/master
<file_sep>## mysql 主从复制原理 MySQL 主从复制是指数据可以从一个MySQL数据库服务器主节点复制到一个或多个从节点。MySQL 默认采用异步复制方式,这样从节点不用一直访问主服务器来更新自己的数据,数据的更新可以在远程连接上进行,从节点可以复制主数据库中的所有数据库或者特定的数据库,或者特定的表。 ### MySQL 主从复制主要用途 #### 读写分离 - 在开发工作中,有时候会遇见某个sql 语句需要锁表,导致暂时不能使用读的服务,这样就会影响现有业务,使用主从复制,让主库负责写,从库负责读,这样,即使主库出现了锁表的情景,通过读从库也可以保证业务的正常运作。 #### 实时灾备,用于故障切换 #### 备份,避免影响业务 ### 主从形式 mysql主从复制 灵活 - 一主一从 - 主主复制 - 一主多从---扩展系统读取的性能,因为读是在从库读取的; - 多主一从---5.7开始支持 - 联级复制--- ![image](http://images2015.cnblogs.com/blog/820365/201608/820365-20160821160605026-595389100.png) ### 主从原理 MySQL主从复制涉及到三个线程,一个运行在主节点(log dump thread),其余两个(I/O thread, SQL thread)运行在从节点: ![image](https://ss1.baidu.com/6ONXsjip0QIZ8tyhnq/it/u=3616190683,3608800796&fm=173&app=49&f=JPEG?w=640&h=251&s=01704730B3307423404091CA030070B3) #### 主节点 binary log dump 线程 当从节点连接主节点时,主节点会创建一个log dump 线程,用于发送bin-log的内容。在读取bin-log中的操作时,此线程会对主节点上的bin-log加锁,当读取完成,甚至在发动给从节点之前,锁会被释放。 #### 从节点I/O线程 当从节点上执行`start slave`命令之后,从节点会创建一个I/O线程用来连接主节点,请求主库中更新的bin-log。I/O线程接收到主节点binlog dump 进程发来的更新之后,保存在本地relay-log中。 #### 从节点SQL线程 SQL线程负责读取relay log中的内容,解析成具体的操作并执行,最终保证主从数据的一致性。 对于每一个主从连接,都需要三个进程来完成。当主节点有多个从节点时,主节点会为每一个当前连接的从节点建一个binary log dump 进程,而每个从节点都有自己的I/O进程,SQL进程。从节点用两个线程将从主库拉取更新和执行分成独立的任务,这样在执行同步数据任务的时候,不会降低读操作的性能。比如,如果从节点没有运行,此时I/O进程可以很快从主节点获取更新,尽管SQL进程还没有执行。如果在SQL进程执行之前从节点服务停止,至少I/O进程已经从主节点拉取到了最新的变更并且保存在本地relay日志中,当服务再次起来之后,就可以完成数据的同步。 要实施复制,首先必须打开Master 端的binary log(bin-log)功能,否则无法实现。 因为整个复制过程实际上就是Slave 从Master 端获取该日志然后再在自己身上完全顺序的执行日志中所记录的各种操作。如下图所示: ![image](https://ss1.baidu.com/6ONXsjip0QIZ8tyhnq/it/u=682895023,3828721615&fm=173&app=49&f=JPEG?w=640&h=255&s=09225D32412A45220AF065DA0000C0B2) #### 复制的基本过程如下: - 从节点上的I/O 进程连接主节点,并请求从指定日志文件的指定位置(或者从最开始的日志)之后的日志内容; - 主节点接收到来自从节点的I/O请求后,通过负责复制的I/O进程根据请求信息读取指定日志指定位置之后的日志信息,返回给从节点。返回信息中除了日志所包含的信息之外,还包括本次返回的信息的bin-log file 的以及bin-log position;从节点的I/O进程接收到内容后,将接收到的日志内容更新到本机的relay log中,并将读取到的binary log文件名和位置保存到master-info 文件中,以便在下一次读取的时候能够清楚的告诉Master“我需要从某个bin-log 的哪个位置开始往后的日志内容,请发给我”; - Slave 的 SQL线程检测到relay-log 中新增加了内容后,会将relay-log的内容解析成在祝节点上实际执行过的操作,并在本数据库中执行。 ### MySQL 主从复制模式 MySQL 主从复制默认是异步的模式。MySQL增删改操作会全部记录在binary log中,当slave节点连接master时,会主动从master处获取最新的bin log文件。并把bin log中的sql relay。 #### 异步模式(mysql async-mode) 异步模式如下图所示,这种模式下,主节点不会主动push bin log到从节点,这样有可能导致failover的情况下,也许从节点没有即时地将最新的bin log同步到本地。 ![image](https://ss0.baidu.com/6ONWsjip0QIZ8tyhnq/it/u=3962694792,2705211925&fm=173&app=49&f=JPEG?w=640&h=282&s=01134530133160231ECE65DA030080B2) #### 半同步模式(mysql semi-sync) 这种模式下主节点只需要接收到其中一台从节点的返回信息,就会commit;否则需要等待直到超时时间然后切换成异步模式再提交;这样做的目的可以使主从数据库的数据延迟缩小,可以提高数据安全性,确保了事务提交后,binlog至少传输到了一个从节点上,不能保证从节点将此事务更新到db中。性能上会有一定的降低,响应时间会变长。如下图所示: ![image](https://ss2.baidu.com/6ONYsjip0QIZ8tyhnq/it/u=3868224875,2450613207&fm=173&app=49&f=JPEG?w=640&h=299&s=8013CD3013C0414B12CD61DA030080B2) <file_sep>Tomcat相关的面试题出场的几率并不高,正式因为如此,很多人忽略了对Tomcat相关技能的掌握,下面这一篇文章最早发布在知识星球,整理了Tomcat相关的系统架构,介绍了Server、Service、Connector、Container之间的关系,各个模块的功能,可以说把这几个掌握住了,Tomcat相关的面试题你就不会有任何问题了!另外,在面试的时候你还要有意识无意识的往Tomcat这个地方引,就比如说常见的Spring MVC的执行流程,一个URL的完整调用链路,这些相关的题目你是可以再往Tomcat处理请求的这个过程去说的! 学了本节之后你应该明白的是: - Server、Service、Connector、Container四大组件之间的关系和联系,以及他们的主要功能点; - Tomcat执行的整体架构,请求是如何被一步步处理的; - Engine、Host、Context、Wrapper相关的概念关系; - Container是如何处理请求的; - Tomcat用到的相关设计模式; ### 一、Tomcat顶层架构 俗话说,站在巨人的肩膀上看世界,一般学习的时候也是先总览一下整体,然后逐个部分个个击破,最后形成思路,了解具体细节, Tomcat的结构很复杂,但是 Tomcat 非常的模块化,找到了 Tomcat最核心的模块,问题才可以游刃而解, 了解了Tomcat的整体架构对以后深入了解Tomcat来说至关重要! 先上一张Tomcat的顶层结构图(图A),如下: ![image](https://github.com/tianhuan168/Doc/raw/master/img/clipboard.png) Tomcat中最顶层的容器是Server,代表着整个服务器,从上图中可以看出,一个Server可以包含至少一个Service,用于具体提供服务。 Service主要包含两个部分:Connector和Container。从上图中可以看出 Tomcat 的心脏就是这两个组件,他们的作用如下: - Connector用于处理连接相关的事情,并提供Socket与Request和Response相关的转化; - Container用于封装和管理Servlet,以及具体处理Request请求; 一个Tomcat中只有一个Server,一个Server可以包含多个Service,一个Service只有一个Container,但是可以有多个Connectors, 这是因为一个服务可以有多个连接,如同时提供Http和Https链接,也可以提供向相同协议不同端口的连接, 示意图如下(Engine、Host、Context下边会说到): ![image](https://github.com/tianhuan168/Doc/raw/master/img/6.png) 多个 Connector 和一个 Container 就形成了一个 Service,有了 Service 就可以对外提供服务了,但是 Service 还要一个生存的环境,必须要有人能够给她生命、掌握其生死大权,那就非 Server 莫属了!所以整个 Tomcat 的生命周期由 Server 控制。 另外,上述的包含关系或者说是父子关系,都可以在tomcat的conf目录下的server.xml配置文件中看出,下图是删除了注释内容之后的一个完整的server.xml配置文件(Tomcat版本为8.0) ![image](https://github.com/tianhuan168/Doc/raw/master/img/7.png) 上边的配置文件,还可以通过下边的一张结构图更清楚的理解: ![image](https://github.com/tianhuan168/Doc/raw/master/img/8.webp) Server标签设置的端口号为8005,shutdown=”SHUTDOWN” ,表示在8005端口监听“SHUTDOWN”命令,如果接收到了就会关闭Tomcat。一个Server有一个Service,当然还可以进行配置,一个Service有多个,Service左边的内容都属于Container的,Service下边是Connector。 二、Tomcat顶层架构小结: - Tomcat中只有一个Server,一个Server可以有多个Service,一个Service可以有多个Connector和一个Container; - Server掌管着整个Tomcat的生死大权; - Service 是对外提供服务的; - Connector用于接受请求并将请求封装成Request和Response来具体处理; - Container用于封装和管理Servlet,以及具体处理request请求; 知道了整个Tomcat顶层的分层架构和各个组件之间的关系以及作用,对于绝大多数的开发人员来说Server和Service对我们来说确实很远,而我们开发中绝大部分进行配置的内容是属于Connector和Container的,所以接下来介绍一下Connector和Container。 ### 三、Connector和Container的微妙关系 由上述内容我们大致可以知道一个请求发送到Tomcat之后,首先经过Service然后会交给我们的Connector,Connector用于接收请求并将接收的请求封装为Request和Response来具体处理,Request和Response封装完之后再交由Container进行处理,Container处理完请求之后再返回给Connector,最后在由Connector通过Socket将处理的结果返回给客户端,这样整个请求的就处理完了! Connector最底层使用的是Socket来进行连接的,Request和Response是按照HTTP协议来封装的,所以Connector同时需要实现TCP/IP协议和HTTP协议! Tomcat既然处理请求,那么肯定需要先接收到这个请求,接收请求这个东西我们首先就需要看一下Connector! 四、Connector架构分析 Connector用于接受请求并将请求封装成Request和Response,然后交给Container进行处理, Container处理完之后在交给Connector返回给客户端。 因此,我们可以把Connector分为四个方面进行理解: - Connector如何接受请求的? - 如何将请求封装成Request和Response的? - 封装完之后的Request和Response如何交给Container进行处理的? -- Container处理完之后如何交给Connector并返回给客户端的? 首先看一下Connector的结构图(图B),如下所示: ![image](https://github.com/tianhuan168/Doc/raw/master/img/9.webp) Connector就是使用ProtocolHandler来处理请求的,不同的ProtocolHandler代表不同的连接类型, 比如:Http11Protocol使用的是普通Socket来连接的,Http11NioProtocol使用的是NioSocket来连接的。 其中ProtocolHandler由包含了三个部件:Endpoint、Processor、Adapter。 - Endpoint用来处理底层Socket的网络连接,Processor用于将Endpoint接收到的Socket封装成Request,Adapter用于将Request交给Container进行具体的处理。 - Endpoint由于是处理底层的Socket网络连接,因此Endpoint是用来实现TCP/IP协议的,而Processor用来实现HTTP协议的,Adapter将请求适配到Servlet容器进行具体的处理。 - Endpoint的抽象实现AbstractEndpoint里面定义的Acceptor和AsyncTimeout两个内部类和一个Handler接口。Acceptor用于监听请求,AsyncTimeout用于检查异步Request的超时,Handler用于处理接收到的Socket,在内部调用Processor进行处理。 至此,我们应该很轻松的回答(1)(2)(3)的问题了,但是(4)还是不知道, 那么我们就来看一下Container是如何进行处理的以及处理完之后是如何将处理完的结果返回给Connector的? ### 五、Container架构分析 Container用于封装和管理Servlet,以及具体处理Request请求,在Connector内部包含了4个子容器,结构图如下(图C): ![image](https://github.com/tianhuan168/Doc/raw/master/img/10.webp) 4个子容器的作用分别是: - Engine:引擎,用来管理多个站点,一个Service最多只能有一个Engine; - Host:代表一个站点,也可以叫虚拟主机,通过配置Host就可以添加站点; - Context:代表一个应用程序,对应着平时开发的一套程序,或者一个WEB-INF目录以及下面的web.xml文件; - Wrapper:每一Wrapper封装着一个Servlet; 下面找一个Tomcat的文件目录对照一下,如下图所示: ![image](https://github.com/tianhuan168/Doc/raw/master/img/11.webp) Context和Host的区别是Context表示一个应用,我们的Tomcat中默认的配置下webapps下的每一个文件夹目录都是一个Context, 其中ROOT目录中存放着主应用,其他目录存放着子应用,而整个webapps就是一个Host站点。 我们访问应用Context的时候,如果是ROOT下的则直接使用域名就可以访问, 例如:www.ledouit.com,如果是Host(webapps)下的其他应用,则可以使用www.ledouit.com/docs进行访问, 当然默认指定的根应用(ROOT)是可以进行设定的,只不过Host站点下默认的主营用是ROOT目录下的。 看到这里我们知道Container是什么,但是还是不知道Container是如何进行处理的以及处理完之后是如何将处理完的结果 返回给Connector的?别急!下边就开始探讨一下Container是如何进行处理的! ### 六、Container如何处理请求的 Container处理请求是使用Pipeline-Valve管道来处理的!(Valve是阀门之意) Pipeline-Valve是责任链模式,责任链模式是指在一个请求处理的过程中有很多处理者依次对请求进行处理, 每个处理者负责做自己相应的处理,处理完之后将处理后的请求返回,再让下一个处理着继续处理。 ![image](https://github.com/tianhuan168/Doc/raw/master/img/12.webp) 但是!Pipeline-Valve使用的责任链模式和普通的责任链模式有些不同!区别主要有以下两点: - 每个Pipeline都有特定的Valve,而且是在管道的最后一个执行,这个Valve叫做BaseValve,BaseValve是不可删除的; - 在上层容器的管道的BaseValve中会调用下层容器的管道。 我们知道Container包含四个子容器,而这四个子容器对应的BaseValve分别在: **StandardEngineValve**、**StandardHostValve**、**StandardContextValve**、**StandardWrapperValve**。 Pipeline的处理流程图如下(图D): ![image](https://github.com/tianhuan168/Doc/raw/master/img/13.webp) - Connector在接收到请求后会首先调用最顶层容器的Pipeline来处理,这里的最顶层容器的Pipeline就是EnginePipeline(Engine的管道); - 在Engine的管道中依次会执行EngineValve1、EngineValve2等等,最后会执行StandardEngineValve,在StandardEngineValve中会调用Host管道,然后再依次执行Host的HostValve1、HostValve2等,最后在执行StandardHostValve,然后再依次调用Context的管道和Wrapper的管道,最后执行到StandardWrapperValve。 - 当执行到StandardWrapperValve的时候,会在StandardWrapperValve中创建FilterChain,并调用其doFilter方法来处理请求,这个FilterChain包含着我们配置的与请求相匹配的Filter和Servlet,其doFilter方法会依次调用所有的Filter的doFilter方法和Servlet的service方法,这样请求就得到了处理! - 当所有的Pipeline-Valve都执行完之后,并且处理完了具体的请求,这个时候就可以将返回的结果交给Connector了,Connector在通过Socket的方式将结果返回给客户端。 <file_sep> ![image](https://images2015.cnblogs.com/blog/37237/201512/37237-20151222220329015-207666376.png) ### 说一说I/O 首先来说一下什么是I/O? 在计算机系统中I/O就是输入(Input)和输出(Output)的意思,针对不同的操作对象,可以划分为磁盘I/O模型,网络I/O模型,内存映射I/O, Direct I/O、数据库I/O等,只要具有输入输出类型的交互系统都可以认为是I/O系统,也可以说I/O是整个操作系统数据交换与人机交互的通道,这个概念与选用的开发语言没有关系,是一个通用的概念。 在如今的系统中I/O却拥有很重要的位置,现在系统都有可能处理大量文件,大量数据库操作,而这些操作都依赖于系统的I/O性能,也就造成了现在系统的瓶颈往往都是由于I/O性能造成的。因此,为了解决磁盘I/O性能慢的问题,系统架构中添加了缓存来提高响应速度;或者有些高端服务器从硬件级入手,使用了固态硬盘(SSD)来替换传统机械硬盘;在大数据方面,Spark越来越多的承担了实时性计算任务,而传统的Hadoop体系则大多应用在了离线计算与大量数据存储的场景,这也是由于磁盘I/O性能远不如内存I/O性能而造成的格局(Spark更多的使用了内存,而MapReduece更多的使用了磁盘)。因此,一个系统的优化空间,往往都在低效率的I/O环节上,很少看到一个系统CPU、内存的性能是其整个系统的瓶颈。也正因为如此,Java在I/O上也一直在做持续的优化,从JDK 1.4开始便引入了NIO模型,大大的提高了以往BIO模型下的操作效率。 这里先给出BIO、NIO、AIO的基本定义与类比描述: - BIO (Blocking I/O):同步阻塞I/O模式,数据的读取写入必须阻塞在一个线程内等待其完成。这里使用那个经典的烧开水例子,这里假设一个烧开水的场景,有一排水壶在烧开水,BIO的工作模式就是, 叫一个线程停留在一个水壶那,直到这个水壶烧开,才去处理下一个水壶。但是实际上线程在等待水壶烧开的时间段什么都没有做。 - NIO (New I/O):同时支持阻塞与非阻塞模式,但这里我们以其同步非阻塞I/O模式来说明,那么什么叫做同步非阻塞?如果还拿烧开水来说,NIO的做法是叫一个线程不断的轮询每个水壶的状态,看看是否有水壶的状态发生了改变,从而进行下一步的操作。 - AIO ( Asynchronous I/O):异步非阻塞I/O模型。异步非阻塞与同步非阻塞的区别在哪里?异步非阻塞无需一个线程去轮询所有IO操作的状态改变,在相应的状态改变后,系统会通知对应的线程来处理。对应到烧开水中就是,为每个水壶上面装了一个开关,水烧开之后,水壶会自动通知我水烧开了。 ##### 进程中的IO调用步骤大致可以分为以下四步: 1. 进程向操作系统请求数据 ; 1. 操作系统把外部数据加载到内核的缓冲区中; 1. 操作系统把内核的缓冲区拷贝到进程的缓冲区 ; 1. 进程获得数据完成自己的功能 ; 当操作系统在把外部数据放到进程缓冲区的这段时间(即上述的第二,三步),如果应用进程是挂起等待的,那么就是同步IO,反之,就是异步IO,也就是AIO 。 ### BIO(Blocking I/O)同步阻塞I/O 这是最基本与简单的I/O操作方式,其根本特性是做完一件事再去做另一件事,一件事一定要等前一件事做完,这很符合程序员传统的顺序来开发思想,因此BIO模型程序开发起来较为简单,易于把握。 但是BIO如果需要同时做很多事情(例如同时读很多文件,处理很多tcp请求等),就需要系统创建很多线程来完成对应的工作,因为BIO模型下一个线程同时只能做一个工作,如果线程在执行过程中依赖于需要等待的资源,那么该线程会长期处于阻塞状态,我们知道在整个操作系统中,线程是系统执行的基本单位,在BIO模型下的线程 阻塞就会导致系统线程的切换,从而对整个系统性能造成一定的影响。当然如果我们只需要创建少量可控的线程,那么采用BIO模型也是很好的选择,但如果在需要考虑高并发的web或者tcp服务器中采用BIO模型就无法应对了,如果系统开辟成千上万的线程,那么CPU的执行时机都会浪费在线程的切换中,使得线程的执行效率大大降低。此外,关于线程这里说一句题外话,在系统开发中线程的生命周期一定要准确控制,在需要一定规模并发的情形下,尽量使用线程池来确保线程创建数目在一个合理的范围之内,切莫编写线程数量创建上限的代码。 ### NIO (New I/O) 同步非阻塞I/O 关于NIO,国内有很多技术博客将英文翻译成No-Blocking I/O,非阻塞I/O模型 ,当然这样就与BIO形成了鲜明的特性对比。NIO本身是基于事件驱动的思想来实现的,其目的就是解决BIO的大并发问题,在BIO模型中,如果需要并发处理多个I/O请求,那就需要多线程来支持,NIO使用了多路复用器机制,以socket使用来说,多路复用器通过不断轮询各个连接的状态,只有在socket有流可读或者可写时,应用程序才需要去处理它,在线程的使用上,就不需要一个连接就必须使用一个处理线程了,而是只是有效请求时(确实需要进行I/O处理时),才会使用一个线程去处理,这样就避免了BIO模型下大量线程处于阻塞等待状态的情景。 相对于BIO的流,NIO抽象出了新的通道(Channel)作为输入输出的通道,并且提供了缓存(Buffer)的支持,在进行读操作时,需要使用Buffer分配空间,然后将数据从Channel中读入Buffer中,对于Channel的写操作,也需要现将数据写入Buffer,然后将Buffer写入Channel中。 如下是NIO方式进行文件拷贝操作的示例,见下图: ``` public static void copyFile(String srcFileName, String dstFileName) { try (FileInputStream in = new FileInputStream(srcFileName); FileOutputStream out = new FileOutputStream(dstFileName)) { FileChannel readChannel = in.getChannel(); FileChannel writeChannel = out.getChannel(); ByteBuffer buffer = ByteBuffer.allocate(1024); while (true) { buffer.clear(); if (readChannel.read(buffer) == 0) { break; } buffer.flip(); writeChannel.write(buffer); } }catch (IOException e){ e.printStackTrace(); } } ``` 通过比较New IO的使用方式我们可以发现,新的IO操作不再面向 Stream来进行操作了,改为了通道Channel,并且使用了更加灵活的缓存区类Buffer,Buffer只是缓存区定义接口, 根据需要,我们可以选择对应类型的缓存区实现类。在java NIO编程中,我们需要理解以下3个对象Channel、Buffer和Selector。 #### Selector Selector 是NIO相对于BIO实现多路复用的基础,Selector 运行单线程处理多个 Channel,如果你的应用打开了多个通道,但每个连接的流量都很低,使用 Selector 就会很方便。例如在一个聊天服务器中。要使用 Selector , 得向 Selector 注册 Channel,然后调用它的 select() 方法。这个方法会一直阻塞到某个注册的通道有事件就绪。一旦这个方法返回,线程就可以处理这些事件,事件的例子有如新的连接进来、数据接收等。 这里我们再来看一个NIO模型下的TCP服务器的实现,我们可以看到Selector 正是NIO模型下 TCP Server 实现IO复用的关键,请仔细理解下段代码while循环中的逻辑,见下图: ![image](https://user-gold-cdn.xitu.io/2017/8/14/46ea294c619f83564eaa2962d0267ae3?imageView2/0/w/1280/h/960/format/webp/ignore-error/1) #### Channel 首先说一下Channel,国内大多翻译成“通道”。Channel和IO中的Stream(流)是差不多一个等级的。只不过Stream是单向的,譬如:InputStream, OutputStream。而Channel是双向的,既可以用来进行读操作,又可以用来进行写操作,NIO中的Channel的主要实现有:FileChannel、DatagramChannel、SocketChannel、ServerSocketChannel;通过看名字就可以猜出个所以然来:分别可以对应文件IO、UDP和TCP(Server和Client)。 #### Buffer NIO中的关键Buffer实现有:ByteBuffer、CharBuffer、DoubleBuffer、 FloatBuffer、IntBuffer、 LongBuffer,、ShortBuffer,分别对应基本数据类型: byte、char、double、 float、int、 long、 short。当然NIO中还有MappedByteBuffer, HeapByteBuffer, DirectByteBuffer等这里先不具体陈述其用法细节。 ##### 说一下 DirectByteBuffer 与 HeapByteBuffer 的区别? 它们 ByteBuffer 分配内存的两种方式。HeapByteBuffer 顾名思义其内存空间在 JVM 的 heap(堆)上分配,可以看做是 jdk 对于 byte[] 数组的封装;而 DirectByteBuffer 则直接利用了系统接口进行内存申请,其内存分配在c heap 中,这样就减少了内存之间的拷贝操作,如此一来,在使用 DirectByteBuffer 时,系统就可以直接从内存将数据写入到 Channel 中,而无需进行 Java 堆的内存申请,复制等操作,提高了性能。既然如此,为什么不直接使用 DirectByteBuffer,还要来个 HeapByteBuffer?原因在于, DirectByteBuffer 是通过full gc来回收内存的,DirectByteBuffer会自己检测情况而调用 system.gc(),但是如果参数中使用了 DisableExplicitGC 那么就无法回收该快内存了,-XX:+DisableExplicitGC标志自动将 System.gc() 调用转换成一个空操作,就是应用中调用 System.gc() 会变成一个空操作,那么如果设置了就需要我们手动来回收内存了,所以DirectByteBuffer使用起来相对于完全托管于 java 内存管理的Heap ByteBuffer 来说更复杂一些,如果用不好可能会引起OOM。Direct ByteBuffer 的内存大小受 -XX:MaxDirectMemorySize JVM 参数控制(默认大小64M),在 DirectByteBuffer 申请内存空间达到该设置大小后,会触发 Full GC。 #### AIO (Asynchronous I/O) 异步非阻塞I/O Java AIO就是Java作为对异步IO提供支持的NIO.2 ,Java NIO2 (JSR 203)定义了更多的 New I/O APIs, 提案2003提出,直到2011年才发布, 最终在JDK 7中才实现。JSR 203除了提供更多的文件系统操作API(包括可插拔的自定义的文件系统), 还提供了对socket和文件的异步 I/O操作。 同时实现了JSR-51提案中的socket channel全部功能,包括对绑定, option配置的支持以及多播multicast的实现。 从编程模式上来看AIO相对于NIO的区别在于,NIO需要使用者线程不停的轮询IO对象,来确定是否有数据准备好可以读了,而AIO则是在数据准备好之后,才会通知数据使用者,这样使用者就不需要不停地轮询了。当然AIO的异步特性并不是Java实现的伪异步,而是使用了系统底层API的支持,在Unix系统下,采用了epoll IO模型,而windows便是使用了IOCP模型。关于Java AIO,本篇只做一个抛砖引玉的介绍,如果你在实际工作中用到了,那么可以参考Netty在高并发下使用AIO的相关技术。 ### 总 结 IO实质上与线程没有太多的关系,但是不同的IO模型改变了应用程序使用线程的方式,NIO与AIO的出现解决了很多BIO无法解决的并发问题,当然任何技术抛开适用场景都是耍流氓,复杂的技术往往是为了解决简单技术无法解决的问题而设计的,在系统开发中能用常规技术解决的问题,绝不用复杂技术,否则大大增加系统代码的维护难度,学习IT技术不是为了炫技,而是要实实在在解决问题。 <file_sep>## Dubbo的负载均衡 ### 背景 Dubbo是一个分布式服务框架,能避免单点故障和支持服务的横向扩容。一个服务通常会部署多个实例。如何从多个服务 Provider 组成的集群中挑选出一个进行调用,就涉及到一个负载均衡的策略。 ### 几个概念 在讨论负载均衡之前,我想先解释一下这3个概念。 1. 负载均衡 1. 集群容错 1. 服务路由 这3个概念容易混淆。他们都描述了怎么从多个 Provider 中选择一个来进行调用。那他们到底有什么区别呢?下面我来举一个简单的例子,把这几个概念阐述清楚吧。 有一个Dubbo的用户服务,在北京部署了10个,在上海部署了20个。一个杭州的服务消费方发起了一次调用,然后发生了以下的事情: 1. 根据配置的路由规则,如果杭州发起的调用,会路由到比较近的上海的20个 Provider。 1. 根据配置的随机负载均衡策略,在20个 Provider 中随机选择了一个来调用,假设随机到了第7个 Provider。 1. 结果调用第7个 Provider 失败了。 1. 根据配置的Failover集群容错模式,重试其他服务器。 1. 重试了第13个 Provider,调用成功。 上面的第1,2,4步骤就分别对应了路由,负载均衡和集群容错。 Dubbo中,先通过路由,从多个 Provider 中按照路由规则,选出一个子集。再根据负载均衡从子集中选出一个 Provider 进行本次调用。如果调用失败了,根据集群容错策略,进行重试或定时重发或快速失败等。 可以看到Dubbo中的路由,负载均衡和集群容错发生在一次RPC调用的不同阶段。最先是路由,然后是负载均衡,最后是集群容错。 本文档只讨论负载均衡,路由和集群容错在其他的文档中进行说明。 ### Dubbo内置负载均衡策略 #### Dubbo内置了4种负载均衡策略: - **RandomLoadBalance**:随机负载均衡。随机的选择一个。是Dubbo的默认负载均衡策略。 - **RoundRobinLoadBalance**:轮询负载均衡。轮询选择一个。 - **LeastActiveLoadBalance**:最少活跃调用数,相同活跃数的随机。活跃数指调用前后计数差。使慢的 Provider 收到更少请求,因为越慢的 Provider 的调用前后计数差会越大。 - **ConsistentHashLoadBalance**:一致性哈希负载均衡。相同参数的请求总是落在同一台机器上。 #### 1.随机负载均衡 顾名思义,随机负载均衡策略就是从多个 Provider 中随机选择一个。但是 Dubbo 中的随机负载均衡有一个权重的概念,即按照权重设置随机概率。比如说,有10个 Provider,并不是说,每个 Provider 的概率都是一样的,而是要结合这10个 Provider 的权重来分配概率。 Dubbo中,可以对 Provider 设置权重。比如机器性能好的,可以设置大一点的权重,性能差的,可以设置小一点的权重。权重会对负载均衡产生影响。可以在Dubbo Admin中对 Provider 进行权重的设置。 ##### 基于权重的负载均衡算法 随机策略会先判断所有的 Invoker 的权重是不是一样的,如果都是一样的,那么处理就比较简单了。使用random.nexInt(length)就可以随机生成一个 Invoker 的序号,根据序号选择对应的 Invoker 。如果没有在Dubbo Admin中对服务 Provider 设置权重,那么所有的 Invoker 的权重就是一样的,默认是100。 如果权重不一样,那就需要结合权重来设置随机概率了。算法大概如下: 假如有4个 Invoker。 invoker | weight ---|--- A | 10 B | 20 C | 20 D | 30 1--------10 -------------------30------------------50 ------------------80 |-----A----|---------B----------|----------C---------|--------D------------| A,B,C和D总的权重是10 + 20 + 20 + 30 = 80 上面的图中一共有4块区域,长度分别是A,B,C和D的权重。使用random.nextInt(10 + 20 + 20 + 30),从80个数中随机选择一个。然后再判断该数分布在哪个区域。比如,如果随机到37,37是分布在C区域的,那么就选择 Invoker C。15是在B区域,54是在D区域。 ##### #### 随机负载均衡源码 ``` public class RandomLoadBalance extends AbstractLoadBalance { private final Random random = new Random(); protected <T> Invoker<T> doSelect(List<Invoker<T>> invokers, URL url, Invocation invocation) { int length = invokers.size(); // Invoker 总数 int totalWeight = 0; // 所有 Invoker 的权重的和 // 判断是不是所有的 Invoker 的权重都是一样的 // 如果权重都一样,就简单了。直接用Random生成索引就可以了。 boolean sameWeight = true; for (int i = 0; i < length; i++) { int weight = getWeight(invokers.get(i), invocation); totalWeight += weight; // Sum if (sameWeight && i > 0 && weight != getWeight(invokers.get(i - 1), invocation)) { sameWeight = false; } } if (totalWeight > 0 && !sameWeight) { // 如果不是所有的 Invoker 权重都相同,那么基于权重来随机选择。权重越大的,被选中的概率越大 int offset = random.nextInt(totalWeight); for (int i = 0; i < length; i++) { offset -= getWeight(invokers.get(i), invocation); if (offset < 0) { return invokers.get(i); } } } // 如果所有 Invoker 权重相同 return invokers.get(random.nextInt(length)); } } ``` #### 2.轮询负载均衡 轮询负载均衡,就是依次的调用所有的 Provider。和随机负载均衡策略一样,轮询负载均衡策略也有权重的概念。 轮询负载均衡算法可以让RPC调用严格按照我们设置的比例来分配。不管是少量的调用还是大量的调用。但是轮询负载均衡算法也有不足的地方,存在慢的 Provider 累积请求的问题,比如:第二台机器很慢,但没挂,当请求调到第二台时就卡在那,久而久之,所有请求都卡在调到第二台上,导致整个系统变慢。 #### 3.最少活跃调用数负载均衡 官方解释: 最少活跃调用数,相同活跃数的随机,活跃数指调用前后计数差,使慢的机器收到更少。 这个解释好像说的不是太明白。目的是让更慢的机器收到更少的请求,但具体怎么实现的还是不太清楚。举个例子:每个服务维护一个活跃数计数器。当A机器开始处理请求,该计数器加1,此时A还未处理完成。若处理完毕则计数器减1。而B机器接受到请求后很快处理完毕。那么A,B的活跃数分别是1,0。当又产生了一个新的请求,则选择B机器去执行(B活跃数最小),这样使慢的机器A收到少的请求。 处理一个新的请求时,Consumer 会检查所有 Provider 的活跃数,如果具有最小活跃数的 Invoker 只有一个,直接返回该 Invoker: ``` if (leastCount == 1) { // 如果只有一个最小则直接返回 return invokers.get(leastIndexs[0]); } ``` 如果最小活跃数的 Invoker 有多个,且权重不相等同时总权重大于0,这时随机生成一个权重,范围在 (0,totalWeight) 间内。最后根据随机生成的权重,来选择 Invoker。 ``` if (! sameWeight && totalWeight > 0) { // 如果权重不相同且权重大于0则按总权重数随机 int offsetWeight = random.nextInt(totalWeight); // 并确定随机值落在哪个片断上 for (int i = 0; i < leastCount; i++) { int leastIndex = leastIndexs[i]; offsetWeight -= getWeight(invokers.get(leastIndex), invocation); if (offsetWeight <= 0) return invokers.get(leastIndex); } } ``` ### 4.一致性Hash算法 使用一致性 Hash 算法,让相同参数的请求总是发到同一 Provider。 当某一台 Provider 崩溃时,原本发往该 Provider 的请求,基于虚拟节点,平摊到其它 Provider,不会引起剧烈变动。 一致性Hash算法可以和缓存机制配合起来使用。比如有一个服务getUserInfo(String userId)。设置了Hash算法后,相同的userId的调用,都会发送到同一个 Provider。这个 Provider 上可以把用户数据在内存中进行缓存,减少访问数据库或分布式缓存的次数。如果业务上允许这部分数据有一段时间的不一致,可以考虑这种做法。减少对数据库,缓存等中间件的依赖和访问次数,同时减少了网络IO操作,提高系统性能。 ### 负载均衡配置 如果不指定负载均衡,默认使用随机负载均衡。我们也可以根据自己的需要,显式指定一个负载均衡。 可以在多个地方类来配置负载均衡,比如 Provider 端,Consumer端,服务级别,方法级别等。 ### 服务端服务级别 ``` <dubbo:service interface="..." loadbalance="roundrobin" /> ``` 该服务的所有方法都使用roundrobin负载均衡。 #### 客户端服务级别 ``` <dubbo:reference interface="..." loadbalance="roundrobin" /> ``` <file_sep>&emsp;&emsp;前些日子去瓜子二手车去面试,整个过程轻松愉快。 跟面试官从架构到底层的各种讨论,以及各种假想情况下的架构设计。 &emsp;&emsp;其中谈到了一个dubbo的负载均衡的策略, 凭着记忆,列出了四种策略,详细的说明了随机策略(默认的)的实现原理,并稍微带过了轮询/最少活跃/一致性哈希的策略。 &emsp;&emsp;引申到了***一致性哈希***的算法,然后引申到了redis的一致性hash是怎么实现的,如果有3台服务器,key均匀的分布在3台服务器组成的hash轮盘上, 如果有一台机器挂掉或者新增一台服务器以后,是怎么实现快速准确定位到key上的。 &emsp;&emsp;当时脑袋一片空白,平时很少去关注集群的东西,面试前也突击了部分redis的面试点,但是这个一致性hash还是真的没有去看过, 凭着自己平时的见解,简单给出了部分方案: 1. **主从复制,一个服务器挂掉,去从salver上去获取,就近原则** 1. **伪装服务器一直存在,平稳迁移key去剩余的其他服务器(没理论经验)** 回来后查了一部分资料,特意收集起来,方便以后查阅 ---- ### 一、Redis集群的使用 &emsp;&emsp;我们在使用Redis的时候,为了保证Redis的高可用,提高Redis的读写性能,最简单的方式我们会做主从复制,组成Master-Master或者Master-Slave的形式,或者搭建Redis集群,进行数据的读写分离,类似于数据库的主从复制和读写分离。如下所示: ![image](https://img-blog.csdn.net/20180313185756947?watermark/2/text/Ly9ibG9nLmNzZG4ubmV0L3UwMTA4NzA1MTg=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70) &emsp;&emsp;同样类似于数据库,当单表数据大于500W的时候需要对其进行分库分表,当数据量很大的时候(标准可能不一样,要看Redis服务器容量)我们同样可以对Redis进行类似的操作,就是分库分表。 &emsp;&emsp;假设,我们有一个社交网站,需要使用Redis存储图片资源,存储的格式为键值对,key值为图片名称,value为该图片所在文件服务器的路径,我们需要根据文件名查找该文件所在文件服务器上的路径,数据量大概有2000W左右,按照我们约定的规则进行分库,规则就是随机分配,我们可以部署8台缓存服务器,每台服务器大概含有500W条数据,并且进行主从复制,示意图如下: ![image](https://img-blog.csdn.net/20180313193304478?watermark/2/text/Ly9ibG9nLmNzZG4ubmV0L3UwMTA4NzA1MTg=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70) &emsp;&emsp;由于规则是随机的,所有我们的一条数据都有可能存储在任何一组Redis中,例如上图我们用户查找一张名称为”**a.png**”的图片,由于规则是随机的,我们不确定具体是在哪一个Redis服务器上的,因此我们需要进行1、2、3、4,4次查询才能够查询到(也就是遍历了所有的Redis服务器),这显然不是我们想要的结果,有了解过的小伙伴可能会想到,随机的规则不行,可以使用类似于数据库中的分库分表规则:按照Hash值、取模、按照类别、按照某一个字段值等等常见的规则就可以出来了!好,按照我们的主题,我们就使用Hash的方式。 ### 为Redis集群使用Hash &emsp;&emsp;可想而知,如果我们使用Hash的方式,每一张图片在进行分库的时候都可以定位到特定的服务器,示意图如下: ![image](https://img-blog.csdn.net/20180313194244214?watermark/2/text/Ly9ibG9nLmNzZG4ubmV0L3UwMTA4NzA1MTg=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70) &emsp;&emsp;上图中,假设我们查找的是”a.png”,由于有4台服务器(排除从库),因此公式为hash(a.png) % 4 = 2 ,可知定位到了第2号服务器,这样的话就不会遍历所有的服务器,大大提升了性能! ### 三、使用Hash的问题 &emsp;&emsp;上述的方式虽然提升了性能,我们不再需要对整个Redis服务器进行遍历!但是,使用上述Hash算法进行缓存时,会出现一些缺陷,主要体现在服务器数量变动的时候,所有缓存的位置都要发生改变! &emsp;&emsp;试想一下,如果4台缓存服务器已经不能满足我们的缓存需求,那么我们应该怎么做呢?很简单,多增加几台缓存服务器不就行了!假设:我们增加了一台缓存服务器,那么缓存服务器的数量就由4台变成了5台。那么原本hash(a.png) % 4 = 2 的公式就变成了hash(a.png) % 5 = ? , &emsp;&emsp;可想而知这个结果肯定不是2的,这种情况带来的结果就是当服务器数量变动时,所有缓存的位置都要发生改变!换句话说,当服务器数量发生改变时,所有缓存在一定时间内是失效的,当应用无法从缓存中获取数据时,则会向后端数据库请求数据(还记得上一篇的《缓存雪崩》吗?)! &emsp;&emsp;同样的,假设4台缓存中突然有一台缓存服务器出现了故障,无法进行缓存,那么我们则需要将故障机器移除,但是如果移除了一台缓存服务器,那么缓存服务器数量从4台变为3台,也是会出现上述的问题! &emsp;&emsp;所以,我们应该想办法不让这种情况发生,但是由于上述Hash算法本身的缘故,使用取模法进行缓存时,这种情况是无法避免的,为了解决这些问题,Hash一致性算法(一致性Hash算法)诞生了! ### 四、一致性Hash算法的神秘面纱 一致性Hash算法也是使用取模的方法,只是,刚才描述的取模法是对服务器的数量进行取模,而一致性Hash算法是对2^32取模,什么意思呢?简单来说,一致性Hash算法将整个哈希值空间组织成一个虚拟的圆环,如假设某哈希函数H的值空间为0-2^32-1(即哈希值是一个32位无符号整形),整个哈希环如下: &emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp; ![image](https://pic2.zhimg.com/80/v2-aef0c79a38a74e46de3ae8ac886ae415_hd.jpg) &emsp;&emsp;整个空间按顺时针方向组织,圆环的正上方的点代表0,0点右侧的第一个点代表1,以此类推,2、3、4、5、6……直到2^32-1,也就是说0点左侧的第一个点代表2^32-1, 0和2^32-1在零点中方向重合,我们把这个由2^32个点组成的圆环称为Hash环。 &emsp;&emsp;下一步将各个服务器使用Hash进行一个哈希,具体可以选择服务器的IP或主机名作为关键字进行哈希,这样每台机器就能确定其在哈希环上的位置,这里假设将上文中四台服务器使用IP地址哈希后在环空间的位置如下: ![image](https://img-blog.csdn.net/20180313201032423?watermark/2/text/Ly9ibG9nLmNzZG4ubmV0L3UwMTA4NzA1MTg=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70) 接下来使用如下算法定位数据访问到相应服务器:将数据key使用相同的函数Hash计算出哈希值,并确定此数据在环上的位置,从此位置沿环顺时针“行走”,第一台遇到的服务器就是其应该定位到的服务器! 例如我们有Object A、Object B、Object C、Object D四个数据对象,经过哈希计算后,在环空间上的位置如下: ![image](https://img-blog.csdn.net/20180313201103575?watermark/2/text/Ly9ibG9nLmNzZG4ubmV0L3UwMTA4NzA1MTg=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70) 根据一致性Hash算法,数据A会被定为到Node A上,B被定为到Node B上,C被定为到Node C上,D被定为到Node D上。 ### 五、一致性Hash算法的容错性和可扩展性 现假设Node C不幸宕机,可以看到此时对象A、B、D不会受到影响,只有C对象被重定位到Node D。一般的,在一致性Hash算法中,如果一台服务器不可用,则受影响的数据仅仅是此服务器到其环空间中前一台服务器(即沿着逆时针方向行走遇到的第一台服务器)之间数据,其它不会受到影响,如下所示: ![image](https://img-blog.csdn.net/20180313203546415?watermark/2/text/Ly9ibG9nLmNzZG4ubmV0L3UwMTA4NzA1MTg=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70) 下面考虑另外一种情况,如果在系统中增加一台服务器Node X,如下图所示: ![image](https://img-blog.csdn.net/20180313201131189?watermark/2/text/Ly9ibG9nLmNzZG4ubmV0L3UwMTA4NzA1MTg=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70) 此时对象Object A、B、D不受影响,只有对象C需要重定位到新的Node X !一般的,在一致性Hash算法中,如果增加一台服务器,则受影响的数据仅仅是新服务器到其环空间中前一台服务器(即沿着逆时针方向行走遇到的第一台服务器)之间数据,其它数据也不会受到影响。 综上所述,一致性Hash算法对于节点的增减都只需重定位环空间中的一小部分数据,具有较好的容错性和可扩展性。 ### 六、Hash环的数据倾斜问题 一致性Hash算法在服务节点太少时,容易因为节点分部不均匀而造成数据倾斜(被缓存的对象大部分集中缓存在某一台服务器上)问题,例如系统中只有两台服务器,其环分布如下: ![image](https://img-blog.csdn.net/20180313205220384?watermark/2/text/Ly9ibG9nLmNzZG4ubmV0L3UwMTA4NzA1MTg=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70) 此时必然造成大量数据集中到Node A上,而只有极少量会定位到Node B上。为了解决这种数据倾斜问题,一致性Hash算法引入了虚拟节点机制,即对每一个服务节点计算多个哈希,每个计算结果位置都放置一个此服务节点,称为虚拟节点。具体做法可以在服务器IP或主机名的后面增加编号来实现。 例如上面的情况,可以为每台服务器计算三个虚拟节点,于是可以分别计算 “Node A#1”、“Node A#2”、“Node A#3”、“Node B#1”、“Node B#2”、“Node B#3”的哈希值,于是形成六个虚拟节点: ![image](https://img-blog.csdn.net/20180313201223343?watermark/2/text/Ly9ibG9nLmNzZG4ubmV0L3UwMTA4NzA1MTg=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70) 同时数据定位算法不变,只是多了一步虚拟节点到实际节点的映射,例如定位到“Node A#1”、“Node A#2”、“Node A#3”三个虚拟节点的数据均定位到Node A上。这样就解决了服务节点少时数据倾斜的问题。在实际应用中,通常将虚拟节点数设置为32甚至更大,因此即使很少的服务节点也能做到相对均匀的数据分布。 <file_sep>### 线程池的创建 线程池通过复用线程,避免线程频繁创建和销毁。 Java的Executors工具类中,提供了5种类型线程池的创建方法,它们的特点和适用场景如下: - 第1种是:固定大小线程池,特点是线程数固定,使用无界队列,适用于任务数量不均匀的场景、对内存压力不敏感,但系统负载比较敏感的场景; ``` ExecutorService ex = Executors.newFixedThreadPool(16); ``` - 第2种是:Cached线程池,特点是不限制线程数,适用于要求低延迟的短期任务场景; ``` ExecutorService ex = Executors.newCachedThreadPool(); ``` - 第3种是:单线程线程池,也就是一个线程的固定线程池,适用于需要异步执行但需要保证任务顺序的场景; ``` ExecutorService ex = Executors.newSingleThreadExecutor(); ``` - 第4种是:Scheduled线程池,适用于定期执行任务场景,支持按固定频率定期执行和按固定延时定期执行两种方式; ``` ExecutorService ex = Executors.newScheduledThreadPool(16); ``` - 第5种是:工作窃取线程池,使用的ForkJoinPool,是固定并行度的多任务队列,适合任务执行时长不均匀的场景。 ``` ExecutorService ex = Executors.newWorkStealingPool(); ``` ### 线程池参数介绍 ``` public ThreadPoolExecutor(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler) ``` - 第1个参数corePoolSize:设置核心线程数。默认情况下核心线程会一直存活。 - 第2个参数maximumPoolSize:设置最大线程数。决定线程池最多可以创建的多少线程。 - 第3个参数keepAliveTime和第4个参数unit:用来设置线程空闲时间,和空闲时间的单位,当线程闲置超过空闲时间就会被销毁。可以通过AllowCoreThreadTimeOut方法来允许核心线程被回收。 - 第5个参数workQueue:设置缓冲队列,图中左下方的三个队列是设置线程池时常使用的缓冲队列。 - 其中**Array BlockingQueue**是一个有界队列,就是指队列有最大容量限制。 - **Linked Blocking Queue**是无界队列,就是队列不限制容量。 - 最后一个是**Synchronous Queue**,是一个同步队列,内部没有缓冲区。 - 第6个参数threadFactory:设置线程池工厂方法,线程工厂用来创建新线程,可以用来对线程的一些属性进行定制,例如线程的Group、线程名、优先级等。一般使用默认工厂类即可。 - 第7个参数handler:设置线程池满时的拒绝策略。 如右下角所示有四种策略: - **abort**策略在线程池满后,提交新任务时会抛出Rejected Execution Exception,这个也是默认的拒绝策略。 - **Discard**策略会在提交失败时对任务直接进行丢弃。 - **CallerRuns**策略会在提交失败时,由提交任务的线程直接执行提交的任务。 - **Discard Oldest**策略会丢弃最早提交的任务 ### 线程池执行流程 我们向线程提交任务时可以使用Execute和Submit,区别就是Submit可以返回一个Future对象,通过Future对象可以了解任务执行情况,可以取消任务的执行,还可获取执行结果或执行异常。Submit最终也是通过Execute执行的。 #### 线程池提交任务时的执行顺序如下: - 向线程池提交任务时,会首先判断线程池中的线程数是否大于设置的核心线程数,如果不大于,就创建一个核心线程来执行任务。 - 如果大于核心线程数,就会判断缓冲队列是否满了,如果没有满,则放入队列,等待线程空闲时执行任务。 - 如果队列已经满了,则判断是否达到了线程池设置的最大线程数,如果没有达到,就创建新线程来执行任务。 - 如果已经达到了最大线程数,则执行指定的拒绝策略。这里需要注意队列的判断与最大线程数判断的顺序,不要搞反。 <file_sep># 八种排序算法原理及Java实现 ## 1. 概述 排序算法分为内部排序和外部排序,内部排序把数据记录放在内存中进行排序,而外部排序因排序的数据量大,内存不能一次容纳全部的排序记录,所以在排序过程中需要访问外存。 ![image](https://user-gold-cdn.xitu.io/2018/9/10/165c15fba21994d3?imageView2/0/w/1280/h/960/format/webp/ignore-error/1) <!-- GFM-TOC --> - [一、冒泡排序](##3.快速排序) - [二、快速排序](##3.快速排序) - [三、堆排序](##3.快速排序) - [四、选择排序](##3.快速排序) - [五、归并排序](##3.快速排序) <!-- GFM-TOC --> ## 2. 冒泡排序 ### 2.1 基本思想 冒泡排序(Bubble Sort)是一种简单的排序算法。它重复访问要排序的数列,一次比较两个元素,如果他们的顺序错误就把他们交换过来。访问数列的工作是重复地进行直到没有再需要交换的数据,也就是说该数列已经排序完成。这个算法的名字由来是因为越小的元素会经由交换慢慢“浮”到数列的顶端,像水中的气泡从水底浮到水面。 ![image](https://user-gold-cdn.xitu.io/2018/9/10/165c1650231bab74?imageslim) ### 2.2 算法描述 冒泡排序算法的算法过程如下: ①. 比较相邻的元素。如果第一个比第二个大,就交换他们两个。 ②. 对每一对相邻元素作同样的工作,从开始第一对到结尾的最后一对。这步做完后,最后的元素会是最大的数。 ③. 针对所有的元素重复以上的步骤,除了最后一个。 ④. 持续每次对越来越少的元素重复上面的步骤①~③,直到没有任何一对数字需要比较。 ### 2.3 代码实现 ``` public static void sort(int[] array) { if (array == null || array.length == 0) { return; } int length = array.length; //外层:需要length-1次循环比较 for (int i = 0; i < length - 1; i++) { //内层:每次循环需要两两比较的次数,每次比较后,都会将当前最大的数放到最后位置,所以每次比较次数递减一次 for (int j = 0; j < length - 1 - i; j++) { if (array[j] > array[j + 1]) { //交换数组array的j和j+1位置的数据 int temp = array[j]; array[j] = array[j + 1]; array[j + 1] = temp; } } } } ``` ## 3. 快速排序 ### 3.1 基本思想 快速排序(Quicksort)是对冒泡排序的一种改进,借用了分治的思想,由<NAME>在1962年提出。它的基本思想是:通过一趟排序将要排序的数据分割成独立的两部分,其中一部分的所有数据都比另外一部分的所有数据都要小,然后再按此方法对这两部分数据分别进行快速排序,整个排序过程可以递归进行,以此达到整个数据变成有序序列。 ### 3.2 算法描述 快速排序使用分治策略来把一个序列(list)分为两个子序列(sub-lists)。步骤为: 1. 从数列中挑出一个元素,称为”基准”(pivot)。 1. 重新排序数列,所有比基准值小的元素摆放在基准前面,所有比基准值大的元素摆在基准后面(相同的数可以到任一边)。在这个分区结束之后,该基准就处于数列的中间位置。这个称为分区(partition)操作。 1. 递归地(recursively)把小于基准值元素的子数列和大于基准值元素的子数列排序。 1. 递归到最底部时,数列的大小是零或一,也就是已经排序好了。这个算法一定会结束,因为在每次的迭代(iteration)中,它至少会把一个元素摆到它最后的位置去。 ![image](https://user-gold-cdn.xitu.io/2018/9/10/165c220dad2f209c?imageslim) ### 3.3 代码实现 #### ①. 挖坑法 用伪代码描述如下: - (1)low = L; high = R; 将基准数挖出形成第一个坑a[low]。 - (2)high--,由后向前找比它小的数,找到后挖出此数填前一个坑a[low]中。 - (3)low++,由前向后找比它大的数,找到后也挖出此数填到前一个坑a[high]中。 - (4)再重复执行②,③二步,直到low==high,将基准数填入a[low]中。 ##### 举例说明: 一个无序数组:[4, 3, 7, 5, 10, 9, 1, 6, 8, 2] - (1)随便先挖个坑,就在第一个元素(基准元素)挖坑,挖出来的“萝卜”(第一个元素4)在“篮子”(临时变量)里备用。 - 挖完之后的数组是这样:[ **坑**, 3, 7, 5, 10, 9, 1, 6, 8,2] - (2)挖右坑填左坑:从右边开始,找个比“萝卜”(元素4)小的元素,挖出来,填到前一个坑里面。 - 填坑之后:[ 2, 3, 7, 5, 10, 9, 1, 6, 8,**坑**] - (3)挖左坑填右坑:从左边开始,找个比“萝卜”(元素4)大的元素,挖出来,填到右边的坑里面。 - 填坑之后:[ 2, 3,**坑**, 5, 10, 9, 1, 6, 8, 7] - (4)挖右坑填左坑:从右边开始,找个比“萝卜”(元素4)小的元素,挖出来,填到前一个坑里面。 - 填坑之后:[ 2, 3, 1, 5, 10, 9,**坑**, 6, 8, 7] - (5)挖左坑填右坑:从左边开始,找个比“萝卜”(元素4)大的元素,挖出来,填到右边的坑里面。 - 填坑之后:[ 2, 3, 1,**坑**, 10, 9, 5, 6, 8, 7] - (6)挖右坑填左坑:从右边开始,找个比“萝卜”(元素4)小的元素,挖出来,填到前一个坑里面,这一次找坑的过程中,找到了上一次挖的坑了,说明可以停了,用篮子里的的萝卜,把这个坑填了就行了,并且返回这个坑的位置,作为分而治之的中轴线。 - 填坑之后:[ 2, 3, 1,**4**, 10, 9, 5, 6, 8, 7] 上面的步骤中,第2,4, 6其实都是一样的操作,3和5的操作也是一样的,代码如下: ``` public static void sort(int arr[], int low, int high) { if (arr == null || arr.length <= 0) { return; } if (low >= high) { return; } int left = low; int right = high; int temp = arr[left]; //保存基准的值 坑1 while (left < right) { while (left < right && arr[right] >= temp) {// 获取基准值右边的小于基准值的下标 right--; } arr[left] = arr[right]; // 从后向前找到比基准小的元素,插入到基准位置坑1中,原来的right下标则重复出现了,此处列为坑2 while (left < right && arr[left] <= temp) { // 获取基准值左边边的大于基准值的下标 left ++; } arr[right] = arr[left]; // 从前往后找到比基准大的元素,放到刚才挖的坑2中,此处的left下标列为坑3 } arr[left] = temp; //基准值填补到坑3中,准备分治递归快排 sort(arr, low, left-1); sort(arr, left + 1, high); } ``` ## 4.堆排序 ### 1、算法思想 1. 将数组构建成大堆二叉树,即所有节点的父节点的值都大于叶子节点的完全二叉树 2. 若叶子节点比父节点大,则交换位置 3. 根节点即为最大值,则将根节点与最后的的一个叶子节点交换位置 4. 重复1,2操作,每次都找最大值则放置最后即可排序完成 ![image](https://user-gold-cdn.xitu.io/2018/6/2/163bedb0f755a69d?imageslim) 此处难以理解,先加进来后续研究 ## 4. 直接插入排序 ### 4.1 基本思想 直接插入排序的基本思想是:将数组中的所有元素依次跟前面已经排好的元素相比较,如果选择的元素比已排序的元素小,则交换,直到全部元素都比较过为止。 ![image](https://user-gold-cdn.xitu.io/2018/9/10/165c25fe0f393246?imageslim) ![image](https://user-gold-cdn.xitu.io/2018/9/10/165c260584694ff9?imageslim) ### 4.3 代码实现 提供两种写法,一种是移位法,一种是交换法。移位法是完全按照以上算法描述实,再插入过程中将有序序列中比待插入数字大的数据向后移动,由于移动时会覆盖待插入数据,所以需要额外的临时变量保存待插入数据,代码实现如下: ``` public static void sort(int[] a) { if (a == null || a.length == 0) { return; } for (int i = 1; i < a.length; i++) { int j = i - 1; int temp = a[i]; // 先取出待插入数据保存,因为向后移位过程中会把覆盖掉待插入数 while (j >= 0 && a[j] > a[i]) { // 如果待是比待插入数据大,就后移 a[j+1] = a[j]; j--; } a[j+1] = temp; // 找到比待插入数据小的位置,将待插入数据插入 } } ``` 而交换法不需求额外的保存待插入数据,通过不停的向前交换带插入数据,类似冒泡法,直到找到比它小的值,也就是待插入数据找到了自己的位置。 ``` public static void sort2(int[] arr) { if (arr == null || arr.length == 0) { return; } for (int i = 1; i < arr.length; i ++) { int j = i - 1; while (j >= 0 && arr[j] > arr[i]) { arr[j + 1] = arr[j] + arr[j+1]; //只要大就交换操作 arr[j] = arr[j + 1] - arr[j]; arr[j + 1] = arr[j + 1] - arr[j]; System.out.println("Sorting: " + Arrays.toString(arr)); } } } ``` ## 6.选择排序 ### 6.1 基本思想 在未排序序列中找到最小(大)元素,存放到未排序序列的起始位置。在所有的完全依靠交换去移动元素的排序方法中,选择排序属于非常好的一种。 ### 6.2 算法描述 - ①. 从待排序序列中,找到关键字最小的元素; - ②. 如果最小元素不是待排序序列的第一个元素,将其和第一个元素互换; - ③. 从余下的 N - 1 个元素中,找出关键字最小的元素,重复①、②步,直到排序结束。 ![image](https://user-gold-cdn.xitu.io/2018/9/10/165c2d4fd254df47?imageslim) ### 6.3 代码实现 ``` public class SelectSort { public static void sort(int[] arr) { for (int i = 0; i < arr.length - 1; i++) { int min = i; // 默认0 for (int j = i+1; j < arr.length; j ++) { //选出之后待排序中值最小的位置 if (arr[j] < arr[min]) { min = j; } } if (min != i) { arr[min] = arr[i] + arr[min]; arr[i] = arr[min] - arr[i]; arr[min] = arr[min] - arr[i]; } } } ``` ## 7.归并排序 归并排序是建立在归并操作上的一种有效的排序算法,1945年由约翰·冯·诺伊曼首次提出。该算法是采用分治法(Divide and Conquer)的一个非常典型的应用,且各层分治递归可以同时进行。 ### 7.1 基本思想 归并排序算法是将两个(或两个以上)有序表合并成一个新的有序表,即把待排序序列分为若干个子序列,每个子序列是有序的。然后再把有序子序列合并为整体有序序列。 ![image](https://user-gold-cdn.xitu.io/2018/9/10/165c2d849cf3a4b6?imageslim) ### 7.2 算法描述 采用递归法: - ①. 将序列每相邻两个数字进行归并操作,形成 floor(n/2)个序列,排序后每个序列包含两个元素; - ②. 将上述序列再次归并,形成 floor(n/4)个序列,每个序列包含四个元素; - ③. 重复步骤②,直到所有元素排序完毕 ![image](https://user-gold-cdn.xitu.io/2018/9/10/165c2d88eb326ec1?imageslim) ### 7.3 代码实现 ``` public class MergeSort { public static int[] sort(int [] a) { if (a.length <= 1) { return a; } int num = a.length >> 1; int[] left = Arrays.copyOfRange(a, 0, num); int[] right = Arrays.copyOfRange(a, num, a.length); return mergeTwoArray(sort(left), sort(right)); } public static int[] mergeTwoArray(int[] a, int[] b) { int i = 0, j = 0, k = 0; int[] result = new int[a.length + b.length]; // 申请额外空间保存归并之后数据 while (i < a.length && j < b.length) { //选取两个序列中的较小值放入新数组 if (a[i] <= b[j]) { result[k++] = a[i++]; } else { result[k++] = b[j++]; } } while (i < a.length) { //序列a中多余的元素移入新数组 result[k++] = a[i++]; } while (j < b.length) {//序列b中多余的元素移入新数组 result[k++] = b[j++]; } return result; } public static void main(String[] args) { int[] b = {3, 1, 5, 4}; System.out.println(Arrays.toString(sort(b))); } } ``` <file_sep># 缓存三大问题及解决方案 ## 1. 缓存来由 随着互联网系统发展的逐步完善,提高系统的qps,目前的绝大部分系统都增加了缓存机制从而避免请求过多的直接与数据库操作从而造成系统瓶颈,极大的提升了用户体验和系统稳定性。 ## 2.缓存处理流程 前台请求,后台先从缓存中取数据,取到直接返回结果,取不到时从数据库中取,数据库取到更新缓存,并返回结果,数据库也没取到,那直接返回空结果。 ![image](http://img-blog.csdn.net/20180919143214712?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2tvbmd0aWFvNQ==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70) ## 3.缓存问题 ### 3.1 缓存穿透 缓存穿透是指查询一个一定不存在的数据,如发起为id为“-1”的数据或id为特别大不存在的数据。因为缓存中也无该数据的信息,则会直接去数据库层进行查询,从系统层面来看像是穿透了缓存层直接达到db,从而称为缓存穿透,没有了缓存层的保护,这种查询一定不存在的数据对系统来说可能是一种危险,如果有人恶意用这种一定不存在的数据来频繁请求系统,不,准确的说是攻击系统,请求都会到达数据库层导致db瘫痪从而引起系统故障。 #### 解决方案 缓存穿透业内的解决方案已经比较成熟,主要常用的有以下几种: 1. bloom filter:类似于哈希表的一种算法,用所有可能的查询条件生成一个bitmap,在进行数据库查询之前会使用这个bitmap进行过滤,如果不在其中则直接过滤,从而减轻数据库层面的压力。 2. 空值缓存:一种比较简单的解决办法,在第一次查询完不存在的数据后,将该key与对应的空值也放入缓存中,只不过设定为较短的失效时间,例如几分钟,这样则可以应对短时间的大量的该key攻击,设置为较短的失效时间是因为该值可能业务无关,存在意义不大,且该次的查询也未必是攻击者发起,无过久存储的必要,故可以早点失效。 3. 接口层增加校验,如用户鉴权校验,id做基础校验,id<=0的直接拦截 ### 3.2 缓存雪崩 在普通的缓存系统中一般例如redis、memcache等中,我们会给缓存设置一个失效时间,但是如果所有的缓存的失效时间相同,那么在同一时间失效时,所有系统的请求都会发送到数据库层,db可能无法承受如此大的压力导致系统崩溃。 #### 解决方案 1. 线程互斥:只让一个线程构建缓存,其他线程等待构建缓存的线程执行完,重新从缓存获取数据才可以,每个时刻只有一个线程在执行请求,减轻了db的压力,但缺点也很明显,降低了系统的qps。 2. 交错失效时间:这种方法时间比较简单粗暴,既然在同一时间失效会造成请求过多雪崩,那我们错开不同的失效时间即可从一定长度上避免这种问题,在缓存进行失效时间设置的时候,从某个适当的值域中随机一个时间作为失效时间即可。 ### 3.3 缓存击穿 缓存击穿是指**缓存中没有但数据库中有的数据**(一般是缓存时间到期),这时由于并发用户特别多,同时读缓存没读到数据,又同时去数据库去取数据,引起数据库压力瞬间增大,造成过大压力。缓存击穿实际上是缓存雪崩的一个特例,大家使用过微博的应该都知道,微博有一个热门话题的功能,用户对于热门话题的搜索量往往在一些时刻会大大的高于其他话题,这种我们成为系统的“热点“,由于系统中对这些热点的数据缓存也存在失效时间,在热点的缓存到达失效时间时,此时可能依然会有大量的请求到达系统,没有了缓存层的保护,这些请求同样的会到达db从而可能引起故障。击穿与雪崩的==区别即在于击穿是对于特定的热点数据==来说,而==雪崩是全部数据==。 #### 解决方案 1. 二级缓存:对于热点数据进行二级缓存,并对于不同级别的缓存设定不同的失效时间,则请求不会直接击穿缓存层到达数据库。 2. 这里参考了阿里双11万亿流量的缓存击穿解决方案,解决此问题的关键在于热点访问。由于热点可能随着时间的变化而变化,针对固定的数据进行特殊缓存是不能起到治本作用的,结合LRU算法能够较好的帮我们解决这个问题。 - LRU(Least recently used,最近最少使用)算法根据数据的历史访问记录来进行淘汰数据,其核心思想是“如果数据最近被访问过,那么将来被访问的几率也更高”。最常见的实现是使用一个链表保存缓存数据,如下图所示 ![image](https://user-gold-cdn.xitu.io/2018/8/3/164ff9d6258344e9?imageView2/0/w/1280/h/960/format/webp/ignore-error/1) - 这个链表即是我们的缓存结构,缓存处理步骤为 - 首先将新数据放入链表的头部 - 在进行数据插入的过程中,如果检测到链表中有数据被再次访问也就是有请求再次访问这些数据,那么就其插入的链表的头部,因为它们相对其他数据来说可能是热点数据,具有保留时间更久的意义 - 最后当链表数据放满时将底部的数据淘汰,也就是不常访问的数据 3.使用互斥锁(mutex key) 业界比较常用的做法,是使用mutex。简单地来说,就是在缓存失效的时候(判断拿出来的值为空),不是立即去load db,而是先使用缓存工具的某些带成功操作返回值的操作(比如Redis的SETNX或者Memcache的ADD)去set一个mutex key,当操作返回成功时,再进行load db的操作并回设缓存;否则,就重试整个get缓存的方法。 ``` // redis public String get(key) { String value = redis.get(key); if (value == null) { //代表缓存值过期 //设置3min的超时,防止del操作失败的时候,下次缓存过期一直不能load db if (redis.setnx(key_mutex, 1, 3 * 60) == 1) { //代表设置成功 value = db.get(key); redis.set(key, value, expire_secs); redis.del(key_mutex); } else { //这个时候代表同时候的其他线程已经load db并回设到缓存了,这时候重试获取缓存值即可 sleep(50); get(key); //重试 } } else { return value; } } // memcache if (memcache.get(key) == null) { // 3 min timeout to avoid mutex holder crash if (memcache.add(key_mutex, 3 * 60 * 1000) == true) { value = db.get(key); memcache.set(key, value); memcache.delete(key_mutex); } else { sleep(50); retry(); } } ``` 4."永远不过期": 这里的“永远不过期”包含两层意思: (1) 从redis上看,确实没有设置过期时间,这就保证了,不会出现热点key过期问题,也就是“物理”不过期。 (2) 从功能上看,如果不过期,那不就成静态的了吗?所以我们把过期时间存在key对应的value里,如果发现要过期了,通过一个后台的异步线程进行缓存的构建,也就是“逻辑”过期 从实战看,这种方法对于性能非常友好,唯一不足的就是构建缓存时候,其余线程(非构建缓存的线程)可能访问的是老数据,但是对于一般的互联网功能来说这个还是可以忍受。 ``` String get(final String key) { V v = redis.get(key); String value = v.getValue(); long timeout = v.getTimeout(); if (v.timeout <= System.currentTimeMillis()) { // 异步更新后台异常执行 threadPool.execute(new Runnable() { public void run() { String keyMutex = "mutex:" + key; if (redis.setnx(keyMutex, "1")) { // 3 min timeout to avoid mutex holder crash redis.expire(keyMutex, 3 * 60); String dbValue = db.get(key); redis.set(key, dbValue); redis.delete(keyMutex); } } }); } return value; } ``` <file_sep>生产者和消费者问题是线程模型中的经典问题:生产者和消费者在同一时间段内共用同一个存储空间,生产者往存储空间中添加产品,消费者从存储空间中取走产品,当存储空间为空时,消费者阻塞,当存储空间满时,生产者阻塞。 ![image](https://github.com/tianhuan168/Doc/raw/master/img/14.webp) ## 现在用四种方式来实现生产者消费者模型 #### 1.wait()和notify()方法的实现 这也是最简单最基础的实现,缓冲区满和为空时都调用wait()方法等待,当生产者生产了一个产品或者消费者消费了一个产品之后会唤醒所有线程。 ``` public class Test1 { private static Integer count = 0; private static final Integer FULL = 10; private static String LOCK = "lock"; // object锁 public static void main(String[] args) { Test1 test1 = new Test1(); new Thread(test1.new Producer()).start(); new Thread(test1.new Consumer()).start(); new Thread(test1.new Producer()).start(); new Thread(test1.new Consumer()).start(); new Thread(test1.new Producer()).start(); new Thread(test1.new Consumer()).start(); new Thread(test1.new Producer()).start(); new Thread(test1.new Consumer()).start(); } class Producer implements Runnable { @Override public void run() { for (int i = 0; i < 10; i++) { try { Thread.sleep(3000); } catch (Exception e) { e.printStackTrace(); } synchronized (LOCK) { while (count == FULL) { try { LOCK.wait(); // 满的时候阻塞 } catch (Exception e) { e.printStackTrace(); } } count++; System.out.println(Thread.currentThread().getName() + "生产者生产,目前总共有" + count); LOCK.notifyAll(); // 不满的时候唤醒 } } } } class Consumer implements Runnable { @Override public void run() { for (int i = 0; i < 10; i++) { try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (LOCK) { while (count == 0) { try { LOCK.wait();// 空的时候也阻塞 等待 } catch (Exception e) { } } count--; System.out.println(Thread.currentThread().getName() + "消费者消费,目前总共有" + count); LOCK.notifyAll(); } } } } } 结果: Thread-0生产者生产,目前总共有1 Thread-4生产者生产,目前总共有2 Thread-3消费者消费,目前总共有1 Thread-1消费者消费,目前总共有0 Thread-2生产者生产,目前总共有1 Thread-6生产者生产,目前总共有2 Thread-7消费者消费,目前总共有1 Thread-5消费者消费,目前总共有0 Thread-0生产者生产,目前总共有1 Thread-4生产者生产,目前总共有2 Thread-3消费者消费,目前总共有1 Thread-6生产者生产,目前总共有2 Thread-1消费者消费,目前总共有1 Thread-7消费者消费,目前总共有0 Thread-2生产者生产,目前总共有1 Thread-5消费者消费,目前总共有0 Thread-0生产者生产,目前总共有1 Thread-4生产者生产,目前总共有2 Thread-3消费者消费,目前总共有1 Thread-7消费者消费,目前总共有0 Thread-6生产者生产,目前总共有1 Thread-2生产者生产,目前总共有2 Thread-1消费者消费,目前总共有1 Thread-5消费者消费,目前总共有0 Thread-0生产者生产,目前总共有1 Thread-4生产者生产,目前总共有2 Thread-3消费者消费,目前总共有1 Thread-1消费者消费,目前总共有0 Thread-6生产者生产,目前总共有1 Thread-7消费者消费,目前总共有0 Thread-2生产者生产,目前总共有1 ``` ### 可重入锁ReentrantLock的实现 java.util.concurrent.lock 中的 Lock 框架是锁定的一个抽象,通过对lock的lock()方法和unlock()方法实现了对锁的显示控制,而synchronize()则是对锁的隐性控制。 可重入锁,也叫做递归锁,指的是同一线程 外层函数获得锁之后 ,内层递归函数仍然有获取该锁的代码,但不受影响,简单来说,该锁维护这一个与获取锁相关的计数器,如果拥有锁的某个线程再次得到锁,那么获取计数器就加1,函数调用结束计数器就减1,然后锁需要被释放两次才能获得真正释放。已经获取锁的线程进入其他需要相同锁的同步代码块不会被阻塞。 ``` public class Test2 { private static Integer count = 0; private static final Integer FULL = 10; //创建一个锁对象 private Lock lock = new ReentrantLock(); //创建两个条件变量,一个为缓冲区非满,一个为缓冲区非空 private final Condition notFull = lock.newCondition(); private final Condition notEmpty = lock.newCondition(); public static void main(String[] args) { Test2 test2 = new Test2(); new Thread(test2.new Producer()).start(); new Thread(test2.new Consumer()).start(); new Thread(test2.new Producer()).start(); new Thread(test2.new Consumer()).start(); new Thread(test2.new Producer()).start(); new Thread(test2.new Consumer()).start(); new Thread(test2.new Producer()).start(); new Thread(test2.new Consumer()).start(); } class Producer implements Runnable { @Override public void run() { for (int i = 0; i < 10; i++) { try { Thread.sleep(3000); } catch (Exception e) { e.printStackTrace(); } //获取锁 lock.lock(); try { while (count == FULL) { try { notFull.await(); } catch (InterruptedException e) { e.printStackTrace(); } } count++; System.out.println(Thread.currentThread().getName() + "生产者生产,目前总共有" + count); //唤醒消费者 notEmpty.signal(); } finally { //释放锁 lock.unlock(); } } } } class Consumer implements Runnable { @Override public void run() { for (int i = 0; i < 10; i++) { try { Thread.sleep(3000); } catch (InterruptedException e1) { e1.printStackTrace(); } lock.lock(); try { while (count == 0) { try { notEmpty.await(); } catch (Exception e) { e.printStackTrace(); } } count--; System.out.println(Thread.currentThread().getName() + "消费者消费,目前总共有" + count); notFull.signal(); } finally { lock.unlock(); } } } } } ``` #### 阻塞队列BlockingQueue的实现 BlockingQueue即阻塞队列,从阻塞这个词可以看出,在某些情况下对阻塞队列的访问可能会造成阻塞。 被阻塞的情况主要有如下两种: 当队列满了的时候进行入队列操作 当队列空了的时候进行出队列操作 因此,当一个线程对已经满了的阻塞队列进行入队操作时会阻塞,除非有另外一个线程进行了出队操作,当一个线程对一个空的阻塞队列进行出队操作时也会阻塞,除非有另外一个线程进行了入队操作。 从上可知,阻塞队列是线程安全的。 下面是BlockingQueue接口的一些方法: 操作 | 抛异常 | 特定值 | 阻塞 |超时 --- |--- |--- |--- |--- 插入 | add(o) |offer(o) | put(o) | offer(o, timeout, timeunit) 移除 | remove(o) | poll(o) | take(o) | poll(timeout, timeunit) 检查 | element(o) | peek(o) | - | - ``` public class Test3 { private static Integer count = 0; //创建一个阻塞队列 final BlockingQueue<Integer> blockingQueue = new ArrayBlockingQueue<>(10); // 大小为10的阻塞队列 public static void main(String[] args) { Test3 test3 = new Test3(); new Thread(test3.new Producer()).start(); new Thread(test3.new Consumer()).start(); new Thread(test3.new Producer()).start(); new Thread(test3.new Consumer()).start(); new Thread(test3.new Producer()).start(); new Thread(test3.new Consumer()).start(); new Thread(test3.new Producer()).start(); new Thread(test3.new Consumer()).start(); } class Producer implements Runnable { @Override public void run() { for (int i = 0; i < 10; i++) { try { Thread.sleep(3000); } catch (Exception e) { e.printStackTrace(); } try { blockingQueue.put(); count++; System.out.println(Thread.currentThread().getName() + "生产者生产,目前总共有" + count); } catch (InterruptedException e) { e.printStackTrace(); } } } } class Consumer implements Runnable { @Override public void run() { for (int i = 0; i < 10; i++) { try { Thread.sleep(3000); } catch (InterruptedException e1) { e1.printStackTrace(); } try { blockingQueue.take(); count--; System.out.println(Thread.currentThread().getName() + "消费者消费,目前总共有" + count); } catch (InterruptedException e) { e.printStackTrace(); } } } } } ``` <file_sep> String有两种赋值方式,第一种是通过“字面量”赋值。比如下面这行: ``` String str = "Hello"; ``` 第二种是通过new关键字创建新对象。比如下面这样: ``` String str = new String("Hello"); ``` <p>这两种方式到底有什么不同。程序执行的时候,内存里到底有几个实例?<b>“实例”</b>存在了内存的哪里?<b>”字面量“</b>又存在了哪里?<b>”变量“</b>又存在了哪里?概念很容易搞混。下面我们一个一个来讲。讲之前,先回顾一下内存。</p> 等主线程开始创建str变量的时候,虚拟机就会到字符串常量池里找,看有没有能equals("Hello")的String。如果找到了,就在栈区当前栈帧的局部变量表里创建str变量,然后把字符串常量池里对Hello对象的引用复制给str变量。找不到的话,才会在heap堆重新创建一个对象,然后把引用驻留到字符串常量区。然后再把引用复制栈帧的局部变量表。 ![image](http://pic2.zhimg.com/80/20568a6ad0ef2860746533595e400716_hd.jpg) 如果我们当时定义了很多个值为"Hello"的String,比如像下面代码,有三个变量str1,str2,str3,也不会在堆上增加String实例。局部变量表里三个变量统一指向同一个堆内存地址。 ``` package com.ciao.shen.java.string; class Test{ public void f(String s){...}; public static void main(String[] args){ String str1 = "Hello"; String str2 = "Hello"; String str3 = "Hello"; ... } } ``` ![image](http://pic4.zhimg.com/80/8e743518809bd37723a4b0e8bf35f332_hd.jpg) 上图中str1,str2,str3之间可以用==来连接。 但如果是用new关键字来创建字符串,情况就不一样了, ``` public static void main(String[] args){ String str1 = "Hello"; String str2 = "Hello"; String str3 = new String("Hello"); ... } ``` 这时候,str1和str2还是和之前一样。但str3因为new关键字会在Heap堆申请一块全新的内存,来创建新对象。虽然字面还是"Hello",但是完全不同的对象,有不同的内存地址。 ![image](http://pic4.zhimg.com/80/fe6b27f35b5491eb562138eda573c238_hd.jpg) ---- 简单描述一下: String str1 = “ABC”; 可能创建一个或者不创建对象。 如果”ABC”这个字符串在java String池里不存在,会在java String池里创建一个创建一个String对象(“ABC”),然后str1指向这个内存地址,无论以后用这种方式创建多少个值为”ABC”的字符串对象,始终只有一个内存地址被分配,之后的都是String的拷贝,Java中称为“字符串驻留”,所有的字符串常量都会在编译之后自动地驻留。 常量池-》创建字符串对象 ABC -》str1指向这个内存地址 String str2 = new String(“ABC”); 至少创建一个对象,也可能两个。因为用到new关键字,肯定会在heap中创建一个str2的String对象,它的value是“ABC”。同时如果这个字符串再java String池里不存在,会在java池里创建这个String对象“ABC”。 heap创建对象str2 - 》 寻找常量池中是否有ABC-》没有就创建-》str2指向内存地址 <file_sep>### redis主从复制 --- ### 概述 - redis的复制功能是支持多个数据库之间的数据同步。 一类是主数据库(master)一类是从数据库(slave),主数据库可以进行读写操作,当发生写操作的时候自动将数据同步到从数据库,而从数据库一般是只读的,并接收主数据库同步过来的数据, 一个主数据库可以有多个从数据库,而一个从数据库只能有一个主数据库。 - 通过redis的复制功能可以很好的实现数据库的读写分离,提高服务器的负载能力。主数据库主要进行写操作,而从数据库负责读操作。 ### 主从复制过程 主从复制过程:见下图 ![image](https://github.com/tianhuan168/Doc/raw/master/img/3.jpg) 过程: - 当一个从数据库启动时,会向主数据库发送sync命令, - 主数据库接收到sync命令后会开始在后台保存快照(执行rdb操作),并将保存期间接收到的命令缓存起来 - 当快照完成后,redis会将快照文件和所有缓存的命令发送给从数据库。 - 从数据库收到后,会载入快照文件并执行收到的缓存的命令。 配置 Redis主从结构支持一主多从 主节点:192.168.33.130 从节点:192.168.33.131 注意:所有从节点的配置都一样 ---- #### 方式1:手动修改配置文件 只需要额外修改从节点中redis的配置文件中的slaveof属性即可 slaveof 192.168.33.130 6379 配置修改图示: ![image](https://github.com/tianhuan168/Doc/raw/master/img/4.jpg) #### 方式2:动态设置 通过redis-cli 连接到从节点服务器,执行下面命令即可。 slaveof 192.168.33.130 6379 <file_sep> java中的值传递和引用传递 --- 这个概念在最早开始学习java基础的时候就被反复提及过,只是当时记得了语法却记不得怎么实际运用,有时候会的了运用却解释不出原理。每次被问到的时候都去随机看上一眼,记几分钟后又忘记了。 可巧今天面试的时候又被问到了(感谢面试官的温故知新),凭着记忆,确定一下java中并没有真正意义上的引用传递,完全都是值传递。因为之前自己特意写了一下相关的demo来做过测试,很果断的说了一下自己的见解。但是似乎面试官不太认可这种说法。本着对技术的尊重和严谨,特意收集资料来验证这个问题。 我们再聊聊这个问题,首先我们必须认识到这个问题一般是相对函数而言的,也就是java中的方法参数,那么我们先来回顾一下Java的**数据类型** **所谓数据类型**,是编程语言中对内存的一种抽象表达方式,我们知道程序是由代码文件和静态资源组成,在程序被运行前,这些代码存在在硬盘里,程序开始运行,这些代码会被转成计算机能识别的内容放到内存中被执行。 ### **Java的数据类型有哪些?** #### 1.基本类型 编程语言中内置的最小粒度的数据类型。 ``` 4种整数类型:byte、short、int、long 2种浮点数类型:float、double 1种字符类型:char 1种布尔类型:boolean ``` ##### 1.1基本数据类型的存储: - A. 基本数据类型的局部变量 定义基本数据类型的局部变量以及数据都是直接存储在内存中的栈上,也就是前面说到的“虚拟机栈”,数据本身的值就是存储在栈空间里面。 例如: ``` int age=50; int weight=50; int grade=6; ``` 在JVM中开辟的结构为: ![image](https://github.com/tianhuan168/Doc/raw/master/img/v1.png) 当我们写“int age=50;”,其实是分为两步的: ``` int age;//定义变量 age=50;//赋值 ``` 首先JVM创建一个名为age的变量,存于局部变量表中,然后去栈中查找是否存在有字面量值为50的内容,如果有就直接把age指向这个地址,如果没有,JVM会在栈中开辟一块空间来存储“50”这个内容,并且把age指向这个地址。因此我们可以知道:我们声明并初始化基本数据类型的局部变量时,变量名以及字面量值都是存储在栈中,而且是真实的内容。 基本数据类型的数据本身是不会改变的,当局部变量重新赋值时,并不是在内存中改变字面量内容,而是重新在栈中寻找已存在的相同的数据,若栈中不存在,则重新开辟内存存新数据,并且把要重新赋值的局部变量的引用指向新数据所在地址。 - B. 基本数据类型的成员变量 成员变量:顾名思义,就是在类体中定义的变量。 ``` public class Person { private int age; private String name; private int grade; static void run(){ System.out.println("run------"); } public static void main(String[] args) { Person per = new Person(); } } ``` 在jvm中具体开辟的内存图如下 ![image](https://github.com/tianhuan168/Doc/raw/master/img/v2.png) 同样是局部变量的age、name、grade却被存储到了堆中为per对象开辟的一块空间中。因此可知:基本数据类型的成员变量名和值都存储于堆中,其生命周期和对象的是一致的。 - C. 基本数据类型的静态变量 jvm中的方法区用来存储一些共享数据,因此基本数据类型的静态变量名以及值存储于方法区的运行时常量池中,静态变量随类加载而加载,随类消失而消失 #### 2.引用数据类型 引用也叫句柄,引用类型,是编程语言中定义的在句柄中存放着实际内容所在地址的地址值的一种数据形式。 ``` 1.类 2.接口 3.数组 ``` ##### 2.1 引用数据类型的存储: 上面提到:堆是用来存储对象本身和数组,而引用(句柄)存放的是实际内容的地址值,因此通过上面的程序运行图,也可以看出,当我们定义一个对象时 ``` Person per=new Person(); ``` 实际上是被拆分了两部分 ``` Person per;//定义变量 per=new Person();//赋值 ``` 在执行Person per;时,JVM先在虚拟机栈中的变量表中开辟一块内存存放per变量,在执行per=new Person()时,JVM会创建一个Person类的实例对象并在堆中开辟一块内存存储这个实例,同时把实例的地址值赋值给per变量。因此可见:对于引用数据类型的对象/数组,变量名存在栈中,变量值存储的是对象的地址,并不是对象的实际内容。 OK 言归正传,回归到值传递和引用传递上来,代码不会欺骗人,我们就从demo说起。 ``` public class Person { // void -int public void testInt(int x){ x = 5; } // return -int public int testIntReturn(int x){ x = 5; return x; } // void - string public void testString(String str){ str = "change"; } public static void main(String[] args) { Person per = new Person(); int x = 1; per.testInt(x); System.out.println("x====" + x); int y = per.testIntReturn(x); System.out.println("y====" + y); String str = "string"; per.testString(str); System.out.println("str====" + str); int age = 10; Obj obj = new Obj(10); obj.setAge(11); System.out.println(obj.getAge()); obj.updateObj(obj); System.out.println(obj.getAge()); obj = obj.updateObjReturn(obj); System.out.println(obj); Obj o = obj.updateObjReturn(obj); System.out.println(o); } } class Obj{ private int age; public Obj(int age) { this.age = age; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public void setAge2(Obj obj){ obj.setAge(22); } public void updateObj(Obj obj){ obj.setAge(22); } public Obj updateObjReturn(Obj obj){ obj.setAge(22); return obj; } } #####输出结果如下######### x====1 y====5 str====string 11 22 dubbo.api.Obj@4554617c dubbo.api.Obj@4554617c Process finished with exit code 0 ``` 从打印结果可以看出。java中是没有引用传递的,即便是对象传递,也是对象中的属性值传递。<file_sep> ![image](http://img-blog.csdn.net/20180717201939345?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzM4OTUwMzE2/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70) - 序列号seq:占4个字节,用来标记数据段的顺序,TCP把连接中发送的所有数据字节都编上一个序号,第一个字节的编号由本地随机产生;给字节编上序号后,就给每一个报文段指派一个序号;序列号seq就是这个报文段中的第一个字节的数据编号。 - 确认号ack:占4个字节,期待收到对方下一个报文段的第一个数据字节的序号;序列号表示报文段携带数据的第一个字节的编号;而确认号指的是期望接收到下一个字节的编号;因此当前报文段最后一个字节的编号+1即为确认号。 - 确认ACK:占1位,仅当ACK=1时,确认号字段才有效。ACK=0时,确认号无效 - 同步SYN:连接建立时用于同步序号。当SYN=1,ACK=0时表示:这是一个连接请求报文段。若同意连接,则在响应报文段中使得SYN=1,ACK=1。因此,SYN=1表示这是一个连接请求,或连接接受报文。SYN这个标志位只有在TCP建产连接时才会被置1,握手完成后SYN标志位被置0。 - 终止FIN:用来释放一个连接。FIN=1表示:此报文段的发送方的数据已经发送完毕,并要求释放运输连接 **PS:ACK、SYN和FIN这些大写的单词表示标志位,其值要么是1,要么是0;ack、seq小写的单词表示序号。** 字段 | 含义 ---|--- URG | 紧急指针是否有效。为1,表示某一位需要被优先处理。 ACK | 确认号是否有效,一般置为1。 PSH | 提示接收端应用程序立即从TCP缓冲区把数据读走。 RST | 对方要求重新建立连接,复位。 SYN | 请求建立连接,并在其序列号的字段进行序列号的初始值设置为1。 FIN | 希望断开连接。 ![image](https://img-blog.csdn.net/20180717202520531?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzM4OTUwMzE2/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70) **第一次握手**:建立连接时,客户端发送syn包(syn=j)到服务器,并进入SYN_SENT状态,等待服务器确认;SYN:同步序列编号(Synchronize Sequence Numbers)。 ![image](http://www.centos.bz/wp-content/uploads/2012/08/100327002911.png) **第二次握手**:服务器收到syn包,必须确认客户的SYN(ack=j+1),同时自己也发送一个SYN包(syn=k),即SYN+ACK包,此时服务器进入SYN_RECV状态; ![image](http://www.centos.bz/wp-content/uploads/2012/08/100327003054.png) **第三次握手**:客户端收到服务器的SYN+ACK包,向服务器发送确认包ACK(ack=k+1),此包发送完毕,客户端和服务器进入ESTABLISHED(TCP连接成功)状态,完成三次握手。 ![image](http://www.centos.bz/wp-content/uploads/2012/08/100327003214.png) ##### **一次三次握手的抓包数据** ![一次三次握手的抓包数据](http://www.centos.bz/wp-content/uploads/2012/08/100327023334.png) ------------------------------------------四次挥手------------------------------------------------- ![image](https://img-blog.csdn.net/20180717204202563?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzM4OTUwMzE2/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70) - 1)客户端进程发出连接释放报文,并且停止发送数据。释放数据报文首部,FIN=1,其序列号为seq=u(等于前面已经传送过来的数据的最后一个字节的序号加1),此时,客户端进入FIN-WAIT-1(终止等待1)状态。 TCP规定,FIN报文段即使不携带数据,也要消耗一个序号。 - 2)服务器收到连接释放报文,发出确认报文,ACK=1,ack=u+1,并且带上自己的序列号seq=v,此时,服务端就进入了CLOSE-WAIT(关闭等待)状态。TCP服务器通知高层的应用进程,客户端向服务器的方向就释放了,这时候处于半关闭状态,即客户端已经没有数据要发送了,但是服务器若发送数据,客户端依然要接受。这个状态还要持续一段时间,也就是整个CLOSE-WAIT状态持续的时间。 - 3)客户端收到服务器的确认请求后,此时,客户端就进入FIN-WAIT-2(终止等待2)状态,等待服务器发送连接释放报文(在这之前还需要接受服务器发送的最后的数据)。 - 4)服务器将最后的数据发送完毕后,就向客户端发送连接释放报文,FIN=1,ack=u+1,由于在半关闭状态,服务器很可能又发送了一些数据,假定此时的序列号为seq=w,此时,服务器就进入了LAST-ACK(最后确认)状态,等待客户端的确认。 - 5)客户端收到服务器的连接释放报文后,必须发出确认,ACK=1,ack=w+1,而自己的序列号是seq=u+1,此时,客户端就进入了TIME-WAIT(时间等待)状态。注意此时TCP连接还没有释放,必须经过2∗∗MSL(最长报文段寿命)的时间后,当客户端撤销相应的TCB后,才进入CLOSED状态。 - 6)服务器只要收到了客户端发出的确认,立即进入CLOSED状态。同样,撤销TCB后,就结束了这次的TCP连接。可以看到,服务器结束TCP连接的时间要比客户端早一些。 ![image](http://www.centos.bz/wp-content/uploads/2012/08/100327023334.png) 1.为什么建立连接协议是三次握手,而关闭连接却是四次握手呢? 这是因为服务端的LISTEN状态下的SOCKET当收到SYN报文的连接请求后,它可以把ACK和SYN(ACK起应答作用,而SYN起同步作用)放在一个报文里来发送。但关闭连接时,当收到对方的FIN报文通知时,它仅仅表示对方没有数据发送给你了;但未必你所有的数据都全部发送给对方了,所以你可能未必会马上会关闭SOCKET,也即你可能还需要发送一些数据给对方之后,再发送FIN报文给对方来表示你同意现在可以关闭连接了,所以它这里的ACK报文和FIN报文多数情况下都是分开发送的。 2.为什么TIME_WAIT状态需要经过2MSL(最大报文段生存时间)才能返回到CLOSE状态? 答:虽然按道理,四个报文都发送完毕,我们可以直接进入CLOSE状态了,但是我们必须假象网络是不可靠的,有可以最后一个ACK丢失。所以TIME_WAIT状态就是用来重发可能丢失的ACK报文。在Client发送出最后的ACK回复,但该ACK可能丢失。Server如果没有收到ACK,将不断重复发送FIN片段。所以Client不能立即关闭,它必须确认Server接收到了该ACK。Client会在发送出ACK之后进入到TIME_WAIT状态。Client会设置一个计时器,等待2MSL的时间。如果在该时间内再次收到FIN,那么Client会重发ACK并再次等待2MSL。所谓的2MSL是两倍的MSL(Maximum Segment Lifetime)。MSL指一个片段在网络中最大的存活时间,2MSL就是一个发送和一个回复所需的最大时间。如果直到2MSL,Client都没有再次收到FIN,那么Client推断ACK已经被成功接收,则结束TCP连接。 【问题3】为什么不能用两次握手进行连接? 答:3次握手完成两个重要的功能,既要双方做好发送数据的准备工作(双方都知道彼此已准备好),也要允许双方就初始序列号进行协商,这个序列号在握手过程中被发送和确认。 现在把三次握手改成仅需要两次握手,死锁是可能发生的。作为例子,考虑计算机S和C之间的通信,假定C给S发送一个连接请求分组,S收到了这个分组,并发 送了确认应答分组。按照两次握手的协定,S认为连接已经成功地建立了,可以开始发送数据分组。可是,C在S的应答分组在传输中被丢失的情况下,将不知道S 是否已准备好,不知道S建立什么样的序列号,C甚至怀疑S是否收到自己的连接请求分组。在这种情况下,C认为连接还未建立成功,将忽略S发来的任何数据分 组,只等待连接确认应答分组。而S在发出的分组超时后,重复发送同样的分组。这样就形成了死锁。 【问题4】如果已经建立了连接,但是客户端突然出现故障了怎么办? TCP还设有一个保活计时器,显然,客户端如果出现故障,服务器不能一直等下去,白白浪费资源。服务器每收到一次客户端的请求后都会重新复位这个计时器,时间通常是设置为2小时,若两小时还没有收到客户端的任何数据,服务器就会发送一个探测报文段,以后每隔75分钟发送一次。若一连发送10个探测报文仍然没反应,服务器就认为客户端出了故障,接着就关闭连接。<file_sep># Doc 整理平时收集到的各种文档。也希望搜索到本内容的小伙伴们也能贡献自己平时收藏的资料和个人开发过程中解决的问题。 <file_sep>## 1.动态代理/静态代理 **区别** 名称 | 备注 --- |--- 静态代理 | 简单,代理模式,是动态代理的理论基础。常见使用在代理模式 jdk动态代理 | 需要有顶层接口才能使用,但是在只有顶层接口的时候也可以使用,常见是mybatis的mapper文件是代理。使用反射完成。使用了动态生成字节码技术。 cglib动态代理| 可以直接代理类,使用字节码技术,不能对 final类进行继承。使用了动态生成字节码技术。 一个对象(客户端)不能或者不想直接引用另一个对象(目标对象),这时可以应用代理模式在这两者之间构建一个桥梁--代理对象。 按照代理对象的创建时期不同,可以分为两种: - 静态代理:事先写好代理对象类,在程序发布前就已经存在了; - 动态代理:应用程序发布后,通过动态创建代理对象。 <font face="微软雅黑" color=#DC143C>静态代理其实就是一个典型的代理模式实现,在代理类中包装一个被代理对象,然后影响被代理对象的行为</font>。 ``` /** * 最顶层接口 歌手 */ interface Singer { void sing(); } /** * 真实实现,一个歌星 */ class Star implements Singer { @Override public void sing() { System.out.println("Star Singing~~~"); } } /** * 代理实现,代理了歌星,唱歌的时候 会先在歌手唱歌之前收钱,然后再唱歌 */ class Agent implements Singer { Star s; public Agent(Star s) { super(); this.s = s; } @Override public void sing() { System.out.println("在歌手唱歌之前收钱...."); s.sing(); } } public class StaticProxy { public static void main(String[] args) { Singer singer = new Agent(new Star()); singer.sing(); } } ``` 其中动态代理又可分为:**JDK动态代理**和**CGLIB代理**。 **JDK动态代理** - 只能代理有实现的接口类 - 自己观察可以从Proxy.newProxyInstance( ClassLoader paramClassLoader, Class<?>[] paramArrayOfClass, InvocationHandler paramInvocationHandler)进行观察 **,简单来看就是先生成新的class文件,然后加载到jvm中,然后使用反射,先用class取得他的构造方法,然后使用构造方法反射得到他的一个实例**。 ``` // 必须继承 InvocationHandler 并实现invoke方法 public class JDKProxy implements InvocationHandler { private Object target; @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("------插入前置通知代码-------------"); // 执行相应的目标方法 Object rs = method.invoke(target,args); System.out.println("------插入后置处理代码-------------"); return rs; } public JDKProxy(Object target) { this.target = target; } // 通过实现Proxy.newProxyInstance()返回被代理对象 public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InstantiationException, InvocationTargetException { MyBean iHello2 = (MyBean) Proxy.newProxyInstance( MyBean.class.getClassLoader(), // 加载接口的类加载器 new Class[]{MyBean.class}, // 一组接口 new JDKProxy(new MyBeanImpl())); // 定义的InvocationHandler iHello2.say("222222222");// 方法调用 } ``` **CGLIB代理** - 不能代理final修饰的类 - 通过生成代理类的子类来实现 - 必须继承MethodInterceptor并实现intercept方法 - ``` // 继承MethodInterceptor并实现intercept方法 public class BookFacadeCglib implements MethodInterceptor { private Object target; // 获取代理对象 public Object getInstance(Object target) { this.target = target; // 创建代理类的子类 Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(this.target.getClass()); // 回调方法 enhancer.setCallback(this); // 创建代理对象 return enhancer.create(); } @Override public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable { System.out.println("事物开始"); methodProxy.invokeSuper(o,objects); System.out.println("事物开始"); return null; } public static void main(String[] args) { BookFacadeCglib cglib=new BookFacadeCglib(); BookFacadeImpl1 bookCglib=(BookFacadeImpl1)cglib.getInstance(new BookFacadeImpl1()); bookCglib.addBook(); } } ``` <file_sep>### ParNew and CMS "Concurrent Mark and Sweep" 是CMS的全称,官方给予的名称是:“Mostly Concurrent Mark and Sweep Garbage Collector”; 年轻代:采用 stop-the-world mark-copy 算法; 年老代:采用 Mostly Concurrent mark-sweep 算法; 设计目标:年老代收集的时候避免长时间的暂停; 能够达成该目标主要因为以下两个原因: 1.它不会花时间整理压缩年老代,而是维护了一个叫做 free-lists 的数据结构,该数据结构用来管理那些回收再利用的内存空间; 2.mark-sweep分为多个阶段,其中一大部分阶段GC的工作是和Application threads的工作同时进行的(当然,gc线程会和用户线程竞争CPU的时间),默认的GC的工作线程为你服务器物理CPU核数的1/4; 首先对真个GC日志有一个大概的认知 ``` 2016-08-23T02:23:07.219-0200: 64.322: [GC (Allocation Failure) 64.322: [ParNew: 613404K->68068K(613440K), 0.1020465 secs] 10885349K->10880154K(12514816K), 0.1021309 secs] [Times: user=0.78 sys=0.01, real=0.11 secs] 2016-08-23T02:23:07.321-0200: 64.425: [GC (CMS Initial Mark) [1 CMS-initial-mark: 10812086K(11901376K)] 10887844K(12514816K), 0.0001997 secs] [Times: user=0.00 sys=0.00, real=0.00 secs] 2016-08-23T02:23:07.321-0200: 64.425: [CMS-concurrent-mark-start] 2016-08-23T02:23:07.357-0200: 64.460: [CMS-concurrent-mark: 0.035/0.035 secs] [Times: user=0.07 sys=0.00, real=0.03 secs] 2016-08-23T02:23:07.357-0200: 64.460: [CMS-concurrent-preclean-start] 2016-08-23T02:23:07.373-0200: 64.476: [CMS-concurrent-preclean: 0.016/0.016 secs] [Times: user=0.02 sys=0.00, real=0.02 secs] 2016-08-23T02:23:07.373-0200: 64.476: [CMS-concurrent-abortable-preclean-start] 2016-08-23T02:23:08.446-0200: 65.550: [CMS-concurrent-abortable-preclean: 0.167/1.074 secs] [Times: user=0.20 sys=0.00, real=1.07 secs] 2016-08-23T02:23:08.447-0200: 65.550: [GC (CMS Final Remark) [YG occupancy: 387920 K (613440 K)]65.550: [Rescan (parallel) , 0.0085125 secs]65.559: [weak refs processing, 0.0000243 secs]65.559: [class unloading, 0.0013120 secs]65.560: [scrub symbol table, 0.0008345 secs]65.561: [scrub string table, 0.0001759 secs][1 CMS-remark: 10812086K(11901376K)] 11200006K(12514816K), 0.0110730 secs] [Times: user=0.06 sys=0.00, real=0.01 secs] 2016-08-23T02:23:08.458-0200: 65.561: [CMS-concurrent-sweep-start] 2016-08-23T02:23:08.485-0200: 65.588: [CMS-concurrent-sweep: 0.027/0.027 secs] [Times: user=0.03 sys=0.00, real=0.03 secs] 2016-08-23T02:23:08.485-0200: 65.589: [CMS-concurrent-reset-start] 2016-08-23T02:23:08.497-0200: 65.601: [CMS-concurrent-reset: 0.012/0.012 secs] [Times: user=0.01 sys=0.00, real=0.01 secs] ``` ## Minor GC 2016-08-23T02:23:07.219-0200: 64.322: [GC (Allocation Failure) 64.322: [ParNew: 613404K->68068K(613440K), 0.1020465 secs] 10885349K->10880154K(12514816K), 0.1021309 secs] [Times: user=0.78 sys=0.01, real=0.11 secs] ``` 1. 2016-08-23T02:23:07.219-0200 – GC发生的时间; 2. 64.322 – GC开始,相对JVM启动的相对时间,单位是秒; 3. GC – 区别MinorGC和FullGC的标识,这次代表的是MinorGC; 4. Allocation Failure – MinorGC的原因,在这个case里边,由于年轻代不满足申请的空间,因此触发了MinorGC; 5. ParNew – 收集器的名称,它预示了年轻代使用一个并行的 mark-copy stop-the-world 垃圾收集器; 6. 613404K->68068K – 收集前->后年轻代的使用情况; 7. (613440K) – 整个年轻代的容量; 8. 0.1020465 secs – 这个解释用原滋原味的解释:Duration for the collection w/o final cleanup. 9. 10885349K->10880154K – 收集前后整个堆的使用情况; 10. (12514816K) – 整个堆的容量; 11. 0.1021309 secs – ParNew收集器标记和复制年轻代活着的对象所花费的时间(包括和老年代通信的开销、对象晋升到老年代时间、垃圾收集周期结束一些最后的清理对象等的花销); 12. 对于 [Times: user=0.95 sys=0.00, real=0.09 secs],这里面涉及到三种时间类型,含义如下: user:GC 线程在垃圾收集期间所使用的 CPU 总时间; sys:系统调用或者等待系统事件花费的时间; real:应用被暂停的时钟时间,由于 GC 线程是多线程的,导致了 real 小于 (user+real),如果是 gc 线程是单线程的话,real 是接近于 (user+real) 时间。 ``` 我们来分析下对象晋升问题(原文中的计算方式有问题): 开始的时候:整个堆的大小是 10885349K,年轻代大小是613404K,这说明老年代大小是 10885349-613404=10271945K, 收集完成之后:整个堆的大小是 10880154K,年轻代大小是68068K,这说明老年代大小是 10880154-68068=10812086K, 老年代的大小增加了:10812086-10271945=608209K,也就是说 年轻代到年老代promot了608209K的数据; ![image](http://images2015.cnblogs.com/blog/893686/201608/893686-20160823113939714-505155420.jpg) ## Full/Major GC CMS 收集器是老年代经常使用的收集器,它采用的是标记-清楚算法,应用程序在发生一次 Full GC 时,典型的 GC 日志信息如下: ``` 2016-08-23T11:23:07.321-0200: 64.425: [GC (CMS Initial Mark) [1 CMS-initial-mark: 10812086K(11901376K)] 10887844K(12514816K), 0.0001997 secs] [Times: user=0.00 sys=0.00, real=0.00 secs] 2016-08-23T11:23:07.321-0200: 64.425: [CMS-concurrent-mark-start] 2016-08-23T11:23:07.357-0200: 64.460: [CMS-concurrent-mark: 0.035/0.035 secs] [Times: user=0.07 sys=0.00, real=0.03 secs] 2016-08-23T11:23:07.357-0200: 64.460: [CMS-concurrent-preclean-start] 2016-08-23T11:23:07.373-0200: 64.476: [CMS-concurrent-preclean: 0.016/0.016 secs] [Times: user=0.02 sys=0.00, real=0.02 secs] 2016-08-23T11:23:07.373-0200: 64.476: [CMS-concurrent-abortable-preclean-start] 2016-08-23T11:23:08.446-0200: 65.550: [CMS-concurrent-abortable-preclean: 0.167/1.074 secs] [Times: user=0.20 sys=0.00, real=1.07 secs] 2016-08-23T11:23:08.447-0200: 65.550: [GC (CMS Final Remark) [YG occupancy: 387920 K (613440 K)]65.550: [Rescan (parallel) , 0.0085125 secs]65.559: [weak refs processing, 0.0000243 secs]65.559: [class unloading, 0.0013120 secs]65.560: [scrub symbol table, 0.0008345 secs]65.561: [scrub string table, 0.0001759 secs][1 CMS-remark: 10812086K(11901376K)] 11200006K(12514816K), 0.0110730 secs] [Times: user=0.06 sys=0.00, real=0.01 secs] 2016-08-23T11:23:08.458-0200: 65.561: [CMS-concurrent-sweep-start] 2016-08-23T11:23:08.485-0200: 65.588: [CMS-concurrent-sweep: 0.027/0.027 secs] [Times: user=0.03 sys=0.00, real=0.03 secs] 2016-08-23T11:23:08.485-0200: 65.589: [CMS-concurrent-reset-start] 2016-08-23T11:23:08.497-0200: 65.601: [CMS-concurrent-reset7: 0.012/0.012 secs] [Times: user=0.01 sys=0.00, real=0.01 secs] ``` CMS Full GC 拆分开来,涉及的阶段比较多,下面分别来介绍各个阶段的情况。 #### 阶段1:Initial Mark(初始标记) 这个是 CMS 两次 stop-the-wolrd 事件的其中一次,它有两个目标:一是标记老年代中所有的GC Roots;二是标记被年轻代中活着的对象引用的对象,标记后示例如下所示: ![image](http://images2015.cnblogs.com/blog/893686/201608/893686-20160823121559480-1209636163.jpg) ``` - 2016-08-23T11:23:07.321-0200: 64.42 – GC事件开始,包括时钟时间和相对JVM启动时候的相对时间,下边所有的阶段改时间的含义相同; - CMS Initial Mark – 收集阶段,开始收集所有的GC Roots和直接引用到的对象; - 10812086K – 当前老年代使用情况; - (11901376K) – 老年代可用容量; - 10887844K – 当前整个堆的使用情况; - (12514816K) – 整个堆的容量; - 0.0001997 secs] [Times: user=0.00 sys=0.00, real=0.00 secs] – 时间计量; ``` #### 阶段 2: Concurrent Mark(并行标记) 这个阶段会遍历整个老年代并且标记所有存活的对象,从“初始化标记”阶段找到的GC Roots开始。并发标记的特点是和应用程序线程同时运行。并不是老年代的所有存活对象都会被标记,因为标记的同时应用程序会改变一些对象的引用等。 标记结果如下: ![image](http://images2015.cnblogs.com/blog/893686/201608/893686-20160823123636120-1371978878.jpg) 在上边的图中,一个引用的箭头已经远离了当前对象(current obj) 分析: ``` 2016-08-23T11:23:07.321-0200: 64.425: [CMS-concurrent-mark-start] 2016-08-23T11:23:07.357-0200: 64.460: [CMS-concurrent-mark1: 035/0.035 secs] [Times: user=0.07 sys=0.00, real=0.03 secs] ``` - CMS-concurrent-mark – 并发收集阶段,这个阶段会遍历整个年老代并且标记活着的对象; - 035/0.035 secs – 展示该阶段持续的时间和时钟时间; - [Times: user=0.07 sys=0.00, real=0.03 secs] – 同上 #### 阶段 3: Concurrent Preclean (并行准备清理) 这个阶段又是一个并发阶段,和应用线程并行运行,不会中断他们。前一个阶段在并行运行的时候,一些对象的引用已经发生了变化,当这些引用发生变化的时候,JVM会标记堆的这个区域为Dirty Card(包含被标记但是改变了的对象,被认为"dirty"),这就是 Card Marking。 如下图: ![image](http://images2015.cnblogs.com/blog/893686/201608/893686-20160823130742433-632265434.jpg) 在pre-clean阶段,那些能够从dirty card对象到达的对象也会被标记,这个标记做完之后,dirty card标记就会被清除了,如下: ![image](http://images2015.cnblogs.com/blog/893686/201608/893686-20160823131353839-1306176212.jpg) 分析: ``` 2016-08-23T11:23:07.357-0200: 64.460: [CMS-concurrent-preclean-start] 2016-08-23T11:23:07.373-0200: 64.476: [CMS-concurrent-preclean: 0.016/0.016 sec] [Times: user=0.02 sys=0.00, real=0.02 secs] ``` - CMS-concurrent-preclean – 这个阶段负责前一个阶段标记了又发生改变的对象标记; - 0.016/0.016 secs – 展示该阶段持续的时间和时钟时间; - [Times: user=0.02 sys=0.00, real=0.02 secs] – 同上 #### 阶段 4: Concurrent Abortable Preclean 又一个并发阶段不会停止应用程序线程。这个阶段尝试着去承担STW的Final Remark阶段足够多的工作。这个阶段持续的时间依赖好多的因素,由于这个阶段是重复的做相同的事情直到发生aboart的条件(比如:重复的次数、多少量的工作、持续的时间等等)之一才会停止。 ``` 2016-08-23T11:23:07.373-0200: 64.476: [CMS-concurrent-abortable-preclean-start] 2016-08-23T11:23:08.446-0200: 65.550: [CMS-concurrent-abortable-preclean: 0.167/1.074 secs] [Times: user=0.20 sys=0.00, real=1.07 secs] ``` - CMS-concurrent-abortable-preclean – 可终止的并发预清理; - 0.167/1.074 secs – 展示该阶段持续的时间和时钟时间(It is interesting to note that the user time reported is a lot smaller than clock time. Usually we have seen that real time is less than user time, meaning that some work was done in parallel and so elapsed clock time is less than used CPU time. Here we have a little amount of work – for 0.167 seconds of CPU time, and garbage collector threads were doing a lot of waiting. Essentially, they were trying to stave off for as long as possible before having to do an STW pause. By default, this phase may last for up to 5 seconds); - [Times: user=0.20 sys=0.00, real=1.07 secs] – 同上 这个阶段很大程度的影响着即将来临的Final Remark的停顿,有相当一部分重要的 configuration options 和 失败的模式; #### 阶段 5: Final Remark 这个阶段是CMS中第二个并且是最后一个STW的阶段。该阶段的任务是完成标记整个年老代的所有的存活对象。由于之前的预处理是并发的,它可能跟不上应用程序改变的速度,这个时候,STW是非常需要的来完成这个严酷考验的阶段。 通常CMS尽量运行Final Remark阶段在年轻代是足够干净的时候,目的是消除紧接着的连续的几个STW阶段。 分析: ``` 2016-08-23T11:23:08.447-0200: 65.550: -- 同上; [GC (CMS Final Remark) -- 收集阶段,这个阶段会标记老年代全部的存活对象,包括那些在并发标记阶段更改的或者新创建的引用对象; [YG occupancy: 387920 K (613440 K)]-- 年轻代当前占用情况和容量; 65.550: [Rescan (parallel) , 0.0085125 secs]--这个阶段在应用停止的阶段完成存活对象的标记工作; 65.559: [weak refs processing, 0.0000243 secs]-- 第一个子阶段,随着这个阶段的进行处理弱引用; 65.5595: [class unloading, 0.0013120 secs]--第二个子阶段卸载未使用的类(that is unloading the unused classes, with the duration and timestamp of the phase); 5.5606: [scrub string table, 0.0001759 secs]-- 最后一个子阶段,清理分别包含类级元数据和内部字符串的符号表和字符串表 [1 CMS-remark: 10812086K(11901376K)] --前后内存 11200006K(12514816K), -- 前后堆 0.0110730 secs] [[Times: user=0.06 sys=0.00, real=0.01 secs] ``` 通过以上5个阶段的标记,老年代所有存活的对象已经被标记并且现在要通过Garbage Collector采用清扫的方式回收那些不能用的对象了。 #### 阶段 6: Concurrent Sweep 和应用线程同时进行,不需要STW。这个阶段的目的就是移除那些不用的对象,回收他们占用的空间并且为将来使用。 ![image](https://github.com/tianhuan168/Doc/raw/master/img/5.jpg) 分析: ``` 2016-08-23T11:23:08.458-0200: 65.561: [CMS-concurrent-sweep-start] 2016-08-23T11:23:08.485-0200: 65.588: [CMS-concurrent-sweep1: 0.027/0.027 secs2] [[Times: user=0.03 sys=0.00, real=0.03 secs] 3 ``` - CMS-concurrent-sweep – 这个阶段主要是清除那些没有标记的对象并且回收空间; - 0.027/0.027 secs – 展示该阶段持续的时间和时钟时间; - [Times: user=0.03 sys=0.00, real=0.03 secs] – 同上 阶段 7: Concurrent Reset 这个阶段并发执行,重新设置CMS算法内部的数据结构,准备下一个CMS生命周期的使用。 ``` 2016-08-23T11:23:08.485-0200: 65.589: [CMS-concurrent-reset-start] 2016-08-23T11:23:08.497-0200: 65.601: [CMS-concurrent-reset1: 0.012/0.012 secs2] [[Times: user=0.01 sys=0.00, real=0.01 secs]3 ``` - CMS-concurrent-reset – 这个阶段重新设置CMS算法内部的数据结构,为下一个收集阶段做准备; - 0.012/0.012 secs – 展示该阶段持续的时间和时钟时间; - [Times: user=0.01 sys=0.00, real=0.01 secs] – 同上 <file_sep>/** * @author: tianhuan * @description: * @Date: 2019/4/1 20:42 */ import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; /** * @author * @create 2019-04-01 20:42 **/ public class FileCopy { public static void copyFile(String srcFileName, String dstFileName) { try (FileInputStream in = new FileInputStream(srcFileName); FileOutputStream out = new FileOutputStream(dstFileName)) { FileChannel readChannel = in.getChannel(); FileChannel writeChannel = out.getChannel(); ByteBuffer buffer = ByteBuffer.allocate(1024); while (true) { buffer.clear(); if (readChannel.read(buffer) == 0) { break; } buffer.flip(); writeChannel.write(buffer); } }catch (IOException e){ e.printStackTrace(); } } } <file_sep># redis的两种持久化方式以及区别 ## 1、前言 最近在项目中使用到Redis做缓存,方便多个业务进程之间共享数据。由于Redis的数据都存放在内存中,如果没有配置持久化,redis重启后数据就全丢失了,于是需要开启redis的持久化功能,将数据保存到磁盘上,当redis重启后,可以从磁盘中恢复数据。redis提供两种方式进行持久化,一种是RDB持久化(原理是将Reids在内存中的数据库记录定时dump到磁盘上的RDB持久化),另外一种是AOF持久化(原理是将Reids的操作日志以追加的方式写入文件)。那么这两种持久化方式有什么区别呢,改如何选择呢?网上看了大多数都是介绍这两种方式怎么配置,怎么使用,就是没有介绍二者的区别,在什么应用场景下使用。 ## 2、二者的区别 RDB持久化是指在指定的时间间隔内将内存中的数据集快照写入磁盘,实际操作过程是fork一个子进程,先将数据集写入临时文件,写入成功后,再替换之前的文件,用二进制压缩存储。 ![image](https://images2015.cnblogs.com/blog/305504/201611/305504-20161124215824425-443367815.png) AOF持久化以日志的形式记录服务器所处理的每一个写、删除操作,查询操作不会记录,以文本的方式记录,可以打开文件看到详细的操作记录。 ![image](https://images2015.cnblogs.com/blog/305504/201611/305504-20161124215837690-696354518.png) ## 3、二者优缺点 ###  RDB存在哪些优势呢? 1. 一旦采用该方式,那么你的整个Redis数据库将只包含一个文件,这对于文件备份而言是非常完美的。比如,你可能打算每个小时归档一次最近24小时的数据,同时还要每天归档一次最近30天的数据。通过这样的备份策略,一旦系统出现灾难性故障,我们可以非常容易的进行恢复。 2. 对于灾难恢复而言,RDB是非常不错的选择。因为我们可以非常轻松的将一个单独的文件压缩后再转移到其它存储介质上。 3. 性能最大化。对于Redis的服务进程而言,在开始持久化时,它唯一需要做的只是fork出子进程,之后再由子进程完成这些持久化的工作,这样就可以极大的避免服务进程执行IO操作了。 4.相比于AOF机制,如果数据集很大,RDB的启动效率会更高。 ### RDB又存在哪些劣势呢? 1.如果你想保证数据的高可用性,即最大限度的避免数据丢失,那么RDB将不是一个很好的选择。因为系统一旦在定时持久化之前出现宕机现象,此前没有来得及写入磁盘的数据都将丢失。 2.由于RDB是通过fork子进程来协助完成数据持久化工作的,因此,如果当数据集较大时,可能会导致整个服务器停止服务几百毫秒,甚至是1秒钟。 ### AOF的优势有哪些呢? - 1). 该机制可以带来更高的数据安全性,即数据持久性。Redis中提供了3中同步策略,即每秒同步、每修改同步和不同步。事实上,每秒同步也是异步完成的,其效率也是非常高的,所差的是一旦系统出现宕机现象,那么这一秒钟之内修改的数据将会丢失。而每修改同步,我们可以将其视为同步持久化,即每次发生的数据变化都会被立即记录到磁盘中。可以预见,这种方式在效率上是最低的。至于无同步,无需多言,我想大家都能正确的理解它。 - 2). 由于该机制对日志文件的写入操作采用的是append模式,因此在写入过程中即使出现宕机现象,也不会破坏日志文件中已经存在的内容。然而如果我们本次操作只是写入了一半数据就出现了系统崩溃问题,不用担心,在Redis下一次启动之前,我们可以通过redis-check-aof工具来帮助我们解决数据一致性的问题。 - 3). 如果日志过大,Redis可以自动启用rewrite机制。即Redis以append模式不断的将修改数据写入到老的磁盘文件中,同时Redis还会创建一个新的文件用于记录此期间有哪些修改命令被执行。因此在进行rewrite切换时可以更好的保证数据安全性。 - 4). AOF包含一个格式清晰、易于理解的日志文件用于记录所有的修改操作。事实上,我们也可以通过该文件完成数据的重建。 ### AOF的劣势有哪些呢? - 1). 对于相同数量的数据集而言,AOF文件通常要大于RDB文件。RDB 在恢复大数据集时的速度比 AOF 的恢复速度要快。 - 2). 根据同步策略的不同,AOF在运行效率上往往会慢于RDB。总之,每秒同步策略的效率是比较高的,同步禁用策略的效率和RDB一样高效。 二者选择的标准,就是看系统是愿意牺牲一些性能,换取更高的缓存一致性(aof),还是愿意写操作频繁的时候,不启用备份来换取更高的性能,待手动运行save的时候,再做备份(rdb)。rdb这个就更有些 eventually consistent的意思了。 ## 4、常用配置 ### RDB持久化配置 Redis会将数据集的快照dump到dump.rdb文件中。此外,我们也可以通过配置文件来修改Redis服务器dump快照的频率,在打开6379.conf文件之后,我们搜索save,可以看到下面的配置信息: save 900 1 #在900秒(15分钟)之后,如果至少有1个key发生变化,则dump内存快照。 save 300 10 #在300秒(5分钟)之后,如果至少有10个key发生变化,则dump内存快照。 save 60 10000 #在60秒(1分钟)之后,如果至少有10000个key发生变化,则dump内存快照。 ### AOF持久化配置 在Redis的配置文件中存在三种同步方式,它们分别是: appendfsync always #每次有数据修改发生时都会写入AOF文件。 appendfsync everysec #每秒钟同步一次,该策略为AOF的缺省策略。 appendfsync no #从不同步。高效但是数据不会被持久化。
c6c360766ab47840570de2d08a87ed8b495291e4
[ "Markdown", "Java" ]
18
Markdown
tianhuan168/Doc
30a0867bba5857152c315e35491725984094b723
f1e5c74d8f98843f596cc74e7b393f1fe3dd74e2
refs/heads/master
<repo_name>yoheikikuta/c-exercise<file_sep>/Basic-Declarations-and-Expressions/4.c #include <stdio.h> int main() { char c1 = 'X'; char c2 = 'M'; char c3 = 'L'; printf("The reverse of %c%c%c is %c%c%c\n", c1, c2, c3, c3, c2, c1); return 0; } <file_sep>/Basic-Declarations-and-Expressions/30.c #include <stdio.h> #include <math.h> int main() { unsigned input; printf("Compute squares of even numbers from 1 to N\n"); printf("Input N : "); scanf("%u", &input); for (int i = 2; i <= input; i+=2) { printf("%i^2 = %.0f\n", i, pow(i,2)); } return 0; } <file_sep>/Basic-Declarations-and-Expressions/35.c #include <stdio.h> int main() { int v1 = 0, v2 = 0; printf("Input a pair of integers (e.g., 10,2): \n"); printf("First integer: "); scanf("%i", &v1); printf("Second integer: "); scanf("%i", &v2); if ( v1 < v2 ) { printf("The input pair is ascending order.\n"); } else if ( v1 > v2 ) { printf("The input pair is descending order.\n"); } else if ( v1 == v2 ) { printf("The input pair is equal numbers.\n"); } return 0; } <file_sep>/book/chap7/func_5.c #include <stdio.h> int sum(int *, int *, int *); int sum(int *a, int *b, int *ans) { *ans = *a + *b; return 0; } int main(int argc, char *argv[]) { int num_1 = 1; int num_2 = 2; int *answer; int ans; answer = &ans; // Need this initialization. if (sum(&num_1, &num_2, answer) != 0) { printf("error\n"); } printf("The answer is ...\n"); printf("answer = %d\n", *answer); return 0; } <file_sep>/Basic-Declarations-and-Expressions/5.c #include <stdio.h> int main() { int height = 7; int width = 5; int perimeter = 2 * height + 2 * width; int area = height * width; printf("Perimeter of the rectangle = %d inches\n", perimeter); printf("Area of the rectangle = %d inches\n", area); return 0; } <file_sep>/book/chap7/ptr_double.c #include <stdio.h> int main(int argc, char *argv[]) { char array[4] = {'A', 'B', 'C', '\0'}; char *ptr = array; char **ptr_double = &ptr; printf("array %p\n", array); printf("array %s\n", array); printf("array[0] %c\n", array[0]); printf("array[1] %c\n", array[1]); printf("array[2] %c\n", array[2]); printf("ptr %p\n", ptr); printf("&ptr %p\n", &ptr); printf("ptr %s\n", ptr); printf("*ptr %c\n", *ptr); printf("*(ptr+1) %c\n", *(ptr+1)); printf("*(ptr+2) %c\n", *(ptr+2)); printf("ptr_double %p\n", ptr_double); printf("*ptr_double %p\n", *ptr_double); printf("&ptr_double %p\n", &ptr_double); printf("*ptr_double %s\n", *ptr_double); printf("**ptr_double %c\n", **ptr_double); printf("*(*ptr_double+1) %c\n", *(*ptr_double+1)); printf("*(*ptr_double+2) %c\n", *(*ptr_double+2)); return 0; } <file_sep>/Basic-Declarations-and-Expressions/1.c #include <stdio.h> int main() { printf("Name : <NAME>\n"); printf("DOB : April 17, 1986\n"); printf("Mobile : 000-0000-0000\n"); return 0; } <file_sep>/Basic-Declarations-and-Expressions/10.c #include <stdio.h> int main() { int v1, v2, result; printf("Please input the first integer: "); scanf("%d", &v1); printf("Please input the second integer: "); scanf("%d", &v2); result = v1 * v2; printf("Result: %d\n" , result); return 0; } <file_sep>/Basic-Declarations-and-Expressions/65.c #include <stdio.h> #include <limits.h> int main() { int total = 199; int num_count = 0; printf("The prime numbers between 1 and 199 are: \n"); printf(" 2"); num_count++; for (int i = 3; i <= total; i++){ int judge_flg; judge_flg = judge_prime(i); if ( judge_flg == 1 ) { printf(" %i", i); num_count++; if ( num_count % 5 == 0 ){ printf("\n"); } } } printf("\n"); return 0; } int judge_prime (int input) { int upto = input / 2 + 1; int judge_flg = 1; for (int i = 2; i <= upto; i++) { if ( input % i == 0 ) { judge_flg = 0; break; } } return judge_flg; } <file_sep>/Basic-Declarations-and-Expressions/22.c #include <stdio.h> int main() { int input[5]; int sum=0; for (int i=0; i < 5; i++){ printf("Input %ith interger: ", i); scanf("%i", &input[i]); if (input[i] % 2 != 0) { sum += input[i]; } } printf("The sum of all odd values is %i.\n", sum); return 0; } <file_sep>/Basic-Declarations-and-Expressions/7.c #include <stdio.h> int main() { int a = 125, b = 12345; long ax = 1234567890; short s = 4043; float x = 2.13459; double dx = 1.1415927; char c = 'W'; unsigned long ux = 2541567890; printf("a + c: %i\n" , a + c); printf("x + c: %f\n", x + c); printf("dx + x: %f\n", dx + x); printf("((int) dx) + ax): %d\n", ((int) dx) + ax); printf("a + x: %f\n", a + x); printf("s + b: %d\n", s + b); printf("ax + b: %d\n", ax + b); printf("s + c: %i\n", s + c); printf("ax + c: %i\n", ax + c); printf("ax + ux: %ld\n", ax + ux); return 0; } <file_sep>/Basic-Declarations-and-Expressions/11.c #include <stdio.h> int main() { float w1, n1, w2, n2; float total_w, total_n; float average; printf("Please input Weight - Item1: "); scanf("%f", &w1); printf("Please input Number of Item1: "); scanf("%f", &n1); printf("Please input Weight - Item2: "); scanf("%f", &w2); printf("Please input Number of Item1: "); scanf("%f", &n2); total_w = w1 * n1 + w2 * n2; total_n = n1 + n2; average = total_w / total_n; printf("Result: %f\n" , average); return 0; } <file_sep>/Basic-Declarations-and-Expressions/69.c #include <stdio.h> #include <math.h> int main(){ int comb_coeff = 0; printf("Mx, 0 1 2 3 4 5 6 7 8 9 10\n"); printf("----------------------------------------------------------\n"); for (int i = 0; i <= 10; i++) { printf("%i,", i); for (int j = 0; j <= i; j++) { comb_coeff = combination(i,j); printf(" %i", comb_coeff); } printf("\n"); } printf("----------------------------------------------------------\n"); return 0; } int combination(int n, int r) { int coeff = 1; if ( n == 0 || r == 0 ) { return coeff; } int numerator = 1; int denom1 = 1; int denom2 = 1; for (int i = 1; i <= n; i++){numerator *= i;}; for (int i = 1; i <= (n-r); i++){denom1 *= i;}; for (int i = 1; i <= r; i++){denom2 *= i;}; coeff = numerator / (denom1 * denom2); return coeff; } <file_sep>/Basic-Declarations-and-Expressions/37.c #include <stdio.h> int main() { int x = 0, y = 0; printf("Input a coordinate in Cartesian system (x,y): \n"); printf("x: "); scanf("%i", &x); printf("y: "); scanf("%i", &y); if ( x >= 0 && y >= 0 ) { printf("Quadrant-I(+,+)\n"); } else if ( x < 0 && y >= 0 ) { printf("Quadrant-II(-,+)\n"); } else if ( x < 0 && y < 0 ) { printf("Quadrant-III(-,-)\n"); } else { printf("Quadrant-IV(+,-)\n"); } return 0; } <file_sep>/Basic-Declarations-and-Expressions/72.c #include <stdio.h> int main(){ int input = 0; int abs_input = 0; printf("Input (negative) integer: "); scanf("%i", &input); if (input < 0) { abs_input = -input; } else { abs_input = input; } printf("Absolute value = %i\n", abs_input); return 0; } <file_sep>/book/chap2/auto-var.c #include <stdio.h> char * func(void) { static char one_string[14] = "hello, world\n"; printf("from func: %s", one_string); return one_string; } int main(int argc, char *argv[]) { printf("from main: %s", func()); return 0; } <file_sep>/Basic-Declarations-and-Expressions/18.c #include <stdio.h> int main() { int input_days=0; int years=0, months=0, days=0; printf("Input no. of days: "); scanf("%i", &input_days); years = input_days / 365; input_days -= years * 365; months = input_days / 30; input_days -= months * 30; days = input_days; printf("%i Year(s)\n", years); printf("%i Month(s)\n", months); printf("%i Day(s)\n", days); return 0; } <file_sep>/book/chap2/auto-var_2.c #include <stdio.h> void func(void) { //int count = 0; static int count = 0; count++; printf("count = %d\n", count); return; } int main(int argc, char *argv[]) { func(); func(); func(); return 0; } <file_sep>/book/chap2/extern_main.c #include <stdio.h> extern int global_number; int main(int argc, char *argv[]) { printf("global_number = %d\n", global_number); return 0; } <file_sep>/Basic-Declarations-and-Expressions/70.c #include <stdio.h> int main(){ int comb_coeff = 0; for (int i = 'A' - 0; i <= 'z' - 0; i++) { if ( (i < '[' - 0) || (i > '`' - 0) ) { printf("[%i-%c] ", i, i); } } printf("\n"); return 0; } <file_sep>/Basic-Declarations-and-Expressions/16.c #include <stdio.h> int main() { int total=0; int n100=0, n50=0, n20=0, n10=0, n5=0, n2=0, n1=0; printf("Input the amount: "); scanf("%i", &total); n100 = total / 100; total -= n100*100; n50 = total / 50; total -= n50*50; n20 = total / 20; total -= n20*20; n10 = total / 10; total -= n10*10; n5 = total / 5; total -= n5*5; n2 = total / 2; total -= n2*2; n1 = total; printf("%i Note(s) of 100.00\n", n100); printf("%i Note(s) of 50.00\n", n50); printf("%i Note(s) of 20.00\n", n20); printf("%i Note(s) of 10.00\n", n10); printf("%i Note(s) of 5.00\n", n5); printf("%i Note(s) of 2.00\n", n2); printf("%i Note(s) of 1.00\n", n1); return 0; } <file_sep>/Basic-Declarations-and-Expressions/17.c #include <stdio.h> int main() { int input_sec=0; int hours=0, mins=0, secs=0; printf("Input seconds: "); scanf("%i", &input_sec); hours = input_sec / (60 * 60); input_sec -= hours * (60 * 60); mins = input_sec / 60; input_sec -= mins * 60; secs = input_sec; printf("H:M:S - %i:%i:%i\n", hours, mins, secs); return 0; } <file_sep>/Basic-Declarations-and-Expressions/14.c #include <stdio.h> int main() { int dist=0; float fuel=0, avg_fuel_consumption=0; printf("Input total distance in km: "); scanf("%i", &dist); printf("Input total fuel spent in liters: "); scanf("%f", &fuel); avg_fuel_consumption = dist / fuel; printf("Average consumption (km/lt): %.2f\n" , avg_fuel_consumption); return 0; } <file_sep>/Basic-Declarations-and-Expressions/66.c #include <stdio.h> #include <stdlib.h> int main() { int num = 50; float rand_max = RAND_MAX; srand(2321); FILE *outputfile; outputfile = fopen("rand.dat", "w"); if (outputfile == NULL) { printf("cannot open\n"); exit(1); } fprintf(outputfile, "%i\n", num); for (int i = 1; i <= num; i++){ float normalized_rand = (rand() / rand_max) - 0.5; fprintf(outputfile, "%f\n", normalized_rand); } fclose(outputfile); return 0; } <file_sep>/book/chap2/extern_sub.c int global_number = 99; <file_sep>/Basic-Declarations-and-Expressions/67.c #include <stdio.h> int main(){ int count, n; float x,y; printf("Input the values of x and n:\n"); printf("x: "); scanf("%f", &x); printf("n: "); scanf("%d", &n); y=1.0; count=1; while(count<=n) { y=y*x; count++; } printf("x=%f; n=%d; \nx to power n=%f\n", x, n,y); return 0; } <file_sep>/book/chap3/zeller.c #include <stdio.h> int main(int argc, char *argv[]) { int year; int month; int day; int week_of_day; year = 2018; month = 8; day = 17; week_of_day = (year + year / 4 - year / 100 + year / 400 + (13 * month + 8) / 5 + day) % 7; printf("%d/%d/%d is %d\n", year, month, day, week_of_day); return 0; } <file_sep>/Basic-Declarations-and-Expressions/12.c #include <stdio.h> int main() { char id[10]; float hr, salary_per_hr; printf("Please input Employees ID (Max 10 chars.): "); scanf("%s", &id); printf("Please input Working hours: "); scanf("%f", &hr); printf("Please input Salary amount/hour: "); scanf("%f", &salary_per_hr); printf("Employees ID = %s\n" , id); printf("Salary = $%.2f\n" , hr * salary_per_hr); return 0; } <file_sep>/book/chap8/struct_3.c #include <stdio.h> const char *string_literal = "hello, world"; struct tag_string { char one_string[16]; }; void print_coordinates(struct tag_coord); struct tag_string *get_stringP(void); struct tag_string get_stringR(void); struct tag_string *get_stringP(void) { struct tag_string a; int i; for (i=0; i < sizeof(a.one_string) - 1 && string_literal[i] != '\0'; i++) { a.one_string[i] = string_literal[i]; } a.one_string[i] = '\0'; return &a; } struct tag_string get_stringR(void) { struct tag_string a; int i; for (i=0; i < sizeof(a.one_string) - 1 && string_literal[i] != '\0'; i++) { a.one_string[i] = string_literal[i]; } a.one_string[i] = '\0'; return a; } int main(int argc, char *argv[]) { struct tag_string *a; struct tag_string b; a = get_stringP(); b = get_stringR(); printf("pointer = %s\n", a->one_string); printf("real = %s\n", b.one_string); return 0; } <file_sep>/book/chap7/ptr_cast.c #include <stdio.h> int main(int argc, char *argv[]) { int i; unsigned char *ptr; int num_1 = 2147483647; long long num_2 = 9223372036854775807; double num_3 = 1.797693e+308; printf("num_1 = %d\n", num_1); ptr = (unsigned char *) &num_1; for (i=0; i< (int) sizeof(num_1); i++) { printf("0x%X ", *ptr); ptr++; } printf("\n"); printf("num_2 = %lld\n", num_2); ptr = (unsigned char *) &num_2; for (i=0; i< (int) sizeof(num_2); i++) { printf("0x%X ", *ptr); ptr++; } printf("\n"); printf("num_3 = %f\n", num_3); ptr = (unsigned char *) &num_3; for (i=0; i< (int) sizeof(num_3); i++) { printf("0x%X ", *ptr); ptr++; } printf("\n"); return 0; } <file_sep>/Basic-Declarations-and-Expressions/28.c #include <stdio.h> int main() { float v[5]; int pos_num=0 ; float sum_pos_num=0; float avg_pos_num=0; for (int i = 0; i < 5; i++) { printf("Input %ith number: ", i); scanf("%f", &v[i]); if (v[i] >= 0) { pos_num++; sum_pos_num += v[i]; } } avg_pos_num = sum_pos_num / pos_num; printf("Number of postive numbers: %i\n", pos_num); printf("Average value of the positive numbers: %f\n", avg_pos_num); return 0; } <file_sep>/Basic-Declarations-and-Expressions/61.c #include <stdio.h> #include <math.h> int main() { float x; printf("Input value of x: "); scanf("%f", &x); printf("The value of sin(1/x) is: %.4f\n", sin(1/x)); return 0; } <file_sep>/Basic-Declarations-and-Expressions/33.c #include <stdio.h> int main() { int v[5]; int max_v = 0, max_pos = 0; printf("Input five integers: "); for ( int i=0; i<5; i++) { printf("%ith integer :\n", i); scanf("%i", &v[i]); if ( v[i] >= max_v ) { max_v = v[i]; max_pos = i; } } printf("Max value is %i:\n", max_v); printf("Max value's position is %i:\n", max_pos); return 0; } <file_sep>/Basic-Declarations-and-Expressions/13.c #include <stdio.h> #include <stdlib.h> int main() { int v1=0, v2=0, v3=0; int v_max_12=0, v_max_123=0; printf("Please input 1st int: "); scanf("%i", &v1); printf("Please input 2nd int: "); scanf("%i", &v2); printf("Please input 3rd int: "); scanf("%i", &v3); v_max_12 = (v1 + v2 + abs(v1 - v2)) / 2; v_max_123 = (v_max_12 + v3 + abs(v_max_12 - v3)) / 2; printf("The maximum value: %i\n" , v_max_123); return 0; } <file_sep>/Basic-Declarations-and-Expressions/68.c #include <stdio.h> #include <math.h> int main(){ int base = 2; printf("=======================================\n"); printf("n, 2 to power n, 2 to power -n\n"); printf("=======================================\n"); for (int i = 0; i <= 10; i++) { printf("%i, %.0f, %f\n", i, pow(base, i), pow(base, -i)); } printf("======================================\n"); return 0; } <file_sep>/book/chap8/struct_2.c #include <stdio.h> struct tag_coord { double x; double y; }; void print_coordinates(struct tag_coord); void print_coordinates(struct tag_coord c) { printf("c.x = %f\n", c.x); printf("c.y = %f\n", c.y); c.x = 12345.00; c.y = 54321.00; } int main(int argc, char *argv[]) { struct tag_coord coord; coord.x = 1.00; coord.y = 2.00; print_coordinates(coord); printf("coord.x = %f\n", coord.x); printf("coord.y = %f\n", coord.y); return 0; } <file_sep>/Basic-Declarations-and-Expressions/36.c #include <stdio.h> int main() { int password = <PASSWORD>; int input = 0; printf("Input password: \n"); scanf("%i", &input); while ( input != password ) { printf("Incorrect password...\n"); printf("Input password: \n"); scanf("%i", &input); } printf("Correct password!\n"); return 0; } <file_sep>/book/chap2/ascii.c #include<stdio.h> int main(int argc, char *argv[]) { int character = 0; while (character < 256) { printf("%c ", character); character++; if ((character % 16) == 0){printf("\n");} } return 0; } <file_sep>/Basic-Declarations-and-Expressions/34.c #include <stdio.h> int main() { int v1 = 0, v2 = 0; int min = 0, max = 0, sum = 0; printf("Input a pair of integers (e.g., 10,2): \n"); printf("First integer: "); scanf("%i", &v1); printf("Second integer: "); scanf("%i", &v2); if ( v1 < v2 ) { min = v1; max = v2; } else { min = v2; max = v1; } for ( int i=min; i<=max; i++) { printf("%i\n", i); sum += i; } printf("Sum of the consective integer is: %i\n", sum); return 0; } <file_sep>/book/chap6/functions.c int sum(int a, int b) { int return_value; return_value = a + b; return return_value; } int sub(int a, int b) { int return_value; return_value = a - b; return return_value; } int mul(int a, int b) { int return_value; return_value = a * b; return return_value; } int div(int a, int b) { int return_value; return_value = a / b; return return_value; } <file_sep>/Basic-Declarations-and-Expressions/64.c #include <stdio.h> #include <limits.h> int main() { int input = 1; int sum = 0, num = 0; float avg = 0; int max = INT_MIN, min = INT_MAX; printf("Input integers. Until you input non-positive integer, the integers will be summed.\n"); while ( input > 0 ) { printf("Input integer: "); scanf("%i", &input); if ( input > 0 ) { sum += input; num++; if ( input >= max ) { max = input; } if ( input < min ) { min = input; } } } avg = sum / num; printf("Average value of the positive integers: %f\n", avg); printf("Maximum value of the positive integers: %i\n", max); printf("Minimum value of the positive integers: %i\n", min); return 0; } <file_sep>/Basic-Declarations-and-Expressions/63.c #include <stdio.h> #include <math.h> int main() { int input = 0; int target_value = 1; int sum = 0; printf("Input a positive number less than 100: "); scanf("%i", &input); for (int i = 1; ; i++) { sum += pow(target_value, 4); target_value += i; if (target_value > input) { break; } } printf("Sum of 1^4 + 2^4 + 4^4 + 7^4 ... m^4 is: %i\n", sum); return 0; } <file_sep>/Basic-Declarations-and-Expressions/31.c #include <stdio.h> int main() { int input; printf("Input an integer: "); scanf("%i", &input); if ( input > 0 ) { if ( input % 2 == 0 ) { printf("The input number is positive even.\n"); } else { printf("The input number is positive odd.\n"); } } else if ( input < 0 ) { if ( input % 2 == 0 ) { printf("The input number is negative even.\n"); } else { printf("The input number is negative odd.\n"); } } else if ( input == 0 ){ printf("The input number is 0.\n"); } return 0; } <file_sep>/book/chap4/pi.c #include <stdio.h> #include <stdlib.h> #include <time.h> int main(int argc, char *argv[]) { double x, y, insect_cnt; int i; insect_cnt = 0.0; i = 0; srand(time(NULL)); while (i < 100000000) { x = (double) rand() / RAND_MAX; y = (double) rand() / RAND_MAX; if ( x * x + y * y < 1.0) { insect_cnt += 1.0; } i++; } printf("%f\n", insect_cnt / i * 4.0); return 0; } <file_sep>/Basic-Declarations-and-Expressions/71.c #include <stdio.h> int main(){ char *str; int char_cnt = 0; printf("Original string: "); scanf("%s", str); for (int i = 0; str[i] != '\0'; i++) {char_cnt++;} printf("Number of characters = %i\n", char_cnt); return 0; } <file_sep>/book/chap7/pointer.c #include <stdio.h> int main(int argc, char *argv[]) { int i; int *i_ptr; i = 1; int j = 2; i_ptr = &j; // *i_ptr = 2; // This does not work (warning) printf("int i is: %i\n", i); printf("address of int i is: %p\n", &i); printf("size of address of int i is: %lu (automatically converted into long unsigned int)\n", sizeof &i); // printf("pointer of int i is: %i\n", *i); // This does not work since pointer of variable does not return address. printf("value of int poiner i_ptr is: %i\n", *i_ptr); printf("address of int pointer i_ptr is: %p\n", i_ptr); printf("address of int j is: %p\n", &j); printf("size of pointer of int pointer i_ptr is: %lu\n", sizeof *i_ptr); printf("\n"); // char str = "test"; // This does not work since array is required. char str[] = "test"; char *str_ptr = "check"; printf("array of characters str is: %s\n", str); printf("address of the first character &str[0] is formatted: %s\n", &str[0]); printf("address of the second character &str[0] is formatted: %s\n", &str[1]); printf("address of the first character &str[0] returns: %p\n", &str[0]); printf("address of the first character &str[1] returns: %p\n", &str[1]); // printf("pointer of the first character &str[1] returns: %p\n", *str[1]); // This does not work. printf("pointer varialbe str_ptr returns: %s\n", str_ptr); printf("address of the first pointer variable &str_ptr[0] is formatted: %s\n", &str_ptr[0]); printf("address of str_ptr is: %p\n", str_ptr); printf("address of the first pointer variable &str_ptr[0] is: %p\n", &str_ptr[0]); printf("address of the incremented pointer ++str_ptr is formatted: %s\n", ++str_ptr); printf("address of the incremented pointer ++str_ptr: %p\n", ++str_ptr); return 0; } <file_sep>/book/chap6/main.c #include <stdio.h> #include "functions.h" int main(int argc, char *argv[]) { int num_1; int num_2; int answer; num_1 = 1; num_2 = 2; answer = sum(num_1, num_2); printf("answer = %d\n", answer); answer = sub(num_1, num_2); printf("answer = %d\n", answer); answer = mul(num_1, num_2); printf("answer = %d\n", answer); answer = div(num_1, num_2); printf("answer = %d\n", answer); return 0; } <file_sep>/Basic-Declarations-and-Expressions/39.c #include <stdio.h> int main() { int v1 = 0, v2 = 0; int min = 0, max = 0, sum = 0; int divisor = 17; printf("Input a pair of integers: \n"); printf("First integer: "); scanf("%i", &v1); printf("Second integer: "); scanf("%i", &v2); if ( v1 < v2 ) { min = v1; max = v2; } else { min = v2; max = v1; } for ( int i=min; i<=max; i++) { if ( i % divisor != 0 ) { sum += i; } } printf("Sum of the numbers which cannot be divided by %i is: %i\n", divisor, sum); return 0; } <file_sep>/Basic-Declarations-and-Expressions/60.c #include <stdio.h> int main() { enum WEEK {Sun, Mon, Tue, Wed, Thu, Fri, Sat}; printf("Sun = %d. \n", Sun); printf("Mon = %d. \n", Mon); printf("Tue = %d. \n", Tue); printf("Wed = %d. \n", Wed); printf("Thu = %d. \n", Thu); printf("Fri = %d. \n", Fri); printf("Sat = %d. \n", Sat); return 0; } <file_sep>/Basic-Declarations-and-Expressions/29.c #include <stdio.h> int main() { int v[5]; float sum_odd_num=0; for (int i = 0; i < 5; i++) { printf("Input %ith integer: ", i); scanf("%i", &v[i]); if (v[i] % 2 != 0) { sum_odd_num += v[i]; } } printf("Sum of the given odd numbers: %i\n", sum_odd_num); return 0; } <file_sep>/Basic-Declarations-and-Expressions/24.c #include <stdio.h> int main() { int v1=0, v2=0; printf("Input 1st interger: "); scanf("%i", &v1); printf("Input 2nd interger: "); scanf("%i", &v2); if (v1 % v2 == 0) { printf("Multiplied!\n"); } else { printf("Not multiplied.\n"); } return 0; } <file_sep>/Basic-Declarations-and-Expressions/8.c #include <stdio.h> int main() { int input = 1329; int year, week, day; year = input / 365; week = (input - 365 * year) / 7; day = (input - 365 * year - 7 * week); printf("Years: %i\n" , year); printf("Weeks: %i\n" , week); printf("Days: %i\n" , day); return 0; } <file_sep>/Basic-Declarations-and-Expressions/19.c #include <stdio.h> #include <assert.h> int main() { int p=0, q=0, r=0, s=0; printf("Input p: "); scanf("%i", &p); printf("Input q: "); scanf("%i", &q); printf("Input r: "); scanf("%i", &r); printf("Input s: "); scanf("%i", &s); assert( r >= 0 ); assert( s >= 0 ); assert( p%2 == 0 ); if ( (q > r) && (s > p) && ( r + s > p + q ) ) { printf("Correct values!\n"); } else { printf("Wrong values!\n"); } return 0; } <file_sep>/Basic-Declarations-and-Expressions/20.c #include <stdio.h> #include <math.h> int main() { float a=0, b=0, c=0; float root1=0, root2=0; printf("Input the first number(a): "); scanf("%f", &a); printf("Input the second number(b): "); scanf("%f", &b); printf("Input the third number(c): "); scanf("%f", &c); root1 = (- b + sqrt( pow(b,2) - 4*a*c )) / (2 * a); root2 = (- b - sqrt( pow(b,2) - 4*a*c )) / (2 * a); printf("Root1: %f\n", root1); printf("Root2: %f\n", root2); return 0; } <file_sep>/Basic-Declarations-and-Expressions/23.c #include <stdio.h> int main() { float input[3]; float v_max, v_mid, v_min; float perimeter; for (int i=0; i < 3; i++){ printf("Input %ith interger: ", i); scanf("%f", &input[i]); } if ( input[0] < (input[1]+input[2]) || input[1] < (input[0]+input[2]) || input[2] < (input[1]+input[0]) ) { perimeter = input[0] + input[1] + input[2]; printf("Valid input values and the perimeter is %f.\n", perimeter); } else { printf("Invalid input values.\n"); } return 0; } <file_sep>/book/chap2/limits.c #include<stdio.h> int main(int argc, char *argv[]) { char char_min, char_max; short short_min, short_max; int int_min, int_max; long long long_long_min, long_long_max; unsigned char unsigned_char_min, unsigned_char_max; unsigned short unsigned_short_min, unsigned_short_max; unsigned int unsigned_int_min, unsigned_int_max; unsigned long unsigned_long_min, unsigned_long_max; unsigned long long unsigned_long_long_min, unsigned_long_long_max; float float_min, float_max; double double_min, double_max; char_min = 0x80 + 1; char_max = 0x7F + 1; short_min = 0x8000 + 1; short_max = 0x7FFF + 1; int_min = 0x80000000 + 1; int_max = 0x7FFFFFFF + 1; long_long_min = 0x8000000000000000 + 1; long_long_max = 0x7FFFFFFFFFFFFFFF + 1; unsigned_char_min = 0x00 + 1; unsigned_char_max = 0xFF + 1; unsigned_short_min = 0x0000 + 1; unsigned_short_max = 0xFFFF + 1; unsigned_int_min = 0x00000000 + 1; unsigned_int_max = 0xFFFFFFFF + 1; unsigned_long_min = 0x00000000 + 1; unsigned_long_max = 0xFFFFFFFF + 1; unsigned_long_long_min = 0x0000000000000000 + 1; unsigned_long_long_max = 0xFFFFFFFFFFFFFFFF + 1; float_min = -3.402823e+38 + 1; float_max = 3.402823e+38 + 1; double_min = -1.797693e+308 + 1; double_max = 1.797693e+308 + 1; printf("char_min = %d, char_max = %d\n", char_min, char_max); printf("short_min = %d, short_max = %d\n", short_min, short_max); printf("int_min = %d, int_max = %d\n", int_min, int_max); printf("long_long_min = %lld, long_long_max = %lld\n", long_long_min, long_long_max); printf("unsigned_char_min = %u, unsigned_char_max = %u\n", unsigned_char_min, unsigned_char_max); printf("unsigned_short_min = %u, unsigned_short_max = %u\n", unsigned_short_min, unsigned_short_max); printf("unsigned_int_min = %u, unsigned_int_max = %u\n", unsigned_int_min, unsigned_int_max); printf("unsigned_long_min = %lu, unsigned_long_max = %lu\n", unsigned_long_min, unsigned_long_max); printf("unsigned_long_long_min = %llu, unsigned_long_long_max = %llu\n", unsigned_long_long_min, unsigned_long_long_max); printf("float_min = %f, float_max = %f\n", float_min, float_max); printf("double_min = %f, double_max = %f\n", double_min, double_max); return 0; } <file_sep>/book/chap2/cast.c #include <stdio.h> int main(int argc, char *argv[]) { int num_1 = 1000; char num_2 = num_1; short num_3 = num_1; printf("int -> char %d\n", num_2); printf("int -> short %d\n", num_3); num_3 = (char) num_1; printf("int -> (char) short %d\n", num_3); return 0; } <file_sep>/Basic-Declarations-and-Expressions/6.c #include <stdio.h> int main() { int radius = 6; float pi = 3.14; float perimeter = 2 * pi * radius; float area = pi * radius * radius; printf("Perimeter of the circle = %f inches\n", perimeter); printf("Area of the circle = %f inches\n", area); return 0; } <file_sep>/book/chap1/nop_nocrt_mac.c int main (int argc, char *argv[]) { return 0; } void _start(int argc) { main(0,0); asm("mov $0x2000001,%rax\n" "mov $0,%rdi\n" "syscall"); } <file_sep>/book/chap6/define.c #include <stdio.h> #define INTEGER_NUM_1 100 #define FLOAT_NUM_1 3.14 #define STRING_1 "%s" #define STRING_2 "hello, world\n" int main(int argc, char *argv[]) { #define INTEGER_NUM_2 200 #define FLOAT_NUM_2 2.71 int a = INTEGER_NUM_1; printf("%d %d\n", a, INTEGER_NUM_2); float b = FLOAT_NUM_1; float c = FLOAT_NUM_2; printf("%f %f\n", b, c); printf(STRING_1, STRING_2); return 0; } <file_sep>/book/chap2/variable.c #include<stdio.h> int main (int argc, char *argv[]) { int number; number = 12345; printf("number is %d\n", number); return 0; } <file_sep>/Basic-Declarations-and-Expressions/32.c #include <stdio.h> int main() { int divisor; int total = 100; printf("Input an integer which will be the divisor: "); scanf("%i", &divisor); for (int i = 1; i <= total; i++) { if ( i % divisor == 3 ) { printf("The number of remider 3 is %i.\n", i); } } return 0; } <file_sep>/Basic-Declarations-and-Expressions/21.c #include <stdio.h> int main() { int input=0; int min=0, max=0, interval=20; max += interval; printf("Input an interger: "); scanf("%i", &input); if (input < 0 || input > 80) { printf("Error. Input integer is negative or larger than 80.\n"); } while (max <= 80) { if (min <= input && input <= max){ printf("Input integer is in [%i,%i].\n", min, max); break; } min += interval; max += interval; } return 0; } <file_sep>/Basic-Declarations-and-Expressions/15.c #include <stdio.h> #include <math.h> int main() { float x1=0, y1=0, x2=0, y2=0; float dist=0; printf("x1: "); scanf("%f", &x1); printf("y1: "); scanf("%f", &y1); printf("x2: "); scanf("%f", &x2); printf("y2: "); scanf("%f", &y2); dist = sqrt( pow(x1 - x2, 2) + pow(y1 - y2, 2) ); printf("Distance between two points: %f\n" , dist); return 0; } <file_sep>/book/chap5/simple_cal_2.c #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <limits.h> int input_number_from_console(const char *prompt, const char *err_msg, long *number) { char input_string[16]; char *endptr; if (number==NULL) { printf("Error.\n"); return -1; } printf("%s", prompt); if (fgets(input_string, sizeof(input_string), stdin) == NULL) { fseek(stdin, 0, SEEK_END); printf("%s", err_msg); return -1; } errno = 0; *number = strtol(input_string, &endptr, 10); if (errno !=0 || *endptr != '\n' || (*number < LONG_MIN || LONG_MAX < *number)) { fseek(stdin, 0, SEEK_END); printf("%s", err_msg); return -1; } return 0; } int main(int argc, char *argv[]) { long a,b; long op; long answer; int c; do { answer = 0; if (input_number_from_console("Input number > ", "\nInput error.\n", &a) == 1) { continue; } if (input_number_from_console("Input number > ", "\nInput error.\n", &b) == 1) { continue; } printf("+---Operator menu---+\n"); printf("| 1. +%*c|\n", 13, ' '); printf("| 2. -%*c|\n", 13, ' '); printf("| 3. *%*c|\n", 13, ' '); printf("| 4. /%*c|\n", 13, ' '); printf("+-------------------+\n"); if (input_number_from_console("Input operator number > ", "\nInput error.\n", &op) == 1) { continue; } switch (op) { case 1: answer = a + b; break; case 2: answer = a - b; break; case 3: answer = a * b; break; case 4: if (b==0) { printf("divide by zero\n"); continue; } else { answer = a / b; } break; default: printf("operator unknown\n"); continue; // NOT REACHED break; } printf("answer is %ld\n", answer); printf("Input q[return] to quit, [return] to continuer.\n"); c = getchar(); if (c == EOF) { fseek(stdin, 0, SEEK_END); } } while (c != 'q'); return 0; } <file_sep>/Basic-Declarations-and-Expressions/62.c #include <stdio.h> int main() { int input = 0, x = 0; int sum = 0; printf("Input a positive number less than 500: "); scanf("%i", &x); input = x; while ( x != 0 ) { sum += x % 10; x /= 10; } printf("Sum of the digit %i is: %i\n", input, sum); return 0; } <file_sep>/Basic-Declarations-and-Expressions/38.c #include <stdio.h> int main() { int divident = 0, divisor = 0; printf("Input two numbers (divident, divisor): \n"); printf("divident: "); scanf("%i", &divident); printf("divisor: "); scanf("%i", &divisor); if ( divident % divisor == 0 ) { printf("Division possible.\n"); } else { printf("Division impossible.\n"); } return 0; } <file_sep>/book/chap4/dice.c #include <stdio.h> #include <stdlib.h> #include <time.h> int main(int argc, char *argv[]) { int c; srand(time(NULL)); do { printf("%d\n", rand() % 6 + 1); c = getchar(); } while (c != 'q'); return 0; }
da2227bd2af56e687d24f68476e4ea14417d7591
[ "C" ]
68
C
yoheikikuta/c-exercise
b5acb1041d3d5a935f3b6d3ca9946fb2de00a26b
6b54cef115cf12263054e3254a07ef719bb3ce10