branch_name stringclasses 149 values | text stringlengths 23 89.3M | directory_id stringlengths 40 40 | languages listlengths 1 19 | num_files int64 1 11.8k | repo_language stringclasses 38 values | repo_name stringlengths 6 114 | revision_id stringlengths 40 40 | snapshot_id stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|
refs/heads/master | <file_sep> <?php
$host="127.0.0.1";
$port="5432";
$user="postgres";
$pass="<PASSWORD>";
$dbname="users";
$cadenaConexion = "host=$host port=$port dbname=$dbname user=$user password=$pass";
$connect = pg_connect($cadenaConexion)or die("Error en la Conexión: ".pg_last_error());
?>
<file_sep><?php include('../includes/header.php');
include('conexion.php');
if (isset($_GET['eliminar'])) {
$data = array('id'=>$_GET['eliminar']);
$res = pg_delete($connect, 'user', $data);
// if ($res) {
// echo "El dato POST será borrado: $res\n";
// } else {
// echo "El usuario debe haber enviado entradas incorrectas\n";
// }
}
$query = "select * from public.user order by id";
$resultado = pg_query($connect, $query) or die("Error en la Consulta SQL");
$numReg = pg_num_rows($resultado);
if($numReg>0){?>
<table class="table">
<thead class="table-inverse">
<tr>
<th>ID</th>
<th>Usuario</th>
<th>Password</th>
<th>
</th>
</tr>
</thead>
<tbody clas="table-striped">
<?php
while ($fila=pg_fetch_array($resultado)) {?>
<tr>
<td><?php echo $fila['id'] ?></td>
<td><?php echo $fila['nombre'] ?></td>
<td><?php echo $fila['pass'] ?></td>
<td>
<a type="button" class="btn btn-success" href="edit.php?editar=<?php echo $fila['id'] ?>"><i class="fa fa-pencil" aria-hidden="true"></i></a>
<a type="button" class="btn btn-danger" href="mostrar.php?eliminar=<?php echo $fila['id'] ?>"><i class="fa fa-trash" aria-hidden="true"></i></a>
</td>
</tr>
<?php }
echo "</tbody>";
echo "</table>";
}else{
echo "No hay Registros";
}
pg_close($connect);
?>
<?php
include('../includes/footer.php'); ?>
<file_sep><?php
include('../includes/header.php');
if(isset($_SESSION["nombre"])){
$n = $_SESSION["n"];
$n2 = $_SESSION["n2"];
echo "<h1>La division de ".$n."/".$n2." es : ".($n/$n2)."</h1>";
include('../includes/footer.php');
}else{
$mensaje = "hola";
header('Location: datos.php?mensaje=$mensaje');
}
?>
<file_sep><?php include('../includes/header.php');
include('conexion.php');
if (isset($_POST ['id'])) {
$data = array('id'=>$_POST ['id']);
$res = pg_update($connect, 'user', $_POST, $data);
header('Location: mostrar.php');
}
if (isset($_GET ['editar'])) {
$data = array('id'=>$_GET['editar']);
$rec = pg_select($connect, 'user', $data);
}
pg_close($connect);
?>
<form class="" action="edit.php" method="post">
<input class="form-control" type="hidden" placeholder="" id="id" name="id" value="<?php echo $rec[0]['id']; ?>">
<div class="form-group row">
<label for="example-text-input" class="col-xs-2 col-form-label">Nombre</label>
<div class="col-xs-10">
<input class="form-control" type="text" placeholder="Introduce tu nombre" id="name" name="nombre" value="<?php echo $rec[0]['nombre']; ?>">
</div>
</div>
<div class="form-group row">
<label for="example-text-input" class="col-xs-2 col-form-label">Password</label>
<div class="col-xs-3">
<input class="form-control" type="password" id="pass" name="pass" placeholder="Introduce una contraseña" value="<?php echo $rec[0]['pass']; ?>">
</div>
</div>
<button type="submit" class="btn btn-primary">Actualizar</button>
</form>
<?php
include('../includes/footer.php'); ?>
<file_sep><?php include('../includes/header.php');
include('conexion.php');
if (isset($_POST ['nombre'])) {
$res = pg_insert($connect, 'user', $_POST);
header('Location: index.php?res=$res');
}
pg_close($connect);
?>
<form class="" action="" method="post">
<div class="form-group row">
<label for="example-text-input" class="col-xs-2 col-form-label">Nombre</label>
<div class="col-xs-10">
<input class="form-control" type="text" placeholder="Introduce tu nombre" id="name" name="nombre" value="">
</div>
</div>
<div class="form-group row">
<label for="example-text-input" class="col-xs-2 col-form-label">Password</label>
<div class="col-xs-3">
<input class="form-control" type="password" id="n1" name="pass" placeholder="Introduce una contraseña" value="">
</div>
</div>
<button type="submit" class="btn btn-primary">Enviar</button>
</form>
<?php
if (isset($_GET['res'])) {
if ($_GET['res']) { ?>
<div class="alert alert-success" role="alert">
<strong>Yeah</strong> Dato insertado correctamente
</div>
<?php
} else {?>
<div class="alert alert-danger" role="alert">
<strong>Oh Espera</strong> Ocurrio un error al insertar
</div>
<?php }
}
include('../includes/footer.php'); ?>
<file_sep><?php
// $jax = new user;
// $jax->nombre = 'Jax';
// $jax->pass = '<PASSWORD>';
// $jax = new user(array('nombre' => 'Jax','pass' => '<PASSWORD>'));
/**
*
*/
class control
{
function __construct()
{
require_once dirname(__FILE__) . '/../php-activerecord/ActiveRecord.php';
ActiveRecord\Config::initialize(function($cfg)
{
$cfg->set_model_directory(dirname(__FILE__) . '/../models');
$cfg->set_connections(array('development' => 'pgsql://postgres:natanahel@127.0.0.1/users'));
// $cfg->set_connections(array('development' => 'mysql://root:@127.0.0.1/users'));
});
}
function alta(){
$data = array('nombre' => $_POST ['name'],'pass' => $_POST ['pw']);
$new = new user($data);
$new->save();
}
function mostrar(){
$find = user::find('all', array('select' => 'nombre, pass'));
return $find;
}
}
// $post = user::create($data);
?>
<file_sep><!DOCTYPE html>
<?php include('../includes/header.php');
include 'controllers/control.php' ?>
<?php
$control = new control();
if(isset($_POST ['name'])){
$control->alta();
}
$find = $control->mostrar();?>
<table width='100%' border='1'> <?php
foreach ($find as $tabla) {
$tabla = $tabla->to_array();
echo "<tr>";
echo "<td>";
echo $tabla['nombre'];
echo "</td>";
echo "<td>";
echo $tabla['pass'];
echo "</td>";
echo "<tr>";
// echo $tabla->nombre;
}
?>
</table>
<?php include('../includes/footer.php'); ?>
<file_sep><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.3/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous">
<link rel="icon" href="../favicon.ico">
<link rel="stylesheet" href="../assets/css/font-awesome.min.css">
<title>Practicas</title>
<style media="screen">
body {
padding-top: 5rem;
}
</style>
</head>
<body>
<nav class="navbar navbar-fixed-top navbar-dark bg-primary">
<a class="navbar-brand active" href="../index.php">Practicas</a>
<ul class="nav navbar-nav">
<li class="nav-item">
<a class="nav-link" href="../practica.php"><i class="fa fa-font" aria-hidden="true"></i> Practica 1</a>
</li>
<li class="nav-item">
<a class="nav-link" href="../practica2.php"><i class="fa fa-table" aria-hidden="true"></i> Practica 2</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" data-toggle="dropdown" href="#"><i class="fa fa-user" aria-hidden="true"></i> Practica 3
<span class="caret"></span></a>
<div class="dropdown-menu" aria-labelledby="Preview">
<a class="dropdown-item" href="../practica3/datos.php">Datos</a>
<a class="dropdown-item" href="../practica3/suma.php">Suma</a>
<a class="dropdown-item" href="../practica3/resta.php">Resta</a>
<a class="dropdown-item" href="../practica3/multiplicacion.php">Multiplicacion</a>
<a class="dropdown-item" href="../practica3/division.php">Division</a>
</div>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" data-toggle="dropdown" href="#"><i class="fa fa-database" aria-hidden="true"></i> Practica 4
<span class="caret"></span></a>
<div class="dropdown-menu" aria-labelledby="Preview">
<a class="dropdown-item" href="../practica4/">Introducir datos</a>
<a class="dropdown-item" href="../practica4/mostrar.php">Mostrar datos</a>
</div>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" data-toggle="dropdown" href="#"><i class="fa fa-database" aria-hidden="true"></i> Practica 5
<span class="caret"></span></a>
<div class="dropdown-menu" aria-labelledby="Preview">
<a class="dropdown-item" href="../practica5/">Introducir datos</a>
<a class="dropdown-item" href="../practica5/mostrar.php">Mostrar datos</a>
</div>
</li>
<?php
session_start();
if (isset($_SESSION["nombre"])){
?>
<li class="nav-item dropdown pull-md-right">
<a class="nav-link dropdown-toggle" data-toggle="dropdown" href="#"><?php echo $_SESSION["nombre"] ?>
<span class="caret"></span></a>
<div class="dropdown-menu" aria-labelledby="Preview">
<a class="dropdown-item" href="../logout.php">logout</a>
</div>
</li>
<?php
}else {
echo "<li class='nav-item pull-md-right'>";
echo "<a class='nav-link' href=''>User</a>";
echo "</li>";
}
?>
</ul>
</nav>
<div class="container">
<file_sep><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<div>
<?php
if(isset($_POST ['datos'])){
$datos = $_POST ['datos'];
for ($i=0; $i < $datos; $i++) {
for ($j=0; $j < $datos; $j++) {
$ran = rand(1,3);
switch ($ran) {
case 1:
$matriz[$i][$j] = 'O';
break;
case 2:
$matriz[$i][$j] = 'G';
break;
case 3:
$matriz[$i][$j] = 'W';
break;
}
}
}
$matriz2 = $matriz;
for ($i=0; $i < $datos; $i++) {
for ($j=0; $j < $datos; $j++) {
//
if ($matriz2[$i][$j] == 'G'){
//
$a=1;
$ban = 1;
while ($ban) {
if ($i-$a >= 0 and $j-$a >= 0) {
if ($matriz2[$i-$a][$j-$a] == 'W') $ban = 0;
else if ($matriz2[$i-$a][$j-$a] == 'G') $ban = 0;
else if ($matriz2[$i-$a][$j-$a] == 'O') $matriz2[$i-$a][$j-$a] = $a;
else if ($matriz2[$i-$a][$j-$a] >= $a) $matriz2[$i-$a][$j-$a] = $a;
}
else {$ban = 0;}
$a++;
}
//
$ban = 1;
$a=1;
while ($ban) {
if ($j-$a >= 0) {
if ($matriz2[$i][$j-$a] == 'W') $ban = 0;
else if ($matriz2[$i][$j-$a] == 'G') $ban = 0;
else if ($matriz2[$i][$j-$a] == 'O') $matriz2[$i][$j-$a] = $a;
else if ($matriz2[$i][$j-$a] >= $a) $matriz2[$i][$j-$a] = $a;
}
else {$ban = 0;}
$a++;
}
//
$ban = 1;
$a=1;
while ($ban) {
if ($i-$a >= 0) {
if ($matriz2[$i-$a][$j] == 'W') $ban = 0;
else if ($matriz2[$i-$a][$j] == 'G') $ban = 0;
else if ($matriz2[$i-$a][$j] == 'O') $matriz2[$i-$a][$j] = $a;
else if ($matriz2[$i-$a][$j] >= $a) $matriz2[$i-$a][$j] = $a;
}
else {$ban = 0;}
$a++;
}
//
$ban = 1;
$a=1;
while ($ban) {
if ($i+$a < $datos and $j+$a < $datos) {
if ($matriz2[$i+$a][$j+$a] == 'W') $ban = 0;
else if ($matriz2[$i+$a][$j+$a] == 'G') $ban = 0;
else if ($matriz2[$i+$a][$j+$a] == 'O') $matriz2[$i+$a][$j+$a] = $a;
else if ($matriz2[$i+$a][$j+$a] >= $a) $matriz2[$i+$a][$j+$a] = $a;
}
else {$ban = 0;}
$a++;
}
//
$ban = 1;
$a=1;
while ($ban) {
if ($j+$a < $datos) {
if ($matriz2[$i][$j+$a] == 'W') $ban = 0;
else if ($matriz2[$i][$j+$a] == 'G') $ban = 0;
else if ($matriz2[$i][$j+$a] == 'O') $matriz2[$i][$j+$a] = $a;
else if ($matriz2[$i][$j+$a] >= $a) $matriz2[$i][$j+$a] = $a;
}
else {$ban = 0;}
$a++;
}
//
$ban = 1;
$a=1;
while ($ban) {
if ($i+$a < $datos) {
if ($matriz2[$i+$a][$j] == 'W') $ban = 0;
else if ($matriz2[$i+$a][$j] == 'G') $ban = 0;
else if ($matriz2[$i+$a][$j] == 'O') $matriz2[$i+$a][$j] = $a;
else if ($matriz2[$i+$a][$j] >= $a) $matriz2[$i+$a][$j] = $a;
}
else {$ban = 0;}
$a++;
}
//
$ban = 1;
$a=1;
while ($ban) {
if ($i+$a < $datos and $j-$a >= 0) {
if ($matriz2[$i+$a][$j-$a] == 'W') $ban = 0;
else if ($matriz2[$i+$a][$j-$a] == 'G') $ban = 0;
else if ($matriz2[$i+$a][$j-$a] == 'O') $matriz2[$i+$a][$j-$a] = $a;
else if ($matriz2[$i+$a][$j-$a] >= $a) $matriz2[$i+$a][$j-$a] = $a;
}
if ($i-$a >= 0 and $j+$a < $datos) {
if ($matriz2[$i-$a][$j+$a] == 'W') $ban = 0;
else if ($matriz2[$i-$a][$j+$a] == 'G') $ban = 0;
else if ($matriz2[$i-$a][$j+$a] == 'O') $matriz2[$i-$a][$j+$a] = $a;
else if ($matriz2[$i-$a][$j+$a] >= $a) $matriz2[$i-$a][$j+$a] = $a;
}
else {$ban = 0;}
$a++;
}
//
$ban = 1;
$a=1;
while ($ban) {
if ($i-$a >= 0 and $j+$a < $datos) {
if ($matriz2[$i-$a][$j+$a] == 'W') $ban = 0;
else if ($matriz2[$i-$a][$j+$a] == 'G') $ban = 0;
else if ($matriz2[$i-$a][$j+$a] == 'O') $matriz2[$i-$a][$j+$a] = $a;
else if ($matriz2[$i-$a][$j+$a] >= $a) $matriz2[$i-$a][$j+$a] = $a;
}
else {$ban = 0;}
$a++;
}
}
}
}
}
echo "<h1>Practica 2</h1>";
echo "<form method='post' action=''>";
echo "<input type='text' name='datos' value='$datos'><br><br>";
echo "<input type='submit' value='enviar'>";
echo "</form>";
echo "</div>";
if(isset($matriz)){
?>
<table width=”100%” border=”1″>
<?php for ($i=0; $i < $datos; $i++) { ?>
<tr>
<?php for ($j=0; $j < $datos; $j++) {?>
<td <?php if ($matriz[$i][$j] == 'W') {echo "bgcolor= '#827E7E' ";}
if ($matriz[$i][$j] == 'G') {echo "bgcolor= '#1E52CC' ";}
?>> <?php echo $matriz[$i][$j];?> </td>
<?php } ?>
</tr>
<?php } ?>
</table>
<br>
<table width=”100%” border=”1″>
<?php for ($i=0; $i < $datos; $i++) { ?>
<tr>
<?php for ($j=0; $j < $datos; $j++) {?>
<td <?php if ($matriz2[$i][$j] == 'W') {echo "bgcolor= '#827E7E' ";}
if ($matriz2[$i][$j] == 'G') {echo "bgcolor= '#1E52CC' ";}
?>> <?php echo $matriz2[$i][$j];?> </td>
<?php } ?>
</tr>
<?php } ?>
</table>
<?php } ?>
</body>
</html>
<file_sep><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<div>
<?php
$newword = "";
$palabra = explode(" ",$_POST ['palabra']);
$word = $_POST ['palabra'];
foreach (array_reverse($palabra) as $key => $value) {
$newword = $newword." ".$value;
}
echo "<h1>Practica 1</h1>";
echo "<form method='post' action=''>";
echo "<input type='text' name='palabra' value='$word'><br><br>";
echo "<input type='text' name='palabra2' value='$newword' disabled><br><br>";
echo "<input type='submit' value='Nuevo'>";
echo "</form>";
echo "</div>";
?>
</body>
</html>
<file_sep><?php
class user extends ActiveRecord\Model
{
static $table_name = 'user';
static $validates_presence_of =array(
// 'id','nombre','pass');
array('nombre'), array('pass'));
}
?>
<file_sep><?php include('../includes/header.php') ?>
<form class="" action="" method="post">
<?php if(isset($_SESSION["nombre"])){echo "<fieldset disabled>";}?>
<div class="form-group row">
<label for="example-text-input" class="col-xs-2 col-form-label">Nombre</label>
<div class="col-xs-10">
<input class="form-control" type="text" placeholder="Introduce tu nombre" id="name" name="name" value="<?php if(isset($_SESSION["nombre"])){echo $_SESSION["nombre"];} ?>">
</div>
</div>
<div class="form-group row">
<label for="example-text-input" class="col-xs-2 col-form-label">Número Uno</label>
<div class="col-xs-3">
<input class="form-control" type="number" id="n1" name="n1" placeholder="Introduce un número" value="<?php if(isset($_SESSION["nombre"])){echo $_SESSION["n"];} ?>">
</div>
</div>
<div class="form-group row">
<label for="example-text-input" class="col-xs-2 col-form-label">Número Dos</label>
<div class="col-xs-3">
<input type="number" class="form-control" id="n2" name="n2"placeholder="Introduce un número" value="<?php if(isset($_SESSION["nombre"])){echo $_SESSION["n2"];} ?>">
</div>
</div>
<button type="submit" class="btn btn-primary">Enviar</button>
<?php if(isset($_SESSION["nombre"])){echo "</fieldset>";}?>
</form>
<?php if(isset($_GET["mensaje"])){?>
<div class="alert alert-danger" role="alert">
<strong>Oh Espera</strong> Debes agregar datos al formulario primero
</div>
<?php } ?>
<?php
if(isset($_SESSION["nombre"])){
}else
if(isset($_POST ['name'])){
$_SESSION["nombre"] = $_POST ['name'];
$_SESSION["n"] = $_POST ['n1'];
$_SESSION["n2"] = $_POST ['n2'];
header('Location: datos.php');
}
?>
<?php include('../includes/footer.php') ?>
<file_sep><?php include('../includes/header.php');
include 'controllers/control.php' ?>
<form class="" action="mostrar.php" method="post">
<div class="form-group row">
<label for="example-text-input" class="col-xs-2 col-form-label">Nombre</label>
<div class="col-xs-10">
<input class="form-control" type="text" placeholder="Introduce tu nombre" id="name" name="name" value="<?php if(isset($_SESSION["nombre"])){echo $_SESSION["nombre"];} ?>">
</div>
</div>
<div class="form-group row">
<label for="example-text-input" class="col-xs-2 col-form-label">Password</label>
<div class="col-xs-3">
<input class="form-control" type="password" id="n1" name="pw" placeholder="Introduce una contraseña" value="<?php if(isset($_SESSION["nombre"])){echo $_SESSION["n"];} ?>">
</div>
</div>
<button type="submit" class="btn btn-primary">Enviar</button>
</form>
<?php include('../includes/footer.php'); ?>
| cc2d647a81a5df6f6f1dab3b8e4e6ee1c4c960e6 | [
"PHP"
] | 13 | PHP | NekroCid/Practicas-Appdatamx | 011cba416a5ca579047df4a2c0ecc5b1e6caafef | f4bf9b5688d4f9623085a4f5f7acf4abffd7705d |
refs/heads/main | <file_sep># 3D_game
We watched Kári's videos from 2019 to learn how to use the textures. What a man.
<file_sep>import OpenGL.error
import OpenGL.GLU
import OpenGL.GL
import sys
from Base3DObjects import *
class Shader3D:
def __init__(self):
vert_shader = glCreateShader(GL_VERTEX_SHADER)
shader_file = open(sys.path[0] + "/simple3D.vert")
glShaderSource(vert_shader, shader_file.read())
shader_file.close()
glCompileShader(vert_shader)
result = glGetShaderiv(vert_shader, GL_COMPILE_STATUS)
if (result != 1): # shader didn't compile
print("Couldn't compile vertex shader\nShader compilation Log:\n" + str(glGetShaderInfoLog(vert_shader)))
frag_shader = glCreateShader(GL_FRAGMENT_SHADER)
shader_file = open(sys.path[0] + "/simple3D.frag")
glShaderSource(frag_shader,shader_file.read())
shader_file.close()
glCompileShader(frag_shader)
result = glGetShaderiv(frag_shader, GL_COMPILE_STATUS)
if (result != 1): # shader didn't compile
print("Couldn't compile fragment shader\nShader compilation Log:\n" + str(glGetShaderInfoLog(frag_shader)))
self.renderingProgramID = glCreateProgram()
glAttachShader(self.renderingProgramID, vert_shader)
glAttachShader(self.renderingProgramID, frag_shader)
glLinkProgram(self.renderingProgramID)
self.positionLoc = glGetAttribLocation(self.renderingProgramID, "a_position")
glEnableVertexAttribArray(self.positionLoc)
self.normalLoc = glGetAttribLocation(self.renderingProgramID, "a_normal")
glEnableVertexAttribArray(self.normalLoc)
self.modelMatrixLoc = glGetUniformLocation(self.renderingProgramID, "u_model_matrix")
self.viewMatrixLoc = glGetUniformLocation(self.renderingProgramID, "u_view_matrix")
self.projectionMatrixLoc = glGetUniformLocation(self.renderingProgramID, "u_projection_matrix")
self.normalLightDirection = glGetUniformLocation(self.renderingProgramID, "u_normal_light_direction")
self.normalLightColor = glGetUniformLocation(self.renderingProgramID, "u_normal_light_color")
self.lightPosition = glGetUniformLocation(self.renderingProgramID, "u_light_position")
self.lightColor = glGetUniformLocation(self.renderingProgramID, "u_light_color")
self.lightDirection = glGetUniformLocation(self.renderingProgramID, "u_light_direction")
self.lightCutoff = glGetUniformLocation(self.renderingProgramID, "u_light_cutoff")
self.lightConst = glGetUniformLocation(self.renderingProgramID, "u_light_constant")
self.lightLinear = glGetUniformLocation(self.renderingProgramID, "u_light_linear")
self.lightQuad = glGetUniformLocation(self.renderingProgramID, "u_light_quad")
self.lightOuterCutoff = glGetUniformLocation(self.renderingProgramID, "u_light_outer_cutoff")
self.flashlightPosition = glGetUniformLocation(self.renderingProgramID, "u_flashlight_position")
self.flashlightActive = glGetUniformLocation(self.renderingProgramID, "use_flashlight")
self.flashlightColor = glGetUniformLocation(self.renderingProgramID, "u_flashlight_color")
self.flashlightDirection = glGetUniformLocation(self.renderingProgramID, "u_flashlight_direction")
self.flashlightCutoff = glGetUniformLocation(self.renderingProgramID, "u_flashlight_cutoff")
self.flashlightConst = glGetUniformLocation(self.renderingProgramID, "u_flashlight_constant")
self.flashlightLinear = glGetUniformLocation(self.renderingProgramID, "u_flashlight_linear")
self.flashlightQuad = glGetUniformLocation(self.renderingProgramID, "u_flashlight_quad")
self.flashlightOuterCutoff = glGetUniformLocation(self.renderingProgramID, "u_flashlight_outer_cutoff")
self.materialDiffuseLoc = glGetUniformLocation(self.renderingProgramID, "u_mat_diffuse")
self.materialSpecularLoc = glGetUniformLocation(self.renderingProgramID, "u_mat_specular")
self.materialShinyLoc = glGetUniformLocation(self.renderingProgramID, "u_mat_shiny")
self.materialEmit = glGetUniformLocation(self.renderingProgramID, "u_mat_emit")
self.textureLoc = glGetAttribLocation(self.renderingProgramID, "a_uv")
glEnableVertexAttribArray(self.textureLoc)
self.diffuse_texture = glGetUniformLocation(self.renderingProgramID, "u_tex_diffuse")
self.specular_texture = glGetUniformLocation(self.renderingProgramID, "u_tex_specular")
#self.colorLoc = glGetUniformLocation(self.renderingProgramID, "u_color")
def use(self):
try:
glUseProgram(self.renderingProgramID)
except OpenGL.error.Error:
print(glGetProgramInfoLog(self.renderingProgramID))
raise
def set_specular_texture(self, i):
glUniform1i(self.specular_texture, i)
def set_diffuse_texture(self, i):
glUniform1i(self.diffuse_texture, i)
def set_model_matrix(self, matrix_array):
glUniformMatrix4fv(self.modelMatrixLoc, 1, True, matrix_array)
def set_view_matrix(self, matrix_array):
glUniformMatrix4fv(self.viewMatrixLoc, 1, True, matrix_array)
def set_projection_matrix(self, matrix_array):
glUniformMatrix4fv(self.projectionMatrixLoc, 1, True, matrix_array)
def set_position_attribute(self, vertex_array):
glVertexAttribPointer(self.positionLoc, 3, GL_FLOAT, False, 0, vertex_array)
def set_normal_attribute(self, vertex_array):
glVertexAttribPointer(self.normalLoc, 3, GL_FLOAT, False, 0, vertex_array)
def set_texture_attribute(self, vertex_array):
glVertexAttribPointer(self.textureLoc, 2, GL_FLOAT, False, 0, vertex_array)
def set_normal_light_direction(self, pos):
glUniform4f(self.normalLightDirection, pos.x, pos.y, pos.z, 1.0)
def set_normal_light_color(self, rgb):
glUniform4f(self.normalLightColor, rgb.r, rgb.g, rgb.b, 1.0)
def set_flashlight_position(self, pos):
glUniform4f(self.flashlightPosition, pos.x, pos.y, pos.z, 1.0)
def set_flashlight_direction(self, pos):
glUniform4f(self.flashlightDirection, pos.x, pos.y, pos.z, 1.0)
def set_flashlight_color(self, rgb):
glUniform4f(self.flashlightColor, rgb.r, rgb.g, rgb.b, 1.0)
def set_flashlight_cutoff(self, f):
glUniform1f(self.flashlightCutoff, f)
def set_flashlight_outer_cutoff(self, f):
glUniform1f(self.flashlightOuterCutoff, f)
def set_flashlight_constant(self, f):
glUniform1f(self.flashlightConst, f)
def set_flashlight_linear(self, f):
glUniform1f(self.flashlightLinear, f)
def set_flashlight_quad(self, f):
glUniform1f(self.flashlightQuad, f)
def set_light_position(self, pos):
glUniform4f(self.lightPosition, pos.x, pos.y, pos.z, 1.0)
def set_light_direction(self, pos):
glUniform4f(self.lightDirection, pos.x, pos.y, pos.z, 1.0)
def set_light_color(self, rgb):
glUniform4f(self.lightColor, rgb.r, rgb.g, rgb.b, 1.0)
def set_light_cutoff(self, f):
glUniform1f(self.lightCutoff, f)
def set_light_outer_cutoff(self, f):
glUniform1f(self.lightOuterCutoff, f)
def set_light_constant(self, f):
glUniform1f(self.lightConst, f)
def set_light_linear(self, f):
glUniform1f(self.lightLinear, f)
def set_light_quad(self, f):
glUniform1f(self.lightQuad, f)
def set_material_shiny(self, s):
glUniform1f(self.materialShinyLoc, s)
def set_material_emit(self, e):
glUniform1f(self.materialEmit, e)
def set_attribute_buffers(self, vertex_buffer_id):
glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer_id)
glVertexAttribPointer(self.positionLoc, 3, GL_FLOAT, False, 8 * sizeof(GLfloat), OpenGL.GLU.ctypes.c_void_p(0))
glVertexAttribPointer(self.normalLoc, 3, GL_FLOAT, False, 8 * sizeof(GLfloat), OpenGL.GLU.ctypes.c_void_p(3 * sizeof(GLfloat)))
glVertexAttribPointer(self.textureLoc, 2, GL_FLOAT, False, 8 * sizeof(GLfloat), OpenGL.GLU.ctypes.c_void_p(6 * sizeof(GLfloat)))
def set_material_diffuse(self, color):
glUniform4f(self.materialDiffuseLoc, color.r, color.g, color.b, 1.0)
def set_material_specular(self, color):
glUniform4f(self.materialSpecularLoc, color.r, color.g, color.b, 1.0)
def set_active_flashlight(self, f):
glUniform1f(self.flashlightActive, f)<file_sep>from OpenGL.GL import *
from OpenGL.GLUT import *
from math import *
import pygame
from pygame.locals import *
import sys
from objloader import *
from Base3DObjects import *
from Shaders import *
from Matrices import *
from Control3DBase import objloader
class GraphicsProgram3D:
def __init__(self):
pygame.init()
pygame.display.set_mode((800,600), pygame.OPENGL|pygame.DOUBLEBUF)
self.shader = Shader3D()
self.shader.use()
self.lvl = 1
self.model_matrix = ModelMatrix()
self.view_matrix = ViewMatrix()
self.view_matrix.look(Point(7, 1, 5), Point(7, 1.0, 0.0), Vector(0, 1, 0))
self.shader.set_view_matrix(self.view_matrix.get_matrix())
"""Sounds"""
self.crash_sound = pygame.mixer.Sound("sounds/scream.wav")
self.lvlup_sound = pygame.mixer.Sound("sounds/lvlcomplete.wav")
self.flashlight_click = pygame.mixer.Sound("sounds/flashlight.wav")
self.jumpscare = pygame.mixer.Sound("sounds/jumpscare.wav")
self.flashlight_angle = 0 #To calculate flashlight yaw
"""Textures"""
self.shader.set_diffuse_texture(0)
self.tex_id_wall_diffuse = self.load_texture("./textures/gravel.jpeg")
self.shader.set_specular_texture(1)
self.tex_id_wall_specular = self.load_texture("./textures/gravel.jpeg")
self.tex_id_vurdulak_diffuse = self.load_texture("./textures/vurdalak_Base_Color.jpg")
self.tex_id_vurdulak_specular = self.load_texture("./textures/vurdalak_Base_Color.jpg")
self.tex_id_flashlight_diffuse = self.load_texture("./textures/black.jpeg")
self.tex_id_flashlight_specular = self.load_texture("./textures/black.jpeg")
self.tex_id_floorandceiling = self.load_texture("./textures/gravel.jpeg")
self.tex_id_floorandceiling_specular = self.load_texture("./textures/gravel.jpeg")
"""Ignore the name this is the start up screen"""
self.tex_id_jumpscare_diffuse = self.load_texture("./textures/screen.png")
self.tex_id_jumpscare_specular = self.load_texture("./textures/screen.png")
self.tex_id_win_screen_diffuse = self.load_texture("./textures/winscreen.png")
self.tex_id_win_screen_specular = self.load_texture("./textures/winscreen.png")
self.projection_matrix = ProjectionMatrix()
self.fov = pi / 2
self.projection_matrix.set_perspective(pi / 2, 800 / 600, 0.5, 100)
self.shader.set_projection_matrix(self.projection_matrix.get_matrix())
self.cube = Cube()
self.scale = Point(1, 1, 1)
self.clock = pygame.time.Clock()
"""Obj models"""
self.obj_model = objloader.load_obj_file(sys.path[0] + '/objects/', 'vurdalak_low.obj')
self.obj_model_flashlight = objloader.load_obj_file(sys.path[0] + '/objects/', 'FlashlightOBJ.obj')
"""Walls: x, y, z positions, and x, y, z scale"""
self.wall_list = [
[15.0, 1.0, 1.0, 0.2, 1.0, 8.0],
[5.0, 1.0, 1.0, 0.2, 1.0, 8.0],
[8.9, 1.0, 5.0, 8.0, 1.0, 0.2],
[14.5, 1.0, 5.0, 1.2, 1.0, 0.2],
[11.1, 1.0, -3.1, 8.0, 1, 0.2],
[5.4, 1.0, -3.1, 1.0, 1.0, 0.2],
[8.0, 1.0, -1.5, 6.0, 1.0, 0.2],
[6.0, 1.0, 1.4, 0.2, 1.0, 4.0],
[5.8, 1.0, 4.0, 1.5, 1.0, 0.2],
[7.4, 1.0, 4.0, 0.2, 1.0, 2.0],
[10.5, 1.0, 3.1, 6.5, 1.0, 0.2],
[11.2, 1.0, 4.1, 5.5, 1.0, 0.2],
[14.0, 1.0, 4.5, 0.2, 1.0, 1.0],
[13.2, 1.0, -0.8, 0.2, 1.0, 4.5],
[10.2, 1.0, 1.4, 6.0, 1.0, 0.2],
[12.0, 1.0, -0.2, 0.2, 1.0, 3.0],
[7.3, 1.0, 0.4, 0.2, 1.0, 1.9],
[8.3, 1.0, -0.6, 0.2, 1.0, 2.0],
[10.9, 1.0, -0.6, 0.2, 1.0, 2.0],
[6.7, 1.0, -0.5, 1.4, 1.0, 0.2],
[9.6, 1.0, 0.5, 2.8, 1.0, 0.2],
[14.0, 1.0, 0.2, 0.2, 1.0, 4.3],
[13.0, 1.0, 2.3, 3.8, 1.0, 0.2],
[10.0, 1.0, 2.7, 0.2, 1.0, 1.0],
[8.7, 1.0, 2.3, 2.5, 1.0, 0.2],
]
self.wall_list2 = [
[10.0, 1.0, 1.0, 0.2, 1.0, 4.0],
[6.2, 1.0, 1.0, 0.2, 1.0, 4.0],
[6.8, 1.0, 3.0, 1.0, 1.0, 0.2],
[9.0, 1.0, 3.0, 2.0, 1.0, 0.2],
[7.2, 1.0, -1.0, 2.0, 1, 0.2],
[9.5, 1.0, -1.0, 1.0, 1, 0.2],
[9.15, 1.0, -0.0, 0.5, 1.0, 0.2],
[7.2, 1.0, -0.0, 2.0, 1, 0.2],
[9.0, 1.0, -0.5, 0.2, 1, 0.8],
[8.75, 1.0, 1.0, 1.3, 1.0, 0.2],
[8.1, 1.0, 0.6, 0.2, 1, 1.0],
[6.8, 1.0, 2.0, 1.0, 1.0, 0.2],
[7.2, 1.0, 1.5, 0.2, 1, 1.0],
[8.65, 1.0, 2.0, 1.3, 1.0, 0.2],
[8.1, 1.0, 2.6, 0.2, 1, 1.0]
]
self.ceilingandfloorlvl1 = [
[8.1, 0.0, 1.0, 4.0, 1.0, 8.0],
[8.1, 2.0, 1.0, 4.0, 1.0, 8.0]
]
self.floor_lvl2 = [
[10, 0.0, 1.0, 10, 1.0, 10.0]
]
self.monster_pos_locations = [
[8.8, 0.6, 2.4, pi/2],
[6.8, 0.6, 1.4, pi],
]
self.monster_pos_locations_lvl_2 = [
[14.5, 0.6, 0.6, pi],
[5.5, 0.4, 4.5, pi/2],
[12.5, 0.4, 0.8, pi]
]
self.close_walls = []
"""A lot of stuff we need"""
self.JUMPSCARE = False
self.JUMPSCARE_other = False
self.collisionLeftWall = False
self.collisionRightWall = False
self.collisionTopWall = False
self.collisionBottomWall = False
self.A_key_down = False
self.D_key_down = False
self.T_key_down = False
self.G_key_down = False
self.UP_key_down = False
self.falling = False
self.check_if_won()
self.check_if_died()
self.collison_check()
self.SPACE_key_down = False
self.p_key_down = False
"""Used to calculate how long the player looks at the monster"""
self.looking_at_monster_count = 1
self.looking_at_monster_count_other = 1
self.won = False
self.ENTER_key_down = True
def check_if_won(self):
if 8.0 <= self.view_matrix.eye.x <= 9 and -0.9 >= self.view_matrix.eye.z >= -1.1 and self.lvl == 1:
self.lvl = 2
pygame.mixer.Sound.play(self.lvlup_sound)
self.view_matrix.look(Point(13.5, 1, 5.5), Point(13.5, 1.0, 0), Vector(0, 1, 0))
self.looking_at_monster_count = 1
self.looking_at_monster_count_other = 1
print("You solved the maze!")
if 7 >= self.view_matrix.eye.x >= 6.0 and -3.0 >= self.view_matrix.eye.z >= -4.0 and self.lvl == 2:
self.won = True
def check_if_died(self):
if (self.view_matrix.eye.x >= 10.0 and self.lvl == 1) or self.view_matrix.eye.x <= 6 and 5 >= self.view_matrix.eye.z >= -3 and self.lvl == 1:
self.falling = True
if self.view_matrix.eye.z >= 5.2 and self.lvl == 1:
self.falling = True
if (self.view_matrix.eye.x >= 30.0 and self.lvl == 2) or self.view_matrix.eye.x <= 5.0 and 10 >= self.view_matrix.eye.z >= -10 and self.lvl == 2:
self.falling = True
if self.view_matrix.eye.z >= 7.3 and self.lvl == 2:
self.falling = True
def check_distance_from_monster(self):
if self.lvl == 1:
look_x_min = 6.1
look_x_max = 7.7
look_z_min = 0.0
look_z_max = 1.0
other_x_min = 8.9
other_x_max = 10.0
other_z_min = 2.0
other_z_max = 3.0
if self.view_matrix.n.z <= 0 and -0.40 <= self.view_matrix.n.x <= 0.80:
if look_x_min <= self.view_matrix.eye.x <= look_x_max:
if look_z_min <= self.view_matrix.eye.z <= look_z_max:
self.looking_at_monster_count += 1
if self.view_matrix.n.x >= 0 and -0.60 <= self.view_matrix.n.z <= 0.40:
if other_x_min <= self.view_matrix.eye.x <= other_x_max:
if other_z_min <= self.view_matrix.eye.z <= other_z_max:
self.looking_at_monster_count_other += 1
if self.lvl == 2:
look_x_min_2 = 13.7
look_x_max_2 = 14.8
look_z_min_2 = -2.7
look_z_max_2 = 0.5
other_x_min_2 = 12.0
other_x_max_2 = 13.0
other_z_min_2 = -2.5
other_z_max_2 = 0.5
third_x_min = 6.5
third_x_max = 7.5
third_z_min = 4.0
third_z_max = 5.0
if self.view_matrix.n.z <= 0 and -0.40 <= self.view_matrix.n.x <= 0.40:
if look_x_min_2 <= self.view_matrix.eye.x <= look_x_max_2:
if look_z_min_2 <= self.view_matrix.eye.z <= look_z_max_2:
self.looking_at_monster_count += 1
if self.view_matrix.n.z <= 0 and -0.40 <= self.view_matrix.n.x <= 0.40:
if other_x_min_2 <= self.view_matrix.eye.x <= other_x_max_2:
if other_z_min_2 <= self.view_matrix.eye.z <= other_z_max_2:
self.looking_at_monster_count += 1
if self.view_matrix.n.x >= 0 and -0.60 <= self.view_matrix.n.z <= 0.40:
if third_x_min <= self.view_matrix.eye.x <= third_x_max:
if third_z_min <= self.view_matrix.eye.z <= third_z_max:
self.looking_at_monster_count_other += 1
def get_walls_closest(self):
for item in self.wall_list2:
if item[0]-2.0 <= self.view_matrix.eye.x <= item[0]+2.0:
if item[2]-2.0 <= self.view_matrix.eye.z <= item[2]+2.0:
if item not in self.close_walls:
self.close_walls.append(item)
continue
else:
if item in self.close_walls:
self.close_walls.remove(item)
def collison_check(self):
if self.lvl == 1:
for item in self.close_walls:
wall_min_x = item[0] - item[3] / 2
wall_max_x = item[0] + item[3] / 2
wall_min_z = item[2] - item[5] / 2
wall_max_z = item[2] + item[5] / 2
if wall_max_x+0.2 >= self.view_matrix.eye.x >= wall_max_x+0.1:
if wall_min_z-0.1 <= self.view_matrix.eye.z <= wall_max_z+0.1:
self.collisionRightWall = True
return True
else:
self.collisionRightWall = False
if wall_min_x-0.2 <= self.view_matrix.eye.x <= wall_min_x-0.1:
if wall_min_z-0.2 <= self.view_matrix.eye.z <= wall_max_z+0.1:
self.collisionLeftWall = True
return True
else:
self.collisionLeftWall = False
if wall_min_z-0.2 <= self.view_matrix.eye.z <= wall_min_z-0.1:
if wall_min_x-0.1 <= self.view_matrix.eye.x <= wall_max_x+0.1:
self.collisionTopWall = True
return True
else:
self.collisionTopWall = False
if wall_max_z+0.2 >= self.view_matrix.eye.z >= wall_max_z+0.1:
if wall_min_x-0.1 <= self.view_matrix.eye.x <= wall_max_x+0.1:
self.collisionBottomWall = True
return True
else:
self.collisionBottomWall = False
if self.lvl == 2:
for item in self.wall_list:
wall_min_x = item[0] - item[3] / 2
wall_max_x = item[0] + item[3] / 2
wall_min_z = item[2] - item[5] / 2
wall_max_z = item[2] + item[5] / 2
if wall_max_x + 0.2 >= self.view_matrix.eye.x >= wall_max_x + 0.1:
if wall_min_z - 0.1 <= self.view_matrix.eye.z <= wall_max_z + 0.1:
self.collisionRightWall = True
return True
else:
self.collisionRightWall = False
if wall_min_x - 0.2 <= self.view_matrix.eye.x <= wall_min_x - 0.1:
if wall_min_z - 0.2 <= self.view_matrix.eye.z <= wall_max_z + 0.1:
self.collisionLeftWall = True
return True
else:
self.collisionLeftWall = False
if wall_min_z - 0.2 <= self.view_matrix.eye.z <= wall_min_z - 0.1:
if wall_min_x - 0.1 <= self.view_matrix.eye.x <= wall_max_x + 0.1:
self.collisionTopWall = True
return True
else:
self.collisionTopWall = False
if wall_max_z + 0.2 >= self.view_matrix.eye.z >= wall_max_z + 0.1:
if wall_min_x - 0.1 <= self.view_matrix.eye.x <= wall_max_x + 0.1:
self.collisionBottomWall = True
return True
else:
self.collisionBottomWall = False
def load_texture(self, image):
""" Loads a texture into the buffer """
texture_surface = pygame.image.load(image)
texture_data = pygame.image.tostring(texture_surface, "RGBA", 1)
width = texture_surface.get_width()
height = texture_surface.get_height()
texid = glGenTextures(1)
glBindTexture(GL_TEXTURE_2D, texid)
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height,
0, GL_RGBA, GL_UNSIGNED_BYTE, texture_data)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)
return texid
def update(self):
delta_time = self.clock.tick() / 1000.0
if self.A_key_down:
self.view_matrix.yaw(-120*delta_time)
self.flashlight_angle += -((2*pi)/3) * delta_time
if self.D_key_down:
self.view_matrix.yaw(120 * delta_time)
self.flashlight_angle += ((2*pi)/3) * delta_time
if self.T_key_down:
self.fov -= 0.25 * delta_time
if self.G_key_down:
self.fov += 0.25 * delta_time
if self.UP_key_down and not self.collisionLeftWall and not self.collisionRightWall and not self.collisionTopWall and not self.collisionBottomWall and not self.ENTER_key_down and not self.won:
self.view_matrix.slide(0, 0, -1.5 * delta_time)
if self.falling:
pygame.mixer.Sound.play(self.crash_sound)
self.view_matrix.eye.y -= 3 * delta_time
"""
Check for direction of player and make him slide accordingly, we also check what part of the wall
the player is hitting. If the player is looking away from the wall that he is colliding with he can walk freely
this fixes the bug that the player can get stuck to the wall. The collisions are very smooth in our program.
"""
if self.UP_key_down:
"""Right side of wall"""
if self.collisionRightWall and self.view_matrix.n.z >= 0 and self.view_matrix.n.x >= 0:
self.view_matrix.slide(1 * delta_time, 0, 0)
if self.collisionRightWall and self.view_matrix.n.z >= 0 and self.view_matrix.n.x <= 0:
self.view_matrix.slide(0, 0, -1 * delta_time)
if self.collisionRightWall and self.view_matrix.n.z <= 0 and self.view_matrix.n.x >= 0:
self.view_matrix.slide(-1 * delta_time, 0, 0)
if self.collisionRightWall and self.view_matrix.n.z <= 0 and self.view_matrix.n.x <= 0:
self.view_matrix.slide(0, 0, -1 * delta_time)
"""Left side of wall"""
if self.collisionLeftWall and self.view_matrix.n.z <= 0 and self.view_matrix.n.x <= 0:
self.view_matrix.slide(1 * delta_time, 0, 0)
if self.collisionLeftWall and self.view_matrix.n.z <= 0 and self.view_matrix.n.x >= 0:
self.view_matrix.slide(0, 0, -1 * delta_time)
if self.collisionLeftWall and self.view_matrix.n.z >= 0 and self.view_matrix.n.x <= 0:
self.view_matrix.slide(-1 * delta_time, 0, 0)
if self.collisionLeftWall and self.view_matrix.n.z >= 0 and self.view_matrix.n.x >= 0:
self.view_matrix.slide(0, 0, -1 * delta_time)
"""Bottom side of wall"""
if self.collisionBottomWall and self.view_matrix.n.z >= 0 and self.view_matrix.n.x >= 0:
self.view_matrix.slide(-1 * delta_time, 0, 0)
if self.collisionBottomWall and self.view_matrix.n.z <= 0 and self.view_matrix.n.x >= 0:
self.view_matrix.slide(0, 0, -1 * delta_time)
if self.collisionBottomWall and self.view_matrix.n.z >= 0 and self.view_matrix.n.x <= 0:
self.view_matrix.slide(1 * delta_time, 0, 0)
if self.collisionBottomWall and self.view_matrix.n.z <= 0 and self.view_matrix.n.x <= 0:
self.view_matrix.slide(0, 0, -1 * delta_time)
"""Top side of wall"""
if self.collisionTopWall and self.view_matrix.n.z <= 0 and self.view_matrix.n.x >= 0:
self.view_matrix.slide(1 * delta_time, 0, 0)
if self.collisionTopWall and self.view_matrix.n.z >= 0 and self.view_matrix.n.x <= 0:
self.view_matrix.slide(0, 0, -1 * delta_time)
if self.collisionTopWall and self.view_matrix.n.z <= 0 and self.view_matrix.n.x <= 0:
self.view_matrix.slide(-1 * delta_time, 0, 0)
if self.collisionTopWall and self.view_matrix.n.z >= 0 and self.view_matrix.n.x >= 0:
self.view_matrix.slide(0, 0, -1 * delta_time)
"""If player is falling, the game ends"""
if self.view_matrix.eye.y <= -4:
pygame.quit()
quit()
print("You died, don't walk away from the area")
"""Basically just a lot of checks for the monster and the player and accounting for death and win"""
if self.looking_at_monster_count >= 350:
self.JUMPSCARE = True
pygame.mixer.Sound.play(self.jumpscare)
if self.looking_at_monster_count >= 400:
self.ENTER_key_down = True
if self.lvl == 1:
self.view_matrix.look(Point(7, 1, 5), Point(7, 1.0, 0.0), Vector(0, 1, 0))
if self.lvl == 2:
self.view_matrix.look(Point(13.5, 1, 5.5), Point(13.5, 1.0, 0), Vector(0, 1, 0))
self.looking_at_monster_count = 1
self.JUMPSCARE = False
self.flashlight_angle = 0
if self.looking_at_monster_count_other >= 350:
self.JUMPSCARE_other = True
pygame.mixer.Sound.play(self.jumpscare)
if self.looking_at_monster_count_other >= 400:
self.ENTER_key_down = True
if self.lvl == 1:
self.view_matrix.look(Point(7, 1, 5), Point(7, 1.0, 0.0), Vector(0, 1, 0))
if self.lvl == 2:
self.view_matrix.look(Point(13.5, 1, 5.5), Point(13.5, 1.0, 0), Vector(0, 1, 0))
self.looking_at_monster_count_other = 1
self.JUMPSCARE_other = False
self.flashlight_angle = 0
if self.p_key_down and self.won:
self.ENTER_key_down = True
self.flashlight_angle = 0
self.lvl = 1
self.view_matrix.look(Point(7, 1, 5), Point(7, 1.0, 0.0), Vector(0, 1, 0))
self.looking_at_monster_count_other = 1
self.looking_at_monster_count = 1
self.won = False
self.p_key_down = False
"""Our functions must be called here in the update"""
self.check_if_won()
self.check_if_died()
self.collison_check()
self.check_distance_from_monster()
self.get_walls_closest()
def display(self):
glEnable(GL_DEPTH_TEST)
glEnable(GL_FRAMEBUFFER_SRGB)
glShadeModel(GL_SMOOTH)
glLoadIdentity()
glMatrixMode(GL_PROJECTION)
glClearColor(0.0, 0.0, 0.0, 1.0)
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)
glViewport(0, 0, 800, 600)
self.projection_matrix.set_perspective(self.fov, 800 / 600, 0.01, 100)
self.shader.set_projection_matrix(self.projection_matrix.get_matrix())
self.shader.set_view_matrix(self.view_matrix.get_matrix())
self.model_matrix.load_identity()
self.cube.set_verticies(self.shader)
""""LIGHTS"""
self.shader.set_normal_light_direction(Point(-0.3, -1.0, -0.4))
self.shader.set_normal_light_color(Color(0.01, 0.01, 0.01))
if self.SPACE_key_down:
"""
We need the spotlight's position vector
(to calculate the fragment-to-light's direction vector),
the spotlight's direction vector, and the cutoff angle are the parameters we'll need for the fragment shader.
To implement attenuation we'll be needing 3 extra values in the fragment shader:
namely the constant, linear and quadratic terms of the equation.
"""
self.shader.set_active_flashlight(1.0)
self.shader.set_flashlight_direction(self.view_matrix.n)
self.shader.set_flashlight_color(Color(0.9725, 0.7647, 0.4667))
self.shader.set_flashlight_position(Point(self.view_matrix.eye.x, self.view_matrix.eye.y - 0.1, self.view_matrix.eye.z))
"""cut off: calculate the cosine value based on an angle and pass the cosine result to the fragment shader."""
self.shader.set_flashlight_cutoff(cos((40 + 6.5) * pi/180))
self.shader.set_flashlight_outer_cutoff(cos((40 + 11.5) * pi/180))
self.shader.set_flashlight_constant(1.0)
self.shader.set_flashlight_linear(0.14)
self.shader.set_flashlight_quad(0.07)
if not self.SPACE_key_down:
self.shader.set_active_flashlight(0.0)
"""
This is almost exactly like the flashlight except we need to point the vector down on the player,
so he get's a nice lantern like lighting around him
"""
self.shader.set_light_direction(self.view_matrix.v)
self.shader.set_light_color(Color(0.9725, 0.7647, 0.4667))
self.shader.set_light_position(
Point(self.view_matrix.eye.x, self.view_matrix.eye.y+0.7, self.view_matrix.eye.z))
self.shader.set_light_cutoff(cos((40 + 6.5) * pi / 180))
self.shader.set_light_outer_cutoff(cos((40 + 11.5) * pi / 180))
self.shader.set_light_constant(1.0)
self.shader.set_light_linear(0.14)
self.shader.set_light_quad(0.07)
"""Drawing and some more drawing....."""
glEnable(GL_TEXTURE_2D)
glActiveTexture(GL_TEXTURE0)
glBindTexture(GL_TEXTURE_2D, self.tex_id_floorandceiling)
glActiveTexture(GL_TEXTURE1)
glBindTexture(GL_TEXTURE_2D, self.tex_id_floorandceiling_specular)
if self.lvl == 1:
for index in self.ceilingandfloorlvl1:
self.model_matrix.push_matrix()
self.model_matrix.add_translation(index[0], index[1], index[2])
self.model_matrix.add_scale(index[3], index[4], index[5])
self.shader.set_model_matrix(self.model_matrix.matrix)
self.cube.draw()
self.model_matrix.pop_matrix()
if self.lvl == 2:
for index in self.floor_lvl2:
self.model_matrix.push_matrix()
self.model_matrix.add_translation(index[0], index[1], index[2])
self.model_matrix.add_scale(index[3], index[4], index[5])
self.shader.set_model_matrix(self.model_matrix.matrix)
self.cube.draw()
self.model_matrix.pop_matrix()
glDisable(GL_TEXTURE_2D)
if self.ENTER_key_down:
glEnable(GL_TEXTURE_2D)
glActiveTexture(GL_TEXTURE0)
glBindTexture(GL_TEXTURE_2D, self.tex_id_jumpscare_diffuse)
glActiveTexture(GL_TEXTURE1)
glBindTexture(GL_TEXTURE_2D, self.tex_id_jumpscare_specular)
self.model_matrix.push_matrix()
self.model_matrix.add_translation(self.view_matrix.eye.x, self.view_matrix.eye.y-0.07, self.view_matrix.eye.z-0.5)
self.model_matrix.add_scale(1.0, 0.5, 0.5)
self.shader.set_model_matrix(self.model_matrix.matrix)
self.cube.draw()
self.model_matrix.pop_matrix()
glDisable(GL_TEXTURE_2D)
if self.won:
glEnable(GL_TEXTURE_2D)
glActiveTexture(GL_TEXTURE0)
glBindTexture(GL_TEXTURE_2D, self.tex_id_win_screen_diffuse)
glActiveTexture(GL_TEXTURE1)
glBindTexture(GL_TEXTURE_2D, self.tex_id_win_screen_specular)
self.model_matrix.push_matrix()
self.model_matrix.add_translation(self.view_matrix.eye.x, self.view_matrix.eye.y-0.07, self.view_matrix.eye.z-0.5)
self.model_matrix.add_scale(1.0, 0.5, 0.5)
self.shader.set_model_matrix(self.model_matrix.matrix)
self.cube.draw()
self.model_matrix.pop_matrix()
glDisable(GL_TEXTURE_2D)
glEnable(GL_TEXTURE_2D)
glActiveTexture(GL_TEXTURE0)
glBindTexture(GL_TEXTURE_2D, self.tex_id_wall_diffuse)
glActiveTexture(GL_TEXTURE1)
glBindTexture(GL_TEXTURE_2D, self.tex_id_wall_specular)
self.shader.set_material_diffuse(Color(0.7, 0.7, 0.7))
self.shader.set_material_specular(Color(0.5, 0.5, 0.5))
self.shader.set_material_shiny(10)
self.shader.set_material_emit(0.0)
if self.lvl == 2:
for index in self.wall_list:
self.model_matrix.push_matrix()
self.model_matrix.add_translation(index[0], index[1], index[2])
self.model_matrix.add_scale(index[3], index[4], index[5])
self.shader.set_model_matrix(self.model_matrix.matrix)
self.cube.draw()
self.model_matrix.pop_matrix()
if self.lvl == 1:
for index in self.wall_list2:
self.model_matrix.push_matrix()
self.model_matrix.add_translation(index[0], index[1], index[2])
self.model_matrix.add_scale(index[3], index[4], index[5])
self.shader.set_model_matrix(self.model_matrix.matrix)
self.cube.draw()
self.model_matrix.pop_matrix()
glDisable(GL_TEXTURE_2D)
glEnable(GL_TEXTURE_2D)
glActiveTexture(GL_TEXTURE0)
glBindTexture(GL_TEXTURE_2D, self.tex_id_flashlight_diffuse)
glActiveTexture(GL_TEXTURE1)
glBindTexture(GL_TEXTURE_2D, self.tex_id_flashlight_specular)
self.shader.set_material_diffuse(Color(0.7, 0.7, 0.7))
self.shader.set_material_specular(Color(0.5, 0.5, 0.5))
self.shader.set_material_shiny(10)
self.shader.set_material_emit(0.0)
self.model_matrix.push_matrix()
self.model_matrix.add_translation(self.view_matrix.eye.x, self.view_matrix.eye.y-0.2, self.view_matrix.eye.z)
self.model_matrix.add_rotate_x(pi/2)
self.model_matrix.add_rotate_z(self.flashlight_angle)
self.model_matrix.add_scale(0.1, 0.1, 0.7)
self.shader.set_model_matrix(self.model_matrix.matrix)
self.obj_model_flashlight.draw(self.shader)
self.model_matrix.pop_matrix()
glDisable(GL_TEXTURE_2D)
glEnable(GL_TEXTURE_2D)
glActiveTexture(GL_TEXTURE0)
glBindTexture(GL_TEXTURE_2D, self.tex_id_vurdulak_diffuse)
glActiveTexture(GL_TEXTURE1)
glBindTexture(GL_TEXTURE_2D, self.tex_id_vurdulak_specular)
if self.lvl == 1:
self.model_matrix.load_identity()
self.cube.set_verticies(self.shader)
for item in self.monster_pos_locations:
self.model_matrix.push_matrix()
if not self.JUMPSCARE and not self.JUMPSCARE_other:
self.model_matrix.add_translation(item[0], item[1], item[2])
if self.JUMPSCARE:
self.model_matrix.add_translation(self.view_matrix.eye.x, self.view_matrix.eye.y-0.6, self.view_matrix.eye.z+0.5)
if self.JUMPSCARE_other:
self.model_matrix.add_translation(self.view_matrix.eye.x-0.35, self.view_matrix.eye.y-0.6, self.view_matrix.eye.z)
self.model_matrix.add_rotate_y(item[3])
self.model_matrix.add_scale(0.4, 0.4, 0.4)
self.shader.set_model_matrix(self.model_matrix.matrix)
self.obj_model.draw(self.shader)
self.model_matrix.pop_matrix()
if self.lvl == 2:
self.model_matrix.load_identity()
self.cube.set_verticies(self.shader)
for item in self.monster_pos_locations_lvl_2:
self.model_matrix.push_matrix()
if not self.JUMPSCARE and not self.JUMPSCARE_other:
self.model_matrix.add_translation(item[0], item[1], item[2])
if self.JUMPSCARE:
self.model_matrix.add_translation(self.view_matrix.eye.x, self.view_matrix.eye.y-0.6, self.view_matrix.eye.z+0.5)
if self.JUMPSCARE_other:
self.model_matrix.add_translation(self.view_matrix.eye.x-0.35, self.view_matrix.eye.y-0.6, self.view_matrix.eye.z)
self.model_matrix.add_rotate_y(item[3])
self.model_matrix.add_scale(0.7, 0.7, 0.7)
self.shader.set_model_matrix(self.model_matrix.matrix)
self.obj_model.draw(self.shader)
self.model_matrix.pop_matrix()
glDisable(GL_TEXTURE_2D)
glDisable(GL_BLEND)
pygame.display.flip()
def program_loop(self):
exiting = False
while not exiting:
for event in pygame.event.get():
if event.type == pygame.QUIT:
print("Quitting!")
exiting = True
elif event.type == pygame.KEYDOWN:
if event.key == K_ESCAPE:
print("Escaping!")
exiting = True
if event.key == K_w:
self.UP_key_down = True
if event.key == K_DOWN:
self.DOWN_key_down = True
if event.key == K_a:
self.A_key_down = True
if event.key == K_d:
self.D_key_down = True
if event.key == K_t:
self.T_key_down = True
if event.key == K_g:
self.G_key_down = True
if event.key == K_SPACE:
pygame.mixer.Sound.play(self.flashlight_click)
self.SPACE_key_down = True
if event.key == K_RETURN:
self.ENTER_key_down = False
if event.key == K_p and self.won:
self.p_key_down = True
if event.key == K_q:
pygame.quit()
quit()
elif event.type == pygame.KEYUP:
if event.key == K_w:
self.UP_key_down = False
if event.key == K_DOWN:
self.DOWN_key_down = False
if event.key == K_a:
self.A_key_down = False
if event.key == K_d:
self.D_key_down = False
if event.key == K_t:
self.T_key_down = False
if event.key == K_g:
self.G_key_down = False
if event.key == K_SPACE:
self.SPACE_key_down = False
self.update()
self.display()
#OUT OF GAME LOOP
pygame.quit()
def start(self):
self.program_loop()
if __name__ == "__main__":
GraphicsProgram3D().start() | ad2beb0dcff2f3575b3e774adbb72dabcfdc3afc | [
"Markdown",
"Python"
] | 3 | Markdown | tomasj20/3D_game | 1b0ec531b5634079b1e5fc59a07a110d302d5edf | 1c09524c672b6e20743bb590394f72a40cd9c9c3 |
refs/heads/master | <file_sep>import { Injectable } from '@angular/core';
import { Users } from '../model/users';
@Injectable({
providedIn: 'root'
})
export class UsersService {
private users: Users[] = new Array();
constructor() {
this.users.push({
name: '<NAME>',
state: 'Tepic',
like: 0,
love: 0,
hobby: ['Tiro', 'Arquería', 'Juegos', 'Ajedrez', 'DINERO']
});
this.users.push({
name: '<NAME>',
state: 'Tepic',
like: 40,
love: 13,
hobby: ['Videojuegos', 'Futbol']
});
}
getUsers(): Users[] {
return this.users;
}
changeInfo(position: number): void{
this.users[position].name = this.users[position].name;
}
}
<file_sep>export class Users {
name: string;
state: string;
like: number;
love: number;
hobby: string[];
}
<file_sep>import { Component } from '@angular/core';
import { Users } from '../model/users';
import { UsersService } from '../services/users.service';
@Component({
selector: 'app-tab1',
templateUrl: 'tab1.page.html',
styleUrls: ['tab1.page.scss']
})
export class Tab1Page {
users: Users[] = new Array();
constructor(private userService: UsersService) {
this.users = this.userService.getUsers();
}
increaseLike(type: number, position: number): void{
if ( type === 0 )
{
this.users[position].like ++;
}
}
increaseLove(type: number, position: number): void{
if ( type === 0 )
{
this.users[position].love ++;
}
}
}
| cadfe80aa3c64c214b54173c012e8a40f5ab913c | [
"TypeScript"
] | 3 | TypeScript | Edwin-Antonio/DAH20203-U3-slides-and-cards | abbaa26ceb239b83680d71ebe6348f653d0afdb8 | 12ab1ca8192f97fb15a4dcf7a1f14ed9db1be068 |
refs/heads/master | <file_sep>/**
* Created by Matthew on 2/7/2016.
*/
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class EmailClient {
public static void main(String argv[]) throws Exception
{
String userInput;
boolean cont = true;
Scanner scanner = new Scanner(System.in);
Socket clientSocket = new Socket("", 6789);
boolean authenticated = false;
while(cont) {
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
System.out.println("Press 1 to log in.");
System.out.println("Press 2 to create an account.");
userInput = scanner.nextLine();
if (userInput.equals("1")) {
System.out.println("Enter your username.");
String username = scanner.nextLine();
System.out.println("Enter your password.");
String pass = scanner.nextLine();
outToServer.writeBytes("login\n");
outToServer.writeBytes(username + "\n");
outToServer.writeBytes(pass + "\n");
if (inFromServer.readLine().equals("success")) {
System.out.println("Login successful!");
authenticated = true;
}
}
if (userInput.equals("2")) {
System.out.println("Enter your desired username.");
String username = scanner.nextLine();
System.out.println("Enter your desired password.");
String pass = scanner.nextLine();
outToServer.writeBytes("createAccount\n");
outToServer.writeBytes(username + "\n");
outToServer.writeBytes(pass + "\n");
System.out.println("Account creation successful!");
authenticated = true;
}
System.out.println();
while (authenticated) {
//after you log in successfully
System.out.println("Press 1 to send a message.");
System.out.println("Press 2 to list subject from all messages.");
System.out.println("Press 3 to quit.");
userInput = scanner.nextLine();
System.out.println();
if (userInput.equals("1")) {
outToServer.writeBytes("sendMessage\n");
BufferedReader message = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the username of the recipient of the message.");
outToServer.writeBytes(message.readLine() + '\n');
System.out.println();
System.out.println("Enter the subject of the message.");
outToServer.writeBytes(message.readLine() + '\n');
System.out.println();
System.out.println("Enter the message to send.");
outToServer.writeBytes(message.readLine() + '\n');
System.out.println("Message Sent!");
} else if (userInput.equals("2")) {
outToServer.writeBytes("recieveSubjects\n");
System.out.println();
int numberOfSubjects = Integer.parseInt(inFromServer.readLine());
for (int i = 0; i < numberOfSubjects; i = i +2) {
System.out.print("Subject: ");
System.out.print(inFromServer.readLine());
System.out.print(" Sender: ");
System.out.println(inFromServer.readLine());
}
System.out.println();
System.out.println("Enter the subject whose email you would like to recieve");
System.out.println("Or press 'q' to go back to menu.");
String option = scanner.nextLine();
System.out.println();
if (!option.equals("q")) {
outToServer.writeBytes("recieveMessage\n");
outToServer.writeBytes(option + "\n");
String messageFromServer = inFromServer.readLine();
System.out.println("Message: " + messageFromServer);
}
} else if (userInput.equals("3")) {
authenticated = false;
cont = false;
}
System.out.println();
System.out.println();
}
}
scanner.close();
clientSocket.close();
}
}
<file_sep># emailserver
Email server and client with pop protocol
| 00cd97fd16189e6865f27f41f2f51d62366cb2c7 | [
"Markdown",
"Java"
] | 2 | Java | mtschiggfrie/emailserver | 7215ae34f3a611165f7153a4d0f1696e42080211 | 2d8c6dbf7391ac0856fdeb2037acadc1e238efea |
refs/heads/master | <file_sep>import React, { Component } from 'react';
export default class SignUpBasic extends Component {
render() {
return (
<div className="container">
<h1 className="titleOne">Create your account</h1>
<h3 className="titleTwo"> Tell us your email and set a password</h3>
<input
className="input-register"
type="email"
value={this.props.email}
placeholder='Email'
onChange={this.onChangeEmail}
/>
<input
className="input-register"
type="password"
value={this.props.password}
placeholder='<PASSWORD>'
onChange={this.props.onChangePassword}
/>
<button className="next-button" onClick={this.props.nextStep}>Next ></button>
<p className="message"> Do You Have an Account? <button onClick={this.props.goto_login} className="goto-button">Login</button></p>
</div>
)
}
}
<file_sep>import React, { Component } from 'react';
import './styles.css';
import SignIn from './containers/SignIn/SignIn';
import SignUpBasic from './containers/SignUp/SignUpBasic';
import SignUpComplete from './containers/SignUp/SignUpComplete';
class AuthContainer extends Component {
constructor(props) {
super(props);
this.state = {
page: 1
}
}
nextStep() {
this.setState({
page : this.state.page + 1
});
}
prevStep() {
this.setState({
page : this.state.page - 1
});
}
goto_login() {
this.setState({
page : 1
});
}
showPage() {
switch (this.state.page) {
case 1:
return <SignIn nextStep={this.nextStep.bind(this)} />
case 2:
return <SignUpBasic nextStep={this.nextStep.bind(this)}
goto_login={this.goto_login.bind(this)} />
case 3:
return <SignUpComplete
goto_login={this.goto_login.bind(this)}
prevStep={this.prevStep.bind(this)}/>
}
}
render() {
return (
this.showPage()
);
}
onChangePassword(text) {
this.setState({password: text});
}
}
export default AuthContainer;
<file_sep>import React, { Component } from 'react';
export default class SignIn extends Component {
render() {
return (
<div className="container">
<h1 className="titleOne">Sign In with Email</h1>
<h3 className="titleTwo"> Enter your email and a password</h3>
<input
className="input-register"
type="email"
placeholder='Email'
value={this.props.currentEmail}
/>
<input
className="input-register"
type="password"
placeholder='<PASSWORD>'
value={this.props.currentPassword}
/>
<input
className="sign-button"
type="submit"
value="Sign In"
onChange={this.submit}
/>
<p className="message"> Dont Have an Account?
<button onClick={this.props.nextStep} className="goto-button">Register</button>
</p>
</div>
)
}
}
<file_sep>// export { default as SignIn } from './SignIn/SignIn';
| a2cbe300cc18c7253060f205ed99cd73b28cbe3e | [
"JavaScript"
] | 4 | JavaScript | ekaprok/Registration | 40e3ff55eda9f13ee54cd6211955fa00433a1ca5 | 7660566d5424b5c356242b32e925fa45366e6fff |
refs/heads/master | <repo_name>handlename/tapper<file_sep>/tapper-runner
#!/bin/sh
exec tapper --options "$@"
<file_sep>/sample/sample_test.go
package main
import (
"testing"
)
func TestOk(t *testing.T) {
t.Log("good")
}
func TestNg(t *testing.T) {
t.Error("failed")
}
<file_sep>/README.md
tapper
====
## Description
tapper is test tool for Golang.
It convert `go test` output to TAP.
## Usage
```bash
$ tapper
ok 1 - TestOk (0.00 seconds)
not ok 2 - TestNg (0.00 seconds)
1..2
```
To use with `prove`, use `tapper-runner`:
```bash
$ prove -v --exec="bash" tapper-runner
tapper-runner ..
ok 1 - TestOk (0.00 seconds)
not ok 2 - TestNg (0.00 seconds)
1..2
Failed 1/2 subtests
Test Summary Report
-------------------
tapper-runner (Wstat: 0 Tests: 2 Failed: 1)
Failed test: 2
Files=1, Tests=2, 1 wallclock secs ( 0.03 usr 0.00 sys + 0.21 cusr 0.07 csys = 0.31 CPU)
Result: FAIL
```
You can set options for `go test` command:
```bash
$ tapper --options="-run Ok"
ok 1 - TestOk (0.00 seconds)
1..1
```
`tapper-runner` too:
```bash
$ prove -v --exec="bash" tapper-runner :: "-run Ok"
tapper-runner ..
ok 1 - TestOk (0.00 seconds)
1..1
ok
All tests successful.
Files=1, Tests=1, 0 wallclock secs ( 0.03 usr 0.01 sys + 0.25 cusr 0.13 csys = 0.42 CPU)
Result: PASS
```
## Install
To install, use `go get`:
```bash
$ go get -d github.com/handlename/tapper
```
After `get`, link `tapper-runner` to your bin directory.
```bash
$ ln -s $GOPATH/src/github.com/handlename/tapper/tapper-runner $GOPATH/bin/tapper-runner
```
## Contribution
1. Fork ([https://github.com/handlename/tapper/fork](https://github.com/handlename/tapper/fork))
1. Create a feature branch
1. Commit your changes
1. Rebase your local changes against the master branch
1. Run test suite with the `go test ./...` command and confirm that it passes
1. Run `gofmt -s`
1. Create new Pull Request
## Author
[handlename](https://github.com/handlename)
<file_sep>/tapper.go
package main
import (
"bufio"
"fmt"
"log"
"os"
"os/exec"
"regexp"
"strings"
"github.com/codegangsta/cli"
)
func main() {
app := cli.NewApp()
app.Name = "tapper"
app.Version = Version
app.Usage = ""
app.Author = "handlename"
app.Email = "nagata<at>handlena.me"
app.Action = doMain
app.Flags = []cli.Flag{
cli.StringFlag{
Name: "options",
Value: "",
Usage: "options for `go test` command",
},
}
app.Run(os.Args)
}
func doMain(c *cli.Context) {
var err error
options := strings.Split(fmt.Sprintf("test -v %s", c.String("options")), " ")
cmd := exec.Command("go", options...)
stdout, err := cmd.StdoutPipe()
if err != nil {
log.Fatalf("error on create pipe: %s", err)
}
err = cmd.Start()
if err != nil {
log.Fatalf("error on run command: %s", err)
}
scanner := bufio.NewScanner(stdout)
pattern, _ := regexp.Compile("^--- (PASS|FAIL): (.+)$")
count := 0
for scanner.Scan() {
matches := pattern.FindStringSubmatch(scanner.Text())
if 0 == len(matches) {
continue
}
count++
var result string
if matches[1] == "PASS" {
result = "ok"
} else {
result = "not ok"
}
fmt.Printf("%s %d - %s\n", result, count, matches[2])
}
fmt.Printf("%d..%d\n", 1, count)
}
| 140fc09973040f82ad0f095cb7435cb7f70ad4d4 | [
"Markdown",
"Go",
"Shell"
] | 4 | Shell | handlename/tapper | 8583223ef38efeeae7d9f2026352188981be9e6b | 7cb63066773971276e262e994d5bb62a2b32f2b7 |
refs/heads/master | <file_sep>############################################################
# Plot csv log files
#
import sys
import matplotlib.pyplot as plt
import matplotlib.dates as dates
import datetime
logamount = len(sys.argv) - 1
class log:
def __init__(self, file):
self.name = ''
self.log = self.readcsv(file)
def readcsv(self, file):
# Leggo il file, rimuovo il fine linea, le "" e sostituisco , con .
with open(file, mode='r') as csvfile:
mylog = [s.strip().replace('\"', '').replace(',', '.').split(';') for s in csvfile]
#Leggo il nome del log
self.name = mylog[2][0]
# Rimuovo la prima e l'ultima riga
mylog = mylog[1:len(mylog) - 2]
# Faccio la trasposizione della lista
mylog = [list(x) for x in zip(*mylog)]
# Tengo solo data/ora e valore
mylog = mylog[1:2] + mylog[2:3]
# Trasformo il valore da stringa a float
mylog[1] = [float(v) for v in mylog[1]]
# Trasformo data/ora in formato datetime
mylog[0] = [dates.date2num(datetime.datetime.strptime(x, '%d.%m.%Y %H:%M:%S')) for x in mylog[0]]
return mylog
def adjust_tbase(logs):
# Inizializzo min e max in base al primo log
minimum = min(logs[0].log[0])
maximum = max(logs[0].log[0])
# Trovo i tempi minimi e massimi presenti in tutti i log
for log in logs:
if (min(log.log[0]) > minimum): minimum = min(log.log[0])
if (max(log.log[0]) < maximum): maximum = max(log.log[0])
newlogs = [[[], []] for i in range(len(logs))]
# Limito la finestra di tempo ai minimi e massimi comuni a tutti i log
# Ricreo la matrice da zero aggiungendo solo i dati da considerare
i = 0
for log in logs:
n = 0
for col in log.log:
x = 0
for v in col:
if n == 0 & (maximum <= v) & (v >= minimum):
newlogs[i][0].append(log.log[0][x])
newlogs[i][1].append(log.log[1][x])
x += 1
n += 1
i += 1
return newlogs
# Lista dei log
logs = []
# Lista dei file selezionati
flist = sys.argv[1:len(sys.argv)]
# Creo un log per ogni file
for f in flist:
logs.append(log(f))
# Matrice dei dati filtrata
pltlogs = adjust_tbase(logs)
# Aggiungo tutti i log al plot con i relativi nomi
i = 0
for log in pltlogs:
plt.plot_date(log[0], log[1], '-', label=logs[i].name)
i += 1
plt.gcf().autofmt_xdate()
plt.legend()
plt.show()
| c85c3fcb931d0e672b8150963ddfc05d495c072e | [
"Python"
] | 1 | Python | ghetto-ch/LOGViewer | 863c0b44dda0520b8804087066a6ab22d47fbb56 | 38cc24219e067fbb47daf9ee9b469c3d8c38d50f |
refs/heads/master | <file_sep>/**
*大数相加、减、乘、除、余
*/
#include <iostream>
#include <string>
using namespace std;
inline int compare(string str1, string str2) //相等返回0,大于返回1,小于返回-1
{
if (str1.size()>str2.size()) return 1; //长度长的整数大于长度小的整数
else if (str1.size()<str2.size()) return -1;
else return str1.compare(str2); //若长度相等,则头到尾按位比较
}
string SUB_INT(string str1, string str2);
string ADD_INT(string str1, string str2) //高精度加法
{
int sign = 1; //sign 为符号位
string str;
if (str1[0] == '-') {
if (str2[0] == '-') {
sign = -1;
str = ADD_INT(str1.erase(0, 1), str2.erase(0, 1));
} else {
str = SUB_INT(str2, str1.erase(0, 1));
}
} else {
if (str2[0] == '-') {
str = SUB_INT(str1, str2.erase(0, 1));
} else { //把两个整数对齐,短整数前面加0补齐
string::size_type L1, L2;
int i;
L1 = str1.size();
L2 = str2.size();
if (L1<L2) {
for (i = 1; i< = L2-L1; i++) str1 = "0"+str1;
} else {
for (i = 1; i< = L1-L2; i++) str2 = "0"+str2;
}
int int1 = 0, int2 = 0; //int2 记录进位
for (i = str1.size()-1; i> = 0; i--) {
int1 = (int(str1[i])-'0'+int(str2[i])-'0'+int2)%10;
int2 = (int(str1[i])-'0'+int(str2[i])-'0'+int2)/10;
str = char(int1+'0')+str;
}
if (int2! = 0) str = char(int2+'0')+str;
}
}
//运算后处理符号位
if ((sign == -1)&&(str[0]! = '0')) str = "-"+str;
return str;
}
string SUB_INT(string str1, string str2) //高精度减法
{
int sign = 1; //sign 为符号位
string str;
int i, j;
if (str2[0] == '-') {
str = ADD_INT(str1, str2.erase(0, 1));
} else {
int res = compare(str1, str2);
if (res == 0) return "0";
if (res<0) {
sign = -1;
string temp = str1;
str1 = str2;
str2 = temp;
}
string::size_type tempint;
tempint = str1.size()-str2.size();
for (i = str2.size()-1; i> = 0; i--) {
if (str1[i+tempint]<str2[i]) {
j = 1;
while (1) {//zhao4zhong1添加
if (str1[i+tempint-j] == '0') {
str1[i+tempint-j] = '9';
j++;
} else {
str1[i+tempint-j] = char(int(str1[i+tempint-j])-1);
break;
}
}
str = char(str1[i+tempint]-str2[i]+':')+str;
} else {
str = char(str1[i+tempint]-str2[i]+'0')+str;
}
}
for (i = tempint-1; i> = 0; i--) str = str1[i]+str;
}
//去除结果中多余的前导0
str.erase(0, str.find_first_not_of('0'));
if (str.empty()) str = "0";
if ((sign == -1) && (str[0]! = '0')) str = "-"+str;
return str;
}
string MUL_INT(string str1, string str2) //高精度乘法
{
int sign = 1; //sign 为符号位
string str;
if (str1[0] == '-') {
sign* = -1;
str1 = str1.erase(0, 1);
}
if (str2[0] == '-') {
sign* = -1;
str2 = str2.erase(0, 1);
}
int i, j;
string::size_type L1, L2;
L1 = str1.size();
L2 = str2.size();
for (i = L2-1; i> = 0; i--) { //模拟手工乘法竖式
string tempstr;
int int1 = 0, int2 = 0, int3 = int(str2[i])-'0';
if (int3! = 0) {
for (j = 1; j< = (int)(L2-1-i); j++) tempstr = "0"+tempstr;
for (j = L1-1; j> = 0; j--) {
int1 = (int3*(int(str1[j])-'0')+int2)%10;
int2 = (int3*(int(str1[j])-'0')+int2)/10;
tempstr = char(int1+'0')+tempstr;
}
if (int2! = 0) tempstr = char(int2+'0')+tempstr;
}
str = ADD_INT(str, tempstr);
}
//去除结果中的前导0
str.erase(0, str.find_first_not_of('0'));
if (str.empty()) str = "0";
if ((sign == -1) && (str[0]! = '0')) str = "-"+str;
return str;
}
string DIVIDE_INT(string str1, string str2, int flag) //高精度除法。flag == 1时, 返回商; flag == 0时, 返回余数
{
string quotient, residue; //定义商和余数
int sign1 = 1, sign2 = 1;
if (str2 == "0") { //判断除数是否为0
quotient = "ERROR!";
residue = "ERROR!";
if (flag == 1) return quotient;
else return residue ;
}
if (str1 == "0") { //判断被除数是否为0
quotient = "0";
residue = "0";
}
if (str1[0] == '-') {
str1 = str1.erase(0, 1);
sign1 * = -1;
sign2 = -1;
}
if (str2[0] == '-') {
str2 = str2.erase(0, 1);
sign1 * = -1;
}
int res = compare(str1, str2);
if (res<0) {
quotient = "0";
residue = str1;
} else if (res == 0) {
quotient = "1";
residue = "0";
} else {
string::size_type L1, L2;
L1 = str1.size();
L2 = str2.size();
string tempstr;
tempstr.append(str1, 0, L2-1);
for (int i = L2-1; i<L1; i++) { //模拟手工除法竖式
tempstr = tempstr+str1[i];
tempstr.erase(0, tempstr.find_first_not_of('0'));//zhao4zhong1添加
if (tempstr.empty()) tempstr = "0";//zhao4zhong1添加
for (char ch = '9'; ch> = '0'; ch--) { //试商
string str;
str = str+ch;
if (compare(MUL_INT(str2, str), tempstr)< = 0) {
quotient = quotient+ch;
tempstr = SUB_INT(tempstr, MUL_INT(str2, str));
break;
}
}
}
residue = tempstr;
}
//去除结果中的前导0
quotient.erase(0, quotient.find_first_not_of('0'));
if (quotient.empty()) quotient = "0";
if ((sign1 == -1)&&(quotient[0]! = '0')) quotient = "-"+quotient;
if ((sign2 == -1)&&(residue [0]! = '0')) residue = "-"+residue ;
if (flag == 1) return quotient;
else return residue ;
}
string DIV_INT(string str1, string str2) //高精度除法, 返回商
{
return DIVIDE_INT(str1, str2, 1);
}
string MOD_INT(string str1, string str2) //高精度除法, 返回余数
{
return DIVIDE_INT(str1, str2, 0);
}
<file_sep># nginx 多站点配置
*在 centos7 下测试通过*
下面是具体的配置过程:
1、在 /etc/nginx 下创建 vhosts 目录
```
mkdir /etc/nginx/vhosts
```
2、在 /etc/nginx/vhosts/ 里创建一个名字为 fafa.tv.conf 的文件,把以下内容拷进去
```
server {
listen 80;
server_name fafa.tv www.fafa.tv;
access_log /www/access_fafatv.log main;
location / {
root /www/fafa.tv;
index index.php index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
location ~ .php$ {
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /www/fafa.tv/$fastcgi_script_name;
include fastcgi_params;
}
location ~ /.ht {
deny all;
}
}
```
3、在 /etc/nginx/vhosts/ 里创建一个名字为 fafa.la.conf 的文件,把以下内容拷进去
```
server {
listen 80;
server_name fafa.la www.fafa.la;
access_log /www/access_fafala.log main;
location / {
root /www/fafa.la;
index index.php index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
location ~ .php$ {
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /www/fafa.la/$fastcgi_script_name;
include fastcgi_params;
}
location ~ /.ht {
deny all;
}
}
```
4、打开 /etc/nginix.conf 文件,在相应位置加入 include 把以上2个文件包含进来
```
user nginx;
worker_processes 1;
# main server error log
error_log /var/log/nginx/error.log ;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
# main server config
http {
include mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] $request '
'"$status" $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
sendfile on;
#tcp_nopush on;
#keepalive_timeout 0;
keepalive_timeout 65;
gzip on;
server {
listen 80;
server_name _;
access_log /var/log/nginx/access.log main;
server_name_in_redirect off;
location / {
root /usr/share/nginx/html;
index index.html;
}
}
# 包含所有的虚拟主机的配置文件
include /etc/nginx/vhosts/*;
}
```<file_sep># Dll项目创建与调用
## 创建
1.新建win32 dll项目,命名为"MyDLL",在分别添加三个文件
testdll.h
```
#ifndef TestDll_H_
#define TestDll_H_
#ifdef MYLIBDLL
#define MYLIBDLL extern "C" _declspec(dllimport)
#else
#define MYLIBDLL extern "C" _declspec(dllexport)
#endif
MYLIBDLL int Add(int plus1, int plus2);
//You can also write like this:
//extern "C" {
//_declspec(dllexport) int Add(int plus1, int plus2);
//};
#endif
```
testdll.cpp
```
#include "stdafx.h"
#include "testdll.h"
#include <iostream>
using namespace std;
int Add(int plus1, int plus2)
{
int add_result = plus1 + plus2;
return add_result;
}
```
mydll.def (模块定义文件)
```
LIBRARY "MyDLL"
EXPORTS
Add @1
```
MyDLL.cpp会自动生成
2. 编译并生成
## 显示调用
新建一个控制台项目,将MyDLL.dll拷贝到当前目录下,在main函数里加如下代码:
```
typedef int(*PF_ADD)(int a,int b);
HINSTANCE hDLL;
hDLL = LoadLibrary("MyDLL.dll");//加载动态链接库MyDll.dll文件;
PF_ADD Add = (PF_ADD)GetProcAddress(hDLL,"Add");
int a;
a = Add(5 , 8);
std::cout<<"比较的结果为"<<a;
FreeLibrary(hDLL);//卸载MyDll.dll文件;
```
如果有报错,可能是:
(1).unicode字节变为多字节
(2)."配置属性"-"调试"-"环境"里填入dll路径,默认是exe路径可不填。
| 9f54586b3e9da171c416113bf0e5df8a163a04ae | [
"Markdown",
"C++"
] | 3 | C++ | fafahome/MyNote | 9414fcc06a7a4f3c48d2b392c32ba4ce2dfa2344 | bd76c4534181e060d6d55ac88d65127236b5bdad |
refs/heads/master | <file_sep>import vrep
vrep.simxFinish(-1) # 关掉之前的连接
clientId = vrep.simxStart("127.0.0.1", 19997, True, True, 5000, 5) #建立和服务器的连接
if clientId != -1: #连接成功
print('connect successfully')
else:
print('connect failed')
vrep.simxFinish(clientId)
print('program ended')
<file_sep># Motion-Planning
## this project is for motion planning class of clemson university CPSC8810
##To start the simulation, you need to install
###1.vrep
###2.v-rep_ExtOMPL
###python script
###OMPL
| d901328d8d355166cbffe3ae15ad214448bc7a08 | [
"Markdown",
"Python"
] | 2 | Python | roothyb/Motion-Planning | 65f9971269a346da103be17955e031bd7b389d10 | 9cc9812f832ecb115f2d26b20b3a9d2f085a22be |
refs/heads/main | <file_sep>import oneCountryTpl from '../templates/oneCountry.hbs';
import severalСountriesTpl from '../templates/severalСountries.hbs';
import { error } from '@pnotify/core';
import '@pnotify/core/dist/BrightTheme.css';
const refs = {
menuList: document.querySelector('.js-menu'),
};
function createMenuList(markup) {
refs.menuList.insertAdjacentHTML('beforeend', markup);
}
function updateCountriesMarkup(countries) {
let markup = null;
if (countries.length > 10) {
error({
text: 'Too many matches found. Please enter a more specific query!'
});
} else if ((countries.length >= 2) & (countries.length <= 10)) {
markup = severalСountriesTpl(countries);
createMenuList(markup);
} else {
markup = oneCountryTpl(countries);
createMenuList(markup);
}
}
export default updateCountriesMarkup;
<file_sep>import './styles.css';
import updateCountriesMarkup from './js/updateCountriesMarkup.js';
import fetchCountries from './js/fetchCountries.js';
import debounce from 'lodash.debounce';
const refs = {
menuList: document.querySelector('.js-menu'),
input: document.querySelector('.input'),
};
function onInput(event) {
let inputValue = event.target.value;
refs.menuList.innerHTML = '';
fetchCountries(inputValue).then(updateCountriesMarkup);
}
refs.input.addEventListener('input', debounce(onInput, 500));
| 3b555980a085c5be3d0ea939297f15c74e359c32 | [
"JavaScript"
] | 2 | JavaScript | volodpopov/goit-js-hw-12-countries | 33e43d55b624da9b30f462a61f49e58dd8f93149 | c4d4ddd998814cb4aecb7c646dc5a28e90b64431 |
refs/heads/master | <repo_name>Br34th7aking/cb-website<file_sep>/guides/views.py
from django.shortcuts import render
from .models import Guide
def guide(request):
all_guides = Guide.objects.all()
return render(request, 'guide.html', {'guides': all_guides})
<file_sep>/main_site/models.py
from django.db import models
class ResourceLink(models.Model):
COURSE_CHOICES = (
('GEN', 'General'),
('FOMB', 'Foundations of Modern Biology'),
('CBB', 'Cell Biology and Biochemistry'),
('MLBA', "Machine Learning for Biomedical Applications"),
('ACB', 'Algorithms in Computational Biology'),
('NB', 'Network Biology'),
('CGAS', 'Computational Gastronomy'),
('IMB', 'Introduction to Mathematical Biology'),
)
name = models.CharField(max_length=250)
link = models.URLField(max_length=300)
description = models.TextField(max_length=300, default='')
contributor = models.CharField(max_length=100, default='')
course = models.CharField(max_length=250, choices=COURSE_CHOICES, default='GEN')
def __str__(self):
return self.name
<file_sep>/main_site/migrations/0002_resourcelink_course.py
# Generated by Django 2.2.4 on 2019-08-04 12:40
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('main_site', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='resourcelink',
name='course',
field=models.CharField(choices=[('GEN', 'General'), ('FOMB', 'Foundations of Modern Biology'), ('CBB', 'Cell Biology and Biochemistry'), ('MLBA', 'Machine Learning for Biomedical Applications'), ('ACB', 'Algorithms in Computational Biology'), ('NB', 'Network Biology'), ('CGAS', 'Computational Gastronomy'), ('IMB', 'Introduction to Mathematical Biology')], default='GEN', max_length=250),
),
]
<file_sep>/guides/migrations/0001_initial.py
# Generated by Django 2.2.4 on 2019-08-03 10:47
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Guide',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=255)),
('course_name', models.CharField(max_length=255)),
('release_date', models.DateField()),
('description', models.TextField()),
('language', models.CharField(max_length=255)),
('image', models.ImageField(upload_to='uploads/')),
('price', models.CharField(max_length=255)),
('pdf_file', models.FileField(upload_to='uploads/')),
],
),
]
<file_sep>/guides/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('guides/', views.guide, name='guide'),
]
<file_sep>/main_site/admin.py
from django.contrib import admin
from .models import ResourceLink
admin.site.register(ResourceLink)
<file_sep>/README.md
# cb-website
This website is a collection of useful resources such as links, guides, project ideas etc. and a discussion forum
that provides users with a platform to interact with others and share their ideas.
<file_sep>/guides/admin.py
from django.contrib import admin
from .models import Guide
# Register your models here.
admin.site.register(Guide)
<file_sep>/main_site/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='home'),
path('faq/', views.faq, name='faq'),
path('resource/', views.resource, name='resource'),
path('about/', views.about_us, name='about'),
]
<file_sep>/guides/models.py
from django.db import models
class Guide(models.Model):
title = models.CharField(max_length=255)
course_name = models.CharField(max_length=255)
release_date = models.DateField()
description = models.TextField()
language = models.CharField(max_length=255)
image = models.ImageField(upload_to='uploads/')
price = models.CharField(max_length=255)
pdf_file = models.FileField(upload_to='uploads/')
def __str__(self):
return self.title
<file_sep>/main_site/migrations/0003_resourcelink_description.py
# Generated by Django 2.2.4 on 2019-08-04 12:43
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('main_site', '0002_resourcelink_course'),
]
operations = [
migrations.AddField(
model_name='resourcelink',
name='description',
field=models.TextField(default='', max_length=300),
),
]
<file_sep>/main_site/views.py
from django.shortcuts import render
from django.http import HttpResponse
def home(request):
return render(request, 'home.html')
def faq(request):
return render(request, 'faq.html')
def resource(request):
return render(request, 'resource.html')
def about_us(request):
return render(request, 'about.html')
| 86e220b5e1ae8d9f339151948d53b677ad256e7a | [
"Markdown",
"Python"
] | 12 | Python | Br34th7aking/cb-website | b1038a075b5416eeaf0daa4d549ce082ff09004e | fc08d69387daccacbf11ca01171ab9737af5d22a |
refs/heads/master | <repo_name>hongjeee/tensorflowForMe<file_sep>/02 - Deep NN (1-hidden layer, ReLU, CrossEntropy, Adam, small_toy_data).py
# coding: utf-8
# 01 -Classification과 동일한 데이터 사용
# ([털, 날개] -> [기타, 포유류, 조류] 분류)
import tensorflow as tf
import numpy as np
#[털, 날개]
x_data = np.array([[0, 0], [1, 0], [1, 1], [0, 0], [0, 0], [0, 1]])
# [기타, 포유류, 조류]
y_data = np.array([
[1, 0, 0], # 기타
[0, 1, 0], # 포유류
[0, 0, 1], # 조류
[1, 0, 0],
[1, 0, 0],
[0, 0, 1]
])
######### 신경망 모델 구성 ###########
X = tf.placeholder(tf.float32)
Y = tf.placeholder(tf.float32)
# 1번 weight의 차원 : [feature 수, hidden layer 뉴런 수] -> [2, 10]
W1 = tf.Variable(tf.random_uniform([2,10], -1., 1.))
# 2번 weight의 차원 : [1번 hidden layer 뉴런 수, class 수] -> [10,3]
W2 = tf.Variable(tf.random_uniform([10,3], -1., 1.))
# bias : 각 layer의 output 수
b1 = tf.Variable(tf.zeros([10]))
b2 = tf.Variable(tf.zeros([3]))
# hidden layer 구성하기
L1 = tf.add(tf.matmul(X,W1), b1)
L1 = tf.nn.relu(L1)
# 최종 output 계산
model = tf.add(tf.matmul(L1, W2), b2)
# tensorflow에서 제공하는 함수를 이용하여 간단하게 cross entropy 적용 가능
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=Y, logits=model))
optimizer = tf.train.AdamOptimizer(learning_rate=0.01)
train_op = optimizer.minimize(cost)
######### 모델 학습 #########
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)
for epoch in range(100):
sess.run(train_op, feed_dict={X:x_data, Y:y_data})
if (epoch+1)%10 == 0:
print (epoch+1, sess.run(cost, feed_dict={X:x_data, Y:y_data}))
# 결과 확인 [기타, 포유류, 조류]
prediction = tf.argmax(model, 1)
target = tf.argmax(Y, 1)
print('예측값:', sess.run(prediction, feed_dict={X: x_data}))
print('실제값:', sess.run(target, feed_dict={Y: y_data}))
is_correct = tf.equal(prediction, target)
accuracy = tf.reduce_mean(tf.cast(is_correct, tf.float32))
print('정확도: %.2f' % sess.run(accuracy * 100, feed_dict={X: x_data, Y: y_data}))
<file_sep>/01 - classification (ReLU, cross_entropy, small_toy_data).py
# coding: utf-8
# Classification
# 털과 날개가 유무로, 포유류인지 조류인지 분류하는 신경망 모델
import tensorflow as tf
import numpy as np
# [털, 날개]
x_data = np.array([[0, 0], [1, 0], [1, 1], [0, 0], [0, 0], [0, 1]])
# [기타, 포유류, 조류] one-hot
y_data = np.array([
[1, 0, 0], #기타
[0, 1, 0], #포유류
[0, 0, 1], #조류
[1, 0, 0],
[1, 0, 0],
[0, 0, 1]
])
##################신경망 모델 구성 ############
X = tf.placeholder(tf.float32)
Y = tf.placeholder(tf.float32)
# 신경망은 2차원, [입력층, 출력층] -> [2,3]
W = tf.Variable(tf.random_uniform([2,3], -1., 1.))
# bias는 각 레이어의 아웃풋 갯수로 설정 (기타, 포유류, 조류) -> 3
b = tf.Variable(tf.random_uniform([3]))
### 신경망에 가중치 W와 bias를 적용
L = tf.add(tf.matmul(X, W), b)
# activation func인 ReLU 적용 (activation function을 거쳐 output이 정규화 됨)
L = tf.nn.relu(L)
# softmax로 전체 합이 1로 만듬 ex) [8.04, 2.78, -6,52] ->[0.53, 0.24, 0.23]
model = tf.nn.softmax(L)
### Loss Function 정의 (classification에서는 cross entropy를 주로 씀)
# 각 개별 결과에 대한 합을 구한 뒤 평균을 냄
# 전체 합이 아닌 개별 결과기 때문에 axis 옵션 사용. 없을 시 전체 합 scalar로 나옴
# cross entropy = p(x)*-log(q(x)) // p(x)는 실제값, q(x)는 예상값
cost = tf.reduce_mean(-tf.reduce_sum(Y*tf.log(model), axis=1))
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.01)
train_op = optimizer.minimize(cost)
############### 신경망 모델 학습 ##############
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)
for epoch in range(100):
sess.run(train_op, feed_dict={X:x_data, Y:y_data})
if(epoch+1)%10 == 0:
print (epoch+1, sess.run(cost, feed_dict={X:x_data, Y:y_data}))
################ 결과 확인 ##############
# tf.argmax 가장 큰 값의 index 알려줌
prediction = tf.argmax(model, axis=1)
target = tf.argmax(Y, axis=1)
print('예측값:', sess.run(prediction, feed_dict={X:x_data}))
print('실제값:', sess.run(target, feed_dict={Y:y_data}))
is_correct = tf.equal(prediction, target)
accuracy = tf.reduce_mean(tf.cast(is_correct, tf.float32))
print('정확도:%.2f'%sess.run(accuracy*100, feed_dict={X:x_data, Y:y_data}))
<file_sep>/README.md
# tensorflowForMe
나만의 실습 공간
https://github.com/golbin/TensorFlow-Tutorials/ 따라하기
-- File Info Detail
01. classification
: Data - 6개의 [털, 날개] 유무 데이터로, [기타, 포유류, 조류] 구분하기
: ReLU (Activation Func), CrossEntropy (Loss Func), Gradient Descent (Optimizer) 이용
02. classification - 1 hidden layer
: Data - 6개의 [털, 날개] 유무 데이터로, [기타, 포유류, 조류] 구분하기
: ReLU (Activation Func), CrossEntropy (Loss Func), Adam (Optimizer) 이용
| 448c1ddea0f5494690155ab617dda464752435a1 | [
"Markdown",
"Python"
] | 3 | Python | hongjeee/tensorflowForMe | 14ac3173dff8c50f046677834c7152d2730bb04b | b8c4b25a3b70367e6add719605f6c8714f5f1af3 |
refs/heads/master | <repo_name>seanmars/excel2json<file_sep>/bin/e2jt.js
#!/usr/bin/env node
var path = require('path');
var fs = require('fs');
var util = require('util');
var cmder = require('commander');
var clc = require('cli-color');
var pkg = require('../package.json');
var e2jt = require('../index.js');
var inputFile;
var inputSheet;
var outputFile;
// setting commander
cmder.version(pkg.version)
.usage('<parse file> [sheet name] [output name]')
.arguments('<file> [sheet] [output]')
.option('-s, --space <space>', 'The white space to insert into the output JSON string for readability purposes')
.option('-t, --template <template>', 'The file path of JSON template')
.option('-o, --outputdir <outputdir>', 'The path of output folder')
.option('--key <name of key>', 'The name of key for data list')
.option('--sheetname [true|false]', 'Auto add sheet name.[true|false]', /^(true|false)$/i, false)
.option('--dict [true|false]', 'Is key-value JSON?[true|false]', /^(true|false)$/i, false)
.action(function (file, sheet, output) {
inputFile = file;
inputSheet = sheet ? sheet : path.basename(file, path.extname(file));
outputFile = (output ? output : inputSheet) + '.json';
})
.parse(process.argv);
// analysis parameter
if (!inputFile) {
console.error(clc.red("ERROR:\n") + 'No file given!');
process.exit(1);
}
if (cmder.template) {
e2jt.loadTemplate(cmder.template, parseCallback);
} else {
parseCallback();
}
function parseCallback(err, templateJson) {
if (err) {
throw err;
}
var fp = path.resolve(inputFile);
var data = e2jt.parse(fp, inputSheet, templateJson, {
nameOfKey: cmder.key,
isKeyVal: cmder.dict,
isAddSheetName: cmder.sheetname
});
var opdir = cmder.outputdir || path.dirname(inputFile);
var space = {
spaces: Number(cmder.space) || 0
};
outputFile = path.resolve(path.join(opdir, outputFile));
e2jt.save(outputFile, data, space, function (err) {
if (err) {
console.log(err);
return;
}
console.log(clc.greenBright('Parse "%s" successed.'), fp);
});
}
<file_sep>/README.md
# excel-to-json-template
Export the data with JSON format from excel;
- [Features](#features)
- [Usage](#usage)
- [Todos](#todos)
- [Change logs](#logs)
## <a name="features"></a>Features
- Import excel, Export JSON;
- Export JSON with prettify or minify;
- Custom JSON template;
## <a name="usage"></a>Usage
### Excel
---
Tag:
- \! => Ignore
- Column == A, it will ignore all the same column and row;
- Column != A, just ignore the same column;
- \# => Title
- The title of data in excel, it will transform to property's name of Object;
- ^ => Top-level attributes
- If use dict(--dict true), all the top-level attributes will be ignored.
| A | B | C |
|---|---|---|
| ^ | key | value |
- \~ => The name of key.
| A | B |
|---|---|
| ~ | name of key |
### Template
- \$ => Use $title_name can map the value to be key in json;
### Example
---
- Use code:
```javascript
var e2jt = require('./index.js');
e2jt.loadTemplate('./template/file/path/file.json', function (err, jsonObj) {
var data = e2jt.parse('./data/file/path/data.xlsx', 'sheet_name', jsonObj);
e2jt.save('path/to/output/output.json', data);
});
```
- Use cli:
```
e2jt /path/of/file
```
More about cli:
```
e2jt -h
```
## <a name="todos"></a>Todos
- CLI;
- Use command to import file(list of file) and parse all of then;
## <a name="logs"></a>Change logs
### 2017-02-17
---
FEATURE
- 增加 CLI 選項,是否自動加入屬性 sheetname。--sheetname [true|false] default = false。
- 增加 CLI 選項,輸出是否為 key-value。--dict [true|false] default = false。 NOTE: 設為 true 時,所有 Top-level attributes(^) 將會被忽略。
- 增加 CLI 選項,資料列的 Key 名稱。--key <name of key>。
- 增加 Tag:"~",資料表中 Tag:"~" 欄位右邊的值會編譯成資料列的 Key 名稱。 NOTE: 此屬性的優先順序比 CLI 的 --key 低。
- 資料列的 Key 名稱預設為 datas。
### 2017-02-16
---
FEATURE
- 增加 $ 前導符號應用,在 Template 當中使用 ${title_name} 將可把數值編譯成 JSON 的 KEY。
Template:
```JSON
{
"$id": {
"name": "name",
"age": "age"
}
}
```
Output:
```JSON
{
"0001": {
"name": "Foobar",
"age": "23"
}
}
```
### 2016-09-06
---
FIXED
- Now can use the recursively Object, Array in template file;
OTHER
- Add more test case;
### 2016-07-28
---
FEATURE
- 增加 tag: attribute(^), 讓使用者可以在 JSON 的 top-level 增加 attribute;
- tag attribute 的位子一定要在 tag title 上方
- tag attribute 由同 row 的三個連續的 column 組成, 順序為 tag > property name > value
IMPROVE
- 修改取得資料的迴圈只需要跑 tag title 以下的 row
OTHER
- 引入 mochajs 增加 Unit test;
### 2016-07-09
---
- Refactoring some code;(rename, add some check...)
### 2016-07-09
---
- Add CLI;
### 2016-07-08
---
- Update the parse function, now can input empyt or null template, it will direct parse(no any transform) all the title in excel to JSON;
### 2016-07-06
---
- Add feature custom template;
<file_sep>/test/test.js
var should = require('should');
var chai = require('chai');
var util = require('util');
var e2jt = require('../index.js');
// #loadSheet()
describe('#loadSheet()', function () {
describe('when type is xlsx', function () {
describe('when file is NOT exist', function () {
it('should throw expect', function (done) {
var filePath = './test/data/none.xlsx';
should.throws(() => e2jt.loadSheet(filePath, 'test'));
done();
});
});
describe('when sheet is exist', function () {
it('should return undefined', function (done) {
var sheet = e2jt.loadSheet('./test/data/test.xlsx', 'none');
should(sheet).not.ok();
done();
});
});
describe('when sheet is NOT exist', function () {
it('should return sheet object', function (done) {
var sheet = e2jt.loadSheet('./test/data/test.xlsx', 'test');
should(sheet).ok();
done();
});
});
describe('without parameter [filePath] and [sheetName]', function () {
it('should return undefined', function (done) {
var sheet = e2jt.loadSheet();
should(sheet).not.ok();
done();
});
});
describe('without parameter [sheetName]', function () {
it('should return undefined', function (done) {
var sheet = e2jt.loadSheet('./test/data/test.xlsx');
should(sheet).not.ok();
done();
});
});
});
// ods
describe('when type is ods', function () {
describe('when file is NOT exist', function () {
it('should throw expect', function (done) {
var filePath = './test/data/none.ods';
should.throws(() => e2jt.loadSheet(filePath, 'test'));
done();
});
});
describe('when sheet is exist', function () {
it('should return undefined', function (done) {
var sheet = e2jt.loadSheet('./test/data/test.ods', 'none');
should(sheet).not.ok();
done();
});
});
describe('when sheet is NOT exist', function () {
it('should return sheet object', function (done) {
var sheet = e2jt.loadSheet('./test/data/test.ods', 'test');
should(sheet).ok();
done();
});
});
describe('without parameter [filePath] and [sheetName]', function () {
it('should return undefined', function (done) {
var sheet = e2jt.loadSheet();
should(sheet).not.ok();
done();
});
});
describe('without parameter [sheetName]', function () {
it('should return undefined', function (done) {
var sheet = e2jt.loadSheet('./test/data/test.ods');
should(sheet).not.ok();
done();
});
});
});
});
// #loadTemplate()
describe('#loadTemplate', function () {
it('should return right JSON Object', function (done) {
e2jt.loadTemplate('./test/data/template.json', function (err, jsonObj) {
should(err).be.a.null();
should(jsonObj).not.be.a.null();
should(jsonObj).have.properties('key');
should(jsonObj).have.properties('attributes');
should(jsonObj).have.properties('array');
should(jsonObj).have.properties('price');
should(jsonObj.key).be.eql('id');
should(jsonObj.attributes).be.Object();
should(jsonObj.attributes.value).be.eql('value');
should(jsonObj.attributes.name).be.eql('name');
should(jsonObj.attributes.array).be.Array();
should(jsonObj.attributes.array[0]).be.eql('value');
should(jsonObj.attributes.array[1]).be.eql('name');
should(jsonObj.array).be.Array();
should(jsonObj.array[0]).be.eql('value');
should(jsonObj.array[1]).be.eql('name');
should(jsonObj.array[2]).be.Object();
should(jsonObj.array[2].value).be.eql('value');
should(jsonObj.array[2].name).be.eql('name');
should(jsonObj.array[3]).be.Array();
should(jsonObj.array[3][0]).be.eql('value');
should(jsonObj.array[3][1]).be.eql('name');
should(jsonObj.price).be.eql('value');
});
done();
});
});
// #parse()
describe('#parse()', function () {
it('should return right JSON Object', function (done) {
e2jt.loadTemplate('./test/data/template.json', function (err, jsonObj) {
if (err) {
done(err);
} else {
var data = e2jt.parse('./test/data/test.xlsx', 'test', jsonObj);
// console.log(JSON.stringify(data, '', 4));
should(data).be.Object();
should(data.version).be.eql('1.0.0');
should(data.name).be.eql('newname');
should(data.datas).be.Array();
should(data.datas.length).be.eql(7);
for (var i = 0; i < data.datas.length; i++) {
var v = i + 1;
should(data.datas[i].key).be.eql('Id_' + v);
should(data.datas[i].attributes).be.Object();
should(data.datas[i].attributes.value).be.eql('Value_' + v);
should(data.datas[i].attributes.array).be.Array();
should(data.datas[i].attributes.array[0]).be.eql(data.datas[i].attributes.value);
should(data.datas[i].attributes.array[1]).be.eql(data.datas[i].attributes.name);
should(data.datas[i].array).be.Array();
should(data.datas[i].array[0]).be.eql(data.datas[i].attributes.value);
should(data.datas[i].array[1]).be.eql(data.datas[i].attributes.name);
should(data.datas[i].array[2]).be.Object();
should(data.datas[i].array[2].value).be.eql(data.datas[i].attributes.value);
should(data.datas[i].array[2].name).be.eql(data.datas[i].attributes.name);
should(data.datas[i].array[3]).be.Array();
should(data.datas[i].array[3][0]).be.eql(data.datas[i].attributes.value);
should(data.datas[i].array[3][1]).be.eql(data.datas[i].attributes.name);
}
}
});
done();
});
});
// #save()
// describe('#save()', function () {
// it('should save right JSON Object', function (done) {
// done();
// });
// });
<file_sep>/index.js
/**
* TODO:
* - Check the value of title cell is valid or not (only alphabet)
* - 增加 CLI 方法, 傳入檔案列表, 依列表依序 parse 各個資料
* - 將 tags 改為使用 Objec 傳入 { tagTitle: '!', tagIgnore: '#', tagAttr: '^' }
* - 改用 Asynchronous 的方式去寫, 能的話引入 async
* - 錯誤的地方使用明確的 exception, 而非回傳 null
* Refactoring:
* - 修改 function A(x,y) call function B(y), 但卻在 A, B 裡都詳細檢查判斷了 y;
* 修正成為只需要在 function B(y) 內檢查就好, A 只需要判斷回傳出來的值
*/
var excel2jsontemplate = (function () {
const DEFAULT_ATTR_SHEETNAME = 'sheetname';
const DEFAULT_ATTR_DATAS = 'datas';
function InitException(message) {
this.message = message;
this.name = 'InitException';
}
if (typeof require === 'undefined') {
throw new InitException('require is undefined');
}
var path = require('path');
var fs = require('fs');
var util = require('util');
var XLSX = require('xlsx');
var jsonfile = require('jsonfile');
var _u = require('underscore');
var _l = require('lodash');
/**
* Load the sheet by file path and sheet name.
*
* @method loadSheet
*
* @param {string} filePath
* @param {string} sheetName
*
* @return {Object} sheet Object of sheet.
*/
function loadSheet(filePath, sheetName) {
if (_u.isEmpty(filePath) || _u.isEmpty(sheetName)) {
return;
}
try {
// check file is exists or not
if (!fs.existsSync(filePath)) {
throw new Error('The file is not exists.');
}
var workbook = XLSX.readFile(filePath);
if (!workbook) {
return;
}
if (_l.indexOf(workbook.SheetNames, sheetName) === -1) {
return;
}
return workbook.Sheets[sheetName];
} catch (e) {
throw e;
}
}
/**
* The cell factory.
*
* @method factoryCell
*
* @param {Object} cell_address { c: column, r: row }
* @param {string} z_value number format string associated with the cell
* @param {Object} rawCell Raw cell object
*
* @return {Object} cell The cell Object.
*/
function factoryCell(cell_address, z_value, rawCell) {
var cell = {
o: rawCell,
v: rawCell ? rawCell.v : null, // raw value
w: rawCell ? rawCell.w : null, // formatted text (if applicable)
c: cell_address.c,
r: cell_address.r,
z: z_value,
};
return cell;
}
/**
* Check the cell is need ignore or not.
* <pre>
* Rules:
* 1. Same column with ignore cell.
* 2. If the column of ignore cell is zero, the same row with ignore cell will be ignored.
* </pre>
*
* @method isNeedIgnore
*
* @param {Object} cell
* @param {Array} ignore cells
*
* @return {Boolean}
*/
function isNeedIgnore(cell, ignores) {
for (var k in ignores) {
if (!ignores.hasOwnProperty(k)) {
continue;
}
var fc = ignores[k];
if (fc.c == cell.c) {
return true;
}
if (fc.c === 0 && fc.r == cell.r) {
return true;
}
}
return false;
}
/**
* Check is tag or not.
*
* @method isTag
*
* @param {Object} cell
* @param {string} tagChar
*
* @return {Boolean}
*/
function isTag(cell, tagChar) {
if (!cell || !cell.v) {
return false;
}
if (typeof cell.v !== 'string') {
return false;
}
if (cell.v != tagChar) {
return false;
}
return true;
}
/**
* Find the cell object of title tag by title char.
*
* @method findTitleTagCell
*
* @param {Object} worksheet
* @param {Object} range
* @param {string} tagTitle
*
* @return {Object} cell The cell of title.
*/
function findTitleTagCell(worksheet, range, tagTitle) {
if (!tagTitle) {
return;
}
for (var ir = range.s.r; ir <= range.e.r; ++ir) {
for (var ic = range.s.c; ic <= range.e.c; ++ic) {
var cell_address = {
c: ic,
r: ir
};
z = XLSX.utils.encode_cell(cell_address);
if (!isTag(worksheet[z], tagTitle)) {
continue;
}
var cell = factoryCell(cell_address, z, worksheet[z]);
return cell;
}
}
return;
}
/**
* Find the cells by tag char.
*
* @method findTagCells
*
* @param {Object} worksheet
* @param {Object} range
* @param {Object} endCell
* @param {string} tagChar
*
* @return {Array} cells The array of cell(s).
*/
function findTagCells(worksheet, range, endCell, tagChar) {
var cells = [];
if (!tagChar) {
return cells;
}
for (var ir = range.s.r; ir <= endCell.r; ++ir) {
for (var ic = range.s.c; ic <= range.e.c; ++ic) {
var cell_address = {
c: ic,
r: ir
};
z = XLSX.utils.encode_cell(cell_address);
if (!isTag(worksheet[z], tagChar)) {
continue;
}
var cell = factoryCell(cell_address, z, worksheet[z]);
cells.push(cell);
}
}
return cells;
}
/**
* Find the cells of title.
*
* @method findTitleCells
*
* @param {Object} worksheet
* @param {Object} range
* @param {Object} titleCell
* @param {Object} ignoreCells
*
* @return {Array} cells The cells of title.
*/
function findTitleCells(worksheet, range, titleCell, ignoreCells) {
var cells = [];
var ir = titleCell.r;
for (var ic = range.s.c; ic <= range.e.c; ++ic) {
var cell_address = {
c: ic,
r: ir
};
z = XLSX.utils.encode_cell(cell_address);
if (z == titleCell.z) {
continue;
}
var cell = factoryCell(cell_address, z, worksheet[z]);
// TODO: check the value is valid or not (only alphabet)
// check the cell is need to ignore or not
if (isNeedIgnore(cell, ignoreCells)) {
continue;
}
if (titleCell && cell.v && (cell.r == titleCell.r)) {
cells[ic] = cell;
}
}
return cells;
}
/**
* fetch all the attribute(s)
*
* @method fetchAttrJson
*
* @param {Object} ws
* @param {Array} attrCells
*
* @return {JSON} cells The JSON Object of attribute.
*/
function fetchAttrJson(ws, attrCells) {
var cells = {};
for (var cell of attrCells) {
var keyAddr = {
c: cell.c + 1,
r: cell.r
},
valAddr = {
c: cell.c + 2,
r: cell.r
};
var zKey = XLSX.utils.encode_cell(keyAddr),
zVal = XLSX.utils.encode_cell(valAddr);
cells[ws[zKey].v] = ws[zVal].v;
}
return cells;
}
/**
* fetch name of key
*
* @method fetchNameOfKeyJson
*
* @param {Object} ws
* @param {Array} cells
*
* @return {string} name of key.
*/
function fetchNameOfKeyJson(ws, cells) {
for (var cell of cells) {
var valAddr = {
c: cell.c + 1,
r: cell.r
};
var zVal = XLSX.utils.encode_cell(valAddr);
return ws[zVal].v;
}
}
/**
* fetch raw data(s)
*
* @method fetchRawData
*
* @param {Object} ws Object of worksheet
* @param {Object} range The range from XLSX.utils.decode_range
* @param {Object} titleCell
* @param {Array} titles
* @param {Array} ignoreCells
*
* @return {Array} rawDatas Array of Cells.
*/
function fetchRawData(ws, range, titleCell, titles, ignoreCells) {
var cells = [];
var rawDatas = [];
var cell_address = {};
for (var ir = titleCell.r + 1; ir <= range.e.r; ++ir) {
var data = {};
for (var ic = range.s.c; ic <= range.e.c; ++ic) {
cell_address = {
c: ic,
r: ir
};
z = XLSX.utils.encode_cell(cell_address);
var cell = factoryCell(cell_address, z, ws[z]);
// title row
if (cell.r == titleCell.r) {
continue;
}
// check the cell is need to ignore or not
if (isNeedIgnore(cell, ignoreCells)) {
continue;
}
// check title cell content
var t = titles[ic];
if (!t || !t.w) {
continue;
}
// save the data
data[t.w] = cell.w;
cells.push(cell);
}
if (_u.isEmpty(data)) {
continue;
}
rawDatas.push(data);
}
return rawDatas;
}
/**
* Parse the excel file and export the data with JSON format.
*
* @method parseSheet
*
* @param {string} filePath
* @param {string} sheetName
* @param {string} tagTitle
* @param {string} tagAttribute
* @param {string} tagNameOfKey
* @param {string} tagIgnore
*
* @return {JSON} result The data of JSON.
*/
function parseSheet(filePath, sheetName, tagTitle, tagAttribute, tagNameOfKey, tagIgnore) {
var ws = loadSheet(filePath, sheetName);
if (!ws) {
return;
}
var ref = ws['!ref'];
if (!ref) {
return;
}
var range = XLSX.utils.decode_range(ref);
// find all tag of title cells
var titleCell = findTitleTagCell(ws, range, tagTitle);
if (!titleCell) {
return;
}
// find all tag of attribute cells
var attrCells = findTagCells(ws, range, titleCell, tagAttribute);
// find all tag of ignore cells
var ignoreCells = findTagCells(ws, range, titleCell, tagIgnore);
// find all tag of name of key cells
var nameOfKeyCells = findTagCells(ws, range, titleCell, tagNameOfKey);
// find all titles with titleCell
var titles = findTitleCells(ws, range, titleCell, ignoreCells);
if (titles.length === 0) {
return;
}
// fetch all attribute cell(s)
var attrs = fetchAttrJson(ws, attrCells);
// fetch name of key
var nameOfKey = fetchNameOfKeyJson(ws, nameOfKeyCells);
// fetch all raw datas
var rawDatas = fetchRawData(ws, range, titleCell, titles, ignoreCells);
return {
nameOfKey: nameOfKey,
attrs: attrs,
rawDatas: rawDatas
};
}
/**
* Map the data to tempalte.
*
* @method map
*
* @param {Object} data
* @param {JSON} template
* @param {Boolean} isKeyVal
*
* @return {JSON} result Mapped data.
*/
function map(data, template, isKeyVal) {
var type = template.constructor;
var obj;
switch (type) {
case Array:
obj = [];
break;
case Object:
obj = {};
break;
default:
return data[template];
}
expr = /^\$/;
for (var key in template) {
if (!template.hasOwnProperty(key)) {
continue;
}
var isValKey = expr.test(key);
var keyVal = isValKey ? map(data, key.replace('$', '')) : key;
var val = template[key];
switch (val.constructor) {
case Array:
obj[keyVal] = [];
for (var index in val) {
var arrVal;
if (val.hasOwnProperty(index)) {
switch (val[index].constructor) {
case Array:
arrVal = map(data, val[index]);
break;
case Object:
arrVal = map(data, val[index]);
break;
default:
arrVal = data[val[index]];
break;
}
obj[keyVal].push(arrVal);
}
}
break;
case Object:
switch (type) {
case Array:
obj.push(map(data, val));
break;
case Object:
obj[keyVal] = map(data, val);
break;
}
break;
default:
switch (type) {
case Array:
obj.push(data[val]);
break;
case Object:
obj[keyVal] = data[val];
break;
}
break;
}
if (isKeyVal) {
obj._key = keyVal;
obj._val = obj[keyVal];
}
}
return obj;
}
/**
* Transform the raw data to the template JSON object.
*
* @method transform
*
* @param {Array} rawData
* @param {JSON} template
* @param {Boolean} isKeyVal
*
* @return {Array} result Array of JSON objects with template.
*/
function transform(rawData, template, isKeyVal) {
// init result object
var result = isKeyVal ? {} : [];
// foreach data to mapping to template
for (var index in rawData) {
if (!rawData.hasOwnProperty(index)) {
continue;
}
// mapping
var obj = map(rawData[index], template, isKeyVal);
if (isKeyVal) {
result[obj._key] = obj._val;
} else {
result.push(obj);
}
}
return result;
}
/**
* Parse the excel file and export the data with JSON format.
*
* @method parse
*
* @param {string} filePath
* @param {string} sheetName
* @param {JSON} template
* @param {Object} options
* @param {Boolean} options.useSheetname = false
* @param {Boolean} options.isKeyVal = false
* @param {string} options.tagTitle = '#'
* @param {string} options.tagAttribute = '^'
* @param {string} options.tagNameOfKey = '~'
* @param {string} options.tagIgnore = '!'
*
* @return {Object} The JSON Object of data
*/
function parse(filePath, sheetName, template, options) {
options = options || {};
nameOfKey = options.nameOfKey;
isAddSheetName = options.isAddSheetName || false;
isKeyVal = options.isKeyVal || false;
tagTitle = options.tagTitle || '#';
tagAttribute = options.tagAttribute || '^';
tagNameOfKey = options.tagNameOfKey || '~';
tagIgnore = options.tagIgnore || '!';
// check sheet name is empty or not
if (!sheetName) {
throw new Error("The sheet name is null or empty.");
}
// check template
template = template || {};
if (!_u.isObject(template) || _u.isArray(template)) {
throw new Error("The JSON template is invaild.");
}
// get data
var objJson = parseSheet(filePath, sheetName,
tagTitle, tagAttribute, tagNameOfKey, tagIgnore);
objJson = objJson || {
attrs: {},
rawDatas: []
};
// copy top-level attribute
var result = objJson.attrs;
if (isAddSheetName) {
result[DEFAULT_ATTR_SHEETNAME] = sheetName;
}
// transform the data if necessary
datas = _u.isEmpty(template) ? objJson.rawDatas : transform(objJson.rawDatas, template, isKeyVal);
if (isKeyVal) {
result = datas;
} else {
nameOfKey = nameOfKey ? nameOfKey : (objJson.nameOfKey || DEFAULT_ATTR_DATAS);
result[nameOfKey] = datas;
}
return result;
}
/**
* Save the JSON to the file.
*
* @method save
*
* @param {string} filePath
* @param {string} jsonObj
* @param {Object} options Set replacer for a JSON replacer[Options].
* @param {Function} callback
*
* @return
*/
function save(filePath, jsonObj, options, callback) {
if (!callback) {
callback = options;
options = {};
}
// check the output directory is exists or not, if not create it.
var dir = path.dirname(filePath);
fs.stat(dir, function (err, data) {
if (err) {
fs.mkdirSync(dir);
}
jsonfile.writeFile(filePath, jsonObj, options, function (err) {
if (callback) {
return callback(err);
}
});
});
}
/**
* Load json file.
*
* @method load
*
* @param {string} filePath
* @param {Function} callback
*
* @return
*/
function loadTemplate(filePath, callback) {
jsonfile.readFile(filePath, function (err, obj) {
if (callback) {
return callback(err, obj);
}
});
}
return {
save: save,
loadTemplate: loadTemplate,
parse: parse,
loadSheet: loadSheet,
factoryCell: factoryCell,
isNeedIgnore: isNeedIgnore,
isTag: isTag,
findTitleTagCell: findTitleTagCell,
findTagCells: findTagCells,
findTitleCells: findTitleCells,
parseSheet: parseSheet,
map: map,
transform: transform,
};
}());
module.exports = excel2jsontemplate;
<file_sep>/decisions.md
# 2016/07/02
轉移到新的 repository, 之前的太雜亂且考慮到應該不需要使用到 web 相關套件,
所以開了一個新的 repository 來繼續撰寫此功能, 並且改名為 excel2json.
新的 repository 中只會有單純的 class 提供 API 來做 excel2json 的功能, 並且提供 cli 來使用.
# 2016/05/29
- Use Node.js:
- Why:
- 相對於 PHP, Python 比較可以馬上架構, 開發
- 想練習 JavaScript
- Pros:
- 上手簡單
- 有大量對此專案有用處的 plugin 可以應用
- 可以承受大量的 Request
- Cons:
- Not enough diving in depth of JavaScript
- 可能會有很多 nested callback, 維護上可能會有點複雜
- NPM
- xlsx => https://github.com/SheetJS/js-xlsx
- 需要讀取 excel 檔案, 眾多的套件中只有這個支援度較完整, 使用上也方便.
- underscore => https://github.com/jashkenas/underscore
- 最一開始需要使用這個套件是為了判斷是否為空的 Array.
- jsonfile => https://github.com/jprichardson/node-jsonfile
- 需要讀取及儲存 JSON 檔案, 此套件方便簡單使用, 且最多人下載.
- commander => https://github.com/tj/commander.js/
- 想要寫 cli, 剛好找到這個套件, 功能完整且最多人下載.
| a00cbe83f90709598bdb843332ed9fffbd441fc1 | [
"JavaScript",
"Markdown"
] | 5 | JavaScript | seanmars/excel2json | fd25d9a3342d09df35d60ac0db4db02a8ecab842 | 5400b009ef8f2ece7400c6c168f68232f1b7e66b |
refs/heads/master | <file_sep>import React from 'react';
import './App.css';
const AppHeader = () => {
return (
<div className="imgRow">
<img className="item-image"
src="https://images.pexels.com/photos/2253832/pexels-photo-2253832.jpeg?cs=srgb&dl=assorted-cosmetic-products-2253832.jpg&fm=jpg"
alt=""
height="400px" />
<img className="item-image"
src="https://images.pexels.com/photos/3750640/pexels-photo-3750640.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260"
alt="" height="400px"
/>
<img className="item-image"
src="https://images.pexels.com/photos/912950/pexels-photo-912950.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260"
alt="" height="400px"
/>
</div>
);
}
export default AppHeader;<file_sep>import React, { useContext } from 'react';
import './../main/App.css';
import MakeUpItem from './MakeUpItem';
import { MakeUpContext } from '../main/MakeUpContext';
const MakeUpItems = () => {
const { makeUpItems } = useContext(MakeUpContext);
return (
<div>
<div>
<p>Found {makeUpItems.length} items </p> <br />
</div>
<div className="makeUpItems" >
{makeUpItems.map(makeUpItem => (
<MakeUpItem
key={makeUpItem.id}
name={makeUpItem.name}
brand={makeUpItem.brand}
image={makeUpItem.image_link}
productLink={makeUpItem.product_link} />
))}
</div>
</div>
);
}
export default MakeUpItems;<file_sep>import React from 'react';
import style from './makeUpItem.module.css';
const MakeUpItem = ({ name, brand, image, productLink }) => {
return (
<div className={style.makeUpItem}>
<img className={style.item - image} src={image} alt="" width="200px" /> <br />
<h1>{name}</h1><br />
<h1>{brand}</h1><br />
<a className={style.buttonStyle} href={productLink}>go to product page</a>
</div>
);
}
export default MakeUpItem;<file_sep>import React from 'react';
import './../main/App.css';
const About = () => {
return (
<h1>About Page</h1>
);
}
export default About;<file_sep>import React from 'react';
import { MakeUpProvider } from './MakeUpContext';
import MakeUpItems from './../components/MakeUpItems';
import AppHeader from './AppHeader';
import Nav from './../navigation/Nav';
import About from './../navigation/About';
import Contact from './../navigation/Contact';
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';
import './App.css';
import MakeUpItemsSearch from './../navigation/MakeUpItemsSearch';
const App = () => {
return (
<Router>
<MakeUpProvider >
<div className="App" >
<AppHeader />
<Nav />
<Switch>
<Route path="/" exact component={Home} />
<Route path="/search" component={MakeUpItemsSearch} />
<Route path="/about" component={About} />
<Route path="/contact" component={Contact} />
</Switch>
</div>
</MakeUpProvider>
</Router>
);
}
const Home = () => (
<div className="makeUpItems" >
<MakeUpItems />
</div>
);
export default App; | 20a78139df4f1cd60884c86d8925067ac30d28de | [
"JavaScript"
] | 5 | JavaScript | madlen96/beauty_freak | 91fa30fb90fbc2a7ff8fa1b6b132dc50d4de1e86 | 85aec7bca49c1d911f2baac05e92be5a8e931ee7 |
refs/heads/main | <file_sep>const express = require("express");
const app = express();
//app.use(cookieParser());
app.use(express.static( __dirname));
exports.allAccess = (req, res) => {
//res.header('Access-Control-Expose-Headers', 'Content-Type, Location');
//res.send(200);
//var token = req.headers["x-access-token"];
//console.log(token);
res.status(200).send("Public Content"); //index.html
//res.sendFile('C:/xampp/htdocs/AuthAPI/app/views/Home_user.html');
};
exports.userBoard = (req, res) => {
//res.status(200).send("User Content.");
res.sendFile('C:/xampp/htdocs/AuthAPI/app/views/Home_user.html');
};
exports.adminBoard = (req, res) => {
//res.status(200).send("Admin Content.");
//console.log(__dirname);
res.sendFile('C:/xampp/htdocs/AuthAPI/app/views/Home_admin.html');
};
exports.moderatorBoard = (req, res) => {
res.sendFile('C:/xampp/htdocs/AuthAPI/app/views/Home_mod.html');
//res.status(200).send("Moderator Content.");
//res.setHeader("Location", "https://stackoverflow.com/questions/40497534/how-to-res-send-to-a-new-url-in-node-js-express/40497649");
//res.end();
};
exports.FetchData = (req, res) => {
var token = req.headers["x-access-token"];
res.status(200).send(token);
};
<file_sep> socketIOConnectionUpdate('Requesting JWT Token from Laravel');
$.ajax({
url: 'http://localhost:8000/token?id=1'
})
.fail(function (jqXHR, textStatus, errorThrown) {
socketIOConnectionUpdate('Something is wrong on ajax: ' + textStatus);
})
.done(function (result, textStatus, jqXHR) {
/*
make connection with localhost 3000
*/
var socket = io.connect('http://localhost:3000');
/*
connect with socket io
*/
socket.on('connect', function () {
socketIOConnectionUpdate('Connected to SocketIO, Authenticating')
socket.emit('authenticate', {token: result.token});
socket.emit('public-my-message', {'msg': 'Hi, Every One.'});
});
/*
If token authenticated successfully then here will get message
*/
socket.on('authenticated', function () {
socketIOConnectionUpdate('Authenticated');
});
/*
If token unauthorized then here will get message
*/
socket.on('unauthorized', function (data) {
socketIOConnectionUpdate('Unauthorized, error msg: ' + data.message);
});
/*
If disconnect socketio then here will get message
*/
socket.on('disconnect', function () {
socketIOConnectionUpdate('Disconnected');
});
/*
Get Userid by server side emit
*/
socket.on('user-id', function (data) {
$('#userid').html(data);
});
/*
Get Email by server side emit
*/
socket.on('user-email', function (data) {
$('#email').html(data);
});
/*
Get receive my message by server side emit
*/
socket.on('receive-my-message', function (data) {
$('#receive-my-message').html(data);
});
});
//});
/*
Function for print connection message
*/
function socketIOConnectionUpdate(str) {
$('#connection').html(str);
}<file_sep>module.exports = {
secret: "<KEY>"//"APIlogin-secret-key"
};
<file_sep>const express = require("express");
const bodyParser = require("body-parser");
const cookieParser = require('cookie-parser');
const cors = require("cors");
//var io = require('socket.io');
//var socketioJwt = require('socketio-jwt');
//require('dotenv').config({path: '../laravel/.env'});*/
var jwt = require("jsonwebtoken");
var bcrypt = require("bcryptjs");
//const config = require("../config/auth.config");
//const Op = db.Sequelize.Op;
const app = express();
app.use(cookieParser());
app.use(express.static(__dirname + '/public'));
var corsOptions = {
origin: "http://localhost:8081"
};
//app.use(express.static(__dirname + '/public'));
app.use(cors(corsOptions));
// parse requests of content-type - application/json
app.use(bodyParser.json());
// parse requests of content-type - application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));
// database
const db = require("./app/models");
const { JsonWebTokenError } = require("jsonwebtoken");
const Role = db.role;
db.sequelize.sync();
// force: true will drop the table if it already exists
// db.sequelize.sync({force: true}).then(() => {
// console.log('Drop and Resync Database with { force: true }');
// initial();
// });
//enable Cross-Origin-Resource-Sharing
app.use(cors({
credentials: true,
exposedHeaders: ['Content-Length', 'X-Foo', 'X-Bar', 'x-access-token', 'Authorization'],
}));
// simple route
app.get("/", (req, res) => {
res.json({ message: "Welcome to Auth-Proto application." });
});
// Another simple route: for testing
app.get("/cubatrytest", (req, res) => {
//let token = req.headers["x-access-token"];
const token = req.cookies["x-access-token"];
//const token = (new URL(document.location)).searchParams.get('token');
res.sendFile(__dirname + '/app/views/Home_user.html');
console.log(token);
});
// Test route for ui/ux
app.get('/login', function (req, res) {
res.sendFile(__dirname + '/app/views/login.html');
});
app.post('/test_log', (req, res) => {
var token = req.headers["x-access-token"];
// Insert Login Code Here
let username = req.body.username;
let password = <PASSWORD>;
res.send(`Username: ${username} Password: ${password}`, token);
});
// routes
require('./app/routes/auth.routes')(app);
require('./app/routes/user.routes')(app);
app.get('/page_test', (req, res) => {
res.sendFile(__dirname + '/app/views/container.html');
})
// set port, listen for requests
const PORT = process.env.PORT || 4848
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}.`);
});
// Accept connection and authorize token
/*io.on('connection', socketioJwt.authorize({
secret: process.env.JWT_SECRET,
timeout: 15000
}));
// When authenticated, send back name + email over socket
io.on('authenticated', function (socket) {
console.log(socket.decoded_token);
socket.emit('name', socket.decoded_token.name);
socket.emit('email', socket.decoded_token.email);
});*/
const CheckToken = (req, res, next) => {
const header = req.headers['x-access-token'];
if(typeof header != 'undefined'){
const bearer = header.split(' ');
const token = bearer[1];
req.token = token;
next();
}
else {
res.sendStatus(403);
}
}
app.get('/req_token', CheckToken, (req,res) => {
//verify over jwt
jwt.verify(req.token, config.secret, (err, authorizedData) => {
if(err){
console.log('ERROR: could not connect ot protected route');
res.send(403);
}
else{
res.json({
message: 'Logged in',
authorizedData
});
console.log('SUCCESS: connected to protected route');
}
})
})
function initial() {
Role.create({
id: 1,
name: "user"
});
Role.create({
id: 2,
name: "moderator"
});
Role.create({
id: 3,
name: "admin"
});
}
<file_sep># Login API prototyping using Node.js
Node.js with JSON Web Token (JWT) Authentication & Sequelize
## Project Requirements ##
- Express JS
- bcryptjs
- jsonwebtoken (JWT)
- Sequelize
- MySQL
## Project Dependencies
### Node.JS
[Node.Js Official Website](https://nodejs.org/en/download/)
### Sequelize/JWT/Mysql Sequelize
```
npm install express sequelize mysql2 body-parser cors jsonwebtoken bcryptjs --save
```
## Project setup
```
npm install
```
### Run
```
node server.js
```
## Demo
<img src="https://github.com/zF-9/AuthAPI/blob/5792be82e48001c3c6fb21e76fd8c6fd3441c8f3/app/img/sign_demo.gif">
| 7f0c5727d30b492fd9c38f45f01971d89b9e7114 | [
"JavaScript",
"Markdown"
] | 5 | JavaScript | zF-9/AuthAPI | 73a39a1a1063305900fc1e6f125dc764ca9a868e | 4c17ba0401614316aff84cce2d36a3365854a74b |
refs/heads/master | <repo_name>wannaRunaway/klwork<file_sep>/kulun_jetpack/app/src/main/java/com/kulun/energynet/login/PasswordLoginActivity.java
package com.kulun.energynet.login;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import androidx.databinding.DataBindingUtil;
import android.os.Bundle;
import androidx.core.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import com.kulun.energynet.R;
import com.kulun.energynet.databinding.ActivityLoginPasswordBinding;
import com.kulun.energynet.main.BaseActivity;
import com.kulun.energynet.main.MainActivity;
import com.kulun.energynet.main.fragment.MainFragment;
import com.kulun.energynet.model.User;
import com.kulun.energynet.network.API;
import com.kulun.energynet.network.InternetWorkManager;
import com.kulun.energynet.network.MyObserver;
import com.kulun.energynet.network.RxHelper;
import com.kulun.energynet.requestbody.LoginPasswordRequest;
import com.kulun.energynet.utils.Mygson;
import com.kulun.energynet.utils.MD5;
import com.kulun.energynet.utils.SharePref;
import com.kulun.energynet.utils.Utils;
/**
* created by xuedi on 2019/8/6
*/
public class PasswordLoginActivity extends BaseActivity implements View.OnClickListener {
private ActivityLoginPasswordBinding binding;
@Override
public void initView(Bundle savedInstanceState) {
binding = DataBindingUtil.setContentView(this, R.layout.activity_login_password);
binding.imgClose.setOnClickListener(this);
binding.imgLogin.setOnClickListener(this);
binding.imgRegister.setOnClickListener(this);
binding.tvLoginCode.setOnClickListener(this);
binding.tvForgetPassword.setOnClickListener(this);
requestMapPermissions();
initEdittext();
}
private void initEdittext() {//初始化输入框
String phone = (String) SharePref.get(PasswordLoginActivity.this, API.phone, "");
String password = (String) SharePref.get(PasswordLoginActivity.this, API.password, "");
if (!phone.equals("")) {
binding.etPhone.setText(phone);
}
if (!password.equals("")) {
binding.etPassword.setText(password);
}
}
@Override
public void onBackPressed() {
Intent intents = new Intent(PasswordLoginActivity.this, MainActivity.class);
intents.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intents);
finish();
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.img_close:
Intent intents = new Intent(PasswordLoginActivity.this, MainActivity.class);
intents.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intents);
finish();
break;
case R.id.img_login:
String phone = binding.etPhone.getText().toString();
String code = binding.etPassword.getText().toString();
if (TextUtils.isEmpty(phone)) {
Utils.snackbar(PasswordLoginActivity.this, "手机号码不能为空");
return;
}
if (!Utils.isPhone(phone, PasswordLoginActivity.this)) {
return;
}
if (TextUtils.isEmpty(code)) {
Utils.snackbar(PasswordLoginActivity.this, "密码不能为空");
return;
}
login(phone, code);
break;
case R.id.img_register:
Intent intent = new Intent(PasswordLoginActivity.this, RegisterActivity.class);
startActivity(intent);
break;
case R.id.tv_login_code:
Intent intent1 = new Intent(PasswordLoginActivity.this, VeriCodeLoginActivity.class);
startActivity(intent1);
break;
case R.id.tv_forget_password:
String tel = binding.etPhone.getText().toString();
Intent intent2 = new Intent(PasswordLoginActivity.this, ForgetPasswordActivity.class);
intent2.putExtra("tel", tel);
startActivity(intent2);
break;
default:
break;
}
}
private void login(String phone, String code) {
try {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);
} catch (Exception e) {
e.printStackTrace();
}
LoginPasswordRequest loginBody = new LoginPasswordRequest();
loginBody.setPhone(phone);
loginBody.setPassword(<PASSWORD>(code));
InternetWorkManager.getRequest().loginPassword(Utils.body(Mygson.getInstance().toJson(loginBody)))
.compose(RxHelper.observableIOMain(this))
.subscribe(new MyObserver<User>() {
@Override
public void onSuccess(User data) {
if (data != null) {
SharePref.put(PasswordLoginActivity.this, API.phone, phone);
SharePref.put(PasswordLoginActivity.this, API.password, code);
}
Utils.userParse(PasswordLoginActivity.this);
}
@Override
public void onFail(int code, String message) {
}
@Override
public void onError() {
}
@Override
public void onClearToken() {
Utils.toLogin(PasswordLoginActivity.this);
}
});
// HashMap<String,String> hashMap = new HashMap<>();
// hashMap.put("phone", phone);
// hashMap.put("password", <PASSWORD>(code));
// new MyRequest().myRequest(API.LOGIN, true,hashMap,true, this, null, null, new Response() {
// @Override
// public void response(JsonObject json, JsonArray jsonArray,boolean isNull) {
// User user = Mygson.getInstance().fromJson(json, User.class);
// if (user != null) {
// SharePref.put(PasswordLoginActivity.this, API.phone, phone);
// SharePref.put(PasswordLoginActivity.this, API.password, code);
// }
// Utils.userParse(json, PasswordLoginActivity.this);
// }
// });
}
private void requestMapPermissions() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
}
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
}
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
}
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
}
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE)
!= PackageManager.PERMISSION_GRANTED) {
}
}
}
<file_sep>/kulun_jetpack/app/src/main/java/com/kulun/energynet/mine/CouponKtActivity.kt
package com.kulun.energynet.mine
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.kulun.energynet.R
import com.kulun.energynet.databinding.ActivityCouponBinding
import com.kulun.energynet.databinding.AdapterCouponBinding
import com.kulun.energynet.main.BaseActivity
import com.kulun.energynet.model.Coupon
import com.kulun.energynet.network.InternetWorkManager
import com.kulun.energynet.network.MyObserver
import com.kulun.energynet.network.RxHelper
import com.kulun.energynet.requestbody.CouponRequest
import com.kulun.energynet.utils.DateUtils
import com.kulun.energynet.utils.Mygson
import com.kulun.energynet.utils.Utils
class CouponKtActivity : BaseActivity() {
private lateinit var binding: ActivityCouponBinding
private lateinit var adapter: MyAdapter
private var couponList: ArrayList<Coupon> = ArrayList<Coupon>()
private var pageNo: Int = 0
override fun initView(savedInstanceState: Bundle?) {
binding = DataBindingUtil.setContentView(this, R.layout.activity_coupon)
binding.header.left.setOnClickListener { finish() }
binding.header.title.setText("优惠券")
binding.smartRefresh.setOnRefreshListener {
pageNo = 0
loadData(true)
}
binding.smartRefresh.setOnLoadMoreListener {
pageNo = pageNo + 1
loadData(false)
}
binding.recyclerView.layoutManager = LinearLayoutManager(applicationContext)
adapter = MyAdapter(couponList)
binding.recyclerView.adapter = adapter
binding.smartRefresh.autoRefresh()
}
private fun loadData(isrefresh: Boolean) {
var conponRequest = CouponRequest()
conponRequest.page = pageNo
InternetWorkManager.getRequest()
.couponList(Utils.body(Mygson.getInstance().toJson(conponRequest)))
.compose(RxHelper.observableIOMain(this@CouponKtActivity))
.subscribe(object : MyObserver<List<Coupon>>() {
override fun onSuccess(data: List<Coupon>?) {
Utils.finishRefresh(binding.smartRefresh)
if (data == null) {
binding.image.visibility =
if (couponList.size > 0) View.GONE else View.VISIBLE
return
}
if (isrefresh) {
couponList.clear()
}
couponList.addAll(data)
binding.image.visibility = if (couponList.size > 0) View.GONE else View.VISIBLE
adapter.notifyDataSetChanged()
}
override fun onFail(code: Int, message: String?) {
Utils.finishRefresh(binding.smartRefresh)
if (code == -1 && couponList.size == 0) {
binding.image.visibility = View.VISIBLE
}
}
override fun onError() {
Utils.finishRefresh(binding.smartRefresh)
}
override fun onClearToken() {
Utils.toLogin(this@CouponKtActivity)
}
})
}
}
private class MyAdapter(couponList: ArrayList<Coupon>) : RecyclerView.Adapter<MyViewHolder>() {
private var couponList: ArrayList<Coupon> = couponList
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
val view: View = LayoutInflater.from(parent.context).inflate(R.layout.adapter_coupon, null)
val adapterbinding: AdapterCouponBinding = DataBindingUtil.bind(view)!!
return MyViewHolder(adapterbinding)
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
/*
* Coupon data = list.get(position);
holder.name.setText(data.getCouponName());
holder.money.setText(data.getAmount() + "元");
holder.text.setText("· 剩余" + (data.getAmount() - data.getUsed()) + "元未使用");
holder.time.setText("· " + DateUtils.timeToDate(data.getBeginDate()) + "至" + DateUtils.timeToDate(data.getExpireDate()));
* */
var data: Coupon = couponList.get(position)
holder.adapterbinding.tvName.setText(data.couponName)
holder.adapterbinding.tvMoney.setText(data.amount.toString() + "元")
holder.adapterbinding.text.setText("· 剩余" + (data.getAmount() - data.getUsed()) + "元未使用")
holder.adapterbinding.tvTime.setText(
"· " + DateUtils.timeToDate(data.getBeginDate()) + "至" + DateUtils.timeToDate(
data.getExpireDate()
)
)
}
override fun getItemCount(): Int {
return couponList.size
}
}
private class MyViewHolder(adapterbinding: AdapterCouponBinding) :
RecyclerView.ViewHolder(adapterbinding.root) {
// fun MyViewHolder(adapterbinding: AdapterCouponBinding) {
// setBinding(adapterbinding)
// }
var adapterbinding: AdapterCouponBinding = adapterbinding
// fun setBinding(binding: AdapterCouponBinding) {
// this.adapterbinding = binding
// }
//
}
<file_sep>/kulun_jetpack/app/src/main/java/com/kulun/energynet/popup/SharePopup.kt
package com.kulun.energynet.popup
import android.content.Context
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.animation.Animation
import androidx.databinding.DataBindingUtil
import com.kulun.energynet.R
import com.kulun.energynet.databinding.PopupShareBinding
import com.kulun.energynet.main.fragment.PromoteFragment
import com.kulun.energynet.main.fragment.Shareinterface
import razerdp.basepopup.BasePopupWindow
class SharePopup(context: Context?, inter: Shareinterface) : BasePopupWindow(context) {
public lateinit var binding: PopupShareBinding
private var myinterface = inter
override fun onCreateContentView(): View {
var view = createPopupById(R.layout.popup_share)
binding = DataBindingUtil.bind(view)!!
binding.cancel.setOnClickListener { dismiss() }
binding.weiFriend.setOnClickListener {
myinterface.sharetoothers()
dismiss()
}
binding.weiCircle.setOnClickListener {
myinterface.sharetocircle()
dismiss()
}
setPopupGravity(Gravity.BOTTOM)
return view
}
}<file_sep>/kulun_jetpack/app/src/main/java/com/kulun/energynet/mine/systemsetting/ISystemSettingPresent.java
package com.kulun.energynet.mine.systemsetting;
import android.app.Activity;
import android.content.Intent;
public interface ISystemSettingPresent {
/*
* 去个人信息
* */
void toPersonal();
/*
* 去修改密码
* */
void tochangepassword();
/*
* 退出登录
* */
void tologinout(Activity activity);
}
<file_sep>/kulun_jetpack/app/src/main/java/com/kulun/energynet/model/WxPayModel.java
package com.kulun.energynet.model;
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
/**
* created by xuedi on 2019/8/26
*/
public class WxPayModel implements Serializable {
/**
{"code":0,"data":{"appid":"wx1238d44896f1a785","noncestr":"1692036619361148522","package":"Sign=WXPay","partnerid":"1602454373","prepayid":"wx01150136736279f386162e97df538f0000",
"sign":"72B8DD0CF6351467344D3510EB420132","timestamp":"1614582096"}}
*/
/**
* package : Sign=WXPay
* appid : wxfeda8ed1ffad13af
* sign : 35D38A0F68ECC49B0A62443137AADDB4
* partnerid : 1552253491
* prepayid : wx260946363605301a211dcfb11798612400
* noncestr : bmEWkk7rHbPL
* timestamp : 1566783996
*/
@SerializedName("package")
private String packageX;
private String appid;
private String sign;
private String partnerid;
private String prepayid;
private String noncestr;
private String timestamp;
public String getPackageX() {
return packageX;
}
public void setPackageX(String packageX) {
this.packageX = packageX;
}
public String getAppid() {
return appid;
}
public void setAppid(String appid) {
this.appid = appid;
}
public String getSign() {
return sign;
}
public void setSign(String sign) {
this.sign = sign;
}
public String getPartnerid() {
return partnerid;
}
public void setPartnerid(String partnerid) {
this.partnerid = partnerid;
}
public String getPrepayid() {
return prepayid;
}
public void setPrepayid(String prepayid) {
this.prepayid = prepayid;
}
public String getNoncestr() {
return noncestr;
}
public void setNoncestr(String noncestr) {
this.noncestr = noncestr;
}
public String getTimestamp() {
return timestamp;
}
public void setTimestamp(String timestamp) {
this.timestamp = timestamp;
}
}
<file_sep>/kulun_coroutine/app/src/main/java/com/kulun/energynet/main/fragment/PromoteFragment.java
package com.kulun.energynet.main.fragment;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import com.kulun.energynet.R;
import com.kulun.energynet.databinding.FragmentPromoteBinding;
import com.kulun.energynet.model.User;
import com.kulun.energynet.network.API;
import com.kulun.energynet.popup.SharePopup;
import com.kulun.energynet.utils.Utils;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.trello.rxlifecycle4.components.support.RxFragment;
public class PromoteFragment extends RxFragment implements Shareinterface {
private FragmentPromoteBinding binding;
private static final int THUMB_SIZE = 150;
private IWXAPI iwxapi;
private SharePopup sharePopup;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_promote, null);
iwxapi = WXAPIFactory.createWXAPI(getContext(), API.wxappid);
binding = DataBindingUtil.bind(view);
binding.webview.getSettings().setUseWideViewPort(true);
binding.webview.getSettings().setLoadWithOverviewMode(true);
binding.webview.loadUrl(API.weburl);
sharePopup = new SharePopup(getContext(), this);
binding.share.setOnClickListener(v -> {
sharePopup.showPopupWindow();
});
return view;
}
private void share(boolean iscircle) {
WXWebpageObject webpage = new WXWebpageObject();
webpage.webpageUrl = API.weburl;
WXMediaMessage msg = new WXMediaMessage(webpage);
msg.title = "微型换电宝—低成本、高回报、专业售后服务";
msg.description = "库仑能网";
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.mipmap.icon);
Bitmap thumbBmp = Bitmap.createScaledBitmap(bmp, THUMB_SIZE, THUMB_SIZE, true);
bmp.recycle();
msg.thumbData = Utils.bmpToByteArray(thumbBmp, true);
SendMessageToWX.Req req = new SendMessageToWX.Req();
req.transaction = buildTransaction("webpage");
req.message = msg;
if (iscircle){
req.scene = mTargetScenecircle;
}else {
req.scene = mTargetSceneothers;
}
iwxapi.sendReq(req);
}
public void onresume() {//promotefragment show
}
private int mTargetScenecircle = SendMessageToWX.Req.WXSceneTimeline;
private int mTargetSceneothers = SendMessageToWX.Req.WXSceneSession;
private String buildTransaction(final String type) {
return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
}
@Override
public void sharetocircle() {
share(true);
}
@Override
public void sharetoothers() {
share(false);
}
}
<file_sep>/kulun_jetpack/app/src/main/java/com/kulun/energynet/model/OssTokenModel.java
package com.kulun.energynet.model;
import java.io.Serializable;
public class OssTokenModel implements Serializable {
// String ak = json.get("AccessKeyId").getAsString();
// String sk = json.get("AccessKeySecret").getAsString();
// String token = json.get("SecurityToken").getAsString();
// String expiration = json.get("Expiration").getAsString();
private String AccessKeyId, AccessKeySecret, SecurityToken, Expiration;
public String getAccessKeyId() {
return AccessKeyId;
}
public void setAccessKeyId(String accessKeyId) {
AccessKeyId = accessKeyId;
}
public String getAccessKeySecret() {
return AccessKeySecret;
}
public void setAccessKeySecret(String accessKeySecret) {
AccessKeySecret = accessKeySecret;
}
public String getSecurityToken() {
return SecurityToken;
}
public void setSecurityToken(String securityToken) {
SecurityToken = securityToken;
}
public String getExpiration() {
return Expiration;
}
public void setExpiration(String expiration) {
Expiration = expiration;
}
}
<file_sep>/kulun_coroutine/app/build.gradle
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
android {
compileSdkVersion 29
buildToolsVersion = '29.0.2'
useLibrary 'org.apache.http.legacy'
defaultConfig {
applicationId "com.kulun.energynet"
minSdkVersion 19
targetSdkVersion 26
versionCode 24
versionName "2.0.4"
testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner'
multiDexEnabled true
signingConfigs {
release {
storeFile file("yuedian.jks")
storePassword "<PASSWORD>"
keyAlias "lansedadao1"
keyPassword "<PASSWORD>"
}
}
lintOptions {
disable 'MissingTranslation'
}
}
buildTypes {
release {
signingConfig signingConfigs.release
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
lintOptions {
checkReleaseBuilds false
abortOnError false
}
}
debug {
signingConfig signingConfigs.release
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
lintOptions {
checkReleaseBuilds false
abortOnError false
}
}
}
buildFeatures {
dataBinding = true
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
encoding "UTF-8"
}
}
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation 'androidx.coordinatorlayout:coordinatorlayout:1.1.0'
testImplementation 'junit:junit:4.13.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
implementation project(path: ':multi-image-selector')
implementation project(path: ':qrcodereaderview')
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
implementation 'com.android.support:design:28.+'
implementation 'com.squareup.okio:okio:2.8.0'
implementation 'com.google.code.gson:gson:2.8.6'
implementation 'com.amap.api:location:5.2.0'
implementation 'com.amap.api:navi-3dmap:7.8.0_3dmap7.8.0'
implementation 'com.amap.api:search:7.7.0'
implementation 'com.github.razerdp:BasePopup:2.2.20'
implementation 'com.scwang.smart:refresh-layout-kernel:2.0.3' //核心必须依赖
implementation 'com.scwang.smart:refresh-header-classics:2.0.3' //经典刷新头
implementation 'com.tencent.mm.opensdk:wechat-sdk-android-without-mta:+'
implementation 'androidx.multidex:multidex:2.0.1'
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'com.google.android.material:material:1.2.0'
implementation 'com.github.limxing:Android-PromptDialog:1.1.3'
implementation 'com.yanzhenjie:permission:2.0.3'
implementation 'com.github.bumptech.glide:glide:4.10.0'
implementation 'com.hjq:toast:8.6'
implementation 'cn.bingoogolapple:bga-qrcode-zxing:1.3.7'
implementation "androidx.constraintlayout:constraintlayout:2.0.1"
implementation 'com.aliyun.dpa:oss-android-sdk:2.9.5'
implementation 'com.contrarywind:wheelview:4.1.0'
implementation 'com.contrarywind:Android-PickerView:4.1.9'
implementation 'com.superluo:textbannerview:1.0.5' //最新版本
//网络请求模块
implementation "com.squareup.okhttp3:okhttp:4.9.0"
implementation 'com.squareup.okhttp3:logging-interceptor:4.7.2'
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:adapter-rxjava3:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
implementation 'io.reactivex.rxjava3:rxandroid:3.0.0'
implementation 'com.trello.rxlifecycle4:rxlifecycle-components:4.0.2'
}
<file_sep>/kulun_coroutine/app/src/main/java/com/kulun/energynet/mine/MyCarActivity.java
package com.kulun.energynet.mine;
import android.content.Intent;
import androidx.databinding.DataBindingUtil;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.kulun.energynet.R;
import com.kulun.energynet.databinding.ActivityMyCarBinding;
import com.kulun.energynet.databinding.AdapterCarBinding;
import com.kulun.energynet.main.BaseActivity;
import com.kulun.energynet.model.Car;
import com.kulun.energynet.model.ResponseModel;
import com.kulun.energynet.model.User;
import com.kulun.energynet.network.InternetWorkManager;
import com.kulun.energynet.network.MyObserver;
import com.kulun.energynet.network.RxHelper;
import com.kulun.energynet.requestbody.SetCurrentCarRequest;
import com.kulun.energynet.requestbody.UnbindCarRequest;
import com.kulun.energynet.network.API;
import com.kulun.energynet.utils.BaseDialog;
import com.kulun.energynet.utils.Mygson;
import com.kulun.energynet.utils.Utils;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.runtime.Permission;
//import org.greenrobot.eventbus.EventBus;
//import org.greenrobot.eventbus.Subscribe;
//import org.greenrobot.eventbus.ThreadMode;
import java.util.ArrayList;
import java.util.List;
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.functions.Consumer;
import io.reactivex.rxjava3.schedulers.Schedulers;
import me.leefeng.promptlibrary.PromptDialog;
public class MyCarActivity extends BaseActivity implements View.OnClickListener {
private ActivityMyCarBinding binding;
private MyAdapter adapter;
private List<Car> list = new ArrayList<>();
private PromptDialog promptDialog;
@Override
public void initView(Bundle savedInstanceState) {
binding = DataBindingUtil.setContentView(this, R.layout.activity_my_car);
binding.header.left.setOnClickListener(this);
binding.header.title.setText("我的车");
binding.header.right.setText("绑定申请");
binding.imgAddCar.setOnClickListener(this);
adapter = new MyAdapter();
binding.recyclerView.setLayoutManager(new LinearLayoutManager(MyCarActivity.this));
binding.recyclerView.setAdapter(adapter);
binding.smartRefresh.setOnRefreshListener(new OnRefreshListener() {
@Override
public void onRefresh(@NonNull RefreshLayout refreshLayout) {
loadData();
}
});
binding.header.right.setOnClickListener(this);
promptDialog = new PromptDialog(this);
}
@Override
protected void onResume() {
super.onResume();
loadData();
}
private void loadData() {
InternetWorkManager.getRequest().carlist()
.compose(RxHelper.observableIOMain(this))
.subscribe(new MyObserver<List<Car>>() {
@Override
public void onSuccess(List<Car> data) {
Utils.finishRefresh(binding.smartRefresh);
list.clear();
if (data != null && data.size() > 0) {
list.addAll(data);
}
adapter.notifyDataSetChanged();
binding.image.setVisibility(list.size() > 0 ? View.GONE : View.VISIBLE);
}
@Override
public void onFail(int code, String message) {
Utils.finishRefresh(binding.smartRefresh);
}
@Override
public void onError() {
Utils.finishRefresh(binding.smartRefresh);
}
@Override
public void onClearToken() {
Utils.toLogin(MyCarActivity.this);
}
});
// new MyRequest().myRequest(API.getmycarlist, false, null, false, this, null, binding.smartRefresh, new Response() {
// @Override
// public void response(JsonObject json, JsonArray jsonArray, boolean isNull) {
// if (jsonArray != null) {
// list.clear();
// list.addAll(Mygson.getInstance().fromJson(jsonArray, new TypeToken<List<Car>>() {
// }.getType()));
// adapter.notifyDataSetChanged();
// binding.image.setVisibility(list.size() > 0 ? View.GONE : View.VISIBLE);
// }
// }
// });
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.left:
finish();
break;
case R.id.img_add_car:
loadinfo();
break;
case R.id.right:
Intent intent1 = new Intent(MyCarActivity.this, CarbindApplyActivity.class);
startActivity(intent1);
break;
}
}
private void loadinfo() {
InternetWorkManager.getRequest().infoGet()
.compose(RxHelper.observableIOMain(this))
.subscribe(new MyObserver<User>() {
@Override
public void onSuccess(User user) {
if (user != null) {
if (!TextUtils.isEmpty(user.getName()) && !TextUtils.isEmpty(user.getIdentity())) {
AndPermission.with(MyCarActivity.this)
.runtime()
.permission(Permission.CAMERA)
.onGranted(permissions -> {
Intent intent = new Intent(MyCarActivity.this, AddCarActivity.class);
startActivity(intent);
})
.onDenied(permissions -> {
// Storage permission are not allowed.
})
.start();
} else {
uploadInfo();
}
}
}
@Override
public void onFail(int code, String message) {
uploadInfo();
}
@Override
public void onError() {
}
@Override
public void onClearToken() {
Utils.toLogin(MyCarActivity.this);
}
});
// new MyRequest().myRequest(API.INFO, false, null, true, this, null, null, new Response() {
// @Override
// public void response(JsonObject json, JsonArray jsonArray, boolean isNull) {
// if (json == null || isNull) {
// uploadInfo();
// return;
// }
// User user = Mygson.getInstance().fromJson(json, User.class);
// if (user != null) {
// if (!TextUtils.isEmpty(user.getName()) && !TextUtils.isEmpty(user.getIdentity())) {
// AndPermission.with(MyCarActivity.this)
// .runtime()
// .permission(Permission.CAMERA)
// .onGranted(permissions -> {
// Intent intent = new Intent(MyCarActivity.this, AddCarActivity.class);
// startActivity(intent);
// })
// .onDenied(permissions -> {
// // Storage permission are not allowed.
// })
// .start();
// } else {
// uploadInfo();
// }
// } else {
// uploadInfo();
// }
// }
// });
}
private void uploadInfo() {
BaseDialog.showDialog(MyCarActivity.this, "温馨提示","请您上传个人信息","确认", new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MyCarActivity.this, PersonalActivity.class);
intent.putExtra(API.register, false);
startActivity(intent);
}
});
}
class MyAdapter extends RecyclerView.Adapter<MyViewHolder> {
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(MyCarActivity.this).inflate(R.layout.adapter_car, parent, false);
AdapterCarBinding adapterCarBinding = DataBindingUtil.bind(view);
MyViewHolder holder = new MyViewHolder(view);
holder.setBinding(adapterCarBinding);
return holder;
}
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
//bind_status=0解绑bind_status=1绑定中bind_status=2解绑中bind_status=3锁定
Car car = list.get(position);
holder.getBinding().name.setText(car.getPlate_number());
holder.getBinding().t1.setText(car.getSoc() + "%");
holder.getBinding().t2.setText(car.getCar_type());
holder.getBinding().t3.setText(car.isBattery_status() ? "正常" : "不正常");
Drawable circledraable = getResources().getDrawable(R.drawable.recharge_choice);
circledraable.setBounds(0, 0, 55, 55);
holder.getBinding().now.setCompoundDrawables(circledraable, null, null, null);
if (car.getBind_status() == 1) {
Drawable drawable = getResources().getDrawable(R.mipmap.sign_binding);
drawable.setBounds(0, 0, 100, 50);
holder.getBinding().name.setCompoundDrawables(null, null, drawable, null);
} else if (car.getBind_status() == 3) {
Drawable drawable = getResources().getDrawable(R.mipmap.sign_lock);
drawable.setBounds(0, 0, 100, 50);
holder.getBinding().name.setCompoundDrawables(null, null, drawable, null);
}
if (car.getMonth_mile() == 0) {
holder.getBinding().progressbar.setVisibility(View.GONE);
holder.getBinding().mile.setVisibility(View.GONE);
} else {
holder.getBinding().mile.setVisibility(View.VISIBLE);
holder.getBinding().progressbar.setVisibility(View.VISIBLE);
holder.getBinding().mile.setText("当前剩余:" + car.getLeft_mile() + " | " + "套餐总量:" + car.getMonth_mile());
holder.getBinding().progressbar.setProgress(car.getLeft_mile() * 100 / car.getMonth_mile());
}
holder.getBinding().now.setOnClickListener(v -> {
dangqian(car.getId());
});
holder.getBinding().unbind.setOnClickListener(v -> {
BaseDialog.showDialog(MyCarActivity.this,"温馨提示", "是否确认解绑","确认", new View.OnClickListener() {
@Override
public void onClick(View v) {
cancelCar(car.getPlate_number());
}
});
});
if (car.isInuse()) {
holder.getBinding().now.setSelected(true);
} else {
holder.getBinding().now.setSelected(false);
}
}
@Override
public int getItemCount() {
return list.size();
}
}
private void dangqian(int id) {
//bind_id
promptDialog.showLoading("正在设为当前车辆");
SetCurrentCarRequest setCurrentCarRequest = new SetCurrentCarRequest();
setCurrentCarRequest.setBind_id(id);
InternetWorkManager.getRequest().setcurrentCar(Utils.body(Mygson.getInstance().toJson(setCurrentCarRequest)))
.compose(RxHelper.observableIOMain(this))
.subscribe(new MyObserver<User>() {
@Override
public void onSuccess(User data) {
loadData();
promptDialog.dismiss();
}
@Override
public void onFail(int code, String message) {
promptDialog.dismiss();
}
@Override
public void onError() {
promptDialog.dismiss();
}
@Override
public void onClearToken() {
Utils.toLogin(MyCarActivity.this);
}
});
// String json = JsonSplice.leftparent + JsonSplice.yin + "bind_id" + JsonSplice.yinandmao + id + JsonSplice.rightparent;
// new MyRequest().spliceJson(API.carnow, true, json, this, promptDialog, null, new Response() {
// @Override
// public void response(JsonObject json, JsonArray jsonArray, boolean isNull) {
// loadData();
// }
// });
}
//bindId[int] 是 绑定ID
private void cancelCar(String plateNo) {
//{
// "plate": "浙ARB104"
//}
promptDialog.showLoading("正在解绑");
// HashMap<String, String> map = new HashMap<>();
// map.put("plate", plateNo);
// new MyRequest().myRequest(API.carunbind, true, map, true, this, promptDialog, null, new Response() {
// @Override
// public void response(JsonObject json, JsonArray jsonArray, boolean isNull) {
// loadData();
// }
// });
UnbindCarRequest unbindCarRequest = new UnbindCarRequest();
unbindCarRequest.setPlate(plateNo);
InternetWorkManager.getRequest().unbindCar(Utils.body(Mygson.getInstance().toJson(unbindCarRequest)))
.compose(RxHelper.observableIOMain(this))
.subscribe(new MyObserver<User>() {
@Override
public void onSuccess(User data) {
Utils.snackbar("申请解绑成功");
promptDialog.dismiss();
loadData();
}
@Override
public void onFail(int code, String message) {
promptDialog.dismiss();
}
@Override
public void onError() {
promptDialog.dismiss();
}
@Override
public void onClearToken() {
Utils.toLogin(MyCarActivity.this);
}
});
}
private class MyViewHolder extends RecyclerView.ViewHolder {
private AdapterCarBinding adapterCarBinding;
public MyViewHolder(View view) {
super(view);
}
public void setBinding(AdapterCarBinding adapterCarBinding) {
this.adapterCarBinding = adapterCarBinding;
}
public AdapterCarBinding getBinding() {
return adapterCarBinding;
}
}
}
<file_sep>/kulun_coroutine/app/src/main/java/com/kulun/energynet/main/MainActivity.java
package com.kulun.energynet.main;
import android.os.Bundle;
import android.view.View;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import com.kulun.energynet.R;
import com.kulun.energynet.databinding.ActivityMainBinding;
import com.kulun.energynet.main.fragment.ListFragment;
import com.kulun.energynet.main.fragment.MainFragment;
import com.kulun.energynet.main.fragment.MineFragment;
import com.kulun.energynet.main.fragment.PromoteFragment;
import com.kulun.energynet.model.User;
import com.kulun.energynet.network.API;
import com.kulun.energynet.utils.Utils;
import com.trello.rxlifecycle4.components.support.RxAppCompatActivity;
public class MainActivity extends RxAppCompatActivity implements View.OnClickListener {
private ActivityMainBinding binding;
private Fragment mainFragment, listFragment, promotefragment, minefragment;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
initFragment();
onclick();
// ImmersionBar.with(this).init();
}
@Override
protected void onResume() {
super.onResume();
//activity onresume fragment show
if (mainFragment != null && !mainFragment.isHidden()) {
((MainFragment) mainFragment).onresume();
}
if (listFragment != null && !listFragment.isHidden()) {
((ListFragment) listFragment).onresume();
}
if (promotefragment != null && !promotefragment.isHidden()) {
((PromoteFragment) promotefragment).onresume();
}
if (minefragment != null && !minefragment.isHidden()) {
((MineFragment) minefragment).onresume();
}
}
private void onclick() {
binding.l1.setOnClickListener(this);
binding.l2.setOnClickListener(this);
binding.l3.setOnClickListener(this);
binding.l4.setOnClickListener(this);
}
private void initFragment() {//初始化activity
if (mainFragment == null) {
mainFragment = new MainFragment();
}
if (promotefragment == null) {
promotefragment = new PromoteFragment();
}
getSupportFragmentManager().beginTransaction()
.add(R.id.content, mainFragment)
.add(R.id.content, promotefragment)
.show(mainFragment)
.hide(promotefragment)
.commitAllowingStateLoss();
binding.mainImage.setImageResource(R.mipmap.main_selected);
binding.mainText.setTextColor(getResources().getColor(R.color.text_color));
}
public void mainScan() {
listtoMainInit();
((MainFragment) mainFragment).scan();
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.l1:
clickMainFragment();
break;
case R.id.l2:
clickListFragment();
break;
case R.id.l3:
clickPromoteFragment();
break;
case R.id.l4:
clickMineFragment();
break;
default:
break;
}
}
private void listtoMainInit() {
if (mainFragment == null) {
mainFragment = new MainFragment();
}
if (mainFragment.isAdded()) {
getSupportFragmentManager().beginTransaction().hide(listFragment).show(mainFragment).commitAllowingStateLoss();
} else {
getSupportFragmentManager().beginTransaction().add(R.id.content, mainFragment).hide(listFragment).show(mainFragment).commitAllowingStateLoss();
}
binding.mainImage.setImageResource(R.mipmap.main_selected);
binding.mainText.setTextColor(getResources().getColor(R.color.text_color));
binding.listImage.setImageResource(R.mipmap.list);
binding.listText.setTextColor(getResources().getColor(R.color.black));
}
private void clickMainFragment() {
hideAll();
if (mainFragment == null) {
mainFragment = new MainFragment();
}
if (mainFragment.isAdded()) {
getSupportFragmentManager().beginTransaction().show(mainFragment).commitAllowingStateLoss();
} else {
getSupportFragmentManager().beginTransaction().add(R.id.content, mainFragment).show(mainFragment).commitAllowingStateLoss();
}
getSupportFragmentManager().beginTransaction().show(mainFragment).commitAllowingStateLoss();
binding.mainImage.setImageResource(R.mipmap.main_selected);
binding.mainText.setTextColor(getResources().getColor(R.color.text_color));
}
private void clickListFragment() {
hideAll();
if (listFragment == null) {
listFragment = new ListFragment();
}
if (listFragment.isAdded()) {
getSupportFragmentManager().beginTransaction().show(listFragment).commitAllowingStateLoss();
} else {
getSupportFragmentManager().beginTransaction().add(R.id.content, listFragment).show(listFragment).commitAllowingStateLoss();
}
binding.listImage.setImageResource(R.mipmap.list_selected);
binding.listText.setTextColor(getResources().getColor(R.color.text_color));
}
private void clickPromoteFragment() {
hideAll();
if (promotefragment == null) {
promotefragment = new PromoteFragment();
}
if (promotefragment.isAdded()) {
getSupportFragmentManager().beginTransaction().show(promotefragment).commitAllowingStateLoss();
} else {
getSupportFragmentManager().beginTransaction().add(R.id.content, promotefragment).show(promotefragment).commitAllowingStateLoss();
}
binding.promoteImage.setImageResource(R.mipmap.promote_selected);
binding.promoteText.setTextColor(getResources().getColor(R.color.text_color));
}
private void clickMineFragment() {
hideAll();
if (minefragment == null) {
minefragment = new MineFragment();
}
if (minefragment.isAdded()) {
getSupportFragmentManager().beginTransaction().show(minefragment).commitAllowingStateLoss();
} else {
getSupportFragmentManager().beginTransaction().add(R.id.content, minefragment).show(minefragment).commitAllowingStateLoss();
}
binding.mineImage.setImageResource(R.mipmap.mine_selected);
binding.mineText.setTextColor(getResources().getColor(R.color.text_color));
}
public void listomainFragmentClickAdapterReserver() {//listadapter click reserver
listtoMainInit();
if (mainFragment != null) {
((MainFragment) mainFragment).getcurrentAppint();
}
}
private void hideAll() {
for (Fragment fragment : getSupportFragmentManager().getFragments()) {
if (fragment.isAdded() && !fragment.isHidden()) {
getSupportFragmentManager().beginTransaction().hide(fragment).commitAllowingStateLoss();
}
}
clearTextAndcolor();
}
private void clearTextAndcolor() {
binding.mainImage.setImageResource(R.mipmap.main);
binding.listImage.setImageResource(R.mipmap.list);
binding.promoteImage.setImageResource(R.mipmap.promote);
binding.mineImage.setImageResource(R.mipmap.mine);
binding.mainText.setTextColor(getResources().getColor(R.color.black));
binding.listText.setTextColor(getResources().getColor(R.color.black));
binding.promoteText.setTextColor(getResources().getColor(R.color.black));
binding.mineText.setTextColor(getResources().getColor(R.color.black));
}
}
<file_sep>/kulun_coroutine/app/src/main/java/com/kulun/energynet/requestbody/InfoRequest.java
package com.kulun.energynet.requestbody;
public class InfoRequest {
// map.put("name", name);
// map.put("identity", id);
private String name, identity;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getIdentity() {
return identity;
}
public void setIdentity(String identity) {
this.identity = identity;
}
}
<file_sep>/kulun_coroutine/app/src/main/java/com/kulun/energynet/requestbody/ReservationRequest.java
package com.kulun.energynet.requestbody;
public class ReservationRequest {
private double longitude, latitude;
private int battery_cnt, city_id;
public double getLongitude() {
return longitude;
}
public void setLongitude(double longitude) {
this.longitude = longitude;
}
public double getLatitude() {
return latitude;
}
public void setLatitude(double latitude) {
this.latitude = latitude;
}
public int getBattery_cnt() {
return battery_cnt;
}
public void setBattery_cnt(int battery_cnt) {
this.battery_cnt = battery_cnt;
}
public int getCity_id() {
return city_id;
}
public void setCity_id(int city_id) {
this.city_id = city_id;
}
}
<file_sep>/kulun_jetpack/app/src/main/java/com/kulun/energynet/mine/PersonalActivity.java
package com.kulun.energynet.mine;
import androidx.databinding.DataBindingUtil;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import com.kulun.energynet.R;
import com.kulun.energynet.databinding.ActivityPersonalBinding;
import com.kulun.energynet.main.BaseActivity;
import com.kulun.energynet.model.User;
import com.kulun.energynet.network.InternetWorkManager;
import com.kulun.energynet.network.MyObserver;
import com.kulun.energynet.network.RxHelper;
import com.kulun.energynet.requestbody.InfoRequest;
import com.kulun.energynet.network.API;
import com.kulun.energynet.utils.Mygson;
import com.kulun.energynet.utils.Utils;
/**
* created by xuedi on 2019/8/28
*/
public class PersonalActivity extends BaseActivity {
private ActivityPersonalBinding binding;
private boolean isRegister;
@Override
public void initView(Bundle savedInstanceState) {
binding = DataBindingUtil.setContentView(this, R.layout.activity_personal);
binding.title.left.setOnClickListener(view -> {
if (isRegister) {
Utils.userParse(this);
} else {
finish();
}
});
binding.tvConfrim.setOnClickListener(view -> {
String name = binding.etName.getText().toString();
String id = binding.etId.getText().toString();
if (TextUtils.isEmpty(name)) {
Utils.snackbar(PersonalActivity.this, "请填写姓名");
return;
}
if (TextUtils.isEmpty(id)) {
Utils.snackbar(PersonalActivity.this, "身份证号码为空");
return;
}
if (!Utils.IDCardValidate(id)) {
Utils.snackbar(PersonalActivity.this, "身份证号格式不正确");
return;
}
postData(name, id);
});
isRegister = getIntent().getBooleanExtra(API.register, false);
loadData();
}
private void loadData() {
InternetWorkManager.getRequest().infoGet()
.compose(RxHelper.observableIOMain(this))
.subscribe(new MyObserver<User>() {
@Override
public void onSuccess(User user) {
if (user != null) {
if (!user.getName().equals("") && !user.getIdentity().equals("")) {
binding.etName.setText(user.getName());
binding.etId.setText(user.getIdentity());
binding.etName.setTextColor(getResources().getColor(R.color.reserverunfinish));
binding.etId.setTextColor(getResources().getColor(R.color.reserverunfinish));
binding.etName.setEnabled(false);
binding.etId.setEnabled(false);
binding.tvConfrim.setVisibility(View.GONE);
}
}
}
@Override
public void onFail(int code, String message) {
}
@Override
public void onError() {
}
@Override
public void onClearToken() {
Utils.toLogin(PersonalActivity.this);
}
});
// new MyRequest().myRequest(API.INFO, false, null, true, this, null, null, new Response() {
// @Override
// public void response(JsonObject json, JsonArray jsonArray, boolean isNull) {
// if (json != null || jsonArray != null) {
// User user = Mygson.getInstance().fromJson(json, User.class);
// if (user != null) {
// if (!user.getName().equals("") && !user.getIdentity().equals("")) {
// binding.etName.setText(user.getName());
// binding.etId.setText(user.getIdentity());
// binding.etName.setTextColor(getResources().getColor(R.color.reserverunfinish));
// binding.etId.setTextColor(getResources().getColor(R.color.reserverunfinish));
// binding.etName.setEnabled(false);
// binding.etId.setEnabled(false);
// binding.tvConfrim.setVisibility(View.GONE);
// }
// }
// }
// }
// });
}
//{
// "name": "名字修改",
// "identity": "1221221121121"
//}
private void postData(String name, String id) {
InfoRequest infoRequest = new InfoRequest();
infoRequest.setName(name);
infoRequest.setIdentity(id);
InternetWorkManager.getRequest().infoPost(Utils.body(Mygson.getInstance().toJson(infoRequest)))
.compose(RxHelper.observableIOMain(this))
.subscribe(new MyObserver<User>() {
@Override
public void onSuccess(User data) {
Utils.snackbar(PersonalActivity.this, "个人信息上传成功");
if (isRegister) {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
Utils.userParse(PersonalActivity.this);
}
}, 500);
} else {
finish();
}
}
@Override
public void onFail(int code, String message) {
}
@Override
public void onError() {
}
@Override
public void onClearToken() {
Utils.toLogin(PersonalActivity.this);
}
});
// HashMap<String, String> map = new HashMap<>();
// map.put("name", name);
// map.put("identity", id);
// new MyRequest().myRequest(API.INFO, true, map, true, this, null, null, new Response() {
// @Override
// public void response(JsonObject json, JsonArray jsonArray, boolean isNull) {
// Utils.snackbar(PersonalActivity.this, "个人信息上传成功");
// if (isRegister) {
// new Handler().postDelayed(new Runnable() {
// @Override
// public void run() {
// Utils.userParse(PersonalActivity.this);
// }
// }, 500);
// } else {
// finish();
// }
// }
// });
}
}
<file_sep>/kulun_coroutine/app/src/main/java/com/kulun/energynet/model/QuestionshowModel.java
package com.kulun.energynet.model;
import java.io.Serializable;
public class QuestionshowModel implements Serializable {
// if (json.has("content")){
// if (json.has("handleContent")){
// binding.fankui.setText("反馈:"+json.get("handleContent").getAsString());
// }
// if (json.has("status")){
// }
private String content, handleContent;
private int status;
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getHandleContent() {
return handleContent;
}
public void setHandleContent(String handleContent) {
this.handleContent = handleContent;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
}
<file_sep>/kulun_coroutine/app/src/main/java/com/kulun/energynet/mine/SystemSettingActivity.java
package com.kulun.energynet.mine;
import android.content.Intent;
import androidx.databinding.DataBindingUtil;
import android.os.Bundle;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.kulun.energynet.R;
import com.kulun.energynet.databinding.ActivitySystemSettingBinding;
import com.kulun.energynet.login.PasswordLoginActivity;
import com.kulun.energynet.main.BaseActivity;
import com.kulun.energynet.model.ResponseModel;
import com.kulun.energynet.model.User;
import com.kulun.energynet.network.InternetWorkManager;
import com.kulun.energynet.network.MyObserver;
import com.kulun.energynet.network.RxHelper;
import com.kulun.energynet.requestparams.Response;
import com.kulun.energynet.network.API;
import com.kulun.energynet.requestparams.MyRequest;
import com.kulun.energynet.utils.SharePref;
import com.kulun.energynet.utils.Utils;
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.functions.Consumer;
import io.reactivex.rxjava3.schedulers.Schedulers;
public class SystemSettingActivity extends BaseActivity {
private ActivitySystemSettingBinding binding;
private long time;
//private String apkpat
@Override
public void initView(Bundle savedInstanceState) {
binding = DataBindingUtil.setContentView(this ,R.layout.activity_system_setting);
binding.title.setText("设置");
//apkpath = getIntent().getStringExtra(API.apppath);
binding.left.setOnClickListener(view -> finish());
binding.rePersonl.setOnClickListener(view -> {
Intent intent = new Intent(SystemSettingActivity.this, PersonalActivity.class);
intent.putExtra(API.register, false);
startActivity(intent);
});
binding.reChangePassword.setOnClickListener(view -> {
Intent intent = new Intent(SystemSettingActivity.this,ChangePasswordActivity.class);
startActivity(intent);
});
binding.tvLoginOut.setOnClickListener(view -> {
if (Utils.isFastClick()){
Utils.snackbar( SystemSettingActivity.this, "点击过快");
return;
}
loginOut();
});
}
private void loginOut() {
InternetWorkManager.getRequest().logout()
.compose(RxHelper.observableIOMain(SystemSettingActivity.this))
.subscribe(new MyObserver<User>() {
@Override
public void onSuccess(User data) {
Intent intent = new Intent(SystemSettingActivity.this, PasswordLoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
User.getInstance().setToken("");
SharePref.put(SystemSettingActivity.this, API.token, "");
SharePref.clear(SystemSettingActivity.this);
startActivity(intent);
finish();
}
@Override
public void onFail(int code, String message) {
}
@Override
public void onError() {
}
@Override
public void onClearToken() {
Utils.toLogin(SystemSettingActivity.this);
}
});
// new MyRequest().myRequest(API.LOGINOUT, true,null,true,this, null, null, new Response() {
// @Override
// public void response(JsonObject json, JsonArray jsonArray,boolean isNull) {
// Intent intent = new Intent(SystemSettingActivity.this, PasswordLoginActivity.class);
// intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
// User.getInstance().setToken("");
// SharePref.put(SystemSettingActivity.this, API.token, "");
// SharePref.clear(SystemSettingActivity.this);
// startActivity(intent);
// finish();
// }
// });
}
}<file_sep>/kulun_coroutine/app/src/main/java/com/kulun/energynet/model/CurrentAppointmentModel.java
package com.kulun.energynet.model;
public class CurrentAppointmentModel {
private String appointment_no, end_time;
private int site_id;
public String getAppointment_no() {
return appointment_no;
}
public void setAppointment_no(String appointment_no) {
this.appointment_no = appointment_no;
}
public String getEnd_time() {
return end_time;
}
public void setEnd_time(String end_time) {
this.end_time = end_time;
}
public int getSite_id() {
return site_id;
}
public void setSite_id(int site_id) {
this.site_id = site_id;
}
}
<file_sep>/kulun_coroutine/app/src/main/java/com/kulun/energynet/main/fragment/MineFragment.java
package com.kulun.energynet.main.fragment;
import android.content.Intent;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.kulun.energynet.R;
import com.kulun.energynet.bill.BillActivity;
import com.kulun.energynet.databinding.FragmentMineBinding;
import com.kulun.energynet.mine.AppointmentKtActivity;
import com.kulun.energynet.mine.CouponKtActivity;
import com.kulun.energynet.mine.DriverclockActivity;
import com.kulun.energynet.mine.MessageActivity;
import com.kulun.energynet.mine.MyCarActivity;
import com.kulun.energynet.mine.PackageListActivity;
import com.kulun.energynet.mine.RechargeActivity;
import com.kulun.energynet.mine.SystemSettingActivity;
import com.kulun.energynet.model.UseBind;
import com.kulun.energynet.model.User;
import com.kulun.energynet.network.InternetWorkManager;
import com.kulun.energynet.network.MyObserver;
import com.kulun.energynet.network.RxHelper;
import com.kulun.energynet.utils.BaseDialog;
import com.kulun.energynet.utils.Utils;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.trello.rxlifecycle4.components.support.RxFragment;
public class MineFragment extends RxFragment implements View.OnClickListener {
private FragmentMineBinding binding;
private UseBind useBind;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_mine, null);
binding = DataBindingUtil.bind(view);
bindClick();
binding.smartRefresh.setOnRefreshListener(new OnRefreshListener() {
@Override
public void onRefresh(@NonNull RefreshLayout refreshLayout) {
loadData();
}
});
loadData();
// StateAppBar.setStatusBarColor(getActivity(), getResources().getColor(R.color.text_color));
// ImmersionBar.with(this).init();
return view;
}
@Override
public void onHiddenChanged(boolean hidden) {
super.onHiddenChanged(hidden);
if (!hidden){//fragment show
onresume();
}
}
public void onresume(){//fragment show
loadData();
}
private void loadData() {
InternetWorkManager.getRequest().infoGet()
.compose(RxHelper.observableIOMain(getActivity()))
.subscribe(new MyObserver<User>() {
@Override
public void onSuccess(User user) {
Utils.finishRefresh(binding.smartRefresh);
if (user == null) return;
Utils.shareprefload(user, getActivity());
if (user.getUse_bind() != null && user.getUse_bind().getId() != 0) {
binding.reCar.setVisibility(View.VISIBLE);
binding.name.setText(user.getUse_bind().getPlate_number() + "");
if (user.getUse_bind().getBind_status() == 1) {
Drawable drawable = getResources().getDrawable(R.mipmap.sign_binding);
drawable.setBounds(0, 0, 100, 50);
binding.name.setCompoundDrawables(null, null, drawable, null);
} else if (user.getUse_bind().getBind_status() == 3) {
Drawable drawable = getResources().getDrawable(R.mipmap.sign_lock);
drawable.setBounds(0, 0, 100, 50);
binding.name.setCompoundDrawables(null, null, drawable, null);
}
binding.t1.setText(user.getUse_bind().getSoc() + "%");
binding.t2.setText(user.getUse_bind().getCar_type());
binding.t3.setText(user.getUse_bind().isBattery_status() ? "正常" : "不正常");
} else {
binding.reCar.setVisibility(View.INVISIBLE);
}
if (user.getUnread() > 0) {
binding.ivMsg.setImageDrawable(getResources().getDrawable(R.mipmap.mine_message_news));
} else {
binding.ivMsg.setImageDrawable(getResources().getDrawable(R.mipmap.mine_message_normal));
}
if (user.getName() == null || user.getName().equals("")) {
binding.tvName.setText("我");
} else {
binding.tvName.setText(user.getName() + "");
}
if (user.getBalance() > 0) {
binding.tvYue.setText("" + user.getBalance());
} else {
binding.tvYue.setText("0");
}
BaseDialog.createQRCodeWithLogo(binding.imgQrcode, getContext(),false, Utils.getAccount(getActivity()), 80);
useBind = user.getUse_bind();
}
@Override
public void onFail(int code, String message) {
Utils.finishRefresh(binding.smartRefresh);
}
@Override
public void onError() {
Utils.finishRefresh(binding.smartRefresh);
}
@Override
public void onClearToken() {
Utils.toLogin(getActivity());
}
});
// new MyRequest().myRequest(API.INFO, false, null, true, this, null, binding.smartRefresh, new Response() {
// @Override
// public void response(JsonObject json, JsonArray jsonArray,boolean isNull) {
// // "name": "王霞",
// // "balance": 700.14
// Utils.shareprefload(json, MineActivity.this);
// useBind = Utils.getusebind( MineActivity.this);
// if (useBind !=null && useBind.getId() != 0) {
// binding.reCar.setVisibility(View.VISIBLE);
// binding.name.setText(useBind.getPlate_number() + "");
// if (useBind.getBind_status()==1){
// Drawable drawable = getResources().getDrawable(R.mipmap.sign_binding);
// drawable.setBounds(0, 0, 100, 50);
// binding.name.setCompoundDrawables(null,null,drawable,null);
// }else if (useBind.getBind_status()==3){
// Drawable drawable = getResources().getDrawable(R.mipmap.sign_lock);
// drawable.setBounds(0, 0, 100, 50);
// binding.name.setCompoundDrawables(null,null,drawable,null);
// }
// binding.t1.setText(useBind.getSoc() + "%");
// binding.t2.setText(useBind.getCar_type());
// binding.t3.setText(useBind.isBattery_status() ? "正常" : "不正常");
// } else {
// binding.reCar.setVisibility(View.INVISIBLE);
// }
// if (json != null) {
// User user = Mygson.getInstance().fromJson(json, User.class);
// if (user.getUnread() > 0){
// binding.ivMsg.setImageDrawable(getResources().getDrawable(R.mipmap.mine_message_news));
// }else {
// binding.ivMsg.setImageDrawable(getResources().getDrawable(R.mipmap.mine_message_normal));
// }
// if (user.getName() == null || user.getName().equals("")) {
// binding.tvName.setText("我");
// }else {
// binding.tvName.setText(user.getName()+"");
// }
// if (user.getBalance() > 0) {
// binding.tvYue.setText("余额:" + user.getBalance());
// } else {
// binding.tvYue.setText("余额:0.00");
// }
// BaseDialog.createQRCodeWithLogo(binding.imgQrcode, MineActivity.this, Utils.getAccount(MineActivity.this), 80);
// }
// }
// });
}
// public static int dip2px(Context context, float dpValue) {
// final float scale = context.getResources().getDisplayMetrics().density;
// return (int) (dpValue * scale + 0.5f);
// }
private void bindClick() {
binding.imgQrcode.setOnClickListener(new MyClickListener(getActivity(), this));
binding.ivMsg.setOnClickListener(new MyClickListener(getActivity(), this));
binding.recharge.setOnClickListener(new MyClickListener(getActivity(), this));
binding.bill.setOnClickListener(new MyClickListener(getActivity(), this));
binding.binding.setOnClickListener(new MyClickListener(getActivity(), this));
binding.activity.setOnClickListener(new MyClickListener(getActivity(), this));
binding.coupon.setOnClickListener(new MyClickListener(getActivity(), this));
binding.reservation.setOnClickListener(new MyClickListener(getActivity(), this));
binding.clock.setOnClickListener(new MyClickListener(getActivity(), this));
binding.setting.setOnClickListener(new MyClickListener(getActivity(), this));
binding.tvName.setOnClickListener(new MyClickListener(getActivity(), this));
binding.customer.setOnClickListener(this);
Drawable drawable = getResources().getDrawable(R.mipmap.arrow_right);
drawable.setBounds(0,0,15,27);
binding.bill.setCompoundDrawables(null,null,drawable,null);
}
@Override
public void onClick(View view) {
Intent intent = null;
switch (view.getId()) {
case R.id.iv_msg:
intent = new Intent(getActivity(), MessageActivity.class);
startActivity(intent);
break;
case R.id.recharge:
intent = new Intent(getActivity(), RechargeActivity.class);
startActivity(intent);
break;
case R.id.binding:
intent = new Intent(getActivity(), MyCarActivity.class);
startActivity(intent);
break;
case R.id.reservation:
intent = new Intent(getActivity(), AppointmentKtActivity.class);
startActivity(intent);
break;
case R.id.coupon:
intent = new Intent(getActivity(), CouponKtActivity.class);
startActivity(intent);
break;
case R.id.clock:
if (Utils.usebindisNotexist(useBind)) {
Utils.snackbar(getActivity(), "请先绑定车辆");
return;
}
if (useBind.getBusiness_type() != 5) {//5是出租车司机
Utils.snackbar(getActivity(), "抱歉,此功能只适用于出租车");
return;
}
intent = new Intent(getActivity(), DriverclockActivity.class);
startActivity(intent);
break;
case R.id.bill:
intent = new Intent(getActivity(), BillActivity.class);
startActivity(intent);
break;
case R.id.activity:
intent = new Intent(getActivity(), PackageListActivity.class);
startActivity(intent);
break;
case R.id.setting:
intent = new Intent(getActivity(), SystemSettingActivity.class);
startActivity(intent);
break;
case R.id.img_qrcode:
String carplate = "";
if (Utils.usebindisNotexist(useBind)) {
carplate = "";
} else {
carplate = useBind.getPlate_number();
}
BaseDialog.showQrDialog(getActivity(), carplate);
break;
case R.id.customer:
Utils.loadkefu(getActivity(), binding.customer);
break;
default:
break;
}
}
}
<file_sep>/kulun_jetpack/app/src/main/java/com/kulun/energynet/main/fragment/Shareinterface.java
package com.kulun.energynet.main.fragment;
public interface Shareinterface {
void sharetocircle();
void sharetoothers();
}
<file_sep>/kulun_coroutine/app/src/main/java/com/kulun/energynet/main/fragment/MainFragment.java
package com.kulun.energynet.main.fragment;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import androidx.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.maps.model.Poi;
import com.amap.api.navi.AmapNaviPage;
import com.amap.api.navi.AmapNaviParams;
import com.amap.api.navi.AmapNaviType;
import com.amap.api.navi.AmapPageType;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.kulun.energynet.R;
import com.kulun.energynet.bill.BillActivity;
import com.kulun.energynet.customizeView.PromotionCarSelect;
//import com.kulun.energynet.customizeView.ShakeListener;
import com.kulun.energynet.databinding.StationBaoAllPopupBinding;
import com.kulun.energynet.model.ResponseModel;
import com.kulun.energynet.popup.StationBaoAllPopup;
import com.kulun.energynet.popup.StationOtherCitiesPopup;
import com.kulun.energynet.popup.StationPopup;
import com.kulun.energynet.customizeView.TimeFinishInterface;
import com.kulun.energynet.databinding.FragmentMainBinding;
import com.kulun.energynet.login.PrivacyActivity;
import com.kulun.energynet.login.UseProtocolActivity;
import com.kulun.energynet.main.ChoseCityActivity;
import com.kulun.energynet.main.StationSelectFragment;
import com.kulun.energynet.main.TimeCount;
import com.kulun.energynet.main.UpdateManager;
import com.kulun.energynet.mine.DriverclockActivity;
import com.kulun.energynet.mine.MapCustomActivity;
import com.kulun.energynet.mine.MessageActivity;
import com.kulun.energynet.mine.MyCarActivity;
import com.kulun.energynet.mine.PackageListActivity;
import com.kulun.energynet.mine.RechargeActivity;
import com.kulun.energynet.mine.ScanActivity;
import com.kulun.energynet.model.Appload;
import com.kulun.energynet.model.City;
import com.kulun.energynet.model.ConsumeListModel;
import com.kulun.energynet.model.CurrentAppointmentModel;
import com.kulun.energynet.model.Message;
import com.kulun.energynet.model.StationAll;
import com.kulun.energynet.model.StationInfo;
import com.kulun.energynet.model.UseBind;
import com.kulun.energynet.model.User;
import com.kulun.energynet.network.InternetWorkManager;
import com.kulun.energynet.network.MyObserver;
import com.kulun.energynet.network.RxHelper;
import com.kulun.energynet.popup.ScanPopup;
import com.kulun.energynet.requestbody.AddAppointmentRequest;
import com.kulun.energynet.requestbody.CancelAppointmentRequest;
import com.kulun.energynet.requestbody.ConsumeRequest;
import com.kulun.energynet.requestbody.ReservationRequest;
import com.kulun.energynet.requestbody.SiteRequest;
import com.kulun.energynet.network.API;
import com.kulun.energynet.utils.BaseDialog;
import com.kulun.energynet.utils.DateUtils;
import com.kulun.energynet.utils.GpsUtil;
import com.kulun.energynet.utils.Mygson;
import com.kulun.energynet.utils.ListUtils;
import com.kulun.energynet.utils.SharePref;
import com.kulun.energynet.utils.Utils;
import com.superluo.textbannerlibrary.ITextBannerItemClickListener;
import com.trello.rxlifecycle4.components.support.RxFragment;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.runtime.Permission;
import java.io.Serializable;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
import static com.yanzhenjie.permission.runtime.Permission.ACCESS_FINE_LOCATION;
import static com.yanzhenjie.permission.runtime.Permission.CAMERA;
import static com.yanzhenjie.permission.runtime.Permission.WRITE_EXTERNAL_STORAGE;
public class MainFragment extends RxFragment implements View.OnClickListener, PromotionCarSelect, TimeFinishInterface {
private PrivacyDialog privacyDialog;
private FragmentMainBinding binding;
private UseBind useBind;
public AMapLocationClient mLocationClient = null;
public AMapLocationClientOption mLocationOption = null;
private AMap aMap;
private List<StationInfo> stationlist = new ArrayList<>();
private List<Marker> markerList = new ArrayList<>();
private final int REQUESTCODE_MAIN = 64, REQUESTCODE_SCAN = 1003, REQUESTCODE_GPS = 1010;
private TimeCount timeCount;
private StationSelectFragment stationSelectFragment;
private GeocodeSearch geocodeSearch;
private UpdateManager updateManager;
private static BitmapDescriptor bitmap = null;
private StationPopup stationPopup;
private StationOtherCitiesPopup stationOtherCitiesPopup;
private StationBaoAllPopup stationBaoAllPopup;
private String appointment_no;
private ScanPopup scanPopup;
private int cityid;
private List<StationAll> stationAllList = new ArrayList<>();
private MainFragment mainFragment;
public AMapLocationListener mLocationListener = new AMapLocationListener() {//
@Override
public void onLocationChanged(AMapLocation amapLocation) {
if (amapLocation != null) {
if (amapLocation.getErrorCode() == 0) {
if (TextUtils.isEmpty(amapLocation.getCity())) {
//有些机型上地位获取到的城市等信息为空,需要根据经纬度查找城市
getAddressByLatLng(amapLocation.getLatitude(), amapLocation.getLongitude());
} else {
if (amapLocation.getLatitude() != 0 && amapLocation.getLongitude() != 0) {
locateInit(amapLocation.getLatitude(), amapLocation.getLongitude());
}
if (!amapLocation.getCity().isEmpty()) {
User.getInstance().setCityName(amapLocation.getCity());
SharePref.put(getActivity(), API.cityName, amapLocation.getCity());
binding.tvCity.setText(amapLocation.getCity());
}
Utils.log(null, "", amapLocation.getCity() + "定位地址" + amapLocation.getCityCode() + amapLocation.getErrorCode() + amapLocation.getErrorInfo() + amapLocation.getLatitude() + amapLocation.getLongitude());
refreshMap(User.getInstance().getLatitude(getActivity()), User.getInstance().getLongtitude(getActivity()));
loadCity(User.getInstance().getLatitude(getActivity()), User.getInstance().getLongtitude(getActivity()), binding.tvCity.getText().toString());
}
} else {
User.getInstance().setCityName("");
//定位失败时,可通过ErrCode(错误码)信息来确定失败的原因,errInfo是错误信息,详见错误码表。
Log.d(Utils.TAG, "location Error, ErdrCode:"
+ amapLocation.getErrorCode() + ", errInfo:"
+ amapLocation.getErrorInfo());
}
}
}
};
private void loadCity(double latitude, double longtitude, String city) {
InternetWorkManager.getRequest().citylist()
.compose(RxHelper.observableIOMain(getActivity()))
.subscribe(new MyObserver<List<City>>() {
@Override
public void onSuccess(List<City> data) {
int position = Utils.getCityPosition(data, city);
if (position != -1) {
cityid = data.get(position).getId();
User.getInstance().setCityid(cityid);
SharePref.put(getActivity(), API.cityId, cityid + "");
loadStation(longtitude, latitude, -1, cityid);
}
}
@Override
public void onFail(int code, String message) {
}
@Override
public void onError() {
}
@Override
public void onClearToken() {
Utils.toLogin(getActivity());
}
});
// new MyRequest().myRequest(API.CITYLIST, false, null, false, getActivity(), null, null, new Response() {
// @Override
// public void response(JsonObject json, JsonArray jsonArray, boolean isNull) {
// List<City> cityList = Mygson.getInstance().fromJson(jsonArray, new TypeToken<List<City>>() {
// }.getType());
// int position = Utils.getCityPosition(cityList, city);
// if (position != -1) {
// cityid = cityList.get(position).getId();
// User.getInstance().setCityid(cityid);
// SharePref.put(MainActivity.getActivity(), API.cityId, cityid + "");
// loadStation(longtitude, latitude, -1, cityid);
// }
// }
// });
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, null);
binding = DataBindingUtil.bind(view);
appload();
if (!(boolean) SharePref.oneget(getActivity(), "agree", false)) {
if (privacyDialog == null) {
privacyDialog = new PrivacyDialog(getActivity(), R.style.mydialog);
privacyDialog.show();
}
}
binding.mapview.onCreate(savedInstanceState);
aMap = binding.mapview.getMap();
aMap.getUiSettings().setZoomControlsEnabled(false);
aMap.setOnMarkerClickListener(markerClickListener);
aMap.setOnCameraChangeListener(new AMap.OnCameraChangeListener() {
@Override
public void onCameraChange(CameraPosition cameraPosition) {
}
@Override
public void onCameraChangeFinish(CameraPosition cameraPosition) {
float a = cameraPosition.zoom;
Utils.log("", "", a + "");
if (a <= 9 && stationAllList.size() == 0) {
loadAllstation();
}
}
});
mLocationClient = new AMapLocationClient(getContext());
init();
binding.finish.setOnClickListener(v -> {
reservation();
});
binding.image2.setOnClickListener(v -> binding.message.setVisibility(View.GONE));
binding.banner.setItemOnClickListener(new ITextBannerItemClickListener() {
@Override
public void onItemClick(String data, int position) {
Intent intent = new Intent(getActivity(), MessageActivity.class);
startActivity(intent);
}
});
stationPopup = new StationPopup(getActivity(), binding.cardview);
stationOtherCitiesPopup = new StationOtherCitiesPopup(getActivity(), binding.cardview);
stationBaoAllPopup = new StationBaoAllPopup(getContext());
mainFragment = this;
return view;
}
public void reservation() {//一键预约
if (Utils.getToken(getActivity()) == null || Utils.getToken(getActivity()).equals("")) {
Utils.toLogin(getActivity());
Utils.snackbar(getActivity(), "请先登陆");
return;
}
if (stationlist.size() == 0) {
Utils.snackbar(getActivity(), "请等待站点刷新");
return;
}
if (Utils.usebindisNotexist(useBind)) {
Utils.snackbar(getActivity(), "请选择当前车辆");
return;
}
ReservationRequest reservationRequest = new ReservationRequest();
if (User.getInstance().getMylatitude(getActivity()) == 0) {//当前没有定位到
reservationRequest.setLongitude(User.getInstance().getLongtitude(getActivity()));
reservationRequest.setLatitude(User.getInstance().getLatitude(getActivity()));
} else {
reservationRequest.setLongitude(User.getInstance().getMylongtitude(getActivity()));
reservationRequest.setLatitude(User.getInstance().getMylatitude(getActivity()));
}
reservationRequest.setBattery_cnt(useBind.getBattery_count());
reservationRequest.setCity_id(User.getInstance().getCityid(getActivity()));
InternetWorkManager.getRequest()
.reservation(Utils.body(Mygson.getInstance().toJson(reservationRequest)))
.compose(RxHelper.observableIOMain(getActivity()))
.subscribe(new MyObserver<StationInfo>() {
@Override
public void onSuccess(StationInfo stationInfo) {
showPopDialog(stationInfo);
if (stationPopup != null) {
stationPopup.setStation(stationInfo);
}
}
@Override
public void onFail(int code, String message) {
}
@Override
public void onError() {
}
@Override
public void onClearToken() {
Utils.toLogin(getActivity());
}
});
}
private void loadAllstation() {//加载全部站点 /api/site/all?exclude=320200 全国站点
InternetWorkManager.getRequest().sitelistall(cityid)
.compose(RxHelper.observableIOMain(getActivity()))
.subscribe(new MyObserver<List<StationAll>>() {
@Override
public void onSuccess(List<StationAll> data) {
stationAllList.addAll(data);
markerAllCreate(stationAllList, null);
}
@Override
public void onFail(int code, String message) {
}
@Override
public void onError() {
}
@Override
public void onClearToken() {
Utils.toLogin(getActivity());
}
});
// String json = "exclude=" + cityid;
// new MyRequest().spliceJson(API.siteall, false, json, getActivity(), null, null, new Response() {
// @Override
// public void response(JsonObject json, JsonArray jsonArray, boolean isNull) {
// if (jsonArray != null) {
// stationAllList.addAll(Mygson.getInstance().fromJson(jsonArray, new TypeToken<List<StationAll>>() {
// }.getType()));
// markerAllCreate(stationAllList, null);
// }
// }
// });
}
//app加载信息
private void appload() {
InternetWorkManager.getRequest().appinfo()
.compose(RxHelper.observableIOMain(getActivity()))
.subscribe(new MyObserver<List<Appload>>() {
@Override
public void onSuccess(List<Appload> data) {
List<Appload> list = data;
String workTime = "", workDay = "", url = "", latestversion = "";
boolean isforce = false;
for (int i = 0; i < list.size(); i++) {
Appload appload = list.get(i);
if (appload.getName().equals("serviceLine") && !appload.getRemark().equals("")) {
String phone = appload.getRemark();
User.getInstance().setCustphone(phone);
SharePref.put(getActivity(), API.customphone, phone);
}
if (appload.getName().equals("workDay") && !appload.getRemark().equals("")) {
workDay = appload.getRemark();
}
if (appload.getName().equals("workTime") && !appload.getRemark().equals("")) {
workTime = appload.getRemark();
}
if (appload.getName().equals("androidLink") && !appload.getRemark().equals("")) {
url = appload.getRemark();
}
if (appload.getName().equals("forceUpdateAndroid") && !appload.getRemark().equals("")) {//强制是1 不强制是0
isforce = appload.getRemark().equals("1") ? true : false;
}
if (appload.getName().equals("latestVersionAndroid") && !appload.getRemark().equals("")) {
latestversion = appload.getRemark();
}
}
if (!url.equals("") && !latestversion.equals("")) {
updateManager = new UpdateManager(mainFragment, getActivity(), latestversion, url);
updateManager.checkUpdate(isforce, "有新版本APP需要更新");
}
if (!"".equals(workTime) && !"".equals(workDay)) {
User.getInstance().setCustinfo(workTime + "\n" + workDay);
SharePref.put(getActivity(), API.custominfo, workTime + "\n" + workDay);
}
}
@Override
public void onFail(int code, String message) {
}
@Override
public void onError() {
}
@Override
public void onClearToken() {
Utils.toLogin(getActivity());
}
});
// new MyRequest().myRequest(API.appload, false, null, false, getActivity(), null, null, new Response() {
// @Override
// public void response(JsonObject json, JsonArray jsonArray, boolean isNull) {
// List<Appload> list = Mygson.getInstance().fromJson(jsonArray, new TypeToken<List<Appload>>() {
// }.getType());
// String workTime = "", workDay = "", url = "", latestversion = "";
// boolean isforce = false;
// for (int i = 0; i < list.size(); i++) {
// Appload appload = list.get(i);
// if (appload.getName().equals("serviceLine") && !appload.getRemark().equals("")) {
// String phone = appload.getRemark();
// User.getInstance().setCustphone(phone);
// SharePref.put(MainActivity.getActivity(), API.customphone, phone);
// }
// if (appload.getName().equals("workDay") && !appload.getRemark().equals("")) {
// workDay = appload.getRemark();
// }
// if (appload.getName().equals("workTime") && !appload.getRemark().equals("")) {
// workTime = appload.getRemark();
// }
// if (appload.getName().equals("androidLink") && !appload.getRemark().equals("")) {
// url = appload.getRemark();
// }
// if (appload.getName().equals("forceUpdateAndroid") && !appload.getRemark().equals("")) {//强制是1 不强制是0
// isforce = appload.getRemark().equals("1") ? true : false;
// }
// if (appload.getName().equals("latestVersionAndroid") && !appload.getRemark().equals("")) {
// latestversion = appload.getRemark();
// }
// }
// if (!url.equals("") && !latestversion.equals("")) {
// updateManager = new UpdateManager(MainActivity.getActivity(), latestversion, url);
// updateManager.checkUpdate(isforce, "有新版本APP需要更新");
// }
// if (!"".equals(workTime) && !"".equals(workDay)) {
// User.getInstance().setCustinfo(workTime + "\n" + workDay);
// SharePref.put(MainActivity.getActivity(), API.custominfo, workTime + "\n" + workDay);
// }
// }
// });
}
private void getAddressByLatLng(double latitude, double longitude) {
geocodeSearch = new GeocodeSearch(getActivity());
geocodeSearch.setOnGeocodeSearchListener(new GeocodeSearch.OnGeocodeSearchListener() {
@Override
public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int code) {
String city = regeocodeResult.getRegeocodeAddress().getCity();
if (longitude != 0 && latitude != 0) {
locateInit(latitude, longitude);
}
if (!city.isEmpty()) {
User.getInstance().setCityName(city);
binding.tvCity.setText(city);
SharePref.put(getActivity(), API.cityName, city);
}
refreshMap(User.getInstance().getLatitude(getActivity()), User.getInstance().getLongtitude(getActivity()));
loadCity(User.getInstance().getLatitude(getActivity()), User.getInstance().getLongtitude(getActivity()), binding.tvCity.getText().toString());
}
@Override
public void onGeocodeSearched(GeocodeResult geocodeResult, int code) {
}
});
LatLonPoint latLonPoint = new LatLonPoint(latitude, longitude);
RegeocodeQuery query = new RegeocodeQuery(latLonPoint, 500f, GeocodeSearch.AMAP);
//异步查询
geocodeSearch.getFromLocationAsyn(query);
}
private void locateInit(double latitude, double longitude) {
User.getInstance().setLatitude(latitude);
User.getInstance().setMylatitude(latitude);
User.getInstance().setLongtitude(longitude);
User.getInstance().setMylongtitude(longitude);
SharePref.put(getActivity(), API.latitude, latitude + "");
SharePref.put(getActivity(), API.mylatitude, latitude + "");
SharePref.put(getActivity(), API.longtitude, longitude + "");
SharePref.put(getActivity(), API.mylongtitude, longitude + "");
}
// 定义 Marker 点击事件监听
AMap.OnMarkerClickListener markerClickListener = new AMap.OnMarkerClickListener() {
@Override
public boolean onMarkerClick(Marker marker) {
if (marker.getObject() instanceof StationInfo) {//当前城市的站点
StationInfo stationInfo = (StationInfo) marker.getObject();
markerCreate(stationlist, stationInfo);
if (stationInfo.getChildSites() != null && stationInfo.getChildSites().size() > 0) {//station and bao
if (User.getInstance().getYuyueId() != -1) {//todo //预约中
showPopDialog(stationInfo.getChildSites().get(0));
if (stationPopup != null) {
stationPopup.setStation(stationInfo.getChildSites().get(0));
}
} else {//不再预约中
showStationAndBaoDialog(stationInfo);
if (stationPopup != null) {
stationPopup.setStation(stationInfo);
}
}
} else {//just station or bao
showPopDialog(stationInfo);
if (stationPopup != null) {
stationPopup.setStation(stationInfo);
}
}
} else {//除了当前城市所有站点
markerAllCreate(stationAllList, (StationAll) marker.getObject());
showAllPopDialog((StationAll) marker.getObject());
}
return true;
}
};
private void showStationAndBaoDialog(StationInfo stationInfo) {
StationInfo childSites = stationInfo.getChildSites().get(0);
StationBaoAllPopupBinding popupBinding = stationBaoAllPopup.binding;
popupBinding.tvName.setText(stationInfo.getName());
popupBinding.tvAddress.setText(stationInfo.getAddress());
popupBinding.tvPhone.setText(stationInfo.getPhone());
popupBinding.tvFareStop.setVisibility(stationInfo.getParkFee().equals("") ? View.GONE : View.VISIBLE);
popupBinding.tvFareStop.setText("停车" + stationInfo.getParkFee() + "元/小时");
Drawable distancedrawable = getResources().getDrawable(R.mipmap.station_record_guide);
distancedrawable.setBounds(0, 0, 60, 60);
popupBinding.tvDistance.setCompoundDrawables(null, distancedrawable, null, null);
float distance = AMapUtils.calculateLineDistance(new LatLng(User.getInstance().getMylatitude(getActivity()), User.getInstance().getMylongtitude(getActivity())), new LatLng(stationInfo.getLatitude(), stationInfo.getLongitude()));
DecimalFormat df = new DecimalFormat("#.00");
if (distance < 1000) {
popupBinding.tvDistance.setText("导航\n" + df.format(distance) + "m");
} else {
popupBinding.tvDistance.setText("导航\n" + df.format(distance / 1000) + "km");
}
popupBinding.tvDistance.setOnClickListener(v -> {
Poi start = new Poi("", new com.amap.api.maps.model.LatLng(User.getInstance().getMylatitude(getActivity()), User.getInstance().getMylongtitude(getActivity())), "");
Poi end = new Poi("", new com.amap.api.maps.model.LatLng(stationInfo.getLatitude(), stationInfo.getLongitude()), "");
AmapNaviPage.getInstance().showRouteActivity(getContext(), new AmapNaviParams(start, null, end, AmapNaviType.DRIVER, AmapPageType.NAVI), null, MapCustomActivity.class);
if (stationPopup != null) {
stationPopup.dismiss();
}
});
int lefticon = 0;
boolean worktime = false;
String startTime = DateUtils.timeTotime(stationInfo.getStart_time());
String endTime = DateUtils.timeTotime(stationInfo.getEnd_time());
worktime = DateUtils.isBelong(startTime, endTime);
if (stationInfo.getStatus() == 2) {
lefticon = R.mipmap.station_repair;
} else {
if (stationInfo.getBattery() > 0 && worktime) {
lefticon = R.mipmap.station_icon;
} else if (stationInfo.getBattery() > 0 && !worktime) {//休息中
lefticon = R.mipmap.station_rest;
} else if (worktime && stationInfo.getBattery() == 0) {//无电池
lefticon = R.mipmap.station_icon;
} else {
lefticon = R.mipmap.station_icon;
}
}
Drawable leftDrawable = getResources().getDrawable(lefticon);
leftDrawable.setBounds(0, 0, 80, 80);
popupBinding.tvName.setCompoundDrawables(leftDrawable, null, null, null);
//init second para
popupBinding.tvNameZhan.setText(stationInfo.getName());
popupBinding.tvPaiduiZhan.setText("排队人数:" + stationInfo.getWaiting());
popupBinding.tvKucunZhan.setText(stationInfo.getBattery() > 0 ? "电池库存:有" : "电池库存:无");
String text_sign;
int color_sign, drawable_clock, drawable_sign;
if (stationInfo.getStatus() == 2) {
text_sign = "维修中";
color_sign = R.color.list_gray;
drawable_clock = R.drawable.shape_gray;
drawable_sign = R.drawable.shape_fill_gray;
} else {
if (stationInfo.getBattery() > 0 && worktime) {
text_sign = "运营中";
color_sign = R.color.text_color;
drawable_clock = R.drawable.shape_blue;
drawable_sign = R.drawable.shape_fill_blue;
} else if (stationInfo.getBattery() > 0 && !worktime) {//休息中
text_sign = "休息中";
color_sign = R.color.yellow;
drawable_clock = R.drawable.shape_yellow;
drawable_sign = R.drawable.shape_fill_yellow;
} else if (worktime && stationInfo.getBattery() == 0) {//无电池
text_sign = "运营中";
color_sign = R.color.text_color;
drawable_clock = R.drawable.shape_blue;
drawable_sign = R.drawable.shape_fill_blue;
} else {
text_sign = "运营中";
color_sign = R.color.text_color;
drawable_clock = R.drawable.shape_blue;
drawable_sign = R.drawable.shape_fill_blue;
}
}
popupBinding.tvSignZhan.setText(text_sign);
popupBinding.tvSignZhan.setBackground(getResources().getDrawable(drawable_sign));
popupBinding.tvClockZhan.setTextColor(getResources().getColor(color_sign));
popupBinding.tvClockZhan.setBackground(getResources().getDrawable(drawable_clock));
popupBinding.tvClockZhan.setText(DateUtils.datetoTime(stationInfo.getStart_time()) + "~" + DateUtils.datetoTime(stationInfo.getEnd_time()));
//bao init
popupBinding.tvNameBao.setText(childSites.getName());
popupBinding.tvDianchiBao.setText("可换电池:" + childSites.getBattery());
String text_sign_bao;
int color_sign_bao, drawable_clock_bao, drawable_sign_bao;
if (stationInfo.getStatus() == 2) {
text_sign_bao = "维修中";
color_sign_bao = R.color.list_gray;
drawable_clock_bao = R.drawable.shape_gray;
drawable_sign_bao = R.drawable.shape_fill_gray;
} else {
if (stationInfo.getBattery() > 0 && worktime) {
/*text_sign = "可预约";
color_sign = R.color.green;
drawable_clock = R.drawable.shape_green;
drawable_sign = R.drawable.shape_fill_green;*/
text_sign_bao = "可预约";
color_sign_bao = R.color.green;
drawable_clock_bao = R.drawable.shape_green;
drawable_sign_bao = R.drawable.shape_fill_green;
} else if (stationInfo.getBattery() > 0 && !worktime) {//休息中
/*text_sign = "休息中";
color_sign = R.color.yellow;
drawable_clock = R.drawable.shape_yellow;
drawable_sign = R.drawable.shape_fill_yellow;*/
text_sign_bao = "休息中";
color_sign_bao = R.color.yellow;
drawable_clock_bao = R.drawable.shape_yellow;
drawable_sign_bao = R.drawable.shape_fill_yellow;
} else if (worktime && stationInfo.getBattery() == 0) {//无电池
/* text_sign = "无电池";
color_sign = R.color.list_gray;
drawable_clock = R.drawable.shape_gray;
drawable_sign = R.drawable.shape_fill_gray;*/
text_sign_bao = "无电池";
color_sign_bao = R.color.list_gray;
drawable_clock_bao = R.drawable.shape_gray;
drawable_sign_bao = R.drawable.shape_fill_gray;
} else {
text_sign_bao = "无电池";
color_sign_bao = R.color.list_gray;
drawable_clock_bao = R.drawable.shape_gray;
drawable_sign_bao = R.drawable.shape_fill_gray;
}
}
popupBinding.tvSignBao.setText(text_sign_bao);
popupBinding.tvSignBao.setBackground(getResources().getDrawable(drawable_sign_bao));
popupBinding.tvClockBao.setBackground(getResources().getDrawable(drawable_clock_bao));
popupBinding.tvClockBao.setTextColor(getResources().getColor(color_sign_bao));
popupBinding.tvClockBao.setText(DateUtils.datetoTime(childSites.getStart_time()) + "~" + DateUtils.datetoTime(childSites.getEnd_time()));
popupBinding.tvYue.setOnClickListener(v -> {
if (Utils.usebindisNotexist(useBind)) {
Utils.snackbar(getActivity(), "请先选择您的车辆,才能预约站点");
return;
}
stationBaoAllPopup.dismiss();
appoint(childSites.getId(), useBind.getCar_id());
});
stationBaoAllPopup.setBackgroundColor(Color.TRANSPARENT);
stationBaoAllPopup.showPopupWindow();
}
private void showPopDialog(StationInfo contentBean) {
stationPopup.name.setText(contentBean.getName());
stationPopup.address.setText(contentBean.getAddress());
stationPopup.phone.setText(contentBean.getPhone());
stationPopup.phone.setOnClickListener(v -> {
if (stationPopup != null) {
stationPopup.dismiss();
}
Intent intent = new Intent(Intent.ACTION_DIAL);
Uri data = Uri.parse("tel:" + contentBean.getPhone());
intent.setData(data);
startActivity(intent);
});
stationPopup.tv_clock.setText(DateUtils.datetoTime(contentBean.getStart_time()) + "~" + DateUtils.datetoTime(contentBean.getEnd_time()));
if (contentBean.getType() == 0) {
stationPopup.paidui.setText("排队人数:" + contentBean.getWaiting());
stationPopup.kucun.setVisibility(View.VISIBLE);
} else if (contentBean.getType() == 1) {
stationPopup.paidui.setText("可换电池:" + contentBean.getBattery());
stationPopup.kucun.setVisibility(View.INVISIBLE);
}
stationPopup.kucun.setText(contentBean.getBattery() > 0 ? "电池库存:有" : "电池库存:无");
boolean worktime = false;
String startTime = DateUtils.timeTotime(contentBean.getStart_time());
String endTime = DateUtils.timeTotime(contentBean.getEnd_time());
worktime = DateUtils.isBelong(startTime, endTime);
int lefticon = 0;
String text_sign;
int color_sign, drawable_clock, drawable_sign;
if (contentBean.getStatus() == 2) {
text_sign = "维修中";
color_sign = R.color.list_gray;
drawable_clock = R.drawable.shape_gray;
drawable_sign = R.drawable.shape_fill_gray;
if (contentBean.getType() == 0) {
lefticon = R.mipmap.station_repair;
} else {
lefticon = R.mipmap.bao_nopower;
}
} else {
if (contentBean.getBattery() > 0 && worktime) {
if (contentBean.getType() == 0) {//0是换电站
text_sign = "运营中";
color_sign = R.color.text_color;
drawable_clock = R.drawable.shape_blue;
lefticon = R.mipmap.station_icon;
drawable_sign = R.drawable.shape_fill_blue;
} else {
if (contentBean.isAppointment()) {
text_sign = "可预约";
color_sign = R.color.green;
drawable_clock = R.drawable.shape_green;
drawable_sign = R.drawable.shape_fill_green;
} else {
text_sign = "运营中";
color_sign = R.color.text_color;
drawable_clock = R.drawable.shape_blue;
drawable_sign = R.drawable.shape_fill_blue;
}
lefticon = R.mipmap.bao_working;
}
} else if (contentBean.getBattery() > 0 && !worktime) {//休息中
text_sign = "休息中";
color_sign = R.color.yellow;
drawable_clock = R.drawable.shape_yellow;
drawable_sign = R.drawable.shape_fill_yellow;
if (contentBean.getType() == 0) {//0是换电站
lefticon = R.mipmap.station_rest;
} else {
lefticon = R.mipmap.bao_rest;
}
} else if (worktime && contentBean.getBattery() == 0) {//无电池
if (contentBean.getType() == 0) {//0是换电站
lefticon = R.mipmap.station_icon;
text_sign = "运营中";
color_sign = R.color.text_color;
drawable_clock = R.drawable.shape_blue;
drawable_sign = R.drawable.shape_fill_blue;
} else {
lefticon = R.mipmap.bao_nopower;
text_sign = "无电池";
color_sign = R.color.list_gray;
drawable_clock = R.drawable.shape_gray;
drawable_sign = R.drawable.shape_fill_gray;
}
} else {
if (contentBean.getType() == 0) {//0是换电站
lefticon = R.mipmap.station_icon;
text_sign = "运营中";
color_sign = R.color.text_color;
drawable_clock = R.drawable.shape_blue;
drawable_sign = R.drawable.shape_fill_blue;
} else {
lefticon = R.mipmap.bao_nopower;
text_sign = "无电池";
color_sign = R.color.list_gray;
drawable_clock = R.drawable.shape_gray;
drawable_sign = R.drawable.shape_fill_gray;
}
}
}
stationPopup.tv_sign.setText(text_sign);
stationPopup.tv_sign.setBackground(getResources().getDrawable(drawable_sign));
stationPopup.tv_clock.setBackground(getResources().getDrawable(drawable_clock));
stationPopup.tv_clock.setTextColor(getResources().getColor(color_sign));
if (contentBean.getParkFee().equals("")) {
stationPopup.tv_fare_stop.setVisibility(View.GONE);
} else {
stationPopup.tv_fare_stop.setVisibility(View.VISIBLE);
stationPopup.tv_fare_stop.setText("停车" + contentBean.getParkFee() + "元/小时");
}
Drawable leftDrawable = getResources().getDrawable(lefticon);
leftDrawable.setBounds(0, 0, 80, 80);
stationPopup.name.setCompoundDrawables(leftDrawable, null, null, null);
Drawable distancedrawable = getResources().getDrawable(R.mipmap.station_record_guide);
distancedrawable.setBounds(0, 0, 60, 60);
stationPopup.distance.setCompoundDrawables(null, distancedrawable, null, null);
if (contentBean.getStatus() == 2) {//2是维修中状态
stationPopup.appoint.setVisibility(View.GONE);
stationPopup.redelayDismiss.setVisibility(View.GONE);
stationPopup.time.setVisibility(View.GONE);
} else {
if (User.getInstance().getYuyueId() != -1) {//预约状态
if (User.getInstance().getYuyueId() == contentBean.getId()) {//预约状态并且是当前得站点
stationPopup.appoint.setVisibility(View.GONE);
stationPopup.redelayDismiss.setVisibility(View.VISIBLE);
stationPopup.time.setVisibility(View.VISIBLE);
} else {
if (contentBean.isAppointment()) {
if (worktime && contentBean.getBattery() > 0) {//在运营时间内 并且电池数量大于0
stationPopup.appoint.setVisibility(View.VISIBLE);
stationPopup.redelayDismiss.setVisibility(View.GONE);
stationPopup.time.setVisibility(View.GONE);
} else {
stationPopup.appoint.setVisibility(View.GONE);
stationPopup.redelayDismiss.setVisibility(View.GONE);
stationPopup.time.setVisibility(View.GONE);
}
} else {
stationPopup.appoint.setVisibility(View.GONE);
stationPopup.redelayDismiss.setVisibility(View.GONE);
stationPopup.time.setVisibility(View.GONE);
}
}
} else {//不是预约状态
if (contentBean.isAppointment()) {//可以预约
if (worktime && contentBean.getBattery() > 0) {//在运营时间内 并且电池数量大于0
stationPopup.appoint.setVisibility(View.VISIBLE);
stationPopup.redelayDismiss.setVisibility(View.GONE);
stationPopup.time.setVisibility(View.GONE);
} else {
stationPopup.appoint.setVisibility(View.GONE);
stationPopup.redelayDismiss.setVisibility(View.GONE);
stationPopup.time.setVisibility(View.GONE);
}
} else {
stationPopup.appoint.setVisibility(View.GONE);
stationPopup.redelayDismiss.setVisibility(View.GONE);
stationPopup.time.setVisibility(View.GONE);
}
}
}
stationPopup.appoint.setOnClickListener(v -> {
if (Utils.usebindisNotexist(useBind)) {
Utils.snackbar(getActivity(), "请先选择您的车辆,才能预约站点");
return;
}
appoint(contentBean.getId(), useBind.getCar_id());
});
stationPopup.delayappointcancel.setOnClickListener(v -> {
if (Utils.usebindisNotexist(useBind)) {
Utils.snackbar(getActivity(), "请在选择您的车辆,才能取消预约站点");
return;
}
cancelAppoint();
});
stationPopup.delayappoint.setOnClickListener(v -> {
if (Utils.usebindisNotexist(useBind)) {
Utils.snackbar(getActivity(), "请在选择您的车辆,才能延时预约站点");
return;
}
delayappoint();
});
// if (UserLogin.getInstance().getAccount() != null) {
float distance = AMapUtils.calculateLineDistance(new LatLng(User.getInstance().getMylatitude(getActivity()), User.getInstance().getMylongtitude(getActivity())), new LatLng(contentBean.getLatitude(), contentBean.getLongitude()));
DecimalFormat df = new DecimalFormat("#.00");
if (distance < 1000) {
stationPopup.distance.setText("导航\n" + df.format(distance) + "m");
} else {
stationPopup.distance.setText("导航\n" + df.format(distance / 1000) + "km");
}
stationPopup.distance.setOnClickListener(view -> {
if (User.getInstance().getYuyueId() == -1 && contentBean.getType() == 1) {
Utils.snackbar(getActivity(), "请预约成功后前往换电");
} else {
Poi start = new Poi("", new com.amap.api.maps.model.LatLng(User.getInstance().getMylatitude(getActivity()), User.getInstance().getMylongtitude(getActivity())), "");
Poi end = new Poi("", new com.amap.api.maps.model.LatLng(contentBean.getLatitude(), contentBean.getLongitude()), "");
AmapNaviPage.getInstance().showRouteActivity(getContext(), new AmapNaviParams(start, null, end, AmapNaviType.DRIVER, AmapPageType.NAVI), null, MapCustomActivity.class);
if (stationPopup != null) {
stationPopup.dismiss();
}
}
});
stationPopup.setBackgroundColor(Color.TRANSPARENT);
stationPopup.showPopupWindow();
}
private void showAllPopDialog(StationAll contentBean) {
stationOtherCitiesPopup.name.setText(contentBean.getName());
stationOtherCitiesPopup.address.setText(contentBean.getAddress());
stationOtherCitiesPopup.phone.setText(contentBean.getPhone());
stationOtherCitiesPopup.phone.setOnClickListener(v -> {
if (stationOtherCitiesPopup != null) {
stationOtherCitiesPopup.dismiss();
}
Intent intent = new Intent(Intent.ACTION_DIAL);
Uri data = Uri.parse("tel:" + contentBean.getPhone());
intent.setData(data);
startActivity(intent);
});
stationOtherCitiesPopup.worktime.setText(DateUtils.datetoTime(contentBean.getStart_time()) + "~" + DateUtils.datetoTime(contentBean.getEnd_time()));
int mipmap = 0;
if (contentBean.getType() == 0) {//换电站
mipmap = R.mipmap.station_icon;
} else {
mipmap = R.mipmap.bao_working;
}
Drawable leftDrawable = getResources().getDrawable(mipmap);
leftDrawable.setBounds(0, 0, 80, 80);
stationOtherCitiesPopup.name.setCompoundDrawables(leftDrawable, null, null, null);
stationOtherCitiesPopup.setBackgroundColor(Color.TRANSPARENT);
stationOtherCitiesPopup.showPopupWindow();
}
private void delayappoint() {// "appointment_no": "AP2949782536458240"
// HashMap<String, String> map = new HashMap<>();
// map.put("appointment_no", appointment_no);
// new MyRequest().myRequest(API.delayappoint, true, map, true, getActivity(), null, null, new Response() {
// @Override
// public void response(JsonObject json, JsonArray jsonArray, boolean isNull) {
// Utils.snackbar(MainActivity.getActivity(), "延时预约成功");
// getcurrentAppint();
// }
// });
CancelAppointmentRequest cancelAppointmentRequest = new CancelAppointmentRequest();
cancelAppointmentRequest.setAppointment_no(appointment_no);
InternetWorkManager.getRequest().delayAppointment(Utils.body(Mygson.getInstance().toJson(cancelAppointmentRequest)))
.compose(RxHelper.observableIOMain(getActivity()))
.subscribe(new MyObserver<User>() {
@Override
public void onSuccess(User data) {
Utils.snackbar(getActivity(), "延时预约成功");
getcurrentAppint();
}
@Override
public void onFail(int code, String message) {
}
@Override
public void onError() {
}
@Override
public void onClearToken() {
Utils.toLogin(getActivity());
}
});
}
private void cancelAppoint() {
// HashMap<String, String> map = new HashMap<>();
// map.put("appointment_no", appointment_no);
// new MyRequest().myRequest(API.cancelappoint, true, map, true, getActivity(), null, null, new Response() {
// @Override
// public void response(JsonObject json, JsonArray jsonArray, boolean isNull) {
// Utils.snackbar(MainActivity.getActivity(), "取消预约成功");
// getcurrentAppint();
// }
// });
CancelAppointmentRequest cancelAppointmentRequest = new CancelAppointmentRequest();
cancelAppointmentRequest.setAppointment_no(appointment_no);
InternetWorkManager.getRequest().cancelAppointment(Utils.body(Mygson.getInstance().toJson(cancelAppointmentRequest)))
.compose(RxHelper.observableIOMain(getActivity()))
.subscribe(new MyObserver<User>() {
@Override
public void onSuccess(User data) {
Utils.snackbar(getActivity(), "取消预约成功");
getcurrentAppint();
}
@Override
public void onFail(int code, String message) {
}
@Override
public void onError() {
}
@Override
public void onClearToken() {
Utils.toLogin(getActivity());
}
});
}
private void appoint(int stationid, int carid) {//预约
//{
// "site_id": 99,
// "car_id": 11391
//}
// HashMap<String, String> map = new HashMap<>();
// map.put("site_id", String.valueOf(station));
// map.put("car_id", String.valueOf(carid));
// new MyRequest().myRequest(API.appoint, true, map, false, MainActivity.getActivity(), null, null, new Response() {
// @Override
// public void response(JsonObject json, JsonArray jsonArray, boolean isNull) {
// Utils.snackbar(MainActivity.getActivity(), "预约成功");
// getcurrentAppint();
// }
// });
AddAppointmentRequest addAppointmentRequest = new AddAppointmentRequest();
addAppointmentRequest.setSite_id(stationid);
addAppointmentRequest.setCar_id(carid);
InternetWorkManager.getRequest().addAppointment(Utils.body(Mygson.getInstance().toJson(addAppointmentRequest)))
.compose(RxHelper.observableIOMain(getActivity()))
.subscribe(new MyObserver<User>() {
@Override
public void onSuccess(User data) {
Utils.snackbar(getActivity(), "预约成功");
getcurrentAppint();
}
@Override
public void onFail(int code, String message) {
}
@Override
public void onError() {
}
@Override
public void onClearToken() {
Utils.toLogin(getActivity());
}
});
}
private void loadStation(double longitude, double latitude, int type, int cityId) {
SiteRequest siteRequest = new SiteRequest();
siteRequest.setLongitude(longitude);
siteRequest.setLatitude(latitude);
siteRequest.setType(type);
siteRequest.setCity_Id(cityId);
siteRequest.setUse(1);
siteRequest.setaId(User.getInstance().getAccountId());
InternetWorkManager.getRequest().sitelist(Utils.body(Mygson.getInstance().toJson(siteRequest)))
.compose(RxHelper.observableIOMain(getActivity()))
.subscribe(new MyObserver<List<StationInfo>>() {
@Override
public void onSuccess(List<StationInfo> data) {
stationlist = data;
boolean ishasHuandianbao = false;
for (int i = 0; i < stationlist.size(); i++) {
if (stationlist.get(i).getType() == 1) {//0是换电站
ishasHuandianbao = true;
}
}
if (ishasHuandianbao) {
binding.finish.setVisibility(View.VISIBLE);
} else {
binding.finish.setVisibility(View.GONE);
}
markerCreate(stationlist, null);
getcurrentAppint();
}
@Override
public void onFail(int code, String message) {
}
@Override
public void onError() {
}
@Override
public void onClearToken() {
Utils.toLogin(getActivity());
}
});
// HashMap<String, String> map = new HashMap<>();
// map.put("longitude", String.valueOf(longitude));
// map.put("latitude", String.valueOf(latitude));
// map.put("type", type);
// map.put("city_Id", String.valueOf(cityId));
// new MyRequest().myRequest(API.SITELIST, true, map, false, getActivity(), null, null, new Response() {
// @Override
// public void response(JsonObject json, JsonArray jsonArray, boolean isNull) {
// stationlist = Mygson.getInstance().fromJson(jsonArray, new TypeToken<List<StationInfo>>() {
// }.getType());
// boolean ishasHuandianbao = false;
// for (int i = 0; i < stationlist.size(); i++) {
// if (stationlist.get(i).getType() == 1) {//0是换电站
// ishasHuandianbao = true;
// }
// }
// if (ishasHuandianbao) {
// binding.finish.setVisibility(View.VISIBLE);
// } else {
// binding.finish.setVisibility(View.GONE);
// }
// markerCreate(stationlist, null);
// getcurrentAppint();
// }
// });
}
@Override
public void onClick(View view) {
Intent intent = null;
switch (view.getId()) {
case R.id.msg:
if (Utils.getToken(getActivity()) == null || Utils.getToken(getActivity()).equals("")) {
Utils.toLogin(getActivity());
Utils.snackbar(getActivity(), "请先登陆");
return;
}
intent = new Intent(getActivity(), MessageActivity.class);
startActivity(intent);
break;
// case R.id.tv_right:
//// if (UserLogin.getInstance().getCityid(MainActivity.getActivity()) == 0){
//// Utils.snackbar(MainActivity.getActivity(), "请先等待定位");
//// return;
//// }
// intent = new Intent(getActivity(), ListFragment.class);
// intent.putExtra("useBind", useBind);
// startActivityForResult(intent, REQUESTCODE_LIST);
// break;
case R.id.tv_city:
intent = new Intent(getActivity(), ChoseCityActivity.class);
startActivityForResult(intent, REQUESTCODE_MAIN);
break;
case R.id.re_carplate:
if (Utils.getToken(getActivity()) == null || Utils.getToken(getActivity()).equals("")) {
Utils.toLogin(getActivity());
Utils.snackbar(getActivity(), "请先登陆");
return;
}
intent = new Intent(getActivity(), MyCarActivity.class);
startActivity(intent);
break;
case R.id.qrcode:
if (Utils.getToken(getActivity()) == null || Utils.getToken(getActivity()).equals("")) {
Utils.toLogin(getActivity());
Utils.snackbar(getActivity(), "请先登陆");
return;
}
String carplate = "";
if (Utils.usebindisNotexist(useBind)) {
carplate = "";
} else {
carplate = useBind.getPlate_number();
}
BaseDialog.showQrDialog(getActivity(), carplate);
break;
case R.id.recharge:
if (Utils.getToken(getActivity()) == null || Utils.getToken(getActivity()).equals("")) {
Utils.toLogin(getActivity());
Utils.snackbar(getActivity(), "请先登陆");
return;
}
intent = new Intent(getActivity(), RechargeActivity.class);
startActivity(intent);
break;
case R.id.daka:
if (Utils.getToken(getActivity()) == null || Utils.getToken(getActivity()).equals("")) {
Utils.toLogin(getActivity());
Utils.snackbar(getActivity(), "请先登陆");
return;
}
if (Utils.usebindisNotexist(useBind)) {
Utils.snackbar(getActivity(), "请先选择车辆");
return;
}
intent = new Intent(getActivity(), DriverclockActivity.class);
startActivity(intent);
break;
case R.id.scan:
scan();
break;
case R.id.img_kefu:
Utils.loadkefu(getActivity(), binding.imgKefu);
break;
case R.id.tv_station_name:
if (stationlist != null) {
stationSelectFragment = new StationSelectFragment(mainFragment);
Bundle bundle = new Bundle();
bundle.putSerializable(API.station, (Serializable) stationlist);
stationSelectFragment.setArguments(bundle);
stationSelectFragment.show(getChildFragmentManager(), "data");
}
break;
default:
break;
}
}
public void installApk() {
if (updateManager != null) {
updateManager.installApk();
}
}
public void setProgress() {
if (updateManager != null) {
updateManager.setProgress();
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUESTCODE_MAIN && resultCode == 1) {//选择城市
String cityName = data.getStringExtra(API.cityName);
binding.tvCity.setText(cityName);
User.getInstance().setCityName(cityName);
SharePref.put(getActivity(), API.cityName, cityName);
double lat = data.getDoubleExtra(API.latitude, 0);
User.getInstance().setLatitude(lat);
SharePref.put(getActivity(), API.latitude, lat + "");
double lon = data.getDoubleExtra(API.longtitude, 0);
User.getInstance().setLongtitude(lon);
SharePref.put(getActivity(), API.longtitude, lon + "");
cityid = data.getIntExtra(API.cityId, 0);
User.getInstance().setCityid(cityid);
SharePref.put(getActivity(), API.cityId, cityid + "");
refreshMap(lat, lon);
User.getInstance().setMainchanged(true);
} else if (requestCode == REQUESTCODE_SCAN && resultCode == 2) {//换点扫码哦
String message = data.getStringExtra(API.code);
if (message.indexOf("=") == -1) {
Utils.snackbar(getActivity(), "请确认当前二维码是站点二维码");
return;
}
if (message.indexOf("station") != -1) {
String[] splite = message.split("=");
postScan(splite[1]);
}
}
// } else if (requestCode == REQUESTCODE_LIST && resultCode == 2) {//列表
// if (User.getInstance().getCityName(getActivity()) != null && !User.getInstance().getCityName(getActivity()).isEmpty()) {
// binding.tvCity.setText(User.getInstance().getCityName(getActivity()));
// }
// if (User.getInstance().getLatitude(getActivity()) != 0) {
// refreshMap(User.getInstance().getLatitude(getActivity()), User.getInstance().getLongtitude(getActivity()));
// }
//// if (UserLogin.getInstance().getCityid(MainActivity.getActivity()) != 0) {
//// loadStation(UserLogin.getInstance().getLongtitude(MainActivity.getActivity()), UserLogin.getInstance().getLatitude(MainActivity.getActivity()), "-1", UserLogin.getInstance().getCityid(MainActivity.getActivity()));
//// }
// int stationId = data.getIntExtra("stationId", -1);
// if (stationId != -1 && User.getInstance().getYuyueId() == -1) {
// if (stationlist.size() > 0) {
// showPopDialog(Utils.getstation(stationlist, stationId));
// if (stationPopup != null) {
// stationPopup.setStation(Utils.getstation(stationlist, stationId));
// }
// }
// }
// }
else if (requestCode == REQUESTCODE_GPS) {
setLocate();
}
}
// //地图显示刷新的位置
// private void refreshLocation(double lat, double lng) {
// LatLng latLng = new LatLng(lat, lng);
// aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 12.0f));
// }
private void postScan(String data) {
int stationId = 0;
if (User.getInstance().getYuyueId() == -1) {
stationId = Integer.parseInt((String) SharePref.get(getActivity(), API.siteid, "-1"));
} else {
stationId = User.getInstance().getYuyueId();
}
if (stationId == -1) {
Utils.snackbar(getActivity(), "当前没有预约,请先预约站点");
return;
}
if (!data.equals(String.valueOf(stationId))) {
Utils.snackbar(getActivity(), "当前预约站点不是扫码站点");
return;
}
BaseDialog.showDialog(getActivity(), "温馨提示", "您已扫码成功,请确认是否换电", "确认", new View.OnClickListener() {
@Override
public void onClick(View v) {
// HashMap<String, String> map = new HashMap<>();
// map.put("appointmentNo", User.getInstance().getAppointment_no(MainActivity.getActivity()));
// new MyRequest().myRequest(API.scanpay, true, map, true, MainActivity.getActivity(), null, null, new Response() {
// @Override
// public void response(JsonObject json, JsonArray jsonArray, boolean isNull) {
// List<BillDetail> list = Mygson.getInstance().fromJson(json.get("detail").getAsJsonArray(), new TypeToken<List<BillDetail>>() {
// }.getType());
// String name = json.get("siteName").getAsString();
// String fare = json.get("realFare").getAsString();
// int recordId = json.get("recordId").getAsInt();
// scanPopup = new ScanPopup(MainActivity.getActivity(), MainActivity.getActivity(), list, name, fare, User.getInstance().getAppointment_no(MainActivity.getActivity()),
// recordId);
// scanPopup.showPopupWindow();
// }
// });
ConsumeRequest consumeRequest = new ConsumeRequest();
consumeRequest.setAppointmentNo(User.getInstance().getAppointment_no(getActivity()));
InternetWorkManager.getRequest().consumegetlist(Utils.body(Mygson.getInstance().toJson(consumeRequest)))
.compose(RxHelper.observableIOMain(getActivity()))
.subscribe(new MyObserver<ConsumeListModel>() {
@Override
public void onSuccess(ConsumeListModel data) {
scanPopup = new ScanPopup(mainFragment, getContext(), data.getDetail(), data.getSiteName(),
data.getRealFare(), User.getInstance().getAppointment_no(getActivity()),
data.getRecordId());
scanPopup.showPopupWindow();
}
@Override
public void onFail(int code, String message) {
}
@Override
public void onError() {
}
@Override
public void onClearToken() {
Utils.toLogin(getActivity());
}
});
}
});
}
public class PrivacyDialog extends Dialog {
Context context;
public PrivacyDialog(Context context, int themeResId) {
super(context, themeResId);
this.context = context;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dialog_privacy);
TextView xieyiTv = findViewById(R.id.tv_xieyi);
TextView privacyTv = findViewById(R.id.tv_privacy);
TextView cancelTv = findViewById(R.id.tv_cancel);
TextView agreeTv = findViewById(R.id.tv_agree);
setCancelable(false);
setCanceledOnTouchOutside(false);
cancelTv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dismiss();
}
});
agreeTv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dismiss();
SharePref.oneput(context, "agree", true);
}
});
xieyiTv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(context, UseProtocolActivity.class);
context.startActivity(intent);
}
});
privacyTv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(context, PrivacyActivity.class);
context.startActivity(intent);
}
});
}
}
private void init() {
bindClick();
AndPermission.with(getActivity())
.runtime()
.permission(WRITE_EXTERNAL_STORAGE, Permission.READ_PHONE_STATE, ACCESS_FINE_LOCATION, CAMERA)
.onGranted(permissions -> {
setLocate();
bluePointLocat(); //定位蓝点
// loadStation(UserLogin.getInstance().getLongtitude(MainActivity.getActivity()),UserLogin.getInstance().getLatitude(MainActivity.getActivity()),
// "-1");
// loadServiceData();
})
.onDenied(permissions -> {
})
.start();
}
//获取当前预约//{
// "appointment_no": "AP2946390799945728",
// "end_time": "2020-12-25T14:19:52+08:00",
// "site_id": 99
public void getcurrentAppint() {
InternetWorkManager.getRequest().currentAppointment()
.compose(RxHelper.observableIOMain(getActivity()))
.subscribe(new MyObserver<CurrentAppointmentModel>() {
@Override
public void onSuccess(CurrentAppointmentModel data) {
if (data == null) {
User.getInstance().setAppointment_no("");
User.getInstance().setYuyueId(-1);
SharePref.put(getActivity(), API.appointment_no, "");
SharePref.put(getActivity(), API.siteid, "-1");
if (stationPopup != null) {
if (stationPopup.getStationInfo() != null) {
StationInfo stationInfo = stationPopup.getStationInfo();
boolean worktime = false;
String startTime = DateUtils.timeTotime(stationInfo.getStart_time());
String endTime = DateUtils.timeTotime(stationInfo.getEnd_time());
worktime = DateUtils.isBelong(startTime, endTime);
if (stationInfo.getType() == 1 && stationInfo.getStatus() != 2 && worktime) {
stationPopup.appoint.setVisibility(View.VISIBLE);
} else {
stationPopup.appoint.setVisibility(View.GONE);
}
} else {
stationPopup.appoint.setVisibility(View.GONE);
}
stationPopup.redelayDismiss.setVisibility(View.GONE);
stationPopup.time.setVisibility(View.GONE);
}
if (timeCount != null) {
timeCount.cancel();
}
} else {
if (data.getAppointment_no() != null) {
appointment_no = data.getAppointment_no();
User.getInstance().setAppointment_no(appointment_no);
SharePref.put(getActivity(), API.appointment_no, appointment_no);
}
if (data.getEnd_time() != null) {
long endTime = DateUtils.date2TimeStamp(data.getEnd_time());
long currentTime = System.currentTimeMillis() / 1000;
long time = endTime - currentTime;
if (time > 0) {
if (stationPopup != null) {
stationPopup.appoint.setVisibility(View.GONE);
stationPopup.redelayDismiss.setVisibility(View.VISIBLE);
stationPopup.time.setVisibility(View.VISIBLE);
}
if (timeCount != null) {
timeCount.cancel();
timeCount = new TimeCount(time * 1000, stationPopup.time, MainFragment.this::timeFinish);
timeCount.start();
} else {
timeCount = new TimeCount(time * 1000, stationPopup.time, MainFragment.this::timeFinish);
timeCount.start();
}
}
Utils.log("", "", endTime + "分割线" + currentTime);
}
if (data.getSite_id() != 0) {
User.getInstance().setYuyueId(data.getSite_id());
SharePref.put(getActivity(), API.siteid, data.getSite_id() + "");
StationInfo stationInfo = Utils.getstation(stationlist, data.getSite_id());
if (stationlist.size() != 0 && stationInfo != null) {
markerCreate(stationlist, stationInfo);
showPopDialog(stationInfo);//获取我的预约
if (stationPopup != null) {
stationPopup.setStation(stationInfo);
}
}
}
}
}
@Override
public void onFail(int code, String message) {
}
@Override
public void onError() {
}
@Override
public void onClearToken() {
Utils.toLogin(getActivity());
}
});
}
public void scan() {
if (Utils.getToken(getActivity()) == null || Utils.getToken(getActivity()).equals("")) {
Utils.toLogin(getActivity());
Utils.snackbar(getActivity(), "请先登陆");
return;
}
if (Utils.usebindisNotexist(useBind)) {
Utils.snackbar(getActivity(), "请先选择车辆");
return;
}
Intent myintent = new Intent(getActivity(), ScanActivity.class);
startActivityForResult(myintent, REQUESTCODE_SCAN);
}
@Override
public void timeFinish() {
timeCount.cancel();
User.getInstance().setYuyueId(-1);
User.getInstance().setAppointment_no("");
SharePref.put(getActivity(), API.appointment_no, "");
SharePref.put(getActivity(), API.siteid, "-1");
// HashMap<String, String> map = new HashMap<>();
// map.put("appointment_no", appointment_no);
// new MyRequest().myRequest(API.cancelappoint, true, map, true, getActivity(), null, null, new Response() {
// @Override
// public void response(JsonObject json, JsonArray jsonArray, boolean isNull) {
// getcurrentAppint();
// }
// });
CancelAppointmentRequest cancelAppointmentRequest = new CancelAppointmentRequest();
cancelAppointmentRequest.setAppointment_no(appointment_no);
InternetWorkManager.getRequest().cancelAppointment(Utils.body(Mygson.getInstance().toJson(cancelAppointmentRequest)))
.compose(RxHelper.observableIOMain(getActivity()))
.subscribe(new MyObserver<User>() {
@Override
public void onSuccess(User data) {
getcurrentAppint();
}
@Override
public void onFail(int code, String message) {
}
@Override
public void onError() {
}
@Override
public void onClearToken() {
Utils.toLogin(getActivity());
}
});
if (stationPopup != null) {
stationPopup.redelayDismiss.setVisibility(View.GONE);
stationPopup.appoint.setVisibility(View.VISIBLE);
stationPopup.time.setVisibility(View.GONE);
}
}
private void bindClick() {
binding.tvCity.setOnClickListener(this);
binding.imgKefu.setOnClickListener(this);
binding.reCarplate.setOnClickListener(this);
binding.tvStationName.setOnClickListener(this);
binding.qrcode.setOnClickListener(this);
binding.scan.setOnClickListener(this);
binding.msg.setOnClickListener(this);
binding.recharge.setOnClickListener(this);
binding.daka.setOnClickListener(this);
}
public void paysuccessLoad() {
getcurrentAppint();
Intent intent = new Intent(getActivity(), BillActivity.class);
startActivity(intent);
}
@Override
public void onDestroy() {
// mLocationClient.onDestroy();
//在activity执行onDestroy时执行mMapView.onDestroy(),销毁地图
binding.mapview.onDestroy();
if (null != mLocationClient) {
mLocationClient.onDestroy();
}
if (timeCount != null) {
timeCount.cancelTime();
timeCount = null;
}
if (privacyDialog != null) {
privacyDialog.dismiss();
privacyDialog = null;
}
super.onDestroy();
}
// @Override
// public void onStop() {
// super.onStop();
// binding.banner.stopViewAnimator();
//// mLocationClient.stopLocation();
// }
@Override
public void onDetach() {
super.onDetach();
binding.banner.stopViewAnimator();
}
private void setLocate() {
if (GpsUtil.isOPen(getActivity())) {
//设置定位回调监听
mLocationClient.setLocationListener(mLocationListener);
//初始化AMapLocationClientOption对象
mLocationOption = new AMapLocationClientOption();
//设置定位模式为AMapLocationMode.Hight_Accuracy,高精度模式。
mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
//获取一次定位结果:
//该方法默认为false。
mLocationOption.setOnceLocation(true);
mLocationClient.setLocationOption(mLocationOption);
mLocationClient.startLocation();
} else {
new AlertDialog.Builder(getActivity()).setTitle("定位失败").setMessage("请检查是否开启定位服务").setPositiveButton("开启", (dialogInterface, i) -> {
Intent intent = new Intent();
intent.setAction(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivityForResult(intent, REQUESTCODE_GPS);
}).setNegativeButton("取消", (dialogInterface, i) -> {
dialogInterface.dismiss();
User.getInstance().setCityName("");
}).create().show();
}
}
private void bluePointLocat() {
MyLocationStyle myLocationStyle;
myLocationStyle = new MyLocationStyle();//初始化定位蓝点样式类myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE);//连续定位、且将视角移动到地图中心点,定位点依照设备方向旋转,并且会跟随设备移动。(1秒1次定位)如果不设置myLocationType,默认也会执行此种模式。
myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_FOLLOW_NO_CENTER);
myLocationStyle.interval(1000); //设置连续定位模式下的定位间隔,只在连续定位模式下生效,单次定位模式下不会生效。单位为毫秒。
aMap.setMyLocationStyle(myLocationStyle);//设置定位蓝点的Style
//aMap.getUiSettings().setMyLocationButtonEnabled(true);设置默认定位按钮是否显示,非必需设置。
aMap.getUiSettings().setRotateGesturesEnabled(false);
aMap.setMyLocationEnabled(true);// 设置为true表示启动显示定位蓝点,false表示隐藏定位蓝点并不进行定位,默认是false。
}
private void markerCreate(List<StationInfo> list, StationInfo s) {
if (ListUtils.isEmpty(list)) {
return;
}
int position = list.indexOf(s);
for (Marker marker : markerList) {
if (marker.getObject() instanceof StationInfo) {
marker.remove();
}
}
for (int i = 0; i < list.size(); i++) {
StationInfo station = list.get(i);
MarkerOptions markerOptions = new MarkerOptions();
LatLng latLng = new LatLng(station.getLatitude(), station.getLongitude());
markerOptions.position(latLng);
boolean worktime = false;
String startTime = DateUtils.timeTotime(station.getStart_time());
String endTime = DateUtils.timeTotime(station.getEnd_time());
worktime = DateUtils.isBelong(startTime, endTime);
int mipmap = 0; // 0运营 1关闭 2维修
if (station.getStatus() == 2) {
if (station.getType() == 0) {
mipmap = R.mipmap.station_repair_map;
} else {
mipmap = R.mipmap.bao_nopower_map;
}
} else {
if (station.getBattery() > 0 && worktime) {
if (station.getType() == 0) {//0是换电站
mipmap = R.mipmap.station_working_map;
} else {
mipmap = R.mipmap.bao_working_map;
}
} else if (station.getBattery() > 0 && !worktime) {//休息中
if (station.getType() == 0) {//0是换电站
mipmap = R.mipmap.station_rest_map;
} else {
mipmap = R.mipmap.bao_rest_map;
}
} else if (worktime && station.getBattery() == 0) {//无电池
if (station.getType() == 0) {//0是换电站
mipmap = R.mipmap.station_working_map;
} else {
mipmap = R.mipmap.bao_nopower_map;
}
} else {
if (station.getType() == 0) {//0是换电站
mipmap = R.mipmap.station_working_map;
} else {
mipmap = R.mipmap.bao_nopower_map;
}
}
}
if (position == i) {
bitmap = BitmapDescriptorFactory.fromBitmap(setImgSize(BitmapFactory.decodeResource(getResources(), mipmap), 128, 144));
} else {
bitmap = BitmapDescriptorFactory.fromBitmap(setImgSize(BitmapFactory.decodeResource(getResources(), mipmap), 96, 108));
}
markerOptions.icon(bitmap);
Marker marker = aMap.addMarker(markerOptions);
marker.setObject(station);
// marker.setMarkerOptions(markerOptions);
markerList.add(marker);
}
}
private void markerAllCreate(List<StationAll> list, StationAll s) {
if (ListUtils.isEmpty(list)) {
return;
}
int position = list.indexOf(s);
for (Marker marker : markerList) {
if (marker.getObject() instanceof StationAll) {
marker.remove();
}
}
for (int i = 0; i < list.size(); i++) {
StationAll station = list.get(i);
MarkerOptions markerOptions = new MarkerOptions();
LatLng latLng = new LatLng(station.getLatitude(), station.getLongitude());
markerOptions.position(latLng);
int mipmap = 0; // 0运营 1关闭 2维修
if (station.getType() == 0) {
mipmap = R.mipmap.station_working_map;
} else {
mipmap = R.mipmap.bao_working_map;
}
if (position == i) {
bitmap = BitmapDescriptorFactory.fromBitmap(setImgSize(BitmapFactory.decodeResource(getResources(), mipmap), 128, 144));
} else {
bitmap = BitmapDescriptorFactory.fromBitmap(setImgSize(BitmapFactory.decodeResource(getResources(), mipmap), 96, 108));
}
markerOptions.icon(bitmap);
Marker marker = aMap.addMarker(markerOptions);
marker.setObject(station);
markerList.add(marker);
}
}
//地图显示刷新的位置
private void refreshMap(double lat, double lng) {
LatLng latLng = new LatLng(lat, lng);
aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 12.0f));
}
public Bitmap setImgSize(Bitmap bm, int newWidth, int newHeight) {
int width = bm.getWidth();
int height = bm.getHeight();
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);
Bitmap newbm = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, true);
return newbm;
}
@Override
public void onHiddenChanged(boolean hidden) {
super.onHiddenChanged(hidden);
if (!hidden) {//fragment show
onresume();
if (User.getInstance().isListchanged()) {//listfragment changed
binding.tvCity.setText(User.getInstance().getCityName(getActivity()));
User.getInstance().setMainchanged(false);
refreshMap(User.getInstance().getLatitude(getActivity()), User.getInstance().getLongtitude(getActivity()));
}
}
}
public void onresume() {//mainfragment show
//在activity执行onResume时执行mMapView.onResume (),重新绘制加载地图
binding.mapview.onResume();
infoGet();
if (User.getInstance().getLatitude(getActivity()) != 0) {
loadCity(User.getInstance().getLatitude(getActivity()), User.getInstance().getLongtitude(getActivity()), User.getInstance().getCityName(getActivity()));
}
loadDialogMessage();
loadScrollMessage();
}
private void loadDialogMessage() {
InternetWorkManager.getRequest().messageList(3, 0, 20)
.compose(RxHelper.observableIOMain(getActivity()))
.subscribe(new MyObserver<List<Message>>() {
@Override
public void onSuccess(List<Message> data) {
if (data != null && data.size() > 0) {
showmessageDialog(data);
}
}
@Override
public void onFail(int code, String message) {
}
@Override
public void onError() {
}
@Override
public void onClearToken() {
Utils.toLogin(getActivity());
}
});
}
private void showmessageDialog(List<Message> data) {
if (data.size() > 0) {
BaseDialog.showcodeDialog(getContext(), "温馨提示", data.get(0).getContent(), "知道了", new View.OnClickListener() {
@Override
public void onClick(View v) {
data.remove(0);
showmessageDialog(data);
}
});
}
}
private void loadScrollMessage() {
InternetWorkManager.getRequest().messageList(2, 0, 1)
.compose(RxHelper.observableIOMain(getActivity()))
.subscribe(new MyObserver<List<Message>>() {
@Override
public void onSuccess(List<Message> data) {
if (data != null && data.size() > 0) {
Message message = data.get(0);
String ss = message.getContent();
if (!ss.equals("") && ss != null) {
binding.banner.setDatas(Utils.getStrList(ss, 18));
binding.message.setVisibility(View.VISIBLE);
binding.banner.startViewAnimator();
return;
}
binding.message.setVisibility(View.GONE);
binding.banner.stopViewAnimator();
}
}
@Override
public void onFail(int code, String message) {
}
@Override
public void onError() {
}
@Override
public void onClearToken() {
Utils.toLogin(getActivity());
}
});
}
@Override
public void onPause() {
super.onPause();
binding.mapview.onPause();
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
binding.mapview.onSaveInstanceState(outState);
}
@Override
public void click(StationInfo station) {
if (station == null) {
binding.tvStationName.setText("");
return;
}
if (ListUtils.isEmpty(stationlist)) {
return;
}
markerCreate(stationlist, station);
binding.tvStationName.setText(station.getName());
if (station.getChildSites() != null && station.getChildSites().size() > 0) {//station and bao
if (User.getInstance().getYuyueId() != -1) {//todo //预约中
showPopDialog(station.getChildSites().get(0));
if (stationPopup != null) {
stationPopup.setStation(station);
}
} else {//不再预约中
showStationAndBaoDialog(station);
if (stationPopup != null) {
stationPopup.setStation(station);
}
}
} else {//just station or bao
showPopDialog(station);
if (stationPopup != null) {
stationPopup.setStation(station);
}
}
// showPopDialog(station);
}
private void infoGet() {
InternetWorkManager.getRequest().infoGet()
.compose(RxHelper.observableIOMain(getActivity()))
.subscribe(new Observer<ResponseModel<User>>() {
@Override
public void onSubscribe(@io.reactivex.rxjava3.annotations.NonNull Disposable d) {
}
@Override
public void onNext(@io.reactivex.rxjava3.annotations.NonNull ResponseModel<User> userResponseModel) {
User user = userResponseModel.getData();
if (user == null) return;
Utils.shareprefload(user, getActivity());//存储个人信息和阿里云信息
User.getInstance().setAccountId(user.getAccountId());
if (user.getUnread() > 0) {
binding.imgMsg.setImageDrawable(getResources().getDrawable(R.mipmap.icon_message_unread));
} else {
binding.imgMsg.setImageDrawable(getResources().getDrawable(R.mipmap.icon_message));
}
if (user.getUse_bind() != null) {
if (user.getUse_bind().getFirst_exchange_sites() != null && !user.getUse_bind().getFirst_exchange_sites().equals("")) {
BaseDialog.showcodeDialog(getContext(), "温馨提示", user.getUse_bind().getFirst_exchange_sites(), "知道了", new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
}
}
Utils.setUseBind(getActivity(), user.getUse_bind());
if (!Utils.usebindisNotexist(user.getUse_bind())) {
binding.tvCarplate.setText(user.getUse_bind().getPlate_number());
if (user.getUse_bind().getBusiness_type() == 5) {//5是出租车司机
binding.daka.setVisibility(View.VISIBLE);
} else {
binding.daka.setVisibility(View.GONE);
}
}
useBind = user.getUse_bind();
if (userResponseModel.getCode() == 7) {
BaseDialog.showcodeDialog(getActivity(), "温馨提示", userResponseModel.getMessage() + "", "去购买", new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), PackageListActivity.class);
startActivity(intent);
}
});
}
if (userResponseModel.getCode() == 5 || userResponseModel.getCode() == 4) {//4是过期,5是token不对,其他的错误暂时都是-1
Utils.toLogin(getActivity());
}
}
@Override
public void onError(@io.reactivex.rxjava3.annotations.NonNull Throwable e) {
}
@Override
public void onComplete() {
}
});
}
}
<file_sep>/kulun_jetpack/app/src/main/java/com/kulun/energynet/mine/systemsetting/SystemSettingActivity.java
package com.kulun.energynet.mine.systemsetting;
import android.content.Intent;
import androidx.databinding.DataBindingUtil;
import android.os.Bundle;
import com.kulun.energynet.R;
import com.kulun.energynet.databinding.ActivitySystemSettingBinding;
import com.kulun.energynet.login.PasswordLoginActivity;
import com.kulun.energynet.main.BaseActivity;
import com.kulun.energynet.mine.ChangePasswordActivity;
import com.kulun.energynet.mine.PersonalActivity;
import com.kulun.energynet.model.User;
import com.kulun.energynet.network.InternetWorkManager;
import com.kulun.energynet.network.MyObserver;
import com.kulun.energynet.network.RxHelper;
import com.kulun.energynet.network.API;
import com.kulun.energynet.utils.SharePref;
import com.kulun.energynet.utils.Utils;
public class SystemSettingActivity extends BaseActivity implements ISystemSettingView{
private ActivitySystemSettingBinding binding;
private SystemSettingPresent systemSettingPresent;
//private String apkpat
@Override
public void initView(Bundle savedInstanceState) {
binding = DataBindingUtil.setContentView(this ,R.layout.activity_system_setting);
systemSettingPresent = new SystemSettingPresent(this);
binding.title.setText("设置");
//apkpath = getIntent().getStringExtra(API.apppath);
binding.left.setOnClickListener(view -> finish());
binding.rePersonl.setOnClickListener(view -> {
systemSettingPresent.toPersonal();
});
binding.reChangePassword.setOnClickListener(view -> {
systemSettingPresent.tochangepassword();
});
binding.tvLoginOut.setOnClickListener(view -> {
systemSettingPresent.tologinout(SystemSettingActivity.this);
});
}
@Override
public void topersonalActivity() {
Intent intent = new Intent(SystemSettingActivity.this, PersonalActivity.class);
intent.putExtra(API.register, false);
startActivity(intent);
}
@Override
public void toChangePassword() {
Intent intent = new Intent(SystemSettingActivity.this, ChangePasswordActivity.class);
startActivity(intent);
}
@Override
public void toLoginOut() {
if (Utils.isFastClick()){
Utils.snackbar( SystemSettingActivity.this, "点击过快");
return;
}
}
}<file_sep>/kulun_jetpack/app/src/main/java/com/kulun/energynet/model/RefundDetail.java
package com.kulun.energynet.model;
import java.io.Serializable;
import java.util.List;
public class RefundDetail implements Serializable {
// "id": 6251,
// "status": 0,
// "amount": "1.00",
// "process": [
// ["退款申请", "2021年02月19日 17:16:27", ""],
// ["审核中", "2021年02月26日 13:55:57", ""]
// ],
// "detail": [{
// "name": "账单类型",
// "value": "退款"
// }, {
// "name": "退款进度",
// "value": ""
// }]
private int id, status;
private String amount;
private List<List<String>> process;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
public List<List<String>> getProcess() {
return process;
}
public void setProcess(List<List<String>> process) {
this.process = process;
}
}
<file_sep>/kulun_coroutine/app/src/main/java/com/kulun/energynet/customizeView/TextViewDinCondensedBold.java
package com.kulun.energynet.customizeView;
import android.content.Context;
import android.graphics.Typeface;
import android.util.AttributeSet;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatTextView;
import com.kulun.energynet.main.MyApplication;
public class TextViewDinCondensedBold extends AppCompatTextView {
Typeface tfDinConBold = Typeface.createFromAsset(MyApplication.getInstance().getAssets(), "fonts/DIN Condensed Bold.woff.ttf");
public TextViewDinCondensedBold(Context context) {
super(context);
setTypeface(tfDinConBold);
}
public TextViewDinCondensedBold(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
setTypeface(tfDinConBold);
}
public TextViewDinCondensedBold(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
setTypeface(tfDinConBold);
}
}
<file_sep>/kulun_jetpack/app/src/main/java/com/kulun/energynet/utils/BaseDialog.java
package com.kulun.energynet.utils;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.AsyncTask;
import androidx.appcompat.app.AlertDialog;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import com.kulun.energynet.R;
import java.util.ArrayList;
import cn.bingoogolapple.qrcode.zxing.QRCodeEncoder;
/**
* created by xuedi on 2019/8/16
*/
public class BaseDialog {
public static void showDialog(Context context,String titleMessage,String contentMessage,String confirmMessage, View.OnClickListener confirmListener){
AlertDialog alertDialog = null;
AlertDialog.Builder builder = new AlertDialog.Builder(context, R.style.mydialog);
View view = LayoutInflater.from(context).inflate(R.layout.dialog_base, null);
builder.setView(view);
alertDialog = builder.create();
TextView title = view.findViewById(R.id.tv_title);
TextView cancel = view.findViewById(R.id.tv_cancel);
TextView confirm = view.findViewById(R.id.tv_confrim);
TextView message = view.findViewById(R.id.tv_message);
title.setText(titleMessage);
cancel.setText("取消");
confirm.setText(confirmMessage);
message.setText(contentMessage);
AlertDialog finalAlertDialog = alertDialog;
cancel.setOnClickListener(view1 -> {
finalAlertDialog.dismiss();
});
AlertDialog finalAlertDialog1 = alertDialog;
confirm.setOnClickListener(view1 -> {
confirmListener.onClick(view1);
finalAlertDialog1.dismiss();
});
alertDialog.show();
}
public static void showcodeDialog(Context context, String titleMessage, String contentMessage,String confirmMessage,View.OnClickListener confirmListener){
AlertDialog alertDialog = null;
AlertDialog.Builder builder = new AlertDialog.Builder(context, R.style.mydialog);
View view = LayoutInflater.from(context).inflate(R.layout.dialog_code, null);
builder.setView(view);
alertDialog = builder.create();
alertDialog.setCancelable(false);
alertDialog.setCanceledOnTouchOutside(false);
TextView title = view.findViewById(R.id.tv_title);
TextView confirm = view.findViewById(R.id.tv_confirm);
TextView textView = view.findViewById(R.id.tv_message);
title.setText(titleMessage);
textView.setText(contentMessage);
confirm.setText(confirmMessage);
AlertDialog finalAlertDialog1 = alertDialog;
confirm.setOnClickListener(view1 -> {
confirmListener.onClick(view1);
finalAlertDialog1.dismiss();
});
alertDialog.show();
}
public static void showcodeblueDialog(Context context, String titleMessage, String contentMessage,String bluelistMessage,String confirmMessage,View.OnClickListener confirmListener){
AlertDialog alertDialog = null;
AlertDialog.Builder builder = new AlertDialog.Builder(context, R.style.mydialog);
View view = LayoutInflater.from(context).inflate(R.layout.dialog_code_blue, null);
builder.setView(view);
alertDialog = builder.create();
alertDialog.setCancelable(false);
alertDialog.setCanceledOnTouchOutside(false);
TextView title = view.findViewById(R.id.tv_title);
TextView confirm = view.findViewById(R.id.tv_confirm);
TextView textView = view.findViewById(R.id.tv_message);
TextView blue = view.findViewById(R.id.tv_message_blue);
title.setText(titleMessage);
textView.setText(contentMessage);
SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(bluelistMessage);
spannableStringBuilder.setSpan(new ForegroundColorSpan(context.getResources().getColor(R.color.text_color)),0,bluelistMessage.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
char[] mychar = bluelistMessage.toCharArray();
for (int i = 0; i < mychar.length; i++) {
if (((Character)mychar[i]).equals('【')){
spannableStringBuilder.setSpan(new ForegroundColorSpan(context.getResources().getColor(R.color.black)),i,i+1, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
}
if (((Character)mychar[i]).equals('】')){
spannableStringBuilder.setSpan(new ForegroundColorSpan(context.getResources().getColor(R.color.black)),i,i+1, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
}
}
blue.setText(spannableStringBuilder);
// blue.setText(bluelistMessage);
confirm.setText(confirmMessage);
AlertDialog finalAlertDialog1 = alertDialog;
confirm.setOnClickListener(view1 -> {
confirmListener.onClick(view1);
finalAlertDialog1.dismiss();
});
alertDialog.show();
}
public static void showQrDialog(Activity context, String carplate){
AlertDialog alertDialog = null;
AlertDialog.Builder builder = new AlertDialog.Builder(context, R.style.mydialog);
View view = LayoutInflater.from(context).inflate(R.layout.dialog_image, null);
builder.setView(view);
alertDialog = builder.create();
ImageView imageView = view.findViewById(R.id.image);
TextView textView = view.findViewById(R.id.carplate);
textView.setText(carplate);
if (carplate.equals("")){
textView.setVisibility(View.GONE);
}else {
textView.setVisibility(View.VISIBLE);
}
createQRCodeWithLogo(imageView,context, true,Utils.getAccount(context)+"&"+carplate, 300);
alertDialog.show();
}
public static void createQRCodeWithLogo(ImageView imageView, Context context,boolean isdialog, String accountNo, int size) {
new AsyncTask<Void, Void, Bitmap>() {
@Override
protected Bitmap doInBackground(Void... params) {
// Bitmap logoBitmap = BitmapFactory.decodeResource(context.getResources(), R.mipmap.icon_car);
if (isdialog) {
return QRCodeEncoder.syncEncodeQRCode(accountNo, size, context.getResources().getColor(R.color.text_color));
}else {
return QRCodeEncoder.syncEncodeQRCode(accountNo, size, context.getResources().getColor(R.color.white), Color.TRANSPARENT, null);
}
}
@Override
protected void onPostExecute(Bitmap bitmap) {
if (bitmap != null) {
imageView.setImageBitmap(bitmap);
} else {
// Toast.makeText(context, "生成二维码失败", Toast.LENGTH_SHORT).show();
}
}
}.execute();
}
}
<file_sep>/kulun_jetpack/app/src/main/java/com/kulun/energynet/requestbody/ClockRequest.java
package com.kulun.energynet.requestbody;
public class ClockRequest {
// map.put("bindId", String.valueOf(useBind.getId()));
// map.put("driverClockType", type+"");//0上班 1下班
// map.put("soc", String.valueOf(soc));
// map.put("carMile", String.valueOf(mile));
private int bindId, driverClockType, soc, carMile;
public int getBindId() {
return bindId;
}
public void setBindId(int bindId) {
this.bindId = bindId;
}
public int getDriverClockType() {
return driverClockType;
}
public void setDriverClockType(int driverClockType) {
this.driverClockType = driverClockType;
}
public int getSoc() {
return soc;
}
public void setSoc(int soc) {
this.soc = soc;
}
public int getCarMile() {
return carMile;
}
public void setCarMile(int carMile) {
this.carMile = carMile;
}
}
<file_sep>/kulun_jetpack/app/src/main/java/com/kulun/energynet/login/ForgetPasswordActivity.java
package com.kulun.energynet.login;
import androidx.databinding.DataBindingUtil;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import com.kulun.energynet.R;
import com.kulun.energynet.databinding.ActivityForgetPasswordBinding;
import com.kulun.energynet.main.BaseActivity;
import com.kulun.energynet.model.ResponseModel;
import com.kulun.energynet.model.User;
import com.kulun.energynet.network.InternetWorkManager;
import com.kulun.energynet.network.MyObserver;
import com.kulun.energynet.network.RxHelper;
import com.kulun.energynet.requestbody.ResetpasswordRequest;
import com.kulun.energynet.requestbody.SmsRequest;
import com.kulun.energynet.utils.MD5;
import com.kulun.energynet.utils.Mygson;
import com.kulun.energynet.utils.TimerCountUtils;
import com.kulun.energynet.utils.Utils;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.functions.Consumer;
import io.reactivex.rxjava3.schedulers.Schedulers;
/**
* created by xuedi on 2019/8/6
*/
public class ForgetPasswordActivity extends BaseActivity implements View.OnClickListener {
private ActivityForgetPasswordBinding binding;
private TimerCountUtils timeCount;
@Override
public void initView(Bundle savedInstanceState) {
binding = DataBindingUtil.setContentView(this, R.layout.activity_forget_password);
binding.imgBack.setOnClickListener(this);
binding.tvSmsReceive.setOnClickListener(this);
binding.tvBack.setOnClickListener(this);
binding.imgRegister.setOnClickListener(this);
timeCount = new TimerCountUtils(binding.tvSmsReceive, 60000, 1000);
if (getIntent() != null && !TextUtils.isEmpty(getIntent().getStringExtra("tel"))) {
binding.etPhone.setText(getIntent().getStringExtra("tel"));
binding.etCode.requestFocus();
}
}
@Override
protected void onDestroy() {
if (timeCount != null) {
timeCount.cancelTime();
timeCount = null;
}
super.onDestroy();
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.img_back:
case R.id.tv_back:
finish();
break;
case R.id.img_register:
String myphones = binding.etPhone.getText().toString();
if (TextUtils.isEmpty(myphones)) {
Utils.snackbar(ForgetPasswordActivity.this, "手机号码不能为空");
return;
}
if (!Utils.isPhone(myphones, ForgetPasswordActivity.this)) {
return;
}
String code = binding.etCode.getText().toString();
if (TextUtils.isEmpty(code)) {
Utils.snackbar(ForgetPasswordActivity.this, "验证码不能为空");
return;
}
String passwordNew = binding.etPasswordNew.getText().toString();
String passwordConfirm = binding.etPasswordConfirm.getText().toString();
if (TextUtils.isEmpty(passwordNew) || TextUtils.isEmpty(passwordConfirm)) {
Utils.snackbar(ForgetPasswordActivity.this, "请输入密码");
return;
}
if (passwordNew.length() < 6) {
Utils.snackbar(ForgetPasswordActivity.this, "密码不能少于6位");
return;
}
if (!passwordNew.equals(passwordConfirm)) {
Utils.snackbar(ForgetPasswordActivity.this, "两次密码输入不一致");
return;
}
if (teshu(passwordNew)) {
Utils.snackbar(ForgetPasswordActivity.this, "密码含有特殊字符");
return;
}
changePassword(myphones, code, passwordNew);
break;
case R.id.tv_sms_receive:
if (Utils.isFastClick()) {
Utils.snackbar(ForgetPasswordActivity.this, "点击过快");
return;
}
String myphone = binding.etPhone.getText().toString();
if (!Utils.isPhone(myphone, ForgetPasswordActivity.this)) {
return;
}
getSmsCode(myphone);
break;
default:
break;
}
}
private void changePassword(String myphones, String code, String passwordNew) {
ResetpasswordRequest resetpasswordRequest = new ResetpasswordRequest();
resetpasswordRequest.setPhone(myphones);
resetpasswordRequest.setSms_code(code);
resetpasswordRequest.setPassword(<PASSWORD>(passwordNew));
InternetWorkManager.getRequest().resetpassword(Utils.body(Mygson.getInstance().toJson(resetpasswordRequest)))
.compose(RxHelper.observableIOMain(ForgetPasswordActivity.this))
.subscribe(new MyObserver<User>() {
@Override
public void onSuccess(User data) {
Utils.snackbar(ForgetPasswordActivity.this, "密码修改成功,请登录");
finish();
}
@Override
public void onFail(int code, String message) {
}
@Override
public void onError() {
}
@Override
public void onClearToken() {
Utils.toLogin(ForgetPasswordActivity.this);
}
});
// HashMap<String, String> map = new HashMap<>();
// map.put("phone", myphones);
// map.put("sms_code", code);
// map.put("password", <PASSWORD>(<PASSWORD>New));
// new MyRequest().myRequest(API.passwordReset, true,map,true, this, null, null, new Response() {
// @Override
// public void response(JsonObject json, JsonArray jsonArray,boolean isNull) {
// Utils.snackbar(ForgetPasswordActivity.this, "密码修改成功,请登录");
// finish();
// }
// });
}
//{
// "phone": "17794590705",
// "sms_type": 1
//}
private void getSmsCode(String myphone) {
// String spliceJson = JsonSplice.leftparent+JsonSplice.yin+"phone"+JsonSplice.yinandmao+JsonSplice.yin+myphone+JsonSplice.yinanddou+
// JsonSplice.yin+"sms_type"+JsonSplice.yinandmao+2+JsonSplice.rightparent;
SmsRequest smsRequest = new SmsRequest();
smsRequest.setPhone(myphone);
smsRequest.setSms_type(2);
InternetWorkManager.getRequest().sms(Utils.body(Mygson.getInstance().toJson(smsRequest)))
.compose(RxHelper.observableIOMain(this))
.subscribe(new MyObserver<User>() {
@Override
public void onSuccess(User data) {
if (timeCount != null) {
timeCount.start();
}
}
@Override
public void onFail(int code, String message) {
}
@Override
public void onError() {
}
@Override
public void onClearToken() {
Utils.toLogin(ForgetPasswordActivity.this);
}
});
// new MyRequest().spliceJson(API.getsms, true,spliceJson, this, null, null, new Response() {
// @Override
// public void response(JsonObject json, JsonArray jsonArray,boolean isNull) {
// if (timeCount != null) {
// timeCount.start();
// }
// }
// });
}
public boolean teshu(String string) {
String regEx = "[ _`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~!@#¥%……&*()——+|{}【】‘;:”“’。,、?]|\n|\r|\t";
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(string);
return m.find();
}
}
<file_sep>/kulun_jetpack/app/src/main/java/com/kulun/energynet/mine/systemsetting/SystemSettingModel.java
package com.kulun.energynet.mine.systemsetting;
import android.app.Activity;
import android.content.Intent;
import com.kulun.energynet.login.PasswordLoginActivity;
import com.kulun.energynet.model.User;
import com.kulun.energynet.network.API;
import com.kulun.energynet.network.InternetWorkManager;
import com.kulun.energynet.network.MyObserver;
import com.kulun.energynet.network.RxHelper;
import com.kulun.energynet.utils.SharePref;
import com.kulun.energynet.utils.Utils;
public class SystemSettingModel implements ISystemSettingModel{
// private ISystemSettingPresent iSystemSettingPresent;
// public SystemSettingModel(ISystemSettingPresent iSystemSettingPresent){
// this.iSystemSettingPresent = iSystemSettingPresent;
// }
@Override
public void loginout(Activity activity) {
InternetWorkManager.getRequest().logout()
.compose(RxHelper.observableIOMain(activity))
.subscribe(new MyObserver<User>() {
@Override
public void onSuccess(User data) {
Intent intent = new Intent(activity, PasswordLoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
User.getInstance().setToken("");
SharePref.put(activity, API.token, "");
SharePref.clear(activity);
activity.startActivity(intent);
activity.finish();
}
@Override
public void onFail(int code, String message) {
}
@Override
public void onError() {
}
@Override
public void onClearToken() {
Utils.toLogin(activity);
}
});
}
}
<file_sep>/kulun_coroutine/app/src/main/java/com/kulun/energynet/main/fragment/MyClickListener.java
package com.kulun.energynet.main.fragment;
import android.app.Activity;
import android.view.View;
import com.kulun.energynet.utils.Utils;
public class MyClickListener implements View.OnClickListener{
private Activity activity;
private View.OnClickListener listener;
public MyClickListener(Activity activity,View.OnClickListener listener){
this.activity = activity;
this.listener = listener;
}
@Override
public void onClick(View v) {
if (Utils.getToken(activity) == null || Utils.getToken(activity).equals("")) {
Utils.toLogin(activity);
Utils.snackbar(activity, "请先登陆");
return;
}
v.setOnClickListener(listener);
}
}
<file_sep>/kulun_coroutine/app/src/main/java/com/kulun/energynet/requestbody/ChangepasswordRequest.java
package com.kulun.energynet.requestbody;
public class ChangepasswordRequest {
//map.put("password", MD5.encode(oldpassword));
// map.put("new_password", MD5.encode(newpassword));
private String password, new_password;
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getNew_password() {
return new_password;
}
public void setNew_password(String new_password) {
this.new_password = new_password;
}
}
<file_sep>/kulun_jetpack/app/src/main/java/com/kulun/energynet/popup/StationBaoAllPopup.java
package com.kulun.energynet.popup;
import android.app.Dialog;
import android.content.Context;
import android.view.Gravity;
import android.view.View;
import androidx.databinding.DataBindingUtil;
import androidx.fragment.app.Fragment;
import com.kulun.energynet.R;
import com.kulun.energynet.databinding.StationBaoAllPopupBinding;
import razerdp.basepopup.BasePopupWindow;
public class StationBaoAllPopup extends BasePopupWindow {
public StationBaoAllPopupBinding binding;
private Context context;
public StationBaoAllPopup(Context context) {
super(context);
setPopupGravity(Gravity.BOTTOM);
this.context = context;
}
public StationBaoAllPopup(Context context, int width, int height) {
super(context, width, height);
}
public StationBaoAllPopup(Fragment fragment) {
super(fragment);
}
public StationBaoAllPopup(Fragment fragment, int width, int height) {
super(fragment, width, height);
}
public StationBaoAllPopup(Dialog dialog) {
super(dialog);
}
public StationBaoAllPopup(Dialog dialog, int width, int height) {
super(dialog, width, height);
}
@Override
public View onCreateContentView() {
View view = createPopupById(R.layout.station_bao_all_popup);
binding = DataBindingUtil.bind(view);
return view;
}
}
<file_sep>/kulun_jetpack/app/src/main/java/com/kulun/energynet/bill/QuestionShowActivity.java
package com.kulun.energynet.bill;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import com.kulun.energynet.R;
import com.kulun.energynet.customizeView.ViewUtils;
import com.kulun.energynet.databinding.ActivityShowActivityBinding;
import com.kulun.energynet.model.Bill;
import com.kulun.energynet.model.BilldetailModel;
import com.kulun.energynet.model.QuestionshowModel;
import com.kulun.energynet.model.RefundDetail;
import com.kulun.energynet.network.InternetWorkManager;
import com.kulun.energynet.network.MyObserver;
import com.kulun.energynet.network.RxHelper;
import com.kulun.energynet.requestbody.QuestionshowRequest;
import com.kulun.energynet.utils.Mygson;
import com.kulun.energynet.utils.Utils;
public class QuestionShowActivity extends AppCompatActivity {
private ActivityShowActivityBinding binding;
private Bill bill;
private String site;
private int exId;
private RefundDetail refundDetail;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = DataBindingUtil.setContentView(this, R.layout.activity_show_activity);
binding.header.title.setText("问题反馈");
binding.header.left.setOnClickListener(v -> finish());
bill = (Bill) getIntent().getSerializableExtra("bill");
site = getIntent().getStringExtra("site");
exId = getIntent().getIntExtra("exId", 0);
binding.station.setText(site + "");
binding.number.setText("订单号:" + getIntent().getStringExtra("orderNo"));
refundDetail = (RefundDetail) getIntent().getSerializableExtra("data");
binding.check.setOnClickListener(v -> {
Intent intent = new Intent(this, RefundDetailActivity.class);
intent.putExtra("data", refundDetail);
startActivity(intent);
});
QuestionshowRequest questionshowRequest = new QuestionshowRequest();
questionshowRequest.setExId(exId);
InternetWorkManager.getRequest().questionshow(Utils.body(Mygson.getInstance().toJson(questionshowRequest)))
.compose(RxHelper.observableIOMain(this))
.subscribe(new MyObserver<QuestionshowModel>() {
@Override
public void onSuccess(QuestionshowModel data) {
if (data.getContent() != null) {
binding.question.setText("问题:" + data.getContent());
binding.imageview.setImageResource(R.mipmap.sign_processing);
}
if (data.getHandleContent() != null) {
binding.fankui.setText("反馈:" + data.getHandleContent());
}
if (data.getStatus() != 0) {
binding.imageview.setImageResource(R.mipmap.sign_success);
}
}
@Override
public void onFail(int code, String message) {
}
@Override
public void onError() {
}
@Override
public void onClearToken() {
Utils.toLogin(QuestionShowActivity.this);
}
});
}
@Override
protected void onResume() {
super.onResume();
InternetWorkManager.getRequest().billDetail(bill.getBid(), bill.getcType())
.compose(RxHelper.observableIOMain(this))
.subscribe(new MyObserver<BilldetailModel>() {
@Override
public void onSuccess(BilldetailModel data) {
refundDetail = data.getRefundDetail();
if (refundDetail.getId() != 0) {//有退款记录
binding.check.setVisibility(View.VISIBLE);
} else {
binding.check.setVisibility(View.GONE);
}
}
@Override
public void onFail(int code, String message) {
}
@Override
public void onError() {
}
@Override
public void onClearToken() {
Utils.toLogin(QuestionShowActivity.this);
}
});
}
}
<file_sep>/kulun_coroutine/app/src/main/java/com/kulun/energynet/network/MyObserver.java
package com.kulun.energynet.network;
import com.kulun.energynet.model.ResponseModel;
import com.kulun.energynet.model.User;
import com.kulun.energynet.utils.SharePref;
import com.kulun.energynet.utils.Utils;
import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;
public abstract class MyObserver<T> implements Observer<ResponseModel<T>> {
@Override
public void onSubscribe(@NonNull Disposable d) {
Utils.log("myobserver onSubscribe");
}
@Override
public void onNext(@NonNull ResponseModel<T> tResponseModel) {
if (tResponseModel.getCode() == 0) {
onSuccess(tResponseModel.getData());
} else {
if (!tResponseModel.getMessage().equals("未查询到优惠券")) {
Utils.snackbar(tResponseModel.getMessage());
}
onFail(tResponseModel.getCode(), tResponseModel.getMessage());
if (tResponseModel.getCode() == 5 || tResponseModel.getCode() == 4) {//4是过期,5是token不对,其他的错误暂时都是-1
onClearToken();
}
}
}
@Override
public void onError(@NonNull Throwable e) {
Utils.snackbar(API.net_error);
onError();
Utils.log("myobserver onError");
}
@Override
public void onComplete() {
Utils.log("myobserver onComplete");
}
public abstract void onSuccess(T data);
public abstract void onFail(int code, String message);
public abstract void onError();
public abstract void onClearToken();
}
<file_sep>/kulun_coroutine/app/src/main/java/com/kulun/energynet/network/RxHelper.java
package com.kulun.energynet.network;
import android.app.Activity;
import android.content.Context;
import androidx.lifecycle.LifecycleOwner;
import com.trello.rxlifecycle4.android.ActivityEvent;
import com.trello.rxlifecycle4.components.RxActivity;
import com.trello.rxlifecycle4.components.support.RxAppCompatActivity;
import com.trello.rxlifecycle4.components.support.RxFragmentActivity;
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.core.Flowable;
import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.ObservableSource;
import io.reactivex.rxjava3.core.ObservableTransformer;
import io.reactivex.rxjava3.schedulers.Schedulers;
public class RxHelper {
public static <T> ObservableTransformer<T,T> observableIOMain(Activity context){
return upstream -> {
Observable<T> observable = upstream.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread());
return composeContext(context, observable);
};
}
private static <T> ObservableSource<T> composeContext(Context context, Observable<T> observable) {
if(context instanceof RxActivity) {
return observable.compose(((RxActivity) context).bindUntilEvent(ActivityEvent.DESTROY));
} else if(context instanceof RxFragmentActivity){
return observable.compose(((RxFragmentActivity) context).bindUntilEvent(ActivityEvent.DESTROY));
}else if(context instanceof RxAppCompatActivity){
return observable.compose(((RxAppCompatActivity) context).bindUntilEvent(ActivityEvent.DESTROY));
}else {
return observable;
}
}
}
<file_sep>/kulun_coroutine/app/src/main/java/com/kulun/energynet/bill/EvaluateActivity.java
package com.kulun.energynet.bill;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.kulun.energynet.R;
import com.kulun.energynet.customizeView.ToastUtils;
import com.kulun.energynet.model.Bill;
import com.kulun.energynet.model.ResponseModel;
import com.kulun.energynet.model.User;
import com.kulun.energynet.network.InternetWorkManager;
import com.kulun.energynet.network.MyObserver;
import com.kulun.energynet.network.RxHelper;
import com.kulun.energynet.requestbody.StatuploadModel;
import com.kulun.energynet.requestparams.MyRequest;
import com.kulun.energynet.requestparams.Response;
import com.kulun.energynet.network.API;
import com.kulun.energynet.utils.JsonSplice;
import com.kulun.energynet.utils.Mygson;
import com.kulun.energynet.utils.Utils;
import java.util.ArrayList;
import java.util.List;
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.functions.Consumer;
import io.reactivex.rxjava3.schedulers.Schedulers;
public class EvaluateActivity extends AppCompatActivity implements View.OnClickListener {
private ImageView mBack;
// private TextView mCommit;
private TextView mSerialNo;
private TextView mStation;
private TextView mStar1;
private TextView mStar2;
private TextView mStar3;
private TextView mStar4;
private TextView mStar5;
private TextView mStarText;
private TextView mTag1;
private TextView mTag2;
private TextView mTag3;
private TextView mTag4;
private String serialNum;
private String stationName;
private List<TextView> list = new ArrayList<TextView>();
private String exchangeRecordId;
private Integer starsNumber = 0;
private String content = "";
private String tagSerial = "";
private String tagContent = "";
private String site;
private int siteid;
private Bill bill;
private int exId;
private String orderNo;
private TextView commit;
private long lastBackTime = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.evaluate);
Intent intent = getIntent();
exchangeRecordId = intent.getStringExtra("exchangeRecordId");
serialNum = intent.getStringExtra("serialNum");
stationName = intent.getStringExtra("stationName");
site = intent.getStringExtra("site");
siteid = intent.getIntExtra("siteid", 0);
bill = (Bill) intent.getSerializableExtra("bill");
exId = getIntent().getIntExtra("exId", 0);
orderNo = getIntent().getStringExtra("orderNo");
bindView();
}
public void bindView() {
mBack = (ImageView) this.findViewById(R.id.left);
// mCommit = (TextView) this.findViewById(R.id.evaluate_commit);
mSerialNo = (TextView) this.findViewById(R.id.evaluate_serial_no);
mStation = (TextView) this.findViewById(R.id.evaluate_station);
mStar1 = (TextView) this.findViewById(R.id.evaluate_star1);
mStar2 = (TextView) this.findViewById(R.id.evaluate_star2);
mStar3 = (TextView) this.findViewById(R.id.evaluate_star3);
mStar4 = (TextView) this.findViewById(R.id.evaluate_star4);
mStar5 = (TextView) this.findViewById(R.id.evaluate_star5);
mStarText = (TextView) this.findViewById(R.id.evaluate_star_text);
mTag1 = (TextView) this.findViewById(R.id.evaluate_tag1);
mTag2 = (TextView) this.findViewById(R.id.evaluate_tag2);
mTag3 = (TextView) this.findViewById(R.id.evaluate_tag3);
mTag4 = (TextView) this.findViewById(R.id.evaluate_tag4);
commit = findViewById(R.id.finish);
commit.setOnClickListener(this);
mSerialNo.setText("订单号:" + orderNo);
mStation.setText(site);
mBack.setOnClickListener(this);
// mCommit.setOnClickListener(this);
mStar1.setOnClickListener(this);
mStar2.setOnClickListener(this);
mStar3.setOnClickListener(this);
mStar4.setOnClickListener(this);
mStar5.setOnClickListener(this);
mTag1.setOnClickListener(this);
mTag2.setOnClickListener(this);
mTag3.setOnClickListener(this);
mTag4.setOnClickListener(this);
list.add(mStar1);
list.add(mStar2);
list.add(mStar3);
list.add(mStar4);
list.add(mStar5);
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.left:
finish();
break;
case R.id.evaluate_star1:
starSelected(1);
break;
case R.id.evaluate_star2:
starSelected(2);
break;
case R.id.evaluate_star3:
starSelected(3);
break;
case R.id.evaluate_star4:
starSelected(4);
break;
case R.id.evaluate_star5:
starSelected(5);
break;
case R.id.evaluate_tag1:
tagSelected(mTag1);
break;
case R.id.evaluate_tag2:
tagSelected(mTag2);
break;
case R.id.evaluate_tag3:
tagSelected(mTag3);
break;
case R.id.evaluate_tag4:
tagSelected(mTag4);
break;
case R.id.finish:
if (System.currentTimeMillis() - lastBackTime > 10 * 1000) {
commit();
lastBackTime = System.currentTimeMillis();
} else { //如果两次按下的时间差小于2秒,则退出程序
ToastUtils.showShort("按键过快,请10秒后再点击哦", this);
}
break;
default:
break;
}
}
private void commit(){
tagSerial = "";
tagContent = "";
if(starsNumber == 0) {
// ToastUtil.showToast(mContext, "请选择评分");
Utils.snackbar(EvaluateActivity.this, "请选择评分");
return;
}
if(mTag1.isSelected()) {
tagSerial = tagSerial + 1;
tagContent = tagContent + mTag1.getText();
}
if(mTag2.isSelected()) {
tagSerial = tagSerial + "," + 2;
tagContent = tagContent + "," + mTag2.getText();
}
if(mTag3.isSelected()) {
tagSerial = tagSerial + "," + 3;
tagContent = tagContent + "," + mTag3.getText();
}
if(mTag4.isSelected()) {
tagSerial = tagSerial + "," + 4;
tagContent = tagContent + "," + mTag4.getText();
}
if(tagSerial.startsWith(",")) {
tagSerial = tagSerial.substring(1);
tagContent = tagContent.substring(1);
}
//{
// "bid": 2697877,
// "siteId": 67,
// "starNumber": 5,
// "tagList": "1,2",
// "tagContent": "站内环境整洁,员工服务热情",
// "content": "非常好"
//}
if (content.equals("")){
Utils.snackbar(EvaluateActivity.this, "请选择星星");
return;
}
if (starsNumber == 0){
Utils.snackbar(EvaluateActivity.this, "请选择星星");
return;
}
// String json = JsonSplice.leftparent+JsonSplice.yin+"exId"+JsonSplice.yinandmao+exId+JsonSplice.dou+
// JsonSplice.yin+"siteId"+JsonSplice.yinandmao+siteid+JsonSplice.dou+
// JsonSplice.yin+"starNumber"+JsonSplice.yinandmao+starsNumber+JsonSplice.dou+
// JsonSplice.yin+"content"+JsonSplice.yinandmao+JsonSplice.yin+content+JsonSplice.yin+JsonSplice.rightparent;
// new MyRequest().spliceJson(API.commentCommit, true, json, EvaluateActivity.this, null, null, new Response() {
// @Override
// public void response(JsonObject json, JsonArray jsonArray, boolean isNull) {
// Utils.snackbar(EvaluateActivity.this, "评价上传成功");
// finish();
// }
// });
StatuploadModel statuploadModel = new StatuploadModel();
statuploadModel.setExId(exId);
statuploadModel.setSiteId(siteid);
statuploadModel.setStarNumber(starsNumber);
statuploadModel.setContent(content);
InternetWorkManager.getRequest().startUpload(Utils.body(Mygson.getInstance().toJson(statuploadModel)))
.compose(RxHelper.observableIOMain(this))
.subscribe(new MyObserver<User>() {
@Override
public void onSuccess(User data) {
Utils.snackbar(EvaluateActivity.this, "评价上传成功");
finish();
}
@Override
public void onFail(int code, String message) {
}
@Override
public void onError() {
}
@Override
public void onClearToken() {
Utils.toLogin(EvaluateActivity.this);
}
});
}
public void starSelected(Integer grade) {
if(grade <= 2) {
tagAllClear();
}
for(int i=0;i<grade;i++) {
list.get(i).setBackgroundResource(R.mipmap.star);
}
for(int i=grade;i<list.size();i++) {
list.get(i).setBackgroundResource(R.mipmap.star2);
}
switch (grade) {
case 1:
starsNumber = 1;
mStarText.setText("不满意,很失望");
content = "不满意,很失望";
break;
case 2:
starsNumber = 2;
mStarText.setText("不满意,有点失望");
content = "不满意,有点失望";
break;
case 3:
starsNumber = 3;
mStarText.setText("一般");
content = "一般";
break;
case 4:
starsNumber = 4;
mStarText.setText("满意");
content = "满意";
break;
case 5:
starsNumber = 5;
mStarText.setText("很满意");
content = "很满意";
break;
default:
break;
}
}
public void tagSelected(TextView view) {
if(starsNumber == 0) {
// ToastUtil.showToast(mContext, "请先选择星级");
Utils.snackbar(EvaluateActivity.this, "请先选择星级");
return;
} else if(starsNumber <= 2) {
// ToastUtil.showToast(mContext, "两星以下不能选择标签");
Utils.snackbar(EvaluateActivity.this, "两星以下不能选择标签");
return;
} else {
if(view.isSelected()) {
view.setSelected(false);
view.setTextColor(Color.parseColor("#8A8A8A"));
} else {
view.setSelected(true);
view.setTextColor(Color.parseColor("#FFD700"));
}
}
}
public void tagAllClear() {
mTag1.setSelected(false);
mTag2.setSelected(false);
mTag3.setSelected(false);
mTag4.setSelected(false);
mTag1.setTextColor(Color.parseColor("#8A8A8A"));
mTag2.setTextColor(Color.parseColor("#8A8A8A"));
mTag3.setTextColor(Color.parseColor("#8A8A8A"));
mTag4.setTextColor(Color.parseColor("#8A8A8A"));
}
}
<file_sep>/kulun_coroutine/app/src/main/java/com/kulun/energynet/requestbody/LoginPasswordRequest.java
package com.kulun.energynet.requestbody;
public class LoginPasswordRequest {
// hashMap.put("phone", phone);
// hashMap.put("password", MD5.encode(code));
private String phone, password;
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = <PASSWORD>;
}
}
<file_sep>/kulun_jetpack/app/src/main/java/com/kulun/energynet/mine/AppointmentKtActivity.kt
package com.kulun.energynet.mine
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.kulun.energynet.R
import com.kulun.energynet.databinding.ActivityReserveBinding
import com.kulun.energynet.databinding.AdapterReserverBinding
import com.kulun.energynet.main.BaseActivity
import com.kulun.energynet.model.Reserver
import com.kulun.energynet.network.InternetWorkManager
import com.kulun.energynet.network.MyObserver
import com.kulun.energynet.network.RxHelper
import com.kulun.energynet.utils.Utils
class AppointmentKtActivity : BaseActivity() {
private lateinit var binding: ActivityReserveBinding
private lateinit var adapter: MyAdapter
private var list = ArrayList<Reserver>()
override fun initView(savedInstanceState: Bundle?) {
binding = DataBindingUtil.setContentView(this, R.layout.activity_reserve)
binding.header.left.setOnClickListener { finish() }
binding.header.title.setText("我的预约")
binding.smartRefresh.setOnRefreshListener {
loadData()
}
binding.smartRefresh.autoRefresh()
adapter = MyAdapter()
binding.recyclerView.layoutManager = LinearLayoutManager(applicationContext)
binding.recyclerView.adapter = adapter
}
private fun loadData() {
InternetWorkManager.getRequest().appointmentList()
.compose(RxHelper.observableIOMain(this))
.subscribe(object : MyObserver<List<Reserver>?>() {
override fun onFail(code: Int, message: String) {
Utils.finishRefresh(binding.smartRefresh)
}
override fun onError() {
Utils.finishRefresh(binding.smartRefresh)
}
override fun onClearToken() {
Utils.toLogin(this@AppointmentKtActivity)
}
override fun onSuccess(data: List<Reserver>?) {
Utils.finishRefresh(binding.smartRefresh)
if (data == null) {
binding.image.visibility = View.VISIBLE
return
}
list.clear()
list.addAll(data)
adapter.notifyDataSetChanged()
binding.image.visibility = if (list.size > 0) View.GONE else View.VISIBLE
}
})
}
inner class MyAdapter : RecyclerView.Adapter<MyViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
var view = LayoutInflater.from(parent.context).inflate(R.layout.adapter_reserver, null)
var adapterBinding = AdapterReserverBinding.bind(view)
return MyViewHolder(adapterBinding)
}
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
val contentBean = list[position]
var status = ""
when (contentBean.status) {
0 -> {
status = "预约中"
colorReserverOrExchangeBatteryDone(holder)
}
1 -> {
status = "取消预约"
colorNotDone(holder)
}
2 -> {
status = "预约超时"
colorNotDone(holder)
}
3 -> {
status = "换电完成"
colorReserverOrExchangeBatteryDone(holder)
}
else -> {
}
}
holder.adapterbinding.tvStatus.setText(status)
holder.adapterbinding.tvStation.setText(contentBean.site)
holder.adapterbinding.carplate.setText("车牌号:" + contentBean.plate)
holder.adapterbinding.tvTime.setText("预约时间:" + contentBean.time)
}
private fun colorReserverOrExchangeBatteryDone(holder: MyViewHolder) {
holder.adapterbinding.tvStatus.setTextColor(ContextCompat.getColor(applicationContext,R.color.black))
holder.adapterbinding.tvTime.setTextColor(ContextCompat.getColor(applicationContext,R.color.black))
holder.adapterbinding.tvStation.setTextColor(ContextCompat.getColor(applicationContext,R.color.black))
holder.adapterbinding.carplate.setTextColor(ContextCompat.getColor(applicationContext,R.color.black))
}
private fun colorNotDone(holder: MyViewHolder) {
holder.adapterbinding.tvStatus.setTextColor(ContextCompat.getColor(applicationContext,R.color.reserverunfinish))
holder.adapterbinding.tvTime.setTextColor(ContextCompat.getColor(applicationContext,R.color.reserverunfinish))
holder.adapterbinding.tvStation.setTextColor(ContextCompat.getColor(applicationContext,R.color.reserverunfinish))
holder.adapterbinding.carplate.setTextColor(ContextCompat.getColor(applicationContext,R.color.reserverunfinish))
}
override fun getItemCount(): Int = list.size
}
class MyViewHolder(adapterbinding: AdapterReserverBinding) :
RecyclerView.ViewHolder(adapterbinding.root) {
var adapterbinding = adapterbinding;
}
}<file_sep>/kulun_jetpack/app/src/main/java/com/kulun/energynet/bill/RefundDetailActivity.java
package com.kulun.energynet.bill;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import com.kulun.energynet.R;
import com.kulun.energynet.databinding.ActivityRefundDetailFromShowBinding;
import com.kulun.energynet.model.RefundDetail;
import com.kulun.energynet.utils.Utils;
import com.trello.rxlifecycle4.components.support.RxAppCompatActivity;
import java.util.List;
public class RefundDetailActivity extends RxAppCompatActivity {
private ActivityRefundDetailFromShowBinding binding;
private RefundDetail refundDetail;
private Drawable drawable;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = DataBindingUtil.setContentView(this ,R.layout.activity_refund_detail_from_show);
binding.header.left.setOnClickListener(v -> finish());
binding.header.title.setText("账单详情");
refundDetail = (RefundDetail) getIntent().getSerializableExtra("data");
binding.money.setText("-"+refundDetail.getAmount()+"元");
String s = "";
switch (refundDetail.getStatus()){
case 0:
s="退款中";
binding.type.setTextColor(getResources().getColor(R.color.yellow));
binding.result.setText("审核中");
binding.result.setTextColor(getResources().getColor(R.color.info));
drawable = getResources().getDrawable(R.mipmap.icon_choice_normal);
drawable.setBounds(0, 0, 50, 50);
binding.result.setCompoundDrawables(drawable, null, null, null);
binding.time1.setText(refundDetail.getProcess().get(0).get(1));
binding.content1.setText(refundDetail.getProcess().get(0).get(2));
binding.time2.setText(refundDetail.getProcess().get(1).get(1));
binding.content2.setText(refundDetail.getProcess().get(1).get(2));
binding.line1.setBackgroundColor(getResources().getColor(R.color.gray));
break;
case 1:
s="退款已通过";
binding.type.setTextColor(getResources().getColor(R.color.black));
binding.result.setText("退款已通过");
binding.result.setTextColor(getResources().getColor(R.color.text_color));
drawable = getResources().getDrawable(R.mipmap.icon_choice_selected);
drawable.setBounds(0, 0, 50, 50);
binding.result.setCompoundDrawables(drawable, null, null, null);
binding.time1.setText(refundDetail.getProcess().get(0).get(1));
binding.content1.setText(refundDetail.getProcess().get(0).get(2));
binding.time2.setText(refundDetail.getProcess().get(1).get(1));
binding.content2.setText(refundDetail.getProcess().get(1).get(2));
binding.line1.setBackgroundColor(getResources().getColor(R.color.text_color));
break;
case 2:
s="退款未通过";
binding.type.setTextColor(getResources().getColor(R.color.red));
binding.result.setText("退款未通过");
binding.result.setTextColor(getResources().getColor(R.color.text_color));
drawable = getResources().getDrawable(R.mipmap.icon_choice_selected);
drawable.setBounds(0, 0, 50, 50);
binding.result.setCompoundDrawables(drawable, null, null, null);
binding.time1.setText(refundDetail.getProcess().get(0).get(1));
binding.content1.setText(refundDetail.getProcess().get(0).get(2));
binding.time2.setText(refundDetail.getProcess().get(1).get(1));
binding.content2.setText(refundDetail.getProcess().get(1).get(2));
binding.line1.setBackgroundColor(getResources().getColor(R.color.text_color));
break;
default:
break;
}
binding.type.setText(s);
}
}
| 1c6894ecafcab0a1468b41075057c763b4dfb22f | [
"Java",
"Kotlin",
"Gradle"
] | 36 | Java | wannaRunaway/klwork | 694615cad7e002aba0c90dfc3be8aba6200b63f6 | 3184f0ea2299d9ee3f97ade63f7665c3467ada80 |
refs/heads/master | <repo_name>kotrma/Savana<file_sep>/english.php
<?php
if (empty($_POST) === false) {
$errors = array();
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
if (empty($name) === true || empty($email) === true || empty($message) === true) {
$errors[] = 'Name,email and message required';
} else {
if (filter_var($email, FILTER_VALIDATE_EMAIL) === false ) {
$errors[] = 'That\'s not a valid email address';
}
}
if (empty($errors) === true) {
//send email
mail('<EMAIL>','Contact form', $message,'From: ' .$email);
//redirect user
header('Location: index.php?sent');
exit();
}
}
?>
<!doctype html>
<!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7" lang=""> <![endif]-->
<!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8" lang=""> <![endif]-->
<!--[if IE 8]> <html class="no-js lt-ie9" lang=""> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" lang="en"> <!--<![endif]-->
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Savana</title>
<meta name="description" content="splav,kafe,odmor,kej,savana">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="apple-touch-icon" href="apple-touch-icon.png">
<link href="https://fonts.googleapis.com/css?family=Open+Sans+Condensed:300" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Slabo+27px" rel="stylesheet">
<link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css" />
<link rel="stylesheet" href="css/animate.min.css">
<link rel="stylesheet" href="css/bootstrap.min.css">
<link rel="stylesheet" href="css/bootstrap-theme.min.css">
<link rel="stylesheet" href="css/main.css">
<link rel="stylesheet" href="css/lightbox.css">
<script src="js/vendor/modernizr-2.8.3-respond-1.4.2.min.js"></script>
</head>
<body>
<!--[if lt IE 8]>
<p class="browserupgrade">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.</p>
<![endif]-->
<nav class="navbar navbar-default navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<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="#">Savana</a>
<div class="language">
<a href="index.php"><img src="img/sr.png"></a>
<a href="english.php"><img src="img/en.png"></a>
</div>
</div>
<div id="navbar" class="navbar-collapse collapse pull-right">
<ul class="nav navbar-nav">
<li><a href="#home">Home</a></li>
<li><a href="#about">About us</a></li>
<li><a href="#portfolio">Prices</a></li>
<li><a href="#gallery">Gallery</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
</div><!--/.navbar-collapse -->
</div>
</nav>
<div id="home">
<div class="container">
<div class="row">
<div class="col-xs-12">
<h1 class="cover wow fadeInDown" data-wow-duration="1s">Savana</h1>
<h2 class="cover wow fadeInUp" data-wow-duration="1s">Phone: 064/110-200-4</h2>
</div>
</div>
</div>
</div>
<div id="about" class="container">
<div class="row">
<h3>About us</h3>
<div class="col-xs-12 col-sm-6 col-md-6 col-lg-6">
<img src="img/about.png" class="img-responsive">
</div>
<div class="col-xs-12 col-sm-6 col-md-6 col-lg-6">
<p>
You believe that there is something deep in our genes that connects us with the African landscapes, something that goes back in time ...</p>
<p>With the rhythm of blues, which made the ambience of soft wood and natural materials, warm as the sun Africa, while the Danube offers you yourself discover how easy it is to be special.</p>
<p>At Savana is just as pleasant to drink an espresso in the morning alone, seen moored the boat and the fishermen, listen to the cries of gulls, enjoy after a walk with the dog ...
</p>
<p>Strange love with the place where you like daily emotion of satisfaction with every guest and conveys a good amount of positive energie.If you like a river, a good espresso, if you share your beautiful moments with your dog, if it is for you to enjoy blues music that you wear in youre genes- to Savana, you say yourself-I belong here, this is my place.
</p>
</div>
</div>
</div>
</div>
<div class="baner">
<div class="container">
<div class="row">
<h2>The best way to find yourself is to lose yourself in the service of others.</h2>
<p>-<NAME></p>
</div>
</div>
</div>
<div id="portfolio" class="container-fluid">
<div class="row">
<h3>Prices</h3>
<div class="col-xs-6 col-sm-4 col-lg-3">
<div class="cover wow fadeInRight" data-wow-duration="3s" data-wow-delay="0s" >
<span class="fa fa-flask fa-2x"></span>
<h4>Juice</h4>
<p>Limunana: 190,00</p>
<p>Guarana 0.25l: 165,00</p>
<p>Red Bull 0.25l: 295,00</p>
<!-- Button trigger modal -->
<button type="button" class="btn btn-success btn-sm" data-toggle="modal" data-target="#myModal">
More...
</button>
</div>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-body">
<table class="table table-bordered">
<tbody>
<tr>
<td>Rosa</td>
<td>0,33</td>
<td>130,00</td>
</tr>
<tr>
<td>Mineralna voda</td>
<td>0,25</td>
<td>130,00</td>
</tr>
<tr>
<td>Cola,Fanta,Sprite,Bitter</td>
<td>0,33</td>
<td>165,00</td>
</tr>
<tr>
<td>Orangina</td>
<td>0,25</td>
<td>175,00</td>
</tr>
<tr>
<td>Limona</td>
<td>0,25</td>
<td>165,00</td>
</tr>
<tr>
<td>Cocta</td>
<td>0,25</td>
<td>165,00</td>
</tr>
<tr>
<td>Ice Tea</td>
<td>0,25</td>
<td>165,00</td>
</tr>
<tr>
<td>Fructal</td>
<td>0,2</td>
<td>175,00</td>
</tr>
<tr>
<td>Limunada</td>
<td>0,30</td>
<td>150,00</td>
</tr>
<tr>
<td>Narandza,Grejp,Mix</td>
<td>0,35</td>
<td>240,00</td>
</tr>
<tr>
<td>Jabuka,Sargarepa</td>
<td>0,35</td>
<td>250,00</td>
</tr>
</tbody>
</table>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Zatvori</button>
</div>
</div>
</div>
</div>
</div>
<div class="col-xs-6 col-sm-4 col-lg-3">
<div class="cover wow fadeInRight" data-wow-duration="3s" data-wow-delay="0s" >
<span class="fa fa-coffee fa-2x"></span>
<h4>Coffee & Tea:</h4>
<p>Espresso: 125,00</p>
<p>Nes: 165,00</p>
<p>Caj: 165,00</p>
<!-- Button trigger modal -->
<button type="button" class="btn btn-success btn-sm" data-toggle="modal" data-target="#myModal1">
More...
</button>
</div>
<!-- Modal -->
<div class="modal fade" id="myModal1" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-body">
<table class="table table-bordered">
<tbody>
<tr>
<td>Espresso sa mlekom</td>
<td>145,00</td>
</tr>
<tr>
<td>Espresso sa slagom</td>
<td>170,00</td>
</tr>
<tr>
<td>Espresso bez kofeina</td>
<td>145,00</td>
</tr>
<tr>
<td>Cappuccino</td>
<td>165,00</td>
</tr>
<tr>
<td>Caffee latte</td>
<td>165,00</td>
</tr>
<tr>
<td>Domaca kafa</td>
<td>135,00</td>
</tr>
<tr>
<td>Ciganska moka</td>
<td>165,00</td>
</tr>
<tr>
<td>Double Dutch</td>
<td>180,00</td>
</tr>
<tr>
<td>Cokofredo</td>
<td>240,00</td>
</tr>
<tr>
<td>Ice coffee</td>
<td>270,00</td>
</tr>
<tr>
<td><NAME></td>
<td>270,00</td>
</tr>
<tr>
<td>Be<NAME></td>
<td>435,00</td>
</tr>
<tr>
<td>Irish Coffee</td>
<td>345,00</td>
</tr>
<tr>
<td>Gusarska kafa</td>
<td>280,00</td>
</tr>
<tr>
<td>Lionska kafa</td>
<td>425,00</td>
</tr>
<tr>
<td>Crni caj sa rumom</td>
<td>275,00</td>
</tr>
<tr>
<td>Caj sa mlekom</td>
<td>185,00</td>
</tr>
</tbody>
</table>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Zatvori</button>
</div>
</div>
</div>
</div>
</div>
<div class="col-xs-6 col-sm-4 col-lg-3">
<div class="cover wow fadeInLeft" data-wow-duration="3s" data-wow-delay="0s" >
<span class="fa fa-bolt fa-2x"></span>
<h4>Shots:</h4>
<p>Ballantine's: 195,00</p>
<p><NAME>: 215,00</p>
<p>Courvoiser v.s: 310,00</p>
<!-- Button trigger modal -->
<button type="button" class="btn btn-success btn-sm" data-toggle="modal" data-target="#myModal2">
More...
</button>
</div>
<!-- Modal -->
<div class="modal fade" id="myModal2" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-body">
<table class="table table-bordered">
<tbody>
<tr>
<td>Chivas Regal 12 y.o.</td>
<td>0,03</td>
<td>310,00</td>
</tr>
<tr>
<td><NAME></td>
<td>0,03</td>
<td>250,00</td>
</tr>
<tr>
<td><NAME>,J&B</td>
<td>0,03</td>
<td>195,00</td>
</tr>
<tr>
<td>Grant's</td>
<td>0,03</td>
<td>175,00</td>
</tr>
<tr>
<td>Jameson</td>
<td>0,03</td>
<td>195,00</td>
</tr>
<tr>
<td>4 Roses</td>
<td>0,03</td>
<td>215,00</td>
</tr>
<tr>
<td>Stock 84,Vinjak</td>
<td>0,03</td>
<td>195,00</td>
</tr>
<tr>
<td>Two Fingers</td>
<td>0,03</td>
<td>195,00</td>
</tr>
<tr>
<td>Smirnoff,Absolut</td>
<td>0,03</td>
<td>175,00</td>
</tr>
<tr>
<td>Beefeather</td>
<td>0,03</td>
<td>160,00</td>
</tr>
<tr>
<td>Bacardi,Havana rum</td>
<td>0,03</td>
<td>175,00</td>
</tr>
<tr>
<td>Domaca rakija</td>
<td>0,03</td>
<td>175,00</td>
</tr>
</tbody>
</table>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Zatvori</button>
</div>
</div>
</div>
</div>
</div>
<div class="col-xs-6 col-sm-4 col-lg-3">
<div class="cover wow fadeInLeft" data-wow-duration="3s" data-wow-delay="0s" >
<span class="fa fa-heart fa-2x"></span>
<h4>Wine:</h4>
<p>Kuvano vino: 250,00</p>
<p>Sangria: 280,00</p>
<p>Jelic: 230,00</p>
<!-- Button trigger modal -->
<button type="button" class="btn btn-success btn-sm" data-toggle="modal" data-target="#myModal3">
More...
</button>
</div>
<!-- Modal -->
<div class="modal fade" id="myModal3" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-body">
<table class="table table-bordered">
<tbody>
<tr>
<td>Aurelius</td>
<td>0,7</td>
<td>2150</td>
</tr>
<tr>
<td>Blatina</td>
<td>0,187</td>
<td>250,00</td>
</tr>
<tr>
<td>Radovanovic CS</td>
<td>0,7</td>
<td>2300,00</td>
</tr>
<tr>
<td>Zilavka</td>
<td>0,187</td>
<td>250,00</td>
</tr>
<tr>
<td><NAME>.</td>
<td>0,7</td>
<td>2150,00</td>
</tr>
<tr>
<td>Tamjanika</td>
<td>0,7</td>
<td>1800,00</td>
</tr>
<tr>
<td><NAME></td>
<td>0,2</td>
<td>230,00</td>
</tr>
<tr>
<td>Champagne</td>
<td>0,7</td>
<td>2100,00</td>
</tr>
<tr>
<td>Prosecco</td>
<td>0,7</td>
<td>1950,00</td>
</tr>
<tr>
<td>Prosecco</td>
<td>0,2</td>
<td>230,00</td>
</tr>
<tr>
<td>Cafe de Paris</td>
<td></td>
<td>1950,00</td>
</tr>
</tbody>
</table>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Zatvori</button>
</div>
</div>
</div>
</div>
</div>
<div class="col-xs-6 col-sm-4 col-lg-3">
<div class="cover wow fadeInRight" data-wow-duration="3s" data-wow-delay="0s" >
<span class="fa fa-beer fa-2x"></span>
<h4>Beer:</h4>
<p>Jelen Fresh: 180,00</p>
<p>Staropramen: 180,00</p>
<p>Amstel: 180,00</p>
<!-- Button trigger modal -->
<button type="button" class="btn btn-success btn-sm" data-toggle="modal" data-target="#myModal4">
More...
</button>
</div>
<!-- Modal -->
<div class="modal fade" id="myModal4" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-body">
<table class="table table-bordered">
<tbody>
<tr>
<td>Heineken</td>
<td>0,25</td>
<td>210,00</td>
</tr>
<tr>
<td><NAME></td>
<td>0,33</td>
<td>210,00</td>
</tr>
<tr>
<td>Erdinger</td>
<td>0,33</td>
<td>250,00</td>
</tr>
<tr>
<td>Kozel tamno toc.</td>
<td>0,50</td>
<td>230,00</td>
</tr>
<tr>
<td>Kozel tamno toc.</td>
<td>0,30</td>
<td>190,00</td>
</tr>
<tr>
<td>Pilsner Urquel toc.</td>
<td>0,50</td>
<td>230,00</td>
</tr>
<tr>
<td>Pilsner Urquel toc.</td>
<td>0,30</td>
<td>190,00</td>
</tr>
<tr>
<td>Valjevsko svetlo toc.</td>
<td>0,50</td>
<td>190,00</td>
</tr>
<tr>
<td>Valjevsko svetlo toc.</td>
<td>0,30</td>
<td>160,00</td>
</tr>
</tbody>
</table>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Zatvori</button>
</div>
</div>
</div>
</div>
</div>
<div class="col-xs-6 col-sm-4 col-lg-3">
<div class="cover wow fadeInRight" data-wow-duration="3s" data-wow-delay="0s" >
<span class="fa fa-glass fa-2x"></span>
<h4>Cocktails:</h4>
<p>Blue Lagoon: 250,00</p>
<p>Black Russian:320,00</p>
<p>Blood Mary: 315,00</p>
<!-- Button trigger modal -->
<button type="button" class="btn btn-success btn-sm" data-toggle="modal" data-target="#myModal5">
More...
</button>
</div>
<!-- Modal -->
<div class="modal fade" id="myModal5" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-body">
<table class="table table-bordered">
<tbody>
<tr>
<td>Blue Sea Brezze</td>
<td>310,00</td>
</tr>
<tr>
<td>Blue Shark</td>
<td>435,00</td>
</tr>
<tr>
<td>Chi-chi</td>
<td>275,00</td>
</tr>
<tr>
<td>Cosmopolitan</td>
<td>355,00</td>
</tr>
<tr>
<td>Caipiroska</td>
<td>275,00</td>
</tr>
<tr>
<td>Caipirinha</td>
<td>355,00</td>
</tr>
<tr>
<td>Kamikaza</td>
<td>370,00</td>
</tr>
<tr>
<td>Long Island Ice Tea</td>
<td>865,00</td>
</tr>
<tr>
<td>Multiple Orgasm</td>
<td>465,00</td>
</tr>
<tr>
<td>Sex On The Beach</td>
<td>355,00</td>
</tr>
<tr>
<td>Woo-woo</td>
<td>375,00</td>
</tr>
<tr>
<td>Tequila Sunrise</td>
<td>265,00</td>
</tr>
<tr>
<td>Sky Light</td>
<td>455,00</td>
</tr>
<tr>
<td>Margarita</td>
<td>370,00</td>
</tr>
<tr>
<td>Blue Elephante</td>
<td>505,00</td>
</tr>
<tr>
<td>Mojito</td>
<td>370,00</td>
</tr>
<tr>
<td>A Day At Beach</td>
<td>365,00</td>
</tr>
<tr>
<td>Pina Colada</td>
<td>370,00</td>
</tr>
<tr>
<td>Mai Tai</td>
<td>460,00</td>
</tr>
<tr>
<td>Blue Havaiian</td>
<td>345,00</td>
</tr>
<tr>
<td>Cuba Libre</td>
<td>245,00</td>
</tr>
<tr>
<td>Godfather</td>
<td>340,00</td>
</tr>
</tbody>
</table>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Zatvori</button>
</div>
</div>
</div>
</div>
</div>
<div class="col-xs-6 col-sm-6 col-lg-3">
<div class="cover wow fadeInLeft" data-wow-duration="3s" data-wow-delay="0s" >
<span class="fa fa-random fa-2x"></span>
<h4>Mix & Liqueur:</h4>
<p>Amaretto: 145,00</p>
<p>Archers: 175,00</p>
<p>Baileyes: 225,00</p>
<!-- Button trigger modal -->
<button type="button" class="btn btn-success btn-sm" data-toggle="modal" data-target="#myModal6">
More...
</button>
</div>
<!-- Modal -->
<div class="modal fade" id="myModal6" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-body">
<table class="table table-bordered">
<tbody>
<tr>
<td>Kahlua</td>
<td>0,03</td>
<td>180,00</td>
</tr>
<tr>
<td>Cointreau</td>
<td>0,03</td>
<td>255,00</td>
</tr>
<tr>
<td>Triple sec</td>
<td>0,03</td>
<td>145,00</td>
</tr>
<tr>
<td>Blue Curacao</td>
<td>0,03</td>
<td>150,00</td>
</tr>
<tr>
<td>Carolans</td>
<td>0,03</td>
<td>225,00</td>
</tr>
<tr>
<td>Visnja</td>
<td>0,03</td>
<td>180,00</td>
</tr>
<tr>
<td>Campari</td>
<td>0,03</td>
<td>170,00</td>
</tr>
<tr>
<td>Gorki List</td>
<td>0,03</td>
<td>160,00</td>
</tr>
<tr>
<td>Jaegermeister</td>
<td>0,03</td>
<td>170,00</td>
</tr>
<tr>
<td>Ramazzoti</td>
<td>0,03</td>
<td>170,00</td>
</tr>
<tr>
<td>Aperol</td>
<td>0,03</td>
<td>170,00</td>
</tr>
<tr>
<td><NAME></td>
<td>0,03</td>
<td>165,00</td>
</tr>
<tr>
<td>Vodka</td>
<td>Juice,tonic</td>
<td>225,00</td>
</tr>
<tr>
<td>Gin</td>
<td>tonik,bitter</td>
<td>210,00</td>
</tr>
<tr>
<td>Campari</td>
<td>Juice</td>
<td>220,00</td>
</tr>
<tr>
<td>Stock,JW,Bacardi</td>
<td>Cola</td>
<td>245,00</td>
</tr>
<tr>
<td>Pelinkovac</td>
<td>Tonic</td>
<td>210,00</td>
</tr>
<tr>
<td>Crno vino</td>
<td>Cola</td>
<td>185,00</td>
</tr>
</tbody>
</table>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Zatvori</button>
</div>
</div>
</div>
</div>
</div>
<div class="col-xs-6 col-sm-6 col-lg-3">
<div class="cover wow fadeInLeft" data-wow-duration="3s" data-wow-delay="0s" >
<span class="fa fa-fire fa-2x"></span>
<h4>Cigars:</h4>
<p>Marlb Red: 280,00</p>
<p>Marlb Gold: 280,00</p>
<p>Marlb Touch: 250,00</p>
<!-- Button trigger modal -->
<button type="button" class="btn btn-success btn-sm" data-toggle="modal" data-target="#myModal7">
More...
</button>
</div>
<!-- Modal -->
<div class="modal fade" id="myModal7" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-body">
<table class="table table-bordered">
<tbody>
<tr>
<td>Toscano Antico</td>
<td>280,00</td>
</tr>
<tr>
<td>Toscano Classico</td>
<td>180,00</td>
</tr>
<tr>
<td>Toscanello</td>
<td>130,00</td>
</tr>
<tr>
<td>Tosc<NAME></td>
<td>140,00</td>
</tr>
<tr>
<td><NAME></td>
<td>140,00</td>
</tr>
</tbody>
</table>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Zatvori</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="baner">
<div class="container">
<div class="row">
<h2>I have a simple taste.I am always satisfied with the best.</h2>
<p>-<NAME></p>
</div>
</div>
</div>
<div id="gallery" class="container">
<h3>Gallery</h3>
<div class="col-xs-12">
<div class="images">
<a href="img/gallery/1.jpg" data-lightbox="start" data-title="The best of Savana"><img src="img/gallery/thumb/1.jpg" alt="List"/></a>
<a href="img/gallery/6.jpg" data-lightbox="start" data-title="The best of Savana"><img src="img/gallery/thumb/6.jpg" alt="List"/></a>
<a href="img/gallery/7.jpg" data-lightbox="start" data-title="The best of Savana"><img src="img/gallery/thumb/7.jpg" alt="List"/></a>
<a href="img/gallery/8.jpg" data-lightbox="start" data-title="The best of Savana"><img src="img/gallery/thumb/8.jpg" alt="List"/></a>
<a href="img/gallery/9.jpg" data-lightbox="start" data-title="The best of Savana"><img src="img/gallery/thumb/9.jpg" alt="List"/></a>
<a href="img/gallery/10.jpg" data-lightbox="start" data-title="The best of Savana"><img src="img/gallery/thumb/10.jpg" alt="List"/></a>
<a href="img/gallery/13.jpg" data-lightbox="start" data-title="The best of Savana"><img src="img/gallery/thumb/13.jpg" alt="List"/></a>
<a href="img/gallery/14.jpg" data-lightbox="start" data-title="The best of Savana"><img src="img/gallery/thumb/14.jpg" alt="List"/></a>
<a href="img/gallery/21.jpg" data-lightbox="start" data-title="The best of Savana"><img src="img/gallery/thumb/21.jpg" alt="List"/></a>
<a href="img/gallery/22.jpg" data-lightbox="start" data-title="The best of Savana"><img src="img/gallery/thumb/22.jpg" alt="List"/></a>
<a href="img/gallery/23.jpg" data-lightbox="start" data-title="The best of Savana"><img src="img/gallery/thumb/23.jpg" alt="List"/></a>
</div>
</div>
</div>
<div id="contact" class="container-fluid">
<div class="row">
<h3>Contact</h3>
<div class="col-xs-12 col-sm-12 col-md-offset-1 col-md-3 col-lg-3">
<?php
if (isset($_GET['sent']) === true) {
echo '<p>Thanks for contacting us!</p>';
} else {
if (empty($errors) === false) {
echo '<ul>';
foreach($errors as $error) {
echo '<li><p>', $error,'</p></li>';
}
echo '</ul>';
}
?>
<form action="" method="post">
<p>
<label for="name">Name:</label></br>
<input id="name" name="name" type="text" <?php if (isset($_POST['name']) === true) { echo 'value="', strip_tags($_POST['name']), '"'; } ?>/>
</p>
<p>
<label for="email">Email:</label></br>
<input id="email" name="email" type="email" <?php if (isset($_POST['email']) === true) { echo 'value="', strip_tags($_POST['email']), '"'; } ?> />
</p>
<p>
<label for="message">Message:</label></br>
<textarea name="message" id="message"><?php if (isset($_POST['message']) === true) { echo strip_tags($_POST['message']); } ?></textarea></p>
</p>
<p>
<button class="center-block" type="submit" name="submit" id="submit" value="submit">Send</button>
</p>
</form>
<?php
}
?>
</div>
<div class="col-xs-12 col-sm-6 col-md-3 col-lg-3 vreme">
<p class="vreme">Address: Kej Oslobodjenja 2</p>
<p class="vreme">Phone: +381 64 11 02 004</p>
<p class="vreme">Facebook: <a target="_blank" href="https://www.facebook.com/splavsavana/"> Facebook</a></p>
<h5>Working Hours:</h5>
<p class="vreme">10:00 -24:00h</p>
<p class="vreme">Wi-Fi: Yes</p>
<p class="vreme">Pet friendly: Yes</p>
<p class="vreme">Parking: Street parking</p>
</div>
<div class="col-xs-12 col-sm-6 col-md-3 col-lg-3">
<div id="map" class="center-block">
<script src='https://maps.googleapis.com/maps/api/js?v=3.exp&key=<KEY>'></script>
<div id='gmap_canvas' style='height:300px;width:280px;'></div>
<style>#gmap_canvas img{max-width:none!important;background:none!important}</style>
<a href='https://www.add-map.net/'>how do i add a google map to my website</a>
<script type='text/javascript' src='https://embedmaps.com/google-maps-authorization/script.js?id=5370866a9929fd8b68e73e1e45094106a329bcc1'></script>
<script type='text/javascript'>function init_map(){var myOptions = {zoom:17,center:new google.maps.LatLng(44.83323828439013,20.42055858077196),mapTypeId: google.maps.MapTypeId.ROADMAP};map = new google.maps.Map(document.getElementById('gmap_canvas'), myOptions);marker = new google.maps.Marker({map: map,position: new google.maps.LatLng(44.83323828439013,20.42055858077196)});infowindow = new google.maps.InfoWindow({content:'<strong>Savana</strong><br><br> Belgrade<br>'});google.maps.event.addListener(marker, 'click', function(){infowindow.open(map,marker);});infowindow.open(map,marker);}google.maps.event.addDomListener(window, 'load', init_map);</script>
</div>
</div>
</div>
</div>
<footer>
<div class="container">
<div class="row">
<div class="col-md-6">
<ul class="footer-menu">
<li><a href="#top">Home</a></li>
</ul>
</div>
<div class="col-md-6 text-right">
<p>© Copyright - <a href="mailto:<EMAIL>">Kotrma</a> - 2016 </p>
</div>
</div>
</div>
</footer>
<script src="js/wow.min.js"></script>
<script src="js/lightbox-plus-jquery.js"></script>
<script src="js/vendor/jquery-1.11.2.min.js"></script>
<script src="js/vendor/bootstrap.min.js"></script>
<script src="js/main.js"></script>
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-87732864-1', 'auto');
ga('send', 'pageview');
</script>
</body>
</html>
| 7477395c664d389f33530928c2f203df1af9b303 | [
"PHP"
] | 1 | PHP | kotrma/Savana | afc507608a2fda51999aa6458fba06d14ca5c51e | 07b7ebabbf0d4c6189f9771845aa8dd27b1966fc |
refs/heads/master | <file_sep>'use strict'; // necessary for es6 output in node
import { browser, element, by, protractor } from 'protractor';
describe('User Input Tests', function () {
beforeAll(function () {
browser.get('');
});
it('should support the click event', function () {
let mainEle = element(by.css('app-click-me'));
let buttonEle = element(by.css('app-click-me button'));
expect(mainEle.getText()).not.toContain('Button clicked');
buttonEle.click().then(function() {
expect(mainEle.getText()).toContain('Button clicked');
});
});
});
| bdf06bc44cb937817ef35b2d49cd5d2deadd057e | [
"TypeScript"
] | 1 | TypeScript | jkaddi/Uploads | 86c68bf9e180c2a277497363d041668ff6ba0b72 | 4a94445ad246c7a76b128574f6bb9ff06654f0e8 |
refs/heads/master | <file_sep>console.log('Product rating app running ...');
let months = {
0: 'Jan',
1: 'Feb',
2: 'Mar',
3: 'Apr',
4: 'May',
5: 'Jun',
6: 'Jul',
7: 'Aug',
8: 'Sep',
9: 'Oct',
10: 'Nov',
11: 'Dec'
}
let parentCard = document.getElementById('parent-card');
let comment;
let name;
let rateList = new Set();
let id = 0;
let reviewList = [];
parentCard.addEventListener('click', function (e) {
console.log(e.target.checked, e.target.id);
if (e.target.checked) {
rateList.add(e.target.id);
} else {
rateList.delete(e.target.id);
}
console.log(rateList)
});
let likeCount = new Set();
function handleLikeBtn(e) {
console.log('likes ', e.id)
if (reviewList && reviewList.length) {
reviewList.forEach((item) => {
if (item.id == e.id && !item.isLikes) {
item.likes = item.likes + 1;
item.isLikes = true;
}
if (item.id == e.id && item.unlikes && item.unlikes >= 1) {
item.unlikes = item.unlikes - 1;
item.isUnLikes = false;
}
});
}
setLocalStorage(reviewList);
console.log('------', reviewList);
// removeULList();
removeElementByIds();
showReviews(reviewList);
}
function handleUnLikeBtn(e) {
console.log('unlikes ', e.id)
if (reviewList && reviewList.length) {
reviewList.forEach((item) => {
if (item.id == e.id && !item.isUnLikes) {
item.unlikes = item.unlikes + 1;
item.isUnLikes = true;
}
if (item.id == e.id && item.isLikes && item.likes >= 1) {
item.likes = item.likes - 1;
item.isLikes = false;
}
});
}
setLocalStorage(reviewList);
console.log('------', reviewList);
// removeULList();
removeElementByIds();
showReviews(reviewList);
}
function removeULList() {
let ulList = document.getElementById('review-ul');
console.log(ulList.parentNode.removeChild(ulList));
showReviews(reviewList);
// if (ulList && ulList.parentNode) {
// console.log('rating card', ulList.parentNode.removeChild(ulList));
// }
}
function removeElementByIds() {
console.log('removing emails ', );
reviewList.forEach((item) => {
let element = document.getElementById(item.id);
if (element && element.parentNode) {
element.parentNode.removeChild(element)
}
});
}
function showReview(rateObj) {
let reviewUL = document.getElementById('review-ul');
console.log(reviewUL);
let liItem = `<li id=${rateObj.id}>
<h4>${rateObj.comment}</h4>
<h4>Rating: ${rateObj.rate}</h4>
<span>${rateObj.name}</span> |
<span>${rateObj.createdAt}</span>|
<span><input id=${rateObj.id} class="unlike-btn" type="button" onclick=handleLikeBtn(this) value="Like"></span>|
<span>${rateObj.likes}</span>
<span><input id=${rateObj.id} class="like-btn" type="button" onclick=handleUnLikeBtn(this) value="UnLike"></span>
<span>${rateObj.unlikes}</span>
</li>
`;
reviewUL.insertAdjacentHTML('afterbegin', liItem);
}
function addReview() {
console.log('adding review');
let rating = Array.from(rateList).length;
let todayDate = new Date();
let reviewObj = {
id: id,
comment: comment.value,
name: name.value,
rate: rating,
createdAt: months[todayDate.getMonth()] + " " + todayDate.getFullYear(),
likes: 0,
isLikes: false,
isUnLikes: false,
unlikes: 0
}
id += 1;
rateList = new Set();
reviewList.push(reviewObj);
setLocalStorage(reviewList);
console.log(reviewList);
showReviews(reviewList);
}
function showReviews(data) {
data.forEach((item) => {
showReview(item);
});
}
function showRatingCard() {
let prodCard = document.getElementById('prod-card');
if (prodCard && prodCard.parentNode) {
console.log('rating card', prodCard.parentNode.removeChild(prodCard));
}
let productCard = `
<div id="prod-card" class="product-comment">
<label>Rate it</label>
<input id=1 type="checkbox">
<input id=2 type="checkbox">
<input id=3 type="checkbox">
<input id=4 type="checkbox">
<input id=5 type="checkbox"><br><br>
<input id='comment' value="" placeholder="write review" type="text" /><br><br>
<input id='name' value="" placeholder="write your name" type="text" /><br>
<br>
<button onclick="addReview()">Rate </button>
<hr>
</div>`;
parentCard.insertAdjacentHTML('afterbegin', productCard);
comment = document.getElementById('comment');
name = document.getElementById('name');
}
function setLocalStorage(data) {
localStorage.setItem('reviews', JSON.stringify(data));
}
function getLocalStorage() {
return JSON.parse(localStorage.getItem('reviews'));
}
function restoringData() {
let data = getLocalStorage();
if (data && data.length) {
reviewList = data;
console.log('onlaoding .......', data)
showReviews(data);
}
}
window.onload = restoringData();<file_sep>console.log('---running email.js---')
// {
// id: 1,
// from: '<EMAIL>',
// to: '<EMAIL>',
// subject: 'SENT email 1',
// text: 'Hi Shaikh this is imran how are you',
// status: 'SENT',
// read_status: null
// },
// {
// id: 2,
// from: '<EMAIL>',
// to: '<EMAIL>',
// subject: 'SENT email 2',
// text: 'Hi Shaikh this is imran how are you',
// status: 'SENT',
// read_status: null
// },
let emailList = [{
id: 0,
from: '<EMAIL>',
to: '<EMAIL>',
subject: 'INBOX email 2',
text: 'Hi xyz this is abc how are you',
status: 'INBOX',
read_status: 'UN_READ'
},
{
id: 1,
from: '<EMAIL>',
to: '<EMAIL>',
subject: 'INBOX email 1',
text: 'Hi Yuvi this is dhoni how are you',
status: 'INBOX',
read_status: 'UN_READ'
},
{
id: 2,
from: '<EMAIL>',
to: '<EMAIL>',
subject: 'DELETED email 1',
text: 'Hi nitish this is vikas how are you',
status: 'DELETED',
read_status: null
}
]
// add new button and provide new email temp -> done
// send email -> done
// maintain temp array for sent email ->done
// show inbox emails - done
// storing email data into localstorage -> done
// show sent list -> done
// show inboc list -> done
// On click New btn , showing multiple emails templat (restrict with 1 only) -done
// show email right side on click li tag -> done
// send btn functionality and maintaingi data over the list and according to sent,inbox and deleted maintain -> done
// add delete functionality -> done
// in place of email content dynamically will add email template-> done
// add mark as read functionality
// add mark as unread functionality
let emailContent = document.getElementById('email-temp');
let id = emailList.length + 1;
let openListChecked = new Set();
// let emailList = [];
let travsedEmailList = new Set();
let emailTemp = document.getElementById('email-temp');
let emailParent = document.getElementById('email-parent');
let emailConte = document.getElementById('email-content');
let btnClickedName = 'INBOX';
function onLiTagClick(id) {
let emailConte = document.getElementById('email-content');
console.log(' p tag ', emailConte);
if (emailConte && emailConte.parentNode) {
console.log(emailConte.parentNode.removeChild(emailConte))
}
let eTemplate = document.getElementById('email-template');
if (eTemplate && eTemplate.parentNode) {
console.log('removing eTemplate when click on email desc')
eTemplate.parentNode.removeChild(eTemplate);
}
let obj = _.find(emailList, {
id: id
});
if (obj) {
let emailContent = `<div id='email-content'>
<lable>To:</lable>
<h4>s${obj.from}</h4>
<label>Subject: </label>
<p> ${obj.subject}</p>
<p> ${obj.text}</p>
</div>`;
emailParent.insertAdjacentHTML('afterbegin', emailContent);
}
}
function markAsRead() {
Array.from(openListChecked).forEach((emailId) => {
setMarkAsReadORUnread(emailId, 'READ');
emailList = updateStatus(emailId,'READ');
setLocalStorage(emailList);
console.log('after that ',emailList);
});
// let emailConte = document.getElementById('email-content');
openListChecked = new Set();
}
function markAsUnRead() {
Array.from(openListChecked).forEach((emailId) => {
setMarkAsReadORUnread(emailId, 'UNREAD');
emailList = updateStatus(emailId,'UNREAD');
setLocalStorage(emailList);
console.log('after that ',emailList);
});
// let emailConte = document.getElementById('email-content');
openListChecked = new Set();
}
function updateStatus (id, status){
let newList = emailList.map((item)=>{
if(item.id == id){
item.readStatus = status;
}
return item;
});
return newList;
}
function updateStatusForDelete (id, status){
let newList = emailList.map((item)=>{
if(item.id == id){
item.readStatus = status;
}
return item;
});
return newList;
}
function removeFromEmails(id){
// return list = emailList.filter((item)=>{
// if(item.id !== id){
// return true;
// }
// });
// let list = _.remove(emailList, function(n){
// console.log(n.id, id);
// return n.id == id;
// });
let newArr = emailList.map((item)=>{
if(item.id == id){
item.status = 'DELETED';
};
return item;
});
console.log('performing remove -> ',newArr);
return emailList;
}
function deleteEmails() {
Array.from(openListChecked).forEach((emailId) => {
removeElementById(emailId);
emailList = removeFromEmails(emailId);
console.log('after that ',emailList);
setLocalStorage(emailList);
});
let emailConte = document.getElementById('email-content');
openListChecked = new Set();
console.log(' removing email content ', emailConte);
if (emailConte && emailConte.parentNode) {
console.log(emailConte.parentNode.removeChild(emailConte))
}
}
function showInboxEmails() {
btnClickedName = 'INBOX';
if (emailList && emailList.length) {
// removeElements('INBOX');
removeElementByIds();
Array.from(emailList).forEach((emailObj) => {
if (emailObj.status === 'INBOX') {
showEmails(emailObj);
travsedEmailList.add(emailObj.id);
}
});
}
}
function showSentEmails() {
btnClickedName = 'SENT';
if (emailList && emailList.length) {
removeElementByIds();
Array.from(emailList).forEach((emailObj) => {
if (emailObj.status === 'SENT') {
showEmails(emailObj);
travsedEmailList.add(emailObj.id);
}
});
}
}
function showDeleteEmails() {
btnClickedName = 'DELETED';
if (emailList && emailList.length) {
removeElementByIds();
Array.from(emailList).forEach((emailObj) => {
if (emailObj.status === 'DELETED') {
showEmails(emailObj);
travsedEmailList.add(emailObj.id);
}
});
}
}
function checkedEmailItems(element) {
if (btnClickedName === 'SENT' || btnClickedName === 'INBOX') {
if (element.checked) {
openListChecked.add(element.id);
} else {
openListChecked.delete(element.id);
}
console.log('openListChecked => ', openListChecked);
}
}
let emailSection = document.getElementById('email-list');
emailSection.addEventListener('click', function (event) {
console.log('checkbox -> ', event.target.checked)
console.log('checkbox -> ', event.target.id);
checkedEmailItems(event.target);
});
function showEmails(emailData, fromEvent) {
let readStatus = emailData.readStatus === 'READ' ? 'line-through' : '';
let emailLi = `<li onclick='onLiTagClick(${emailData.id})' id='${emailData.id}'>
<input type='checkbox' id='${emailData.id}'>
<p class='text terms-checkbox' style="text-decoration:${readStatus}" id='${emailData.id}'>${emailData.subject}</p>
</li>`
let emailSection = document.getElementById('email-list');
// if(fromEvent === 'SENT'){
// showSentEmails();
// }
if (emailData) {
emailSection.insertAdjacentHTML('afterbegin', emailLi);
}
}
function removeElementByIds() {
console.log('removing emails ', );
emailList.forEach((item) => {
let element = document.getElementById(item.id);
if (element && element.parentNode) {
element.parentNode.removeChild(element)
}
});
}
function setMarkAsReadORUnread(id,status) {
let cssValue = status === 'READ' ? 'line-through' : ''
let element = document.getElementById(id);
let paraText = element.children[1];
let checkbox = element.children[0];
checkbox.checked = false;
console.log('******** ',)
paraText.setAttribute('style',"text-decoration:"+cssValue);
}
function removeElementById(id) {
let element = document.getElementById(id);
if (element && element.parentNode) {
element.parentNode.removeChild(element)
}
}
function showNewTemplate(e) {
let eTemplate = document.getElementById('email-template');
let eContent = document.getElementById('email-content');
if (eTemplate && eTemplate.parentNode) {
console.log('removing extra child')
eTemplate.parentNode.removeChild(eTemplate);
}
if (eContent && eContent.parentNode) {
eContent.parentNode.removeChild(eContent);
}
let emailTemplate = `<div id='email-template'>
<br>To: <input value="" type="text" id="email-to" placeholder="<EMAIL>">
Subject: <input value ="" id="email-subject" type="text"><br>
<textarea id="email-text" placeholder="write an email">
</textarea><br><br>
<input type='button' value="Send" id="sent-btn"/>
</div>`;
console.log(emailParent);
emailParent.insertAdjacentHTML('afterbegin', emailTemplate);
enableSendBtn();
}
function enableSendBtn() {
let sentBtn = document.getElementById('sent-btn');
if (sentBtn !== null) {
sentBtn.addEventListener('click', saveEmail);
}
}
function saveEmail() {
let emailTo = document.getElementById('email-to').value;
let emailSubject = document.getElementById('email-subject').value;
let emailText = document.getElementById('email-text').value;
id = id + 1;
let emailObject = {
id: id,
from: '<EMAIL>',
to: emailTo,
subject: emailSubject,
text: emailText ,
status: 'SENT',
readStatus: null
}
emailList.push(emailObject);
setLocalStorage(emailList);
console.log(emailObject);
if (btnClickedName === 'SENT') {
showSentEmails();
}
// showEmails(emailObject, 'SENT')
}
function setLocalStorage(emails) {
localStorage.setItem('email-list', JSON.stringify(emails));
}
window.onload = persistingEmails();
function getLocalStorage(){
return JSON.parse(localStorage.getItem('email-list'));
}
function persistingEmails() {
// let fakedata =
let mergedData = getLocalStorage() == null ? [].concat(emailList) : getLocalStorage().concat(emailList);
let uniqList = _.uniqBy(mergedData,'id');
emailList = uniqList;
setLocalStorage(uniqList);
console.log('persisting emails',uniqList);
id = uniqList.length;
}<file_sep>const express = require('express');
const app = express();
const PORT = process.env.PORT || 5000
app.use(express.static('public'));
app.listen(PORT,function(){
console.log('App is running');
}); | 63508277413328dd75f8a555eef03a0eced62cbc | [
"JavaScript"
] | 3 | JavaScript | imran-mind/email-client | 34798bda8bb84ddb8d06ed9d5e12010a3aff8d39 | 17877ed432a4bbba8a5bc81d765776addf8525b3 |
refs/heads/master | <repo_name>madkote/timing-asgi<file_sep>/timing_asgi/utils.py
import resource
import time
from .interfaces import MetricNamer
def get_cpu_time():
resources = resource.getrusage(resource.RUSAGE_SELF)
# add up user time (ru_utime) and system time (ru_stime)
return resources[0] + resources[1]
class TimingStats(object):
def __init__(self, name=None):
self.name = name
def start(self):
self.start_time = time.time()
self.start_cpu_time = get_cpu_time()
def stop(self):
self.end_time = time.time()
self.end_cpu_time = get_cpu_time()
def __enter__(self):
self.start()
return self
@property
def time(self):
return self.end_time - self.start_time
@property
def cpu_time(self):
return self.end_cpu_time - self.start_cpu_time
def __exit__(self, exc_type, exc_value, traceback):
self.stop()
class PathToName(MetricNamer):
def __init__(self, prefix):
self.prefix = prefix
def __call__(self, scope):
path = scope.get('path')[1:]
return f"{self.prefix}.{path.replace('/', '.')}"
<file_sep>/Makefile
setup:
poetry install
test:
poetry run pytest -s --cov-report term-missing --cov=timing_asgi tests/
test_%:
poetry run pytest -vsx tests -k $@ --pdb
lint:
poetry run flake8 timing_asgi/ tests/
clean:
rm -rf dist/ pip-wheel-metadata *.egg-info
<file_sep>/pyproject.toml
[tool.poetry]
name = "timing-asgi"
version = "0.2.0"
description = "ASGI middleware to emit timing metrics with something like statsd"
authors = ["<NAME> <<EMAIL>>"]
license = "MIT"
[tool.poetry.dependencies]
python = "^3.6"
alog = "^0.9.13"
[tool.poetry.dev-dependencies]
starlette = "^0.12.0"
pytest = "^4.3"
pytest-cov = "^2.6"
requests = "^2.21"
pytest-asyncio = "^0.10.0"
asynctest = "^0.12.2"
flake8 = "^3.7"
[build-system]
requires = ["poetry>=0.12"]
build-backend = "poetry.masonry.api"
| 0d02381d4c830056f76ce91353d8e2d4a64c31cc | [
"TOML",
"Python",
"Makefile"
] | 3 | Python | madkote/timing-asgi | bcfdc7edeaccc5aed44e3792ba5d0426bfc7c31d | 0e39daab8faa5356c49085d4e64f137bed89bb92 |
refs/heads/master | <repo_name>aguilalv/TDDPython<file_sep>/features/steps/my_list.py
from selenium.webdriver.common.keys import Keys
import time
@when(u'I visit "{url}"')
def visit(context,url):
context.browser.get(url)
@then(u'I will see the page title mentions "{expected_title}"')
def see_title_mentions(context,expected_title):
title = context.browser.title
context.test.assertIn(expected_title,title)
@then(u'I will see the page header mentions "{expected_header}"')
def see_header_mentions(context,expected_header):
header = context.browser.find_element_by_tag_name('h1').text
context.test.assertIn(expected_header,header)
@then(u'I will see a text box and will be prompted to input "{expected_prompt}"')
def see_text_box_with_ptompt(context,expected_prompt):
inputbox = context.browser.find_element_by_id('id_new_item')
placeholder = inputbox.get_attribute('placeholder')
context.test.assertEqual(placeholder,expected_prompt)
@when(u'I type "{text_input}" into a text box and press enter')
def type_text_and_press_enter(context,text_input):
inputbox = context.browser.find_element_by_id('id_new_item')
inputbox.send_keys(text_input)
inputbox.send_keys(Keys.ENTER)
time.sleep(1)
@then(u'I will see the row lists "{expected_item}" item in a table')
def see_item_in_table(context,expected_item):
table = context.browser.find_element_by_id('id_list_table')
rows = table.find_elements_by_tag_name('tr')
context.test.assertIn(expected_item,[row.text for row in rows])
@given(u'I have typed "{text_input}" into a text box and press enter')
def typed_text_input(context,text_input):
inputbox = context.browser.find_element_by_id('id_new_item')
inputbox.send_keys(text_input)
inputbox.send_keys(Keys.ENTER)
time.sleep(1)
<file_sep>/README.md
# TDDPython
Second review of <NAME>´s TDD in Python book
<file_sep>/.coveragerc
[run]
source =
*/lists/*
| 50b358ae018b8967730ab961d5c1a14fb8c8203e | [
"Markdown",
"Python",
"INI"
] | 3 | Python | aguilalv/TDDPython | 4ff20df982ca72b15acfbf4e8540604b928bdc69 | 7837ae1fbf39486b20cdfd24693f60ba80da2a49 |
refs/heads/main | <file_sep>import React from "react";
import { AiOutlineStar, AiFillStar } from "react-icons/ai";
import { IoIosPeople } from "react-icons/io";
import { BiPlayCircle } from "react-icons/bi";
import { BsArrowRight } from "react-icons/bs";
import Rating from "react-rating";
const Details = (props) => {
const { courseTitle, price, description, image, instructor, star, enrol } =
props.details;
return (
<div className="bg-white rounded-md p-3 mb-8 shadow-md">
<div className="image ">
<img className="w-screen rounded-lg" src={image} alt="" />
</div>
<div className="details pt-5">
<h4 className="font-semibold text-lg leading-6">{courseTitle}</h4>
<p className="flex items-center my-3 text-sm">
<BiPlayCircle className="inline-block text-purple-500"></BiPlayCircle>{" "}
<span className="pl-1">20 Lesson</span>
</p>
<p>{description}</p>
<p className="pt-3 text-sm -semibold">Instructor: {instructor}</p>
<p className="flex pt-5 items-center">
<IoIosPeople className="text-2xl text-purple-500 inline-block"></IoIosPeople>
<span className="pl-2">{enrol}</span>
</p>
<div className="flex pt-5 items-center pt-2">
<p className="">
<span className="pr-3 font-bold pr-10 text-purple-500 text-lg">
${price.discountPrice}
</span>
</p>
<p className="text-sm">
<Rating
className="text-purple-500"
emptySymbol={<AiOutlineStar></AiOutlineStar>}
fullSymbol={<AiFillStar></AiFillStar>}
initialRating={star}
readonly
></Rating>{" "}
<span className="font-semibold">{star} Rating</span>
</p>
</div>
</div>
</div>
);
};
export default Details;
<file_sep>import React from "react";
import DesignCourse from "../Design/DesignCourse/DesignCourse.js";
import UseCourses from "../Hooks/UseCourses";
const Design = () => {
const [courses] = UseCourses();
const webCourses = courses.filter(
(course) => course.courseMain === "graphics"
);
return (
<>
<div className="w-4/6 m-auto py-16">
<div className="grid grid-cols-4 gap-10">
{webCourses.map((course) => (
<DesignCourse course={course} key={course.code}></DesignCourse>
))}
</div>
</div>
</>
);
};
export default Design;
<file_sep>import { BrowserRouter as Router, Switch, Route } from "react-router-dom";
import "./App.css";
import Development from "./Components/Development/Development";
import Footer from "./Components/Footer/Footer";
import Headers from "./Components/Headers/Headers";
import Home from "./Components/Home/Home";
import "./index.css";
import Courses from "./Components/Courses/Courses";
import Software from "./Components/Software/Software";
import Design from "./Components/Design/Design";
import About from "./Components/About/About";
import DetailsCourse from "./Components/DetailsCourse/DetailsCourse";
import NotFound from "./Components/NotFound/NotFound";
function App() {
return (
<div>
<Router>
<Headers></Headers>
<Switch>
<Route exact path="/">
<Home></Home>
</Route>
<Route path="/home">
<Home></Home>
</Route>
<Route path="/courses">
<Courses></Courses>
</Route>
<Route path="/software">
<Software></Software>
</Route>
<Route path="/design">
<Design></Design>
</Route>
<Route path="/development">
<Development></Development>
</Route>
<Route path="/about">
<About></About>
</Route>
<Route path="/details">
<DetailsCourse></DetailsCourse>
</Route>
<Route path="*">
<NotFound></NotFound>
</Route>
</Switch>
<Footer></Footer>
</Router>
</div>
);
}
export default App;
<file_sep>import React from "react";
const AboutTeachers = (props) => {
const { name, designation, teamsMemberImage } = props.teacher;
console.log(props.teacher);
return (
<div className="rounded-md shadow-md flex justify-center text-center p-5">
<div>
<div className="image flex justify-center">
<img
className="w-40"
style={{ borderRadius: "50%" }}
src={teamsMemberImage}
alt=""
/>
</div>
<div className="details pt-4">
<h2 className="text-xl font-semibold">{name}</h2>
<p>{designation}</p>
</div>
</div>
</div>
);
};
export default AboutTeachers;
<file_sep>import React from "react";
import { Link } from "react-router-dom";
import image from "../../hero-image.png";
import { MdOutlineDeveloperBoard } from "react-icons/md";
import { SiMicrosoftsharepoint, SiAdobeindesign } from "react-icons/si";
const Home = () => {
return (
<div>
<div className=" hero-home bg-purple-200">
<div className="flex w-4/6 m-auto pt-10 items-center justify-between">
<div className="information pr-20">
<h1 className="text-5xl leading-14 font-bold pb-4">
Start Your Learning Our{" "}
<span className="text-purple-500">Experts Trainers</span>
</h1>
<p className=" text-base leading-14">
Build yor skill from world-class universities and companies, you
can learn online and earn certificates and degree
</p>
<Link to="./courses">
<button className="bg-purple-600 py-2 px-5 text-white mt-5 cursor-pointer">
Discover
</button>
</Link>
</div>
<div className="hero-image">
<img className="w-full" src={image} alt="" />
</div>
</div>
</div>
<div className="services-container ">
<div className="services w-4/6 m-auto my-10 ">
<h1 className="text-4xl font-bold ">Our Top Course Categories</h1>
<div className="grid grid-cols-3 gap-16 mt-10">
<Link to="./development">
<div className="development bg-purple-100 hover:bg-purple-500 hover:text-white p-10 text-left">
<MdOutlineDeveloperBoard className="text-white text-6xl mb-4 bg-purple-400 rounded p-3 "></MdOutlineDeveloperBoard>
<h4 className="text-2xl mb-2 font-semibold">Web Development</h4>
<p className="mb-2">
Web development is the work involved in developing a Web site
for the Internet (World Wide Web) or an intranet (a private
network)....
</p>
<p className="font-bold">More Than 8+ Courses</p>
</div>
</Link>
<Link to="./design">
<div className="design bg-purple-100 hover:bg-purple-500 hover:text-white hover:shadow-lg p-10 text-left">
<SiAdobeindesign className="text-white text-6xl mb-4 bg-purple-400 rounded p-3 "></SiAdobeindesign>
<h4 className="text-2xl mb-2 font-semibold">
{" "}
Graphics Design
</h4>
<p className="mb-2">
Graphic design is a craft where professionals create visual
content to communicate messages. By applying visual hierarchy
and page...
</p>
<p className="font-bold">More Than 4+ Courses</p>
</div>
</Link>
<Link to="./software">
<div className="design bg-purple-100 hover:bg-purple-500 hover:text-white hover:shadow-lg p-10 text-left">
<SiMicrosoftsharepoint className="text-white text-6xl mb-4 bg-purple-400 rounded p-3 "></SiMicrosoftsharepoint>
<h4 className="text-2xl mb-2 font-semibold">
Software Development
</h4>
<p className="mb-2">
Software development is the process of conceiving, specifying,
designing, programming, documenting, testing, and bug fixing
involved in creating...
</p>
<p className="font-bold">More Than 7+ Courses</p>
</div>
</Link>
</div>
</div>
</div>
</div>
);
};
export default Home;
<file_sep>import React from "react";
import logo from "../../logo.png";
import { NavLink } from "react-router-dom";
import { HiOutlineMail } from "react-icons/hi";
import { FiPhone } from "react-icons/fi";
import { BsFacebook, BsInstagram, BsLinkedin, BsTwitter } from "react-icons/bs";
const Footer = () => {
return (
<div className="bg-purple-500">
<div className="w-4/6 m-auto">
<div className="footer-top flex justify-between pt-10">
<div className="logo-details w-2/6">
<img className="w-32" src={logo} alt="" />
<p className="text-white mt-3">
Learn Hub is a popular online learning platform that gives people
a chance to develop their careers and explore a wide variety of
hobbies. From web development to public speaking, they offer a
broad range of courses.
</p>
</div>
<div className="contact">
<a
className="text-white block pb-3"
href="mailto: <EMAIL>?body=My custom mail body"
>
<HiOutlineMail className="inline-block mr-2"></HiOutlineMail>
<EMAIL>
</a>
<a className="text-white block pb-5" href="tel:+880 1865748726">
<FiPhone className="inline-block mr-2"></FiPhone>
+880 1865748726
</a>
<div className="flex">
<a href="facebook.com" className="text-white pr-4">
<BsFacebook></BsFacebook>
</a>
<a href="instragram.com" className="text-white pr-4">
<BsInstagram></BsInstagram>
</a>
<a href="linkedin.com" className="text-white pr-4">
<BsLinkedin></BsLinkedin>
</a>
<a href="twitter.com" className="text-white">
<BsTwitter></BsTwitter>
</a>
</div>
</div>
</div>
<hr className="my-8" />
<div className="footer-bottom flex justify-between pb-10">
<div className="footer-link">
<NavLink to="/home" className="text-white no-underline ">
Home
</NavLink>
<NavLink to="/courses" className="text-white no-underline ml-6">
Courses
</NavLink>
<NavLink to="/cart" className="text-white no-underline ml-6">
Cart
</NavLink>
<NavLink to="/about" className="text-white no-underline ml-6">
About
</NavLink>
</div>
<div>
<p className="text-white">
Development By{" "}
<a href="sohan" className="font-bold">
<NAME>
</a>
</p>
</div>
</div>
</div>
</div>
);
};
export default Footer;
<file_sep>import React from "react";
import UseTeachers from "../Hooks/UseTeachers";
import AboutTeachers from "./AboutTeachers/AboutTeachers";
const About = () => {
const [teachers] = UseTeachers();
return (
<div className="w-4/6 m-auto py-16">
<h1 className="text-2xl font-bold mb-5">Our Team Members</h1>
<div className="grid grid-cols-4 gap-10">
{teachers.map((teacher) => (
<AboutTeachers teacher={teacher} key={teacher.id}></AboutTeachers>
))}
</div>
</div>
);
};
export default About;
<file_sep>import React from "react";
import UseCourses from "../Hooks/UseCourses";
import Details from "./Details/Details";
const DetailsCourse = () => {
const [courses] = UseCourses();
return (
<div className="w-4/6 m-auto py-16">
{courses.map((details) => (
<Details details={details} key={details.code}></Details>
))}
</div>
);
};
export default DetailsCourse;
<file_sep>import SoftwareCourse from "../Software/SoftwareCourse/SoftwareCourse.js";
import UseCourses from "../Hooks/UseCourses";
const Software = () => {
const [courses] = UseCourses();
const webCourses = courses.filter(
(course) => course.courseMain === "software"
);
return (
<div className="w-4/6 m-auto py-16">
<div className="grid grid-cols-4 gap-10">
{webCourses.map((course) => (
<SoftwareCourse course={course} key={course.code}></SoftwareCourse>
))}
</div>
</div>
);
};
export default Software;
<file_sep>import React, { useState } from "react";
import DetailsCourse from "../DetailsCourse/DetailsCourse";
import UseCourses from "../Hooks/UseCourses";
import ItemCourse from "../ItemCourse/ItemCourse";
const Courses = () => {
const [courses] = UseCourses();
return (
<div className="w-4/6 m-auto py-16">
<div className="grid grid-cols-4 gap-10">
{courses.map((course) => (
<ItemCourse course={course} key={course.code}></ItemCourse>
))}
</div>
</div>
);
};
export default Courses;
| 958193154495d275f87b44a57cc357cc438a32de | [
"JavaScript"
] | 10 | JavaScript | sohantalukder/learn-hub | b70af8b5b939f7b63c14759f9bbf2281cd19be61 | fadc6df96be801a7e0e76c948928553394ae8158 |
refs/heads/master | <repo_name>jkirkpatrick24/node-web-scraper-app<file_sep>/index.js
var request = require('request');
var cheerio = require('cheerio');
var fs = require('fs');
var URL = 'http://substack.net/images/'
request(URL, (error, response, body) => {
if (!error) {
var data = scrape(body);
dataToCSV(data);
}
});
function scrape(text){
var data = [];
var $ = cheerio.load(text);
$('tr').each(function(i,elem){
var permissions = $(this).children().first().text();
var absUrl = URL + $(this).children().last().text();
var fileType = "dir";
if (!permissions.includes("d")) {
fileType = $(this).children().last().text().split('.').pop();
}
data[i] = permissions + ',' + absUrl + ',' + fileType;
});
return data;
}
function dataToCSV(data){
fs.writeFile('./data.CSV', data.join('\n'), err => {
if (err) {
console.log('error');
}
console.log("file was saved");
});
}
| fb6605536ae22d6256b95b078d3e55c646945e87 | [
"JavaScript"
] | 1 | JavaScript | jkirkpatrick24/node-web-scraper-app | 4e867af4b98f726f124703040a14ae46b9f461a1 | 974a1fda5924beefd90b331db7f0fc78bfd81c34 |
refs/heads/master | <file_sep>#include <iostream>
#include <math.h>
#include <fstream>
#include <stdlib.h>
using namespace std;
float M_eff(int, int, float);
int main(int argc, char *argv[])
{
int T = atoi(argv[1]);
double c_ave = atof(argv[2]);
ifstream p(argv[3]);
int conf = atoi(argv[4]);
//ofstream p2("now/Meff.txt");
int skip_int;
double skip_double;
double corr[T];
double mass[T][conf];
for(int j=0;j<conf;j++)
{
for(int i=0;i<T;i++)
p>>skip_int>>corr[i];
for(int i=0;i<T-1;i++)
mass[i][j] = M_eff(T, i, (corr[i+1]-c_ave)/(corr[i]-c_ave));
}
p.close();
//p2.close();
double ave;
double err;
for(int i=0;i<T-1;i++)
{
ave=0;
err=0;
for(int j=0;j<conf;j++)
{
ave+=mass[i][j];
err+=mass[i][j]*mass[i][j];
}
ave/=conf;
err=sqrt((err/conf-ave*ave))*sqrt(conf);
cout<<i<<"\t"<<ave<<"\t"<<err<<endl;
}
}
float M_eff(int Tot_T, int T_sites, float goal)
{
float up=2.0, down=0;
while(up-down>0.00001)
{
if((cosh((up+down)/2*(Tot_T/2-T_sites-1))/cosh((up+down)/2*(Tot_T/2-T_sites))-goal)*(cosh((down)/2*(Tot_T/2-T_sites-1))/cosh((down)/2*(Tot_T/2-T_sites))-goal)<0)
up=(up+down)/2;
else down=(up+down)/2;
}
return up;
}
| 30ba3ccb46401c7f5677cf072f0bb29d37ea3080 | [
"C"
] | 1 | C | PhyFrancis/KPP_DA | 9c9b9554c482c2faa25ed9075a7bb71c518ad826 | 7cc165a4e446c5c14a3e8172c7aa00eaf795f060 |
refs/heads/master | <repo_name>gehaiqing/util<file_sep>/src/platform.ts
/**
* 是否在微信中
*/
export function isWx(): boolean {
return navigator.userAgent.indexOf('MicroMessenger') > -1
}<file_sep>/src/index.ts
export * from './cookie'
export * from './date'
export * from './string'
export * from './platform'
export * from './url'<file_sep>/src/url.ts
/**
* 获取url参数
* @param name 参数名称
* @param url 链接地址,默认为当前地址。可以为完整路径,也可以只是参数部分
*/
export function getQueryString(name: string, url?: string) {
url = url || window.location.href
let search = url.indexOf('?') > -1 ? url.split('?')[1] : url
let reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i')
let r = search.match(reg)
if (r != null) {
return decodeURIComponent(r[2])
}
return null
}
/**
* 替换url中的参数
* @param url 链接。可以为完整路径,也可以只是参数部分
* @param name 参数名称
* @param value 参数值
*/
export function replaceQueryString(url: string, name: string, value: string) {
let reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i')
return url.replace(reg, (str, start, val, end) => {
return start + name + '=' + value + end
})
}<file_sep>/src/string.ts
/**
* 将字符串转为html片段
* @param str
*/
export function text2html(str: string) {
let div = document.createElement('div')
div.innerHTML = str
div.remove()
return div.innerText || div.textContent
}
/**
* 去除字符串中的emoji表情
* @param str
*/
export function removeEmoji(str: string): string {
let ranges = [
'\ud83c[\udf00-\udfff]',
'\ud83d[\udc00-\ude4f]',
'\ud83d[\ude80-\udeff]'
]
return str.replace(new RegExp(ranges.join('|'), 'g'), '')
}<file_sep>/src/cookie.ts
/**
* 获取cookie
* @param name cookie名称
*/
export function getCookie(name: string) {
const reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)')
const arr = document.cookie.match(reg)
return arr ? unescape(arr[2]) : null
}
/**
* 设置cookie
* @param name 名称
* @param value 值
* @param attrs 属性
*/
export function setCookie(name: string, value: string,
attrs: { path: string, domain?: string, expires?: number | string } = { path: '/' }) {
if (typeof attrs.expires === 'number') {
let exdate = new Date()
exdate.setTime(exdate.getTime() + attrs.expires)
attrs.expires = exdate.toUTCString()
}
let attrsString = Object.keys(attrs).reduce((pre, key) => {
return pre + `;${key}=${(attrs as any)[key]} `
}, '')
document.cookie = `${name}=${escape(value)}${attrsString}`
}
/**
* 删除cookie
* @param name cookie名称
* @param attrs 属性
*/
export function removeCookie(name: string,
attrs: { path: string, domain?: string, [key: string]: any } = { path: '/' }) {
setCookie(name, '', { ...attrs, expires: -1 })
}
<file_sep>/.eslintrc.js
module.exports = {
root: true,
extends: ['eslint-config-alloy/typescript'],
plugins: [],
rules: {
indent: [
'error',
2,
{
SwitchCase: 1,
flatTernaryExpressions: true
}
],
semi: ['error', 'never'],
'no-param-reassign': 'off',
'no-unused-vars': 'warn', //未使用的变量
'no-new': 'off' //new操作
}
}
| 70b89b018abf537108c04eb70520f748f6cdd6af | [
"JavaScript",
"TypeScript"
] | 6 | TypeScript | gehaiqing/util | b12070d81912b64de80982b3f39a3e2ad4013d14 | a2537c0d8027354cc234df6d2e4296b0eea169f0 |
refs/heads/master | <repo_name>mk4555/ttt-3-display_board-example-v-000<file_sep>/lib/display_board.rb
# Define a method display_board that prints a 3x3 Tic Tac Toe Board
def display_board
row = " | | "
divider = "-----------"
puts (row)
puts(divider)
puts(row)
puts(divider)
puts(row)
end
display_board
| b9475be8a37005da4bf59700313c49d10f568663 | [
"Ruby"
] | 1 | Ruby | mk4555/ttt-3-display_board-example-v-000 | 1e1763554bb6a96b35c21fa4f99aa78fc546a2f4 | c84b1f0e83194e5eceacb44a3e718b7f8dbd06e4 |
refs/heads/master | <file_sep>var anno2timing = 400;
var anno3timing = 400;
var anno5timing = 400;
var anno11timing = 400;
function annoHide(anno, $target, $annoElem, returnFromOnShow) {
var handler = returnFromOnShow
$target[0].removeEventListener('click', handler)
};
function annoShow(anno, $target, $annoElem) {
var handler = function () { anno.hide(); setTimeout(function () { anno2timing = 0; }, 400) }
$target[0].addEventListener('click', handler)
return handler
};
var anno1 = new Anno({
target: '#hl1',
content: "При строительстве дома прежде всего нужно учитывать стоимость "
+ "земельного участка, которая зависит от расположения и "
+ "удаленности от Краснодара"
+ "<br/><br/><span class='bold'>У вас уже есть участок?</span>",
buttons: [],
position: "center-top",
onShow: function (anno, $target, $annoElem) {
var handler = function () { anno.hide(); setTimeout(function () { anno2timing = 0; }, 400) }
$target[0].addEventListener('click', handler)
return handler
},
onHide: function (anno, $target, $annoElem, returnFromOnShow) {
var handler = returnFromOnShow
$target[0].removeEventListener('click', handler);
anno1 = {};
}
})
var anno3 = new Anno([{
target: '#hl2',
content: "Здесь отображается средняя стоимость земли",
buttons: [{ text: 'Далее' }],
className: "align-center",
position: "center-top"
}, {
target: '#hl3_1',
content: "Когда определитесь с параметрами, нажмите здесь, чтобы перейти к проектированию",
buttons: [{ text: 'Понятно', click: function (anno, evt) { anno.hide(); } }],
className: "align-center",
position: "center-top",
onHide: function (anno, $target, $annoElem, returnFromOnShow) {
anno3 = {};
}
}])
var anno2 = new Anno({
target: '#hl3',
content: "Выберите расположение участка",
buttons: [],
className: "align-center",
position: "center-top",
onShow: function (anno, $target, $annoElem) {
var handler = function () { anno.hide(); setTimeout(function () { anno3timing = 0; }, 400) }
$target[0].addEventListener('click', handler)
return handler
},
onHide: function (anno, $target, $annoElem, returnFromOnShow) {
var handler = returnFromOnShow;
$target[0].removeEventListener('click', handler);
anno2 = {};
}
})
var anno4 = new Anno({
target: '#hl4',
content: "Дом невозможно построить без проекта, а это тоже затраты и их нужно учитывать"
+ "<br/><br/><span class='bold'>У вас уже есть проект?</span>",
buttons: [],
className: "center-align",
position: "center-top",
onShow: function (anno, $target, $annoElem) {
var handler = function () { anno.hide(); setTimeout(function () { anno5timing = 0; }, 400) }
$target[0].addEventListener('click', handler)
return handler
},
onHide: function (anno, $target, $annoElem, returnFromOnShow) {
var handler = returnFromOnShow
$target[0].removeEventListener('click', handler)
anno4 = {};
}
})
var anno5 = new Anno({
target: '#hl5',
content: "У нас очень большая база типовых проектов, из "
+ "которой вы можете выбрать подходящий вам вариант"
+ "<br/><br/> А также отличные проектировщики, которые "
+ "воплотят в проекте любую вашу мечту",
buttons: [{ text: 'Понятно', click: function (anno, evt) { anno.hide(); } }],
className: "align-center",
position: "center-top",
onShow: function (anno, $target, $annoElem) {
var handler = function () { anno.hide(); }
$target[0].addEventListener('click', handler)
return handler
},
onHide: function (anno, $target, $annoElem, returnFromOnShow) {
var handler = returnFromOnShow;
$target[0].removeEventListener('click', handler);
anno5 = {};
}
})
var anno6 = new Anno({
target: '#hl6',
content: "Стоимость дома зависит от множества факторов:"
+ "<br/>- стоимости стройматериалов"
+ "<br/>- площади"
+ "<br/>- этажности и т.д."
+ "<br/><br/>Выберите параметры, и мы сможем вас "
+ "сориентировать по средней цене, исходя из нашего опыта"
,
buttons: [{ text: 'Понятно', click: function (anno, evt) { anno.hide(); } }],
className: "align-center",
position: "right",
onShow: function (anno, $target, $annoElem) {
var handler = function () { anno.hide(); }
$target[0].addEventListener('click', handler)
return handler
},
onHide: function (anno, $target, $annoElem, returnFromOnShow) {
var handler = returnFromOnShow;
$target[0].removeEventListener('click', handler);
anno6 = {};
}
})
var anno7 = new Anno({
target: '#hl7',
content: "Мы можем оформить всю разрешительную документацию, либо вы можете это сделать сами"
+ "<br/><br/><span class='bold'>Используйте переключатели, чтобы выбрать, какую документацию вам необходимо оформить</span>"
,
buttons: [{ text: 'Понятно', click: function (anno, evt) { anno.hide(); } }],
className: "align-center",
position: "right",
onShow: function (anno, $target, $annoElem) {
var handler = function () { anno.hide(); }
$target[0].addEventListener('click', handler)
return handler
},
onHide: function (anno, $target, $annoElem, returnFromOnShow) {
var handler = returnFromOnShow;
$target[0].removeEventListener('click', handler);
anno7 = {};
}
})
var anno8 = new Anno([{
target: '#hl8',
content: "Ваш ориентировочный расчет готов.<br/><br/>Вы можете прямо в формах"
+ " изменить значения полей, чтобы получить новую итоговую сумму",
buttons: [{ text: 'Далее' }],
className: "align-center",
position: "center-top"
}, {
target: '#hl9',
content: "Здесь отображается итоговая стоимость по вашим параметрам",
buttons: [{ text: 'Далее' }],
className: "align-center",
position: "center-top"
}, {
target: '#hl10',
content: "Более точно сориентироваться по цене вам помогут примеры наших "
+ "выполненных работ, которые мы предоставляем со стоимостью реализации",
buttons: [{ text: 'Понятно', click: function (anno, evt) { anno.hide(); } }],
className: "align-center",
position: "center-top"
}])
var anno11 = new Anno({
target: '#hl11',
content: "Чтобы избежать отправки каталога роботам и конкурентам, "
+ "у нас выполняется ручная проверка каждой заявки"
+ "<br/><br/>Поэтому, если вы действительно заинтересованы, "
+ "то заполните форму ниже и дождитесь звонка нашего менеджера",
buttons: [{ text: 'Понятно', click: function (anno, evt) { anno.hide(); } }],
className: "align-center",
position: { "left":"auto", "top": "120px" },
arrowPosition: "right",
onShow: function (anno, $target, $annoElem) {
var handler = function () { anno.hide(); }
$target[0].addEventListener('click', handler)
return handler
},
onHide: function (anno, $target, $annoElem, returnFromOnShow) {
var handler = returnFromOnShow;
$target[0].removeEventListener('click', handler);
anno11 = {};
}
})<file_sep>"use strict";
var yaCounter47830858 = new Ya.Metrika({ id: 47830858, triggerEvent: true });
var mobileConfirmed = false;
function reach(goal, params) {
if (!params) {
params = {};
}
yaCounter47830858.reachGoal(goal, params, function () {
// console.log("YaCounter: the goal '" + goal + "' has been reached");
});
};
$(document).on('yacounter47830858inited', function () {
// console.log('счетчик yaCounter можно использовать');
});
$(document).ready(function () {
$('select').formSelect();
var os = getMobileOperatingSystem();
switch (os) {
case "iOS": {
$(".toggles").show();
break;
}
case "Android": {
$(".switch").css("opacity", "1");
break;
}
default: {
$("i.material-icons").css("opacity", "1");
break;
}
}
$(".start-btn").click(function (event) {
$(event.currentTarget).hide();
$("#wizard").show();
$(".slogan.welcome").hide();
setTimeout(function () {
anno1.show();
}, 500);
$("body").css({
"overflow": "auto",
"max-height": "auto"
});
});
$("body").css({
"overflow": "hidden",
"max-height": "100%"
});
$("#subtext").addClass("hide-on-large-only");
$("#wizard").hide();
$(".regions").hide();
$(".projs").hide();
$(".step").hide();
$(".contact-form-wrapper").hide();
$("#step1").show();
$(".confirm").click(function () {
$("#wizard, #wizard-mobile").hide();
$(".contact-form-wrapper").show();
setTimeout(function () {
anno11.show();
}, anno11timing);
});
$(".nextpage").click(nextPage);
$("[data-group]").click(selectButtonInGroup);
$("select").change(selectDropdownItem);
$("#contact_phone").keypress(phoneInput);
$("#step1 .nextpage, #step2 .nextpage, #step3 .nextpage").hide();
$("#step1 #hl3 button").click(function () {
setTimeout(function () {
anno3.show();
}, anno3timing);
});
$("#step1 .nextpage").click(function () {
anno4.show();
});
$("#step2 .nextpage").click(function () {
anno6.show();
});
$("#step3 .nextpage").click(function () {
anno7.show();
});
$("#step4 .nextpage").click(function () {
anno8.show();
});
$(".step button").click(function (event) {
$(event.currentTarget).closest(".step").find(".nextpage").show();
});
$("#wizard-mobile .toggle, #wizard-mobile .confirm").click(function (event) {
var goalName = $(event.currentTarget).attr("data-info") + "_Input_Changed";
reach(goalName);
});
$("#wizard-mobile select").change(function (event) {
var goalName = $(event.currentTarget).attr("data-info") + "_Input_Changed";
reach(goalName);
});
$("#wizard-mobile .confirm").click(function () {
mobileConfirmed = true;
});
$("#wizard .nextpage, #wizard .confirm").click(function (event) {
var goalName = $(event.currentTarget).closest(".step").attr("data-info") + "_Settings_Passed";
reach(goalName);
});
$(".socialweb").click(function (event) {
var goalName = $(event.currentTarget).attr("data-info") + "_Social_Direct";
reach(goalName);
});
$(".send").click(function () {
var validerror = validContacts();
if (validerror) {
$("#contact_phone").css("border", "inset thin red");
$(".valid-message").show();
return;
}
reach(mobileConfirmed ? "Mobile_Contacts_Passed" : "Contacts_Passed");
var data = [];
data.push("---------------------");
data.push("Информация о клиенте:");
data.push("---------------------");
data.push("Имя: " + $("#contact_name").val());
data.push("Почта: " + $("#contact_email").val());
data.push("Телефон: " + $("#contact_phone").val());
data.push("---------------------");
data.push("Информация о заказе:");
data.push("---------------------");
data = data.concat(groups.map(function (g) {
return g.name + ": " + (g.selectedIndex != null ? g.selectedIndex === -1 ? "не выбрано" : g.items[g.selectedIndex] : g.selected ? "да" : "нет");
}));
//console.log($("#contact_name").val(), data);
$.ajax({
method: "post",
url: "send.php",
data: { data: data },
error: function error(res) {
M.toast({
html: 'Произошли технические неполадки. Попробуйте еще раз'
});
//console.log("Failed", res);
},
success: function success(res) {
$(".thanks").show();
$(".contacts").hide();
//console.log("OK", res);
}
});
});
var phones = [{ "mask": "+7 (8##) ###-####" }];
$('#contact_phone').inputmask({
mask: phones,
greedy: true,
prefix: "+7 ",
definitions: {
'8': { validator: "[0-7, 9]" },
'#': { validator: "[0-9]", cardinality: 1 }
}
});
var gr = groups.map(function (x) {
return x.group;
});
gr = gr.filter(function (x, i) {
return gr.indexOf(x) === i;
}).map(function (x) {
return groups.find(function (g) {
return g.group === x;
}).name;
});
gr.forEach(function (g) {
return $(".price-" + getGroup(g)).text(getPrice(g));
});
$(".price-total").text(getTotalPrice());
});
function getMobileOperatingSystem() {
var userAgent = navigator.userAgent || navigator.vendor || window.opera;
// Windows Phone must come first because its UA also contains "Android"
if (/windows phone/i.test(userAgent)) {
return "Windows Phone";
}
if (/android/i.test(userAgent)) {
return "Android";
}
// iOS detection from: http://stackoverflow.com/a/9039885/177710
if (/iPad|iPhone|iPod/.test(userAgent) && !window.MSStream) {
return "iOS";
}
return "unknown";
}
function nextPage(event, sender) {
var stepid = $(event.currentTarget).closest(".step").attr("id").slice(-1);
$("#step" + stepid).hide();
$("#step" + ++stepid).show();
}
function selectDropdownItem(event, sender) {
var id = event.currentTarget.className.split('-')[0];
var index = $(event.currentTarget).val();
var group = groups.find(function (x) { return x.id === id }).name;
var target = $('[data-index="' + index + '"][data-group="' + group + '"]').attr("data-target");
if (index == -1) {
if (group === "тип проекта") {
$(".projs").hide();
selectItemInGroup("нужен проект", 0);
}
if (group === "тип участка") {
$(".regions").hide();
selectItemInGroup("нужен участок", 0);
$(".additional").hide();
}
} else {
$("[data-group='" + group + "']").removeClass("selected");
$('[data-index="' + index + '"][data-group="' + group + '"]').addClass("selected");
if (group === "тип проекта") {
$(".projs").show();
selectItemInGroup("нужен проект", 1);
}
if (group === "тип участка") {
$(".regions").show();
selectItemInGroup("нужен участок", 1);
$(".additional").show();
}
}
selectItemInGroup(group, index);
$("#" + target).css("background-image", "url(\"images/" + target + "/" + index + ".png\")");
$(".price-" + getGroup(group)).text(getPrice(group));
$(".price-total").text(getTotalPrice());
$("." + getId(group) + "-dropdown").val(index).formSelect();
}
function selectButtonInGroup(event, sender) {
var group = $(event.currentTarget).attr("data-group");
var index = $(event.currentTarget).attr("data-index");
var toHide = $(event.currentTarget).attr("data-area-hide");
var toShow = $(event.currentTarget).attr("data-area-show");
var target = $(event.currentTarget).attr("data-target");
$("." + toHide).hide();
$("." + toShow).show();
if (isToggle(group)) {
var checked = index != null ? index === "1" : !$(event.currentTarget).find("input[type=checkbox]").prop("checked");
$(event.currentTarget).find("i").text(checked ? "check_circle" : "radio_button_unchecked");
$("button.toggle[data-group='" + group + "']").find("i").text(checked ? "check_circle" : "radio_button_unchecked");
$("button.toggle[data-group='" + group + "']").find("input[type=checkbox]").prop("checked", checked);
$("button[data-group='" + group + "']").removeClass("selected");
$("button[data-group='" + group + "'][data-index='" + (checked ? 1 : 0) + "']").addClass("selected");
} else {
$("button[data-group='" + group + "']").removeClass("selected");
$(event.currentTarget).addClass("selected");
}
if (group === "нужен участок" && index === "0") {
group = "тип участка";
index = "-1";
$("button[data-group='" + group + "']").removeClass("selected");
$(".additional").hide();
}
if (group === "нужен проект" && index === "0") {
group = "тип проекта";
index = "-1";
$("button[data-group='" + group + "']").removeClass("selected");
}
if (group === "нужен проект" && index === "1") {
setTimeout(function () {
anno5.show();
}, anno5timing);
}
if (group === "нужен участок" && index === "1") {
$(".additional").show();
setTimeout(function () {
anno2.show();
}, anno2timing);
}
selectItemInGroup(group, index);
$("#" + target).css("background-image", "url(\"images/" + target + "/" + index + ".png\")");
$(".price-" + getGroup(group)).text(getPrice(group));
$(".price-total").text(getTotalPrice());
$("." + getId(group) + "-dropdown").val(index).formSelect();
}
function validContacts() {
if ($("#contact_phone").val().length == 0) {
return "Укажите номер телефона";
};
if ($("#contact_phone").val().indexOf("_") > 0) {
return "Укажите корректный номер телефона";
};
}
function isToggle(groupName) {
return !Array.isArray(groups.find(function (x) {
return x.name === groupName;
}).items);
}
function selectItemInGroup(groupName, index) {
if (isToggle(groupName)) {
groups.find(function (x) {
return x.name === groupName;
}).selected = index != null ? !!+index : !groups.find(function (x) {
return x.name === groupName;
}).selected;
// //console.log("here", groups.find(x => x.name === groupName).selected);
} else {
groups.find(function (x) {
return x.name === groupName;
}).selectedIndex = index;
}
}
function getPrice(groupName) {
var g = groups.find(function (x) {
return x.name === groupName;
});
return isToggle(groupName) ? g.selected ? convertToString(g.value, g.fixed) : "" : convertToString(groups.filter(function (x) {
return x.group === g.group;
}).reduce(function (prev, curr) {
return prev * (curr.values[curr.selectedIndex] ? curr.values[curr.selectedIndex] : 0);
}, 1), g.fixed);
}
function getTotalPrice() {
var gr = groups.map(function (x) {
return x.group;
});
gr = gr.filter(function (x, i) {
return gr.indexOf(x) === i;
});
return convertToString(gr.reduce(function (prev, c) {
return Math.round(prev + groups.filter(function (x) {
return x.group === c;
}).reduce(function (prev, curr) {
//console.log(curr.id, (curr.values ? curr.values[curr.selectedIndex] : (curr.selected ? curr.value : 0)));
return prev * (curr.values ? curr.values[curr.selectedIndex] ? curr.values[curr.selectedIndex] : 0 : curr.selected ? curr.value : 0);
}, 1));
}, groups.find(function (x) {
return x.name === "тип участка";
}).selectedIndex > -1 ? 30000 : 0));
}
function getGroup(groupName) {
var g = groups.find(function (x) {
return x.name === groupName;
});
return g.group;
}
function getId(groupName) {
var g = groups.find(function (x) {
return x.name === groupName;
});
return g.id;
}
function convertToNumber(str) {
return +str.replace(/\D/g, "");
}
function convertToString(num, fixed) {
var s = "";
if (!Number.isNaN(num)) {
for (var i = 0; i < 10; i++) {
s = num % 10 + s;
num = Math.floor(num / 10);
if (num <= 0) break;
s = num % 10 + s;
num = Math.floor(num / 10);
if (num <= 0) break;
s = num % 10 + s;
num = Math.floor(num / 10);
if (num <= 0) break;
s = " " + s;
}
} else {
s = "0";
}
return s !== "0" ? (fixed ? "" : "От ") + s + " рублей" : "";
}
function formatPhoneNumber(raw) {
return raw.replace(/[^\d\+]/g, "").replace(/$8/);
}
function phoneInput(key, sender) {
$("#contact_phone").css("border", "inset 0px red");
$(".valid-message").hide();
if (key.target.value.length === 0 && key.charCode === 56) return false;
//console.log(key.target.value);
}
var groups = [{
"group": "regions",
"name": "нужен участок",
"id": "regionNeeded",
"items": ["Участок есть", "Нужен подбор"],
"values": [0, 1],
"selectedIndex": 1
}, {
"group": "regions",
"name": "тип участка",
"id": "region",
"items": ["Прикубанский округ", "Центральный округ", "Западный округ", "Карасунский округ", "0-15 км (за городом)", "15-35 км (за городом)", "35-100 км (за городом)", "Побережье черного моря"],
"values": [300000, 2000000, 2000000, 1000000, 200000, 100000, 50000, 300000],
"selectedIndex": 0
}, {
"group": "projects",
"name": "нужен проект",
"id": "projectNeeded",
"items": ["Проект есть", "Требуется разработка"],
"values": [0, 1],
"selectedIndex": 1
}, {
"group": "projects",
"name": "тип проекта",
"id": "project",
"items": ["Типовой проект", "Индивидуальный проект"],
"values": [20000, 30000],
"selectedIndex": 0
}, {
"group": "building",
"name": "комплектация",
"id": "building",
"items": ["Коробка", "Предчистовая отделка", "Дом с ремонтом"],
"values": [20000, 25000, 32000],
"selectedIndex": 0
}, {
"group": "building",
"name": "площадь",
"id": "area",
"items": ["100-150M2", "150-200M2", "200-250M2", ">250M2"],
"values": [10, 15, 20, 25],
"selectedIndex": 0,
"step": 3
}, {
"group": "building",
"name": "этажность",
"id": "floors",
"items": ["1 этаж", "2 этажа", "3 этажа"],
"values": [12, 20, 27],
"selectedIndex": 0,
"step": 3
}, {
"group": "underground",
"name": "цокольный этаж",
"id": "underground",
"value": 0,
"selected": false
}, {
"group": "garage",
"name": "гараж",
"id": "garage",
"value": 0,
"selected": false
}, {
"group": "monsarde",
"name": "монсарда",
"id": "monsarde",
"value": 0,
"selected": false
}, {
"group": "permission",
"name": "разрешение на строительство",
"id": "permission",
"fixed": true,
"value": 20000,
"selected": true
}, {
"group": "electro",
"name": "подключение электричества",
"id": "electro",
"fixed": true,
"value": 20000,
"selected": true
}, {
"group": "usability",
"name": "разрешение на эксплуатацию",
"id": "usability",
"fixed": true,
"value": 20000,
"selected": true
}, {
"group": "water",
"name": "подключение воды",
"id": "water",
"value": 50000,
"selected": true
}, {
"group": "gas",
"name": "подключение газа",
"id": "gas",
"value": 150000,
"selected": true
}];
if (!Array.prototype.find) {
Object.defineProperty(Array.prototype, 'find', {
value: function (predicate) {
// 1. Let O be ? ToObject(this value).
if (this == null) {
throw new TypeError('"this" is null or not defined');
}
var o = Object(this);
// 2. Let len be ? ToLength(? Get(O, "length")).
var len = o.length >>> 0;
// 3. If IsCallable(predicate) is false, throw a TypeError exception.
if (typeof predicate !== 'function') {
throw new TypeError('predicate must be a function');
}
// 4. If thisArg was supplied, let T be thisArg; else let T be undefined.
var thisArg = arguments[1];
// 5. Let k be 0.
var k = 0;
// 6. Repeat, while k < len
while (k < len) {
// a. Let Pk be ! ToString(k).
// b. Let kValue be ? Get(O, Pk).
// c. Let testResult be ToBoolean(? Call(predicate, T, « kValue, k, O »)).
// d. If testResult is true, return kValue.
var kValue = o[k];
if (predicate.call(thisArg, kValue, k, o)) {
return kValue;
}
// e. Increase k by 1.
k++;
}
// 7. Return undefined.
return undefined;
},
configurable: true,
writable: true
});
}
Number.isNaN = Number.isNaN || function (value) {
return typeof value === 'number' && isNaN(value);
}
window.requestAnimationFrame = (function () {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function (/* function */ callback, /* DOMElement */ element) {
window.setTimeout(callback, 1000 / 60);
};
})();
window.scrollTop = null;
<file_sep># atlant-web-material<file_sep><?php
header('Content-Type: application/x-www-form-urlencoded; charset: utf-8');
$obj = join("\r\n", $_POST["data"]);
$header = 'MIME-Version: 1.0' . "\r\n" . 'Content-type: text/plain; charset=UTF-8' . "\r\n";
echo mail("<EMAIL>", "Atlant Web", $obj , $header);
?> | 7d4a98be299e9163aa96269519490644c0dbb203 | [
"JavaScript",
"PHP",
"Markdown"
] | 4 | JavaScript | kkutepow/atlant-web-material | a506376c7933749be469a89486a7b700d005a545 | dd0802324eaf2feac9f7d8fc4ea275c592dedd04 |
refs/heads/master | <repo_name>georgebarkerukfast/forms-task<file_sep>/yearlist.php
<?php
date_default_timezone_set("Europe/London");
$currentYear = date("Y") - 1;
?>
<select class='largeInputMonthYear' name='dobYear' required title='Please select a year'>
<?php
if (isset($_POST['dobYear']) && $_POST['dobYear'] != "")
{
$year = $_POST['dobYear'];
echo "<option value='$year' selected>$year</option>";
}
else
{
echo "<option value='' disabled selected>Year</option>";
}
for ($year = $currentYear; $year >= 1900; $year--)
{
echo "<option value='$year'>$year</option>";
}
?>
</select><file_sep>/index.php
<?php
session_start();
include 'Database.php';
if (isset($_SESSION['barker_logged_in']))
{
$email = $_SESSION['barker_logged_in'];
$firstname = getFirstname($email);
}
if (isset($_COOKIE['barker_logged_in']))
{
$email = $_COOKIE['barker_logged_in'];
$firstname = getFirstname($email);
}
function getFirstname($email)
{
$database = new Database("darrentask");
$result = $database->getUser($email);
$result = mysqli_fetch_assoc($result);
return $result['firstname'];
}
?>
<html>
<head>
<title></title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div id="formContainer">
<?php if (isset($_COOKIE['barker_logged_in']) || isset($_SESSION['barker_logged_in']))
{?>
<h1>Welcome to the site, <?php echo $firstname?>!</h1>
<h2>There's not too much to see here right now...</h2><br>
<?php
if (isset($_COOKIE['barker_logged_in']))
{
echo "<h3>Right now, you're here using a cookie.<br>This means that if you close
this page, you'll automatically be signed in for the next 7 days when you come back to us.
If you choose to logout, this cookie will be destroyed, and you'll have log back in again on your next visit.</h3>";
}
else
{
echo "<h3>Right now, you're here using a session. This means that once you close your browser, you'll be signed out,
and on your next visit you'll have to sign back in again.</h3>";
}
?>
<a href="logout.php"><button class="button"><span>Logout</span></button></a>
<?php
}
else
{
?>
<!-- #BEBCB9-->
<h1>Welcome to the site!</h1>
<a href="login.php"><button class="button"><span>Login</span></button></a>
<a href="register.php"><button class="button"><span>Register</span></button></a>
<?php
}
?>
</div>
</body>
</html><file_sep>/viewrecords.php
<?php
include 'Database.php';
function validation($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$database = new Database("darrentask");
//$database = new Database("george_barker");
$records = $database->getAllRecords();
?>
<html>
<head>
<link rel="stylesheet" href="css/style.css">
<title></title>
</head>
<body>
<div id="formContainer">
<h1>All Records</h1>
<?php
while ($record = $records->fetch_assoc()) //loop through the records.
{//the array index is associative; can specify a column in the table.
echo "<div id='record'>"; //start of record div
echo "User ID: " . validation($record['userid']) . "<br>";
echo "Name: " . validation($record['firstname']) . " " . validation($record['surname']) . "<br>";
echo "Email: " . validation($record['email']) . "<br>";
echo "Mobile number: " . validation($record['mobilenumber']) . "<br>";
if ($record['homenumber'] != "")
echo "Home number: " . validation($record['homenumber']) . "<br>";
echo "Address line 1: " . validation($record['addressline1']) . "<br>";
if ($record['addressline2'] != "")
echo "Address line 2" . validation($record['addressline2']) . "<br>";
echo "City: " . validation($record['city']) . "<br>";
if ($record['county'] != "")
echo "County: " . validation($record['county']) . "<br>";
echo "Postcode: " . validation($record['postcode']) . "<br>";
echo "Country: " . validation($record['country']) . "<br>";
echo "Date of birth: " . validation($record['dateofbirth']) . "<br>";
echo "</div>"; //end of record div
}
?>
</div>
</body>
</html><file_sep>/data.php
<?php
session_start();
include 'Database.php';
if (isset($_SESSION['firstname']))
{
$firstname = $_SESSION['firstname'];
$surname = $_SESSION['surname'];
$email = $_SESSION['email'];
$mobile = $_SESSION['mobile'];
$home = $_SESSION['home'];
$addressline1 = $_SESSION['addressline1'];
$addressline2 = $_SESSION['addressline2'];
$city = $_SESSION['city'];
$county = $_SESSION['county'];
$postcode = $_SESSION['postcode'];
$country = $_SESSION['country'];
$dateofbirth = $_SESSION['dateofbirth'];
$gender = $_SESSION['gender'];
$password = validation($surname) . substr(validation($firstname), 0, 1) . rand(1,9) . rand(1,9) . rand(1, 9);
$database = new Database("darrentask");
// $database = new Database("george_barker");
$database->insertRecord($firstname, $surname, $email, $mobile, $home,
$addressline1, $addressline2, $city, $county, $postcode, $country, $dateofbirth, $gender, $password);
}
else
{
header('Location: register.php');
}
function validation($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<html>
<head>
<link rel="stylesheet" href="css/style.css">
<title></title>
</head>
<body>
<div id="formContainer">
<h1>Thank you for registering, <?php echo validation($firstname) ?>!</h1>
<h2>To confirm, the information you entered is...</h2>
<ul>
<li>Name: <?php echo validation($firstname) . " " . validation($surname) ?></li>
<li>Gender: <?php echo $gender ?></li>
<li>Email: <?php echo $email ?></li>
<li>Mobile number: <?php echo validation($mobile) ?></li>
<?php if ($home != "")
echo "<li>Home number: " . $home . "</li>"; ?>
<li>Address Line 1: <?php echo validation($addressline1) ?></li>
<?php if ($addressline2 != "")
echo "<li>Address Line 2: " . validation($addressline2) . "</li>"; ?>
<li>City: <?php echo $city ?></li>
<?php if ($county != "")
echo "<li>County: " . validation($county) . "</li>"; ?>
<li>Postcode: <?php echo validation($postcode) ?></li>
<li>Country: <?php echo validation($country) ?></li>
<li>Date of birth: <?php echo validation($dateofbirth) ?></li>
<!-- length of first & last no more than 23 chars? -->
<li>Password: <?php echo $password ?></li>
</ul>
<h2>This information has now been added to our<a href="viewrecords.php"> database</a>.</h2>
<br>
<h2>Now you're signed up, you can login <a href="login.php">here</a>, using the password <?php echo $password ?></h2>
</div>
</body>
</html>
<file_sep>/login.php
<?php
session_start();
include 'Database.php';
$database = new Database("darrentask");
$success;
if (isset($_POST['login']))
{
$email = $_POST['email'];
$password = $_POST['password'];
$results = $database->login($email, $password);
$success = $results->num_rows;
if ($success > 0)
{
$_SESSION['barker_logged_in'] = $email;
if (isset($_POST['rememberme']))
{
setcookie("barker_logged_in", $email, time()+(86400 * 7));
}
header('Location: index.php');
}
}
?>
<html>
<head>
<title></title>
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<div id="loginFormContainer">
<h1>George's login page!</h1><br>
<form id='loginForm' action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="post">
<label for="email">Email: </label>
<input class='largeInput nospace' type='text' name='email' value='<?php if (isset($_POST['email'])) echo htmlspecialchars($_POST['email']); ?>'>
<br><br>
<label for="password">Password: </label>
<input class='largeInput' type="<PASSWORD>" name="password">
<br>
<p class='red'><?php if (isset($success)) if ($success == 0) echo "<br>Oops!<br>The email or password you've entered is incorrect.<br>"?></p><br>
<label for="rememberme">Remember me for 7 days: </label>
<input id='checkbox' type="checkbox" name="rememberme">
<br><br>
<input id='largeSubmit' type="submit" value="Log in!" name="login">
<br><br>
<!-- label that says about either being wrong -->
<p>Not already registered with us?<br>You're missing out! <a href="index.php"><i>Click here </i></a> to get started.</p>
<br>
<p>Forgotten your password?<br>Oh dear! <a href="index.php"><i>Click here </i></a> to reset.</p>
</form>
</div>
</body>
</html><file_sep>/register.php
<?php
session_start();
//trim it, if trim still = "" then its bad
//if array has a count of > 0, then do the div
$errors = array();
$assocErrors = array();
function validate($string)
{
$validatedString = $string;
$validatedString = str_replace(" ", "", $validatedString);
$validatedString = str_replace(range(0, 9), "", $validatedString);
return $validatedString;
}
function isMonth($month)
{
if ($month == "January" || "February" || "March" || "April" || "May" || "June" || "July" || "August" || "September" || "October" || "November" || "December")
{
return true;
}
else
{
return false;
}
}
function dateCreator($day, $month, $year)
{
if ($month == "January")
$month = "01";
else if ($month == "February")
$month = "02";
else if ($month == "March")
$month = "03";
else if ($month == "April")
$month = "04";
else if ($month == "May")
$month = "05";
else if ($month == "June")
$month = "06";
else if ($month == "July")
$month = "07";
else if ($month == "August")
$month = "08";
else if ($month == "September")
$month = "09";
else if ($month == "October")
$month = "10";
else if ($month == "November")
$month = "11";
else if ($month == "December")
$month = "12";
$completeDate = $day . "-" . $month . "-" . $year;
return $completeDate;
}
$phoneRegex = "^((\+44\s?\d{4}|\(?\d{5}\)?)\s?\d{6})|((\+44\s?|0)7\d{3}\s?\d{6})^";
$emailRegex = "[^@]+@[^@]+\.[a-zA-Z]{2,6}";
$htmlPostcodeRegex = "(^[Bb][Ff][Pp][Oo]\s*[0-9]{1,4})|(^[Gg][Ii][Rr]\s*0[Aa][Aa]$)|([Aa][Ss][Cc][Nn]|[Bb][Bb][Nn][Dd]|[Bb][Ii][Qq][Qq]|[Ff][Ii][Qq][Qq]|[Pp][Cc][Rr][Nn]|[Ss][Ii][Qq][Qq]|[Ss][Tt][Hh][Ll]|[Tt][Dd][Cc][Uu]\s*1[Zz][Zz])|(^([Aa][BLbl]|[Bb][ABDHLNRSTabdhlnrst]?|[Cc][ABFHMORTVWabfhmortvw]|[Dd][ADEGHLNTYadeghlnty]|[Ee][CHNXchnx]?|[Ff][KYky]|[Gg][LUYluy]?|[Hh][ADGPRSUXadgprsux]|[Ii][GMPVgmpv]|[JE]|[je]|[Kk][ATWYatwy]|[Ll][ADELNSUadelnsu]?|[Mm][EKLekl]?|[Nn][EGNPRWegnprw]?|[Oo][LXlx]|[Pp][AEHLORaehlor]|[Rr][GHMghm]|[Ss][AEGK-PRSTWYaegk-prstwy]?|[Tt][ADFNQRSWadfnqrsw]|[UB]|[ub]|[Ww][A-DFGHJKMNR-Wa-dfghjkmnr-w]?|[YO]|[yo]|[ZE]|[ze])[1-9][0-9]?[ABEHMNPRVWXYabehmnprvwxy]?\s*[0-9][ABD-HJLNP-UW-Zabd-hjlnp-uw-z]{2}$)";
$postcodeRegex = "/^[A-Z]{1,2}[0-9][0-9A-Z]? ?[0-9][A-Z]{2}$/i";
$firstname = $surname = $email = $mobile = $home = $addressline1 = $addressline2 = $city = $county = $postcode = $country = $dateofbirth = $dobDay = $dobMonth = $dobYear = $completeDob = $termsandconditions = $gender = "";
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (isset($_POST['firstname']))
{
$_SESSION['firstname'] = $firstname = $_POST['firstname'];
if ($firstname != "")
{
if (validate($firstname) == "")
$assocErrors['firstname'] = "The firstname you have entered is not correct. Firstnames cannot contain numbers.";
}
else
{
$assocErrors['firstname'] = "Please enter a first name.";
}
}
else
{
$assocErrors['firstname'] = "Please enter a first name.";
}
if (isset($_POST['surname']))
{
$_SESSION['surname'] = $surname = $_POST['surname'];
if ($surname != "")
{
if (validate($surname) == "")
$assocErrors['surname'] = "The surname you have entered is not correct. Surnames cannot contain numbers.";
}
else
{
$assocErrors['surname'] = "Please enter a surname.";
}
}
else
{
$assocErrors['surname'] = "Please enter a surname.";
}
if (isset($_POST['gender']))
{
$_SESSION['gender'] = $gender = $_POST['gender'];
}
else
{
$assocErrors['gender'] = "Please select a gender.";
}
if (isset($_POST['email']))
{
$_SESSION['email'] = $email = $_POST['email'];
if ($email != "")
{
if (filter_var($email, FILTER_VALIDATE_EMAIL) == false)
$assocErrors['email'] = "The email you have entered is not correct.";
}
else
{
$assocErrors['email'] = "Please enter an email.";
}
}
else
{
$assocErrors['email'] = "Please enter an email.";
}
if (isset($_POST['mobilenumber']))
{
$_SESSION['mobile'] = $mobile = $_POST['mobilenumber'];
if ($mobile != "")
{
if (preg_match($phoneRegex, $mobile) == 0)
$assocErrors['mobile'] = "The mobile number you have entered is not correct.<br>An example format of a valid input is '07825309640'.";
}
else
{
$assocErrors['mobile'] = "Please enter a mobile number.";
}
}
else
{
$assocErrors['mobile'] = "Please enter a mobile number.";
}
if (isset($_POST['homenumber']))
{
$_SESSION['home'] = $home = $_POST['homenumber'];
if ($home != "")
if ((preg_match($phoneRegex, $home) == 0) && $home != "")
$assocErrors['home'] = "The home number you have entered is not correct.<br>An example format of a valid input is '01612153711'.";
}
if (isset($_POST['addressline1']))
{
$_SESSION['addressline1'] = $addressline1 = $_POST['addressline1'];
if ($addressline1 != "")
{
if (str_replace(" ", "", $addressline1) == "")
$assocErrors['addressline1'] = "The address line 1 you have entered is not correct.";
}
else
{
$assocErrors['addressline1'] = "Please enter an address line 1.";
}
}
else
{
$assocErrors['addressline1'] = "Please enter an address line 1.";
}
if (isset($_POST['addressline2']))
{
$_SESSION['addressline2'] = $addressline2 = $_POST['addressline2'];
if ($addressline2 != "")
if (str_replace(" ", "", $addressline2) == "")
$assocErrors['addressline2'] = "The address line 2 you have entered is not correct.";
}
if (isset($_POST['city']))
{
$_SESSION['city'] = $city = $_POST['city'];
if ($city != "")
{
if (validate($city) == "")
$assocErrors['city'] = "The city you have entered is not correct.";
}
else
{
$assocErrors['city'] = "Please enter a city.";
}
}
else
{
$assocErrors['city'] = "Please enter a city.";
}
if (isset($_POST['county']))
{
$_SESSION['county'] = $county = $_POST['county'];
if ($county != "")
if (validate($county) == "")
$assocErrors['county'] = "The county you have entered is not correct.";
}
if (isset($_POST['postcode']))
{
$_SESSION['postcode'] = $postcode = $_POST['postcode'];
if ($postcode != "")
{
if (preg_match($postcodeRegex, $postcode) == 0)
{
$assocErrors['postcode'] = "The postcode you have entered is not correct.<br>An example format of a valid input for a postcode is 'M15 5QJ'.";
}
}
else
{
$assocErrors['postcode'] = "Please enter a postcode.";
}
}
else
{
$assocErrors['postcode'] = "Please enter a postcode.";
}
if (isset($_POST['termsandconditions']))
{
$_SESSION['termsandconditions'] = $termsandconditions = $_POST['termsandconditions'];
}
else
{
$assocErrors['termsandconditions'] = "You must agree to the terms and conditions to proceed.";
}
if (isset($_POST['country']))
{
$_SESSION['country'] = $country = $_POST['country'];
}
else
{
$assocErrors['country'] = "Please select a country.";
}
if(isset($_POST['dobDay'], $_POST['dobMonth'], $_POST['dobYear']))
{
$dobDay = floatval($_POST['dobDay']);
$dobMonth = $_POST['dobMonth'];
$dobYear = floatval($_POST['dobYear']);
// var_dump(isMonth($dobMonth));
if ( ((int)$dobDay == $dobDay) && ((int)$dobYear) == $dobYear)
{
if ($dobDay >= 1 || $dobDay <= 31)
{
if ((($dobMonth == ("April" || "June" || "September" || "November")) && ($dobDay >= 31)))
{
$assocErrors['dob'] = "The month you have entered does not have that many days.";
}
if (($dobMonth == "February") && ($dobDay > 29))
{
$assocErrors['dob'] = "The month you have entered does not have that many days.";
}
else
{
if (count($assocErrors) == 0)
{
$completeDob = dateCreator($dobDay, $dobMonth, $dobYear);
$_SESSION['dateofbirth'] = $completeDob;
}
}
}
else //else for the dob being between 1 and 30
{
$assocErrors['dob'] = "This is an invalid date number!";
}
}
else //else for any of the params not being a real number
{
$assocErrors['dob'] = "This is an invalid date!";
}
}
else
{
$assocErrors['dob'] = "Please enter a date.";
}
if (count($assocErrors) == 0)
{
header('Location: data.php');
}
}
?>
<html>
<head>
<title>Form</title>
<link rel="stylesheet" href="css/style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<script>
$(function()
{
$('.nospace').on('keypress', function(e)
{
if (e.which == 32)
return false;
});
});
</script>
</head>
<body>
<?php if (count($assocErrors) != 0 ) {
echo '<div id="errors">';
echo '<p>Unfortunately, there were some issues with the information you\'ve provided.<br>These issues are highlighted in red below. Please correct these to proceed.</p>';
echo '</div>';
}
?>
<div id="formContainer">
<h1>George's Form!</h1>
<!-- By using this bit of PHP, XSS is prevented inside the URL -->
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
<p>Fill in the details below to complete registration! <br> * Denotes a required field.</p><br>
<label for="firstname">Name*: </label>
<input class='largeInput nospace' type="text" name="firstname" placeholder="Firstname" value="<?php if (isset($_POST['firstname'])) echo htmlspecialchars($_POST['firstname']); ?>" title="Please enter a firstname." required>
<input class='largeInput nospace' type="text" name="surname" placeholder="Surname" value="<?php if (isset($_POST['surname'])) echo htmlspecialchars( $_POST['surname']); ?>" title="Please enter a surname." required> <br>
<label class='red' for="firstname"><?php if (isset($assocErrors['firstname'])) echo $assocErrors['firstname'] ?></label><br>
<label class='red' for="surname"><?php if (isset($assocErrors['surname'])) echo $assocErrors['surname']?></label><br><br>
<label for="gender">Gender*: </label>
<!-- if checked -->
<input class='radioPadding' type="radio" name="gender" value="male"
<?php
if (isset($_POST['gender']))
{
if ($_POST['gender'] == "male")
{
echo "checked='checked'";
}
}
?>> Male
<input class='radioPadding' type="radio" name="gender" value="female"
<?php
if (isset($_POST['gender']))
{
if ($_POST['gender'] == "female")
{
echo "checked='checked'";
}
}
?>> Female<br>
<label class='red' for="gender"><?php if (isset($assocErrors['gender'])) echo $assocErrors['gender']?></label><br><br>
<label for="email">Email*: </label>
<input class='largeInput nospace' type="text" name="email" placeholder="" required pattern="<?php echo $emailRegex ?>" title="Please enter a valid email address." value="<?php if (isset($_POST['email'])) echo htmlspecialchars($_POST['email']); ?>" ><br>
<label class='red' for="email"><?php if (isset($assocErrors['email'])) echo $assocErrors['email']?></label><br>
<br><label for="mobilenumber">Phone number: </label>
<input class='largeInput nospace' type="text" name="mobilenumber" placeholder="Mobile number*" pattern="<?php echo $phoneRegex ?>" value="<?php if (isset($_POST['mobilenumber'])) echo htmlspecialchars($_POST['mobilenumber']); ?>" title="Please enter a valid phone number, eg. '07825309640'." required>
<input class='largeInput nospace' type="text" name="homenumber" placeholder="Home number" pattern="<?php echo $phoneRegex ?>" value="<?php if (isset($_POST['homenumber'])) echo htmlspecialchars($_POST['homenumber']); ?>" title="Please enter a valid phone number, eg. '01612153711'."><br>
<label class='red' for="mobilenumber"><?php if (isset($assocErrors['mobile'])) echo $assocErrors['mobile']?></label><br>
<label class='red' for="homenumber"><?php if (isset($assocErrors['home'])) echo $assocErrors['home']?></label><br><br>
<label for="addressline1">Address: </label>
<input class='largeInput' type="text" name="addressline1" placeholder="Address Line 1*" value="<?php if (isset($_POST['addressline1'])) echo htmlspecialchars($_POST['addressline1']);?>" required title="Please enter an address line 1.">
<!-- <label for="addressline2">Address Line 2</label><br>-->
<input class='largeInput' type="text" name="addressline2" placeholder="Address Line 2" value="<?php if (isset($_POST['addressline2'])) echo htmlspecialchars($_POST['addressline2']);?>"><br>
<label class='red' for="addressline1"><?php if (isset($assocErrors['addressline1'])) echo $assocErrors['addressline1']?></label><br>
<label class='red' for="addressline2"><?php if (isset($assocErrors['addressline2'])) echo $assocErrors['addressline2']?></label><br><br>
<label for="city">City*: </label>
<input class='largeInput' type="text" name="city" value="<?php if (isset($_POST['city'])) echo htmlspecialchars($_POST['city']); ?>" required title="Please enter a city."><br>
<label class='red' for="city"><?php if (isset($assocErrors['city'])) echo $assocErrors['city']?></label><br><br>
<label for="county">County: </label>
<input class='largeInput' type="text" name="county" value="<?php if (isset($_POST['county'])) echo htmlspecialchars($_POST['county']); ?>"><br><br>
<label class='red' for="county"><?php if (isset($assocErrors['county'])) echo $assocErrors['county']?></label><br>
<label for="postcode" >Postcode*: </label>
<input class='largeInput' type="text" name="postcode" required pattern="<?php echo $htmlPostcodeRegex ?>" title="Please enter a valid postcode, eg. 'M15 5QJ'" value="<?php if (isset($_POST['postcode'])) echo htmlspecialchars($_POST['postcode']); ?>" ><br>
<label class='red' for="postcode"><?php if (isset($assocErrors['postcode'])) echo $assocErrors['postcode']?></label><br><br>
<label for="country">Country*: </label>
<?php include 'countrylist.php'; ?><br>
<label class='red' for="country"><?php if (isset($assocErrors['country'])) echo $assocErrors['country']?></label><br><br>
<label for="dateofbirth">Date of Birth*: </label>
<!--<input class='tallLargeInput' type="date" name="dateofbirth" placeholder="Date of birth" required>-->
<input type="text" class="largeInputDay" name="dobDay" maxlength="2" placeholder="Day" value="<?php if (isset($_POST['dobDay'])) echo htmlspecialchars($_POST['dobDay']); ?>" >
<?php include 'monthlist.php'; ?>
<?php include 'yearlist.php'; ?>
<label class='red' for="dateofbirth"><?php if (isset($assocErrors['dob'])) echo $assocErrors['dob']?></label><br>
<br><br>
<label for="termsandconditions">Do you agree to the terms and conditions?*</label>
<input id='largeInput' type="checkbox" name="termsandconditions" required><br>
<label class='red' for="termsandconditions"><?php if (isset($assocErrors['termsandconditions'])) echo $assocErrors['termsandconditions']?></label><br><br>
<input id='largeSubmit' type="submit" value="Register!"><br>
</form>
</div>
</body>
</html><file_sep>/Database.php
<?php
class Database
{
private $name;
private $databaseConnection;
public function Database($name)
{
$this->name = $name;
$this->databaseConnection = new mysqli("localhost", "root", "", $this->name);
// $this->databaseConnection = new mysqli("localhost", "george_barker", "<PASSWORD>", $this->name);
if ($this->databaseConnection->connect_errno > 0)
{
die("Unable to connect to database, " . $database->connect_error);
}
}
public function insertRecord($firstname, $surname, $email, $mobile, $home, $addressline1, $addressline2, $city, $county, $postcode, $country, $dateofbirth, $gender, $password)
{
//Create statement object. Every database must have a statement object.
$statement = $this->databaseConnection->stmt_init();
//sql statement, ? represents a placeholder.
$sql = "INSERT INTO users_forms VALUES(NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
//prepare an SQL statement for execution
$statement->prepare($sql);
//first param is data type of the following parameters for the query.
$statement->bind_param("ssssssssssssss", $firstname, $surname, $email, $mobile, $home, $addressline1, $addressline2, $city, $county, $postcode, $country, $dateofbirth, $gender, $password);
//executes the statement on the database side.
$statement->execute();
}
public function login($email, $password)
{
$statement = $this->databaseConnection->stmt_init();
$sql = "SELECT * FROM users_forms WHERE email= ? AND password = ?";
$statement->prepare($sql);
$statement->bind_param("ss", $email, $password);
$statement->execute();
$results = $statement->get_result();
return $results;
}
public function getAllRecords()
{
$statement = $this->databaseConnection->stmt_init();
$sql = "SELECT * FROM users_forms";
$statement->prepare($sql);
$statement->execute();
$results = $statement->get_result();
return $results;
/*while ($record = $results->fetch_assoc()) //loop through the records.
{
//the array index is associative; can specify a column in the table.
echo $record['productid'] . "<br>";
}*/
}
public function getUser($email)
{
$statement = $this->databaseConnection->stmt_init();
$sql = "SELECT * FROM users_forms WHERE email = ?";
$statement->prepare($sql);
$statement->bind_param("s", $email);
$statement->execute();
$results = $statement->get_result();
return $results;
}
}
<file_sep>/monthlist.php
<select class="largeInputMonthYear" name="dobMonth" required title="Please select a month" value="<?php if (isset($_POST['dobMonth'])) echo $_POST['dobMonth'] ?>">
<?php
if (isset($_POST['dobMonth']))
{
$month = $_POST['dobMonth'];
echo "<option value='$month' selected>$month</option>";
}
else
{
echo "<option value='' disabled selected>Month</option>";
}
?>
<!-- <option value='' disabled selected>Month</option> -->
<option value="January">January</option>
<option value="February">February</option>
<option value="March">March</option>
<option value="April">April</option>
<option value="May">May</option>
<option value="June">June</option>
<option value="July">July</option>
<option value="August">August</option>
<option value="September">September</option>
<option value="October">October</option>
<option value="November">November</option>
<option value="December">December</option>
</select> | deb7de687e8c1326f8318b67156190a2d6c97899 | [
"PHP"
] | 8 | PHP | georgebarkerukfast/forms-task | 0415a4787126f961a9d32d8c7455954c8e562529 | c88e7848c23005bf232de0e4aa2740571eda091e |
refs/heads/master | <repo_name>ajeshmahto/gitVS<file_sep>/PartyInvites2/IUserRepository.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PartyInvites2
{
public interface IUserRepository
{
void Add(User newUser);
User FetchByLoginname(String loginName);
void SubmitChanges();
}
}
<file_sep>/PartyInvites2/User.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace PartyInvites2
{
public class User
{
public String LoginName
{
get;set;
}
}//git code
} | 82d47aacf4e2f9e745a126b8dd53f5bfacccf9f5 | [
"C#"
] | 2 | C# | ajeshmahto/gitVS | 7f1527f27e39324301e16b281c0e42afe9b9a735 | e78186f02c861696edc4e4518f2d17576ade9320 |
refs/heads/master | <repo_name>andyrkn/msd-bc<file_sep>/h1/migrations/3_distribute_funding.js
const DistributeFunding = artifacts.require("DistributeFunding");
module.exports = function (deployer) {
deployer.deploy(DistributeFunding);
};
<file_sep>/h1/test/distribute-funding-tests.js
const DistributeFunding = artifacts.require("DistributeFunding");
contract('DistributeFunding', accounts => {
it('should allow owner to add beneficiary', async () => {
const instance = await DistributeFunding.new();
const ratio = 10;
const result = await instance.add(accounts[1], ratio, { "from": accounts[0] });
assert.equal(accounts[1], result.logs[0].args.identifier);
assert.equal(ratio, result.logs[0].args.ratio.words[0]);
});
it('should reject non-owner to add beneficiary', async () => {
const instance = await DistributeFunding.new();
const ratio = 10;
try {
const result = await instance.add(accounts[1], ratio, { "from": accounts[1] });
console.log("passed");
assert(false);
}
catch (_) { }
});
it('should route ratios correctly', async () => {
const instance = await DistributeFunding.new();
const ratio1 = 15;
const ratio2 = 25;
const sum = 120;
const addition1 = await instance.add(accounts[1], ratio1, { "from": accounts[0] });
const addition2 = await instance.add(accounts[2], ratio2, { "from": accounts[0] });
const result = await instance.distribute({ "value": sum, "from": accounts[0] });
assert.equal(accounts[1], result.logs[0].args.identifier);
assert.equal(accounts[2], result.logs[1].args.identifier);
assert.equal(Math.floor(ratio1 * 100 / sum), result.logs[0].args.amount.words[0]);
assert.equal(Math.floor(ratio2 * 100 / sum), result.logs[1].args.amount.words[0]);
});
//https://stackoverflow.com/questions/52740950/how-to-send-wei-eth-to-contract-address-using-truffle-javascript-test
}); | 05ae2e246a8cf2fdbb58a6bcec51918ce3527368 | [
"JavaScript"
] | 2 | JavaScript | andyrkn/msd-bc | be1c9ea4851f0559ae6cbfbb29065f08c314d20e | e563fc1c1e3aecc3655d5e1b8a3c1e8d22562827 |
refs/heads/master | <repo_name>sharada-umarane/SalesDashboard<file_sep>/public/config/config.js
/**
* Created by sharadau on 07-04-2015.
*/
//var service_base_url = 'https://boiling-eyrie-9085.herokuapp.com';
//var service_base_url = 'https://desolate-crag-3719.herokuapp.com';
var service_base_url = 'http://localhost:3000';
//var presale_email_id = "<EMAIL>";
var presale_email_id = "<EMAIL>";
var presale_email_cc_id = "<EMAIL>";
var email_from = "<EMAIL>";
<file_sep>/public/scripts/controllers/prospect.edit.js
'use strict';
/**
* @ngdoc function
* @name dashboardApp.controller:ProspectEditCtrl
* @description
* # ProspectEditCtrl
* Controller of the dashboardApp
*/
angular.module('dashboardApp')
.controller('ProspectEditCtrl', function ($scope, $state, $stateParams, ProspectService, Emails) {
$scope.awesomeThings = [
'HTML5 Boilerplate',
'AngularJS',
'Karma'
];
if($stateParams.prospectId)
{
ProspectService.getProspect($stateParams.prospectId)
.success (function (data){
$scope.prospect = data;
console.log(data);
$scope.newProspect = JSON.parse(JSON.stringify($scope.prospect));
})
.error (function (error){
console.log (error.msg);});
}
$scope.updateProspect = function (newProspect) {
newProspect = newProspect || {};
$scope.newProspect = {};
if(newProspect._id) {
ProspectService.updateProspect(newProspect);
}else
{
newProspect._id = getUniqueTime();
ProspectService.addProspect(newProspect);
console.log("email sts:"+newProspect.sendEmail);
//send email
if(newProspect.sendEmail)
{
console.log("Send email on");
var newEmail = {};
var subject = "Presale Prospect: "+newProspect.name;
var from = email_from;
var from_name = email_from;
newEmail.send_date = new Date().toDateString();
newEmail.to = presale_email_id;
newEmail.contents = subject + " is initialized." + " \r\nProspect Description: "+newProspect.description + " \r\nComments: "+ newProspect.othercomments;
Emails.sendEmail(newEmail, from, from_name, subject, newProspect._id,1);
}
}
$state.transitionTo('auth.prospect.view', {prospectId: newProspect._id});
};
$scope.cancelUpdate = function() {
$scope.newProspect = JSON.parse(JSON.stringify($scope.prospect));
};
$scope.addUniqueItem = function (collection, item) {
collection = collection || [];
if (-1 === collection.indexOf(item)) {
collection.push(item);
}
};
});
<file_sep>/public/scripts/controllers/prospect.view.js
'use strict';
/**
* @ngdoc function
* @name dashboardApp.controller:ProspectViewCtrl
* @description
* # ProspectViewCtrl
* Controller of the dashboardApp
*/
angular.module('dashboardApp')
.controller('ProspectViewCtrl', function ($scope, $stateParams, $parse, $upload,$sce, ProspectService, Emails, auth) {
$scope.awesomeThings = [
'HTML5 Boilerplate',
'AngularJS',
'Karma'
];
$scope.textAreas1=[];
$scope.textAreas2=[];
$scope.textAreas3=[];
$scope.textAreas4=[];
$scope.textAreas5=[];
$scope.addMore=function(stage){
if(stage == '1')
{
$scope.textAreas1.push({textBox:""});
}else if(stage == '2')
{
$scope.textAreas2.push({textBox:""});
}else if(stage == '3')
{
$scope.textAreas3.push({textBox:""});
}else if(stage == '4')
{
$scope.textAreas4.push({textBox:""});
}else if(stage == '5')
{
$scope.textAreas5.push({textBox:""});
}
}
$scope.SaveNotes=function(prospectId,stage){
var notes = new Array();
var sender = auth.profile.name;
if(stage=='1') {
for (var i = 0; i < $scope.textAreas1.length; i++) {
console.log($scope.textAreas1[i].textBox);
notes[i] = $scope.textAreas1[i].textBox + "\n\r" + "-" + sender;
}
}
if(stage=='2') {
for (var i = 0; i < $scope.textAreas2.length; i++) {
console.log($scope.textAreas2[i].textBox);
notes[i] = $scope.textAreas2[i].textBox + "\n\r" + "-" + sender;
}
}
if(stage=='3') {
for (var i = 0; i < $scope.textAreas3.length; i++) {
console.log($scope.textAreas3[i].textBox);
notes[i] = $scope.textAreas3[i].textBox + "\n\r" + "-" + sender;
}
}
if(stage=='4') {
for (var i = 0; i < $scope.textAreas4.length; i++) {
console.log($scope.textAreas4[i].textBox);
notes[i] = $scope.textAreas4[i].textBox + "\n\r" + "-" + sender;
}
}
if(stage=='5') {
for (var i = 0; i < $scope.textAreas5.length; i++) {
console.log($scope.textAreas5[i].textBox);
notes[i] = $scope.textAreas5[i].textBox + "\n\r" + "-" + sender;
}
}
//update notes
ProspectService.saveNotes(prospectId, notes, stage);
}
//$scope.newProspect = {};
$scope.fileSelection = function($files){
// $files[0].name = $files[0].name + Date.now();
//console.log("file name updated:"+Date.now());
$scope.uploadFiles = $files;
};
$scope.onFileSelect = function($files, newProspect) {
//$files: an array of files selected, each file has name, size, and type.
for (var i = 0; i < $files.length; i++) {
var file = $files[i];
$scope.upload = $upload.upload({
url: service_base_url+'/api/fileupload', //upload.php script, node.js route, or servlet url
//url: 'htt://localhost:63342/Phantom-Server/public/', //upload.php script, node.js route, or servlet url
method: 'POST',
//headers: {'header-key': 'header-value'},
//withCredentials: true,
data: {myObj: file.name},
file: file // or list of files ($files) for html5 only
//fileName: 'doc.jpg' or ['1.jpg', '2.jpg', ...] // to modify the name of the file(s)
// customize file formData name ('Content-Desposition'), server side file variable name.
//fileFormDataName: myFile, //or a list of names for multiple files (html5). Default is 'file'
// customize how data is added to formData. See #40#issuecomment-28612000 for sample code
//formDataAppender: function(formData, key, val){}
}).progress(function(evt) {
console.log('percent: ' + parseInt(100.0 * evt.loaded / evt.total));
}).success(function(data, status, headers, config) {
// file is uploaded successfully
console.log(newProspect);
//$scope.newProspect.uploadStatus.value = "File uploaded successfully!!!";
console.log("uploaded file name:"+data);
}).error(function (err) {
// file failed to upload
console.log("upload error"+err);
});
//.error(...)
//.then(success, error, progress);
// access or attach event listeners to the underlying XMLHttpRequest.
//.xhr(function(xhr){xhr.upload.addEventListener(...)})
}
/* alternative way of uploading, send the file binary with the file's content-type.
Could be used to upload files to CouchDB, imgur, etc... html5 FileReader is needed.
It could also be used to monitor the progress of a normal http post/put request with large data*/
// $scope.upload = $upload.http({...}) see 88#issuecomment-31366487 for sample code.
};
//$stateParams.prospectId = 3;
ProspectService.getProspect($stateParams.prospectId)
.success (function (data){
$scope.prospect = data;
$scope.prospect.participants = "<EMAIL>";
if(typeof $scope.prospect.questionsDoc != 'string')
{
$scope.prospect.questionsDoc = "";
}
for(var k=0;k<$scope.prospect.notes1.length;k++)
{
$scope.textAreas1.push({textBox:$scope.prospect.notes1[k]});
}
for(var k=0;k<$scope.prospect.notes2.length;k++)
{
$scope.textAreas2.push({textBox:$scope.prospect.notes2[k]});
}
for(var k=0;k<$scope.prospect.notes3.length;k++)
{
$scope.textAreas3.push({textBox:$scope.prospect.notes3[k]});
}
for(var k=0;k<$scope.prospect.notes4.length;k++)
{
$scope.textAreas4.push({textBox:$scope.prospect.notes4[k]});
}
for(var k=0;k<$scope.prospect.notes5.length;k++)
{
$scope.textAreas5.push({textBox:$scope.prospect.notes5[k]});
}
$scope.newProspect = JSON.parse(JSON.stringify($scope.prospect));
})
.error (function (error){
console.log (error.msg);});
$scope.deleteProspect = function(prospectId, name) {
if (confirm("Do you want to delete prospect "+name) == true) {
// todo code for deletion
ProspectService.deleteProspectById(prospectId)
.success (function (data){
console.log(data);
})
.error (function (error){
console.log (error.msg);});
}
}
//retrieve emails for stage1
Emails.getEmailsForProspectStage($stateParams.prospectId, "1")
.success (function (data){
$scope.emailsForStage1 = data;
})
.error (function (error){
console.log (error.msg);});
$scope.acceptProspect = function(newProspect, prospectId, stage, stage_id) {
// newProspect = newProspect || {};
// $scope.newProspect = {};
// console.log("notes:"+notes);
//console.log("notess:"+newProspect.closureNotes);
//console.log(newProspect);
$scope.onFileSelect($scope.uploadFiles, newProspect);
// ProspectService.updateStage(prospectId, stage, stage_id);
ProspectService.ClosureDetails(prospectId, stage, stage_id, newProspect.closureNotes, $scope.uploadFiles[0].name);
$scope.prospect.state_id = stage_id;
$scope.prospect.engagementLetter = $scope.uploadFiles[0].name;
};
$scope.addQuestions = function(newProspect, prospectId) {
var filename = '';
if((typeof $scope.uploadFiles) == 'object')
{
console.log("add question");
$scope.onFileSelect($scope.uploadFiles, newProspect);
filename = $scope.uploadFiles[0].name;
$scope.prospect.questionsDoc = $scope.uploadFiles[0].name;
}
ProspectService.addQuestions(prospectId, newProspect.questions, filename);
};
$scope.rejectProspect = function(newProspect, prospectId, stage, stage_id) {
newProspect = newProspect || {};
$scope.newProspect = {};
//console.log("notess:"+newProspect.closureNotes);
ProspectService.ClosureDetails(prospectId, stage, stage_id, "closurenotes","");
$scope.prospect.state_id = stage_id;
};
$scope.markComplete = function(prospectId, stage, stage_id) {
ProspectService.updateStage(prospectId, stage, stage_id);
$scope.prospect.state_id = stage_id;
};
//stage2 email
Emails.getEmailsForProspectStage($stateParams.prospectId, "2")
.success (function (data){
$scope.emailsForStage2 = data;
})
.error (function (error){
console.log (error.msg);});
//stage3 email
Emails.getEmailsForProspectStage($stateParams.prospectId, "3")
.success (function (data){
$scope.emailsForStage3 = data;
})
.error (function (error){
console.log (error.msg);});
//stage4 email
Emails.getEmailsForProspectStage($stateParams.prospectId, "4")
.success (function (data){
$scope.emailsForStage4 = data;
})
.error (function (error){
console.log (error.msg);});
//stage5 email
Emails.getEmailsForProspectStage($stateParams.prospectId, "5")
.success (function (data){
$scope.emailsForStage5 = data;
})
.error (function (error){
console.log (error.msg);});
//uncategorized emails
//Emails.getUncategorizedEmailsForProspect($stateParams.prospectId)
Emails.getEmailsForProspectStage($stateParams.prospectId,"0")
.success (function (data){
$scope.uncategorizedEmails = data;
console.log("uncategorized emails:"+$scope.uncategorizedEmails);
$scope.uncategorizedEmails.forEach(function (eml) {
console.log("stage:"+eml.stage);
console.log("subject:"+eml.subject);
});
})
.error (function (error){
console.log (error.msg);});
$scope.renderHtml = function(html_code)
{
console.log("html:"+html_code);
var changed_html = html_code.replace("\\n\\r","jjjjjjjjjjjjjjj");
console.log("replaced html:"+changed_html);
//return $sce.trustAsHtml(html_code);
return (changed_html);
};
$scope.oneAtATime = true;
$scope.status = {
isFirstOpen: true,
isFirstDisabled: false
};
});
<file_sep>/config/config-dev.js
module.exports = {
//db: 'mongodb://localho
// st/dashboard',
db: 'mongodb://sharada:<EMAIL>:53251/dashboard',
//baseUrl:"http://localhost:3000",
// baseUrl:"http://desolate-crag-3719.herokuapp.com",
presalesEmailId:"<EMAIL>",
presalesEmailPwd:"<PASSWORD>"
};
<file_sep>/public/scripts/services/emails.js
'use strict';
/**
* @ngdoc service
* @name dashboardApp.emails
* @description
* # emails
* Service in the dashboardApp.
*/
angular.module('dashboardApp')
.service('Emails', function ($http) {
// AngularJS will instantiate a singleton by calling "new" on this function
var emails = [];
this.getEmailsForProspectStage = function (prospect_id, stage) {
//prospect_id = 1;
var successCallback, errorCallback;
var response = {
success: function (callback) {successCallback = callback; return response;},
error: function (callback) {errorCallback = callback; return response;}
};
$http.get(service_base_url+'/api/emails/'+prospect_id+'_'+stage)
.success(function(item){
successCallback(item);
})
.error(function(error){
if (error) {
console.log(error);
errorCallback({msg: 'No emails with prospect id ' + prospect_id + ' for stage '+stage});
}
});
return response;
};
this.getUncategorizedEmails = function () {
var successCallback, errorCallback;
var response = {
success: function (callback) {successCallback = callback; return response;},
error: function (callback) {errorCallback = callback; return response;}
};
$http.get(service_base_url+'/api/emails/ulist/')
.success(function(item){
successCallback(item);
})
.error(function(error){
if (error) {
console.log(error);
errorCallback({msg: 'No uncategorized emails'});
}
});
return response;
};
this.getUncategorizedEmailsForProspect = function (prospect_id) {
//prospect_id = 1;
var successCallback, errorCallback;
var response = {
success: function (callback) {successCallback = callback; return response;},
error: function (callback) {errorCallback = callback; return response;}
};
$http.get(service_base_url+'/api/emails/view/'+prospect_id)
.success(function(item){
successCallback(item);
})
.error(function(error){
if (error) {
console.log(error);
errorCallback({msg: 'No uncategorized emails with prospect id ' + prospect_id });
}
});
return response;
};
this.sendEmail = function(newEmail, from, from_name, subject, prospect_id, stage) {
//add prospect to nodejs server
newEmail.stage = stage;
newEmail.subject = subject;
newEmail.from = from;
newEmail.from_name = from_name;
newEmail.to = newEmail.to;//"<EMAIL>";
newEmail.message = newEmail.contents + "\r\n\r\nPlease note this email is generated using Presales Dashboard.";
newEmail.prospect_id = prospect_id;
newEmail.cc = presale_email_cc_id;
newEmail.send_date = new Date().toDateString();
console.log(newEmail);
$http.post(service_base_url+'/api/emails', newEmail)
.success(function (item) {
emails.push(item);
console.log("Email sent successfully!!!");
})
.error(function (error) {
if (error) {
errorCallback(error);
}
});
};
this.updateEmail = function (email_id, prospect_id, stage) {
console.log("update email:"+email_id+" stage:"+stage);
//prospect_id = 1;
var successCallback, errorCallback;
var response = {
success: function (callback) {successCallback = callback; return response;},
error: function (callback) {errorCallback = callback; return response;}
};
var emails = {};
emails.stage = stage;
//emails.prospect_id = prospect_id;
$http.put(service_base_url+'/api/emails/update/'+email_id,emails)
.success(function(item){
successCallback(item);
})
.error(function(error){
if (error) {
console.log(error);
errorCallback({msg: 'No emails with email id ' + email_id });
}
});
return response;
};
});
| 49e41ffeae07e5f27b28a0f5a8c60d893b93b4d2 | [
"JavaScript"
] | 5 | JavaScript | sharada-umarane/SalesDashboard | 33c3611984ab73d2a8259fa5e457749799c039d5 | ed4371dd9cae53b20e76de7cdadc90ebe02dc7f8 |
refs/heads/main | <repo_name>Srijita-Mandal/Sparks-Bank-Website<file_sep>/transactionscript.php
<?php
$con = mysqli_connect('127.0.0.1','root','');
if(!$con)
{
echo 'Not connected to server';
}
if(!mysqli_select_db($con,'basic_banking_system'))
{
echo 'DAtabase not selected';
}
$sender = $_POST['sender'];
$receiver = $_POST['receiver'];
$amount = $_POST['amount'];
$sql= "INSERT INTO transactions (sender,receiver,amount,status) VALUES ('$sender' , '$receiver' , '$amount' , 'Transferred Succesfully')";
if(!mysqli_query($con,$sql))
{
echo 'Not inserted';
}
else
{
$sql = "SELECT * FROM customers INNER JOIN transactions ON customers.name=transactions.sender";
$query = mysqli_query($con,$sql);
$sql1 = mysqli_fetch_array($query);
$sql = "SELECT * FROM customers INNER JOIN transactions ON customers.name=transactions.receiver";
$query = mysqli_query($con,$sql);
$sql2 = mysqli_fetch_array($query);
if(($amount)<0)
{
echo '<script type="text/javascript">';
echo ' alart("Oops! Negative values cannot be transferred")';
echo '</script>';
}
else if(($amount) > $sqli['balance'])
{
echo '<script type="text/javascript">';
echo ' alart("Bad Luck! Insufficient Balance")';
echo '</script>';
}
else if(($amount)==0)
{
echo '<script type="text.javascript">';
echo ' alart("Oops! Zero value cannot be transferred")';
echo '</script>';
}
else{
$newbalance = $sqli1['balance'] - $amount;
$sql="UPDATE customers INNER JOIN transactions ON customers.name=transactions.sender SET balance = $newbalance";
mysqli_query($con,$sql);
$newbalance = $sqli2['balance'] + $amount;
$sql="UPDATE customers INNER JOIN transactions ON customers.name=transactions.receiver SET balance = $newbalance";
mysqli_query($con,$sql);
}
header('location:success.php');
}
?><file_sep>/contact.php
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Contact</title>
<?php
include 'link.php';
?>
<link rel="stylesheet" href="style.css">
</head>
<body>
<?php
include 'header.php';
?><br><br>
<!-- Main -->
<div class="content">
<div class="container">
<div class="row">
<div class="col-md-8">
<h2 class="p-bold" style="color:#0000ff">Live Support</h2>
<div class="box-padding-10" style="color:800080">
<h4>24 Hours | 7 Days a Week | 365 Days a Year - Live Technical Support</h4>
<hr>
<p class="text-muted">We are with you always.Contact us if you face any types of issue or any queries.We will provide you all the necessary support.Stay connected.stay safe. </p>
</div>
</div>
<div class="col-md-4">
<img src="https://i.postimg.cc/Gm7RmVW5/images-10.jpg" class="img-responsive live-support-img" alt="Live Support">
</div>
</div>
<div class="row">
<div class="col-md-7">
<h2 class="p-bold" style="color:#0000ff">Contact Us</h2>
<div class="box-padding-10">
<form action="#" method="POST">
<div class="form-group">
<label for="name">Name</label>
<input type="text" name="name" class="form-control" pattern="^[A-Za-z\s]{1,}[\.]{0,1}[A-Za-z\s]{0,}$" required>
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="email" name="email" class="form-control" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$" required>
</div>
<div class="form-group">
<label for="message">Message</label>
<textarea name="message" cols="85" class="form-control" rows="7"></textarea>
</div>
<input type="submit" class="btn btn-primary" value="Submit">
</form>
</div>
</div>
<div class="col-md-5">
<div class="box-padding-rl">
<h2 class="p-bold" style="color:#0000ff">Contact Information</h2>
<p class="text-muted">500, <NAME>, Kolkata-700009</p>
<p class="text-muted">12-568-875, 3rd flore, Manthouse building</p>
<p class="text-muted">INDIA</p>
<p class="text-muted">Phone : +91-123-0000000</p>
<p class="text-muted">Email : <EMAIL></p>
<p class="text-muted">Follow On: <a href="#" class="fa fa-google" style="color:#ff0000"></a> <a href="#" class="fa fa-facebook"></a> <a href="#" class="fa fa-instagram" style="color:#800080"></a> <a href="#" class="fa fa-twitter"></a> <a href="#" class="fa fa-linkedin" style="color:#041412"></a></p>
</div>
</div>
</div>
</div>
</div><br><br><br>
<!-- Main End -->
<!-- Footer -->
<?php
include 'footer.php';
?>
<!-- Footer End -->
</body>
</html>
<file_sep>/config.php
<?php
$server="localhost";
$username="root";
$password="";
$db="basic_banking_system";
$con=mysqli_connect($server,$username,$password,$db);
if($con)
{
}
else
die("connection to this database failed due to" . mysqli_connect_error());
?>
<file_sep>/home.php
<html>
<head>
<meta charset="UTF-8">
<title>Sparks Bank</title>
<?php
include 'link.php';
?>
<link rel="stylesheet" href="style.css">
</head>
<body>
<nav class="navbar navbar-inverse navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#mynavbar">
<span class="iconbar"></span>
<span class="iconbar"></span>
<span class="iconbar"></span>
</button>
<a href="home.php" class="navbar-brand"> Sparks Bank</a>
</div>
<div class="collapse navbar-collapse" id="mynavbar">
<ul class="nav navbar-nav navbar-right">
<li><a href="about.php"><span class="glyphicon glyphicon-user"></span> About Us</a></li>
<li><a href="contact.php"><span class="glyphicon glyphicon-phone"></span> Contact</a></li>
<li><a href="#"><span class="glyphicon glyphicon-log-in"></span> Login</a></li>
</ul>
</div>
</div>
</nav><br><br>
<div class="container column-style">
<div class="row" id="hero"><br><br>
<div class="col-md-6 column-style" id="logo">
<img src="https://i.postimg.cc/T13jKfvP/Frame-4-removebg-preview.png"><br>
<div id="name"> Sparks Bank</div>
<h3><b>Be a member of our sparks family!!</b></h3>
</div>
<div class="col-md-6 column-style" id="image1">
<img src="https://i.postimg.cc/NjPtWMLs/pic-5.jpg"><br><br><br><br><br>
<a href="xd.php"> <img src="https://i.postimg.cc/sxD3Z02m/get-in-on-google-play.png" id="gplay"></a><br>
</div>
</div>
</div><br><br>
<div class="container column-style">
<div class="row">
<h3 id="name2"><b>Enjoy Our Special Facilities:</b></h3><br>
<div class="col-md-4">
<a href="#">
<div class="thumbnail"><img src="https://i.postimg.cc/ZnFJ9zZC/onboarding-3.png"></div>
</a>
</div>
<div class="col-md-4">
<a href="#">
<div class="thumbnail"><img src="https://i.postimg.cc/zvfxhnYK/onboarding-4.png"></div>
</a>
</div>
<div class="col-md-4">
<a href="#">
<div class="thumbnail"><img src="https://i.postimg.cc/JhcxdT1j/onboarding-5.png"></div>
</a>
</div>
</div>
</div>
<div class="container">
<div class="row row-style">
<h3 id="name3"><b>Go to Actions:</b></h3><br>
<div class="col-md-4">
<div class="panel panel-success">
<div class="panel-body">
<a href="customers.php"><img src="https://i.postimg.cc/hG166kT0/customers.jpg"></a>
</div>
<div class="panel-footer">
<a href="customers.php"><p><h3> View Customers</h3></p></a>
</div>
</div>
</div>
<div class="col-md-4">
<div class="panel panel-success">
<div class="panel-body">
<a href="transactions.php"><img src="https://i.postimg.cc/tgkv2hGS/transactions.jpg"></a>
</div>
<div class="panel-footer">
<a href="transaction.php"><p><h3> Make Transactions</h3></p></a>
</div>
</div>
</div>
<div class="col-md-4">
<div class="panel panel-success">
<div class="panel-body">
<a href="transactionhistory.php"><img src="https://i.postimg.cc/X7mdPm77/pic-12-2.jpg"></a>
</div>
<div class="panel-footer">
<a href="transactionhistory.php"><p><h3> Transaction History</h3></p></a>
</div>
</div>
</div>
</div>
</div><br><br><br>
<?php
include 'footer.php';
?>
</body>
</html>
<file_sep>/transactionhistory.php
<html>
<head>
<title>Transaction</title>
<?php
include 'link.php';
?>
<link rel="stylesheet" href="style.css">
</head>
<body>
<?php
include 'header.php';
?><br>
<div class="container column-style">
<div class="row" id="bg2">
<div class="col-md-6 column-style">
<img src="https://i.postimg.cc/T13jKfvP/Frame-4-removebg-preview.png" id="logocus">
<div id="heading1"><h1><b>Transaction History</b></h1></div>
</div>
</div>
</div><br><br>
<div class="container">
<div class="table-responsive-sm">
<table class="table table-hover table-striped table-condensed table-bordered">
<thead>
<tr>
<th class="text-center">S.No.</th>
<th class="text-center">Sender</th>
<th class="text-center">Receiver</th>
<th class="text-center">Amount</th>
<th class="text-center">Status</th>
<th class="text-center">Date & Time</th>
</tr>
</thead>
<tbody>
<?php
include 'config.php';
$sql="SELECT * FROM transactions";
$query=mysqli_query($con,$sql);
while($rows = mysqli_fetch_assoc($query))
{
?>
<tr>
<td class="py-2"><?php echo $rows['tid']; ?></td>
<td class="py-2"><?php echo $rows['sender']; ?></td>
<td class="py-2"><?php echo $rows['receiver']; ?></td>
<td class="py-2"><?php echo $rows['amount']; ?></td>
<td class="py-2"><?php echo $rows['status']; ?></td>
<td class="py-2"><?php echo $rows['datetime']; ?></td>
<?php
}
?>
</tbody>
</table>
</div>
</div><br>
<div class="col-md-5">
</div>
<div>
<a href="home.php"><button class="btn btn-primary"> Back to Home </button></a>
</div> <br><br>
<div class="row">
<footer>
<div class="container">
Copyright © <NAME> ,
Internship project of The Sparks Foundation.
</div>
</footer>
</div>
</body>
</html><file_sep>/basic_banking_system (1).sql
-- phpMyAdmin SQL Dump
-- version 5.0.2
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1:3306
-- Generation Time: Jun 19, 2021 at 08:20 AM
-- Server version: 5.7.31
-- PHP Version: 7.3.21
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `basic_banking_system`
--
-- --------------------------------------------------------
--
-- Table structure for table `customers`
--
DROP TABLE IF EXISTS `customers`;
CREATE TABLE IF NOT EXISTS `customers` (
`customers_id` int(10) NOT NULL AUTO_INCREMENT,
`name` varchar(20) NOT NULL,
`email` varchar(20) NOT NULL,
`phone` varchar(12) NOT NULL,
`balance` varchar(10) NOT NULL,
PRIMARY KEY (`customers_id`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=latin1;
--
-- Dumping data for table `customers`
--
INSERT INTO `customers` (`customers_id`, `name`, `email`, `phone`, `balance`) VALUES
(1, 'Neel', '<EMAIL>', '9862465625', '20000'),
(2, 'Payel', '<EMAIL>', '9654157825', '25000'),
(3, 'Debasish', '<EMAIL>', '8562351574', '30000'),
(4, 'Arun', '<EMAIL>', '8698741253', '28500'),
(5, 'Rajdeep', '<EMAIL>', '9856661020', '57000'),
(6, 'Arunima', '<EMAIL>', '8612125540', '40000'),
(7, 'Megha', '<EMAIL>', '9965784123', '42000'),
(8, 'Varun', '<EMAIL>', '8951202031', '42500'),
(9, 'Akash', '<EMAIL>', '9965253510', '36000'),
(10, 'Piyali', '<EMAIL>', '7605291414', '27000');
-- --------------------------------------------------------
--
-- Table structure for table `transfer`
--
DROP TABLE IF EXISTS `transfer`;
CREATE TABLE IF NOT EXISTS `transfer` (
`transaction_no` int(10) NOT NULL AUTO_INCREMENT,
`sender_id` int(10) NOT NULL,
`sender` varchar(20) NOT NULL,
`receiver` varchar(20) NOT NULL,
`status` enum('transferred','processed') NOT NULL,
PRIMARY KEY (`transaction_no`),
UNIQUE KEY `sender_id` (`sender_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Constraints for dumped tables
--
--
-- Constraints for table `transfer`
--
ALTER TABLE `transfer`
ADD CONSTRAINT `transfer_ibfk_1` FOREIGN KEY (`sender_id`) REFERENCES `customers` (`customers_id`);
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep>/xd.php
<html>
<head>
<meta charset="UTF-8">
<title>Customers</title>
<?php
include 'link.php';
?>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container" id="bgcolor">
<div class="col-md-4"></div>
<div class="col-md-4"><h2>It's not a real world website.<br>Do you really think there is an app to download from playstore?! :P</h2></div>
</div>
<div class="col-md-4"></div>
</body>
</html><file_sep>/success.php
<html>
<head>
<meta charset="UTF-8">
<title>Success</title>
<?php
include 'link.php';
?>
<link rel="stylesheet" href="style.css">
</head>
<body>
<?php
include 'header.php';
?><br><br><br>
<img src="https://i.postimg.cc/N0DfvvDh/pic-10.gif" id="image3"><br><br>
<h2 id="msg"><i>Transacted Successfully </i></h2><br><br>
<div class="row">
<div class="col-md-5">
</div>
<div>
<a href="transactionhistory.php"> <button type="button" class="btn btn-success"> View Transaction History </button></a>
</div>
</div>
</body>
</html><file_sep>/transaction.php
<html>
<head>
<title>Transaction</title>
<?php
include 'link.php';
?>
<link rel="stylesheet" href="style.css">
</head>
<body>
<?php
include 'header.php';
?><br>
<div class="container">
<div class="row row-style">
<div class="col-md-6">
<img src="https://i.postimg.cc/q7pym46M/pic-9.jpg" class="img-responsive signup-image" alt="Image" id="image2">
</div>
<div class="col-md-4">
<div class="panel panel-primary">
<div class="panel-heading">
<centre><h3><i>Transfer Money</i></h3></centre>
</div>
<div class="panel-body">
<centre>
<img src="https://i.postimg.cc/hjwphrGS/user.png" class="img-responsive" id="user"><br>
<form method="POST" action="transactionscript.php">
<div class="form-group">
<b>Sender:</b><input type="text" class="form-control" name="sender" required><br>
<b>Transfer to:</b><br><select name="receiver" required>
<option value="Neel">Neel</option>
<option value="Payel">Payel</option>
<option value="Debasish">Debasish</option>
<option value="Arun">Arun</option>
<option value="Rajdeep">Rajdeep</option>
<option value="Arunima">Arunima</option>
<option value="Megha">Megha</option>
<option value="Varun">Varun</option>
<option value="Akash">Akash</option>
<option value="Piyali">Piyali</option>
</select><br><br>
<b>Amount:</b></br><input type="number" name="amount" required>
</div>
</centre>
</div>
<div class="panel-footer">
<centre>
<p><i> Are you confirm to make this Transaction? </i></p>
<button type="submit" value="submit" class="btn btn-primary"> Transfer</button> <a href="home.php"><button type="button" class="btn btn-default"> Cancel </button></a>
</centre>
</div>
</form>
</div>
</div>
</div>
</div>
</body>
</html><file_sep>/customers.php
<html>
<head>
<meta charset="UTF-8">
<title>Customers</title>
<?php
include 'link.php';
?>
<link rel="stylesheet" href="style.css">
</head>
<body>
<?php
include 'header.php';
?>
<div class="container column-style">
<div class="row" id="bg1">
<div class="col-md-6 column-style">
<img src="https://i.postimg.cc/T13jKfvP/Frame-4-removebg-preview.png" id="logocus">
<div id="heading1"><h1><b>Customers</b></h1></div>
</div>
</div>
</div><br><br>
<div class="container">
<centre>
<table class="table table-striped table-bordered table-hover">
<thead>
<tr>
<th>customers_id</th>
<th>Name</th>
<th>Email</th>
<th>Contact No.</th>
<th>Balance</th>
<th></th>
</tr>
</thead>
<tbody>
<?php
include 'config.php';
$sql="SELECT * FROM customers";
$query=mysqli_query($con,$sql);
while($rows = mysqli_fetch_assoc($query))
{
?>
<tr>
<td class="py-2"><?php echo $rows['customers_id']; ?></td>
<td class="py-2"><?php echo $rows['name']; ?></td>
<td class="py-2"><?php echo $rows['email']; ?></td>
<td class="py-2"><?php echo $rows['phone']; ?></td>
<td class="py-2"><?php echo $rows['balance']; ?></td>
<td><a href="transaction.php" name="add" value="add" class="btn btn-primary">Make Transaction</td>
<?php
}
?>
</tbody>
</table>
</centre>
</div><br><br><br><br>
<?php
include 'footer.php';
?>
</body>
</html><file_sep>/README.md
# Sparks-Bank-Website<file_sep>/about.php
<html>
<head>
<meta charset="UTF-8">
<title>About</title>
<?php
include 'link.php';
?>
<link rel="stylesheet" href="style.css">
</head>
<body>
<?php
include 'header.php';
?>
<div class="container column-style">
<div class="row" id="bg1">
<div class="col-md-6 column-style">
<img src="https://i.postimg.cc/T13jKfvP/Frame-4-removebg-preview.png" id="logocus">
<div id="heading1"><h1><b>About Sparks Bank</b></h1></div>
</div>
</div>
</div><br><br>
<div class="container">
<div class="col-md-6">
<p>Sparks Bank is an Online Banking website to transfer money easily.It's a trusted and secure money transaction platform from last 30 years with more than 10,000 customers.You can enjoy our special facilities through login portal.Enjoy commision free stock trading.Online investing and transaction has never been easier than it is right now. <br>Be a member of our Sparks Bank. </p>
</div>
<div class="col-md-6" id="image4">
<img src="https://i.postimg.cc/W3mWzP7D/pic-13.jpg" class="img-responsive img-rounded">
</div>
</div><br><br><br><br><br>
<?php
include 'footer.php';
?>
</body>
</html> | 3f39c4f9c3195604b5d7af22d8798427e9a006c1 | [
"Markdown",
"SQL",
"PHP"
] | 12 | PHP | Srijita-Mandal/Sparks-Bank-Website | 92deeeed9b3d4f2078c492e9d8e7046308e0b711 | 7c500b12d50f87e940309069cd06ccdc89963ba7 |
refs/heads/master | <repo_name>echmykhun/vk-io<file_sep>/preload/setting.js
'use strict';
/* Основные настройки */
exports.settings = {
/* Идентификатор пользователя */
id: null,
/* Email/логин/телефон от аккаунта */
email: null,
/* Пароль от аккаунта */
pass: null,
/* Токен */
token: null,
/* Приложения для авторизации */
app: null,
/* Секретный ключ приложения */
key: null,
/* Версия vk api */
version: 5.45,
/* Лимит запросов в секунду */
limit: 3
};
/**
* Устанавливает настройки модуля
* @param {object} object настройки
* @returns {object} текущий объект
*/
exports.setting = function(object){
/* Копируем объект */
var setting = this.extend({},this.settings);
/* Наследуем конфиг */
this.settings = this.extend(setting,object);
return this;
};<file_sep>/index.js
'use strict';
var
/* File Stream */
fs = require('fs'),
/* Utility */
util = require('util'),
/* Основа модуля */
io = function(){
/* Текущий статус модуля */
this.status = {
/* Кол-во ошибок за инициализацию */
errors: 0,
/* Кол-во выполненых методов vk */
execute: 0,
/* Кол-во отправленных сообщений */
outbox: 0,
/* Кол-во полученных сообщений longpoll */
inbox: 0,
/* Задания */
tasks: {
/* Включен ли работник */
launched: false,
/* Список задач */
queue: [],
/* Идентификатор таймера */
id: null
},
/* Статус longpoll */
longpoll: {
/* Статус longpoll */
launched: false,
/* Пропуск ID сообщений */
skip: [],
/* Сервер longpoll */
server: null,
/* Ключ авторизации */
key: null,
/* TimeStamp последних событий */
ts: null,
/* Режим работы long poll */
mode: null
}
};
/* Список методов api */
this.api = {};
/* Установка базовых методов vk api */
this._apiMethodsList.forEach((method) => {
var
/* Путь метода */
path = method.split('.'),
/* Группа метода */
group = path[0];
/* Ставим группу */
this.api[group] = this.api[group] || {};
/* Ставим обработчик */
this.api[group][path[1]] = (params) => {
/* Возврашаем promise */
return this._api(method,params);
};
});
/* Добавляет методы в основу */
var method = (name,methods) => {
/* Алиас метода */
this[name] = {};
/* Проходимся по списку методов */
methods.forEach((item) => {
var
/* Путь метода */
path = item.path.split('.'),
/* Последний элемент */
end = path.length-1,
/* Алиас */
self = this[name];
/* Проходимся по пути метода */
path.forEach((key,i) => {
/* Если последний элемент */
if (end === i) {
return self[key] = item.handler.bind(this);
}
/* Установка ссылки на элемент */
self = self[key] = self[key] || {};
});
/* Ставим алиас */
self = this[name];
});
};
/* Ставим свой обработчик сообщений */
this.api.messages.send = (params) => {
/* Для сборки массива */
if (params.attachment && Array.isArray(params.attachment)) {
params.attachment = params.attachment.join(',');
}
/* Возврашаем promise */
return new this.promise((resolve,reject) => {
this._api('messages.send',params)
.then((id) => {
/* Увеличиваем кол-во сообщений */
++this.status.outbox;
/* Возвращаем id */
resolve(id);
})
.catch(reject);
});
};
/* Добавляем управления потоками */
method('stream',this._streamHandlers);
method('upload',this._uploadHandlers);
};
/* Наследуем EventEmitter */
util.inherits(io,require('events').EventEmitter);
/* Папки с прототипами модуля */
['preload','include','extesions']
/* Наследование прототипов */
.forEach(function(dir){
var
/* Путь до папки */
dir = __dirname+'/'+dir+'/',
/* Считывание файлов директории */
files = fs.readdirSync(dir),
/* Кеш длины массива */
length = files.length,
/* Regex проверки что файл js расширения */
regex = /.*\.js/,
/* Остальные переменные */
file,i;
/* Проходимся по списку файлов */
for (i = 0; i < length; ++i) {
/* Текущий элемент */
file = files[i];
/* Проверка что файл js */
if (regex.test(file)) {
/* Наследуем */
util._extend(io.prototype,require(dir+file));
}
}
});
/* Экспорт модуля */
module.exports = io; | 25bc59c4d0e886bbfabf638423134466779d0223 | [
"JavaScript"
] | 2 | JavaScript | echmykhun/vk-io | a1be83d1ae5790869e4cd2859aee8e2f4c859991 | d653d67bcf1b8ddf75fdcee09697770a707f30a2 |
refs/heads/master | <file_sep># BookListApp
Android App for searching books using google books API
## Concepts used:
Recycler View based on custom View
RESTful Api
JSON parsing
Intents
<file_sep>package com.example.sammhit.booklist;
import android.content.AsyncTaskLoader;
import android.content.Context;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
/**
* Created by sammhit on 6/3/18.
*/
public class BookLoader extends AsyncTaskLoader<List<Book>> {
private String searchQ;
public BookLoader(Context context, String searchQ){
super(context);
this.searchQ =searchQ;
}
@Override
public List<Book> loadInBackground() {
if (!searchQ.isEmpty()){
Log.i("BookLoader","loadInbAckground called");
ArrayList<Book> books = QueryUtils.extractBooks("https://www.googleapis.com/books/v1/volumes?q="+searchQ+"&maxResults=30&orderBy=relevance");
return books;
}
return null;
}
}
<file_sep>package com.example.sammhit.booklist;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
/**
* Created by sammhit on 6/3/18.
*/
public class Book {
private String title, avgRatings;
private String author;
private String imageUrl, previewUrl;
public Book(String titleBook, String authorBook, String avgRatingsBook, String imageUrlBook, String previewUrlBook) {
title = titleBook;
author = authorBook;
avgRatings = avgRatingsBook;
imageUrl = imageUrlBook;
previewUrl =previewUrlBook;
}
public String getTitle() {
return title;
}
public String getAuthor() {
return author;
}
public String getAvgRatings() {
return avgRatings;
}
public String getImageUrl() {
return imageUrl;
}
public String getPreviewUrl(){
return previewUrl;
}
}
| ee61a70d11aad0bce304d430d5accaacf0a7ca27 | [
"Markdown",
"Java"
] | 3 | Markdown | sammhit/BookListApp | f9ebf6849aa4bf69bcbb4475a13c0647eca161b4 | a479318bf7b67ccadf6d5a95a95f7f7d978e33c3 |
refs/heads/main | <file_sep># hero-re
Reverse engineering of the HERO sensor used by Logitech mice
The Hero is a sensor developed in house by Logitech, it's a follow up to the mercury sensor.
## Pin Configuration

Pin no. | Funcion | Type | Description
:---: | :---: | :---: | :---:
1 | GND | ? |
2 | VDD | Power | Sensor power input
3 | GND | Power |
4 | GND | ? |
5 | IR LED K | LED drive | IR LED Cathode
6 | GND | ? |
7 | NC | NC |
8 | GND | ? |
9 | NC | NC |
10 | GND | ? |
11 | NC | NC |
12 | GND | ? |
13 | NC | NC |
14 | NC | NC |
15 | GND | Power |
16 | DEC | Power | External decoupling for internal 1.7V
17 | SCLK | SPI |
18 | MISO | SPI | also used as motion/wake up pin
19 | MOSI | SPI |
20 | CS | SPI |
## Interface
The Hero sensor uses Serial Peripheral Interface (SPI) as a comunications layer
Chip Select is active low
It uses CPOL = 1, CPHA = 1, aka MODE = 3

Parameter | Value | Unit
:---: | :---: | :---:
Clock Frequency | 4.0 | MHz
Read and write operations are determined by bit 8, the following 7 bits provide the address of the opperation
Value | Operation
:---: | :---:
1 | Read
0 | Write
The following 8 bits are data, either from the host in a write, or to the host in a read
In a read, during the data phase, another address can be sent with the read bit set, allowing consecutive reads
Consecutive writes are apparently allowed
## Registers
address | Function | Values | Default | Info
:---: | :---: | :---: | :---: | :---:
0x00 | ? | | | Status or flag register?
0x03 | ? | | 0x20 usually, switches between 0x30 and 0x20 in sleep, 0x28 in deep sleep | when 0x28, rest mode is active after ~1 second inactivity, irrespective of reg 0x22 and has frame period 8 times greater than specified in reg 0x21.
0x05 | delta y high | | | signed 16 bit, 2's complement, top 8
0x06 | delta y low | | | signed 16 bit, 2's complement, bot 8
0x07 | delta x high | | | signed 16 bit, 2's complement, top 8
0x08 | delta x low | | | signed 16 bit, 2's complement, bot 8
0x0C | y DPI | DPI = (value + 1) * 50 | | 0x00 - 0xFF (50 - 12800 DPI)
0x0D | x DPI | DPI = (value + 1) * 50 | | 0x00 - 0xFF (50 - 12800 DPI)
0x16 | ? | | | seems to be related to surface
0x20 | maximum frame period (run) | period = 20us * value, floor of 100us | 0x32 = 50 (1000 fps) | when in motion, frame period may be lower than this value. in other words, framerate increases when in motion. if value <= 5, tracking at slow speeds suffers. no obvious difference in slow speed tracking quality for value >= 6.
0x21 | frame period (rest) | period = 80us * value | ? |
0x22 | run-to-rest timeout | (0.5 * value + 1) seconds | 0xc8 = 200 |
## SROM
the hero sensor needs firmware to be uploaded to it at startup, we call this SROM
srom "extraction" tools are available in [tools](tools/)
ready to use blobs are available in this repo [openinput-fw/sensor-blobs](https://github.com/openinput-fw/sensor-blobs)
## Sensor "overclocking"
by default the hero sensor in the g305 is configured to run at roughly 1000 frames/s, and scales up to 12000 frames/s depending on the motion speed.
apparently, register 0x20 controls the maximum frame period (and hence, the minimum framerate) and can be set such that the minimum framerate is slightly above 8000 frames/s.
## Example Driver
Even though the sensor is not thoroughly documented, we have a working proof of concept [driver](https://github.com/qsxcv/q305/blob/main/mouse/hero.h)
<file_sep>firmware version: 68.1.14
pcb: 210-001843 Rev.008
to view .kvdat files, install http://www.qdkingst.com/en/download
# todo:
* capture sleep to deepsleep transition (takes several minutes inactivity)
* check everything for lo (endurance) power mode
<file_sep>#!/usr/bin/env python3
import argparse
import os
import struct
import sys
from pathlib import Path
def find_offset(value_list):
for offset in range(len(value_list)):
if(value_list[offset] == 0x2E):
return offset
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Format hex list (direct extract from mosi on logic analyzer startup) file to bin blob')
parser.add_argument('-i', '--input', type=str,
help='Input file.')
parser.add_argument('-b', '--binary', type=str,
help='binary to write.')
parser.add_argument('-o', '--offset', type=str,
help='offset of srom, automatic if not specified')
args = parser.parse_args()
if not args.input or not os.path.exists(args.input):
print(f'{args.input} doesn\'t exist', file=sys.stderr)
exit(1)
if not args.binary:
print('binary file required.', file=sys.stderr)
exit(1)
try:
binary = open(args.binary, 'wb')
except PermissionError as e:
print(f'can\'t open {args.binary}: {str(e)}', file=sys.stderr)
exit(1)
try:
input_file = open(args.input, 'r')
except PermissionError as e:
print(f'can\'t open {args.input}: {str(e)}', file=sys.stderr)
exit(1)
value_list = []
for line in input_file.readlines():
value_list.append(int(line, 16))
if not args.offset:
offset = find_offset(value_list)
else:
offset = args.offset
for value in value_list[offset+1:offset+(2*4096):2]:
binary.write(bytes([value]))
<file_sep>#!/bin/bash
sigrok-cli -i ../la_captures/g305_sigrok_pulseview/startup.sr -P spi:miso=MISO:mosi=MOSI:clk=SCLK:cs=CS:cpol=1:cpha=1 -A spi=mosi-data > startup-mosi
sed -i -e 's/spi-1: //g' startup-mosi
| c9b822019316b72fdce2818a1051410275f31142 | [
"Markdown",
"Python",
"Shell"
] | 4 | Markdown | perigoso/hero-re | bb581106416b598e6119c1924a025d34540bdd7b | 260266ecf14389f1827aea345095af1a9dd8c185 |
refs/heads/master | <file_sep>require_relative "./app"
run KittenManager
<file_sep>source "https://rubygems.org"
group :development, :test do
gem "rspec"
gem "rake"
gem "json"
gem "sinatra"
gem "httparty"
end
group :test do
gem 'capybara'
gem 'rspec'
gem 'rubocop'
gem 'simplecov', require: false
gem 'simplecov-console', require: false
end
git_source(:github) {|repo_name| "https://github.com/#{repo_name}" }
<file_sep>require 'elect.rb'
require 'json'
describe Elect do
it 'makes an anticipated JSON with an id' do
test_vote = Elect.new('cat', 'kitty1234')
parsed_body = JSON.parse(test_vote.json)
expect(parsed_body['image_id']).to eq('kitty1234')
end
it 'creates an expected JSON voting object using voting intention' do
test_vote = Elect.new('cat', 'kitty1234')
parsed_body = JSON.parse(test_vote.json)
expect(parsed_body['value']).to eq(1)
end
it 'passes a vote to the CAT API' do
test_vote = Elect.new('cat', '4t1')
expect(test_vote.cast).to eq('OK')
end
end
<file_sep>require 'sinatra/base'
require './lib/photo'
require './lib/elect'
class KittenManager < Sinatra::base
get '/' do
url = Photo.new
url.view_random_photo
@source = url.url_link
erb :'photo/index'
end
post '/elect' do
vote = 'not'
vote = 'cat' if params[:play] == 'Cat'
url = Photo.new
vote = Elect.new(vote, url.url_link)
vote.cast
redirect '/vote/cast'
end
get '/elect/cast' do
url = Photo.new
url.view_random_photo
@source = url.url_link
erb :'vote/cast'
end
end
<file_sep>require 'photo.rb'
describe Photo do
it 'receives a URL address from within catapi' do
test_case = Photo.new
test_case.view_random_photo
expect(test_case.url_to_retrieve).to include('catapi')
end
it 'receives a class variable' do
test_case = Photo.new
test_case.view_random_photo
another_test = Photo.new
sample_to_test = another_test.url_link
expect(sample_to_test).to include('catapi')
end
end
| 03a3587e94d4ae48ffcc19f4e158469e99aad8c3 | [
"Ruby"
] | 5 | Ruby | ac4059/catbank | 562c0cca6a30a060ea7dfd95e97ef89a0eb1fc54 | 8f7a01e18248738c23b1bb8e1affc255ba872335 |
refs/heads/master | <file_sep>import React from 'react';
import {shallow, mount, render} from 'enzyme';
import {expect} from 'chai';
import sinon from 'sinon';
import FormNovaPochta from '../index';
/*
describe('Прбный тест', () => {
it('simulates click events', () => {
const buttonClick = sinon.spy();
// console.log(buttonClick);
const wrapper = shallow(
<MyComponent handleClick={buttonClick}/>
);
wrapper.find('button').simulate('click');
expect(buttonClick.calledOnce).to.equal(true);
});
});
*/
// Shallow Rendering
// https://github.com/airbnb/enzyme/blob/master/docs/api/shallow.md
describe('Тест элементов модуля', () => {
const wrapper = shallow(<FormNovaPochta apiKey="not"/>);
const state = wrapper.state();
it('Количество тегов <select>: 3', () => {
let wf = wrapper.find('select');
expect(wf).to.have.length(3);
});
it('Пустой массив `state.listAreas`', () => {
expect(state.listAreas).to.have.length(0);
});
it('Пустой массив `state.listCities:`', () => {
expect(state.listCities).to.have.length(0);
});
it('Пустой массив `state.listCitiesCurrent`', () => {
expect(state.listCitiesCurrent).to.have.length(0);
});
it('Пустой массив `state.listWarehouses`', () => {
let state = wrapper.state();
expect(state.listWarehouses).to.have.length(0);
});
/*
it('simulates click events', () => {
const buttonClick = sinon.spy();
const wrapper = shallow(
<MyComponent handleClick={buttonClick}/>
);
wrapper.find('button').simulate('click');
expect(buttonClick.calledOnce).to.equal(true);
});
*/
});
// Full DOM Rendering
// https://github.com/airbnb/enzyme/blob/master/docs/api/mount.md
describe('Full DOM Rendering', () => {
it('Test apiKey to set props', () => {
const wrapper = mount(<FormNovaPochta apiKey='Test apiKey' />);
expect(wrapper.props().apiKey).to.equal('Test apiKey');
// wrapper.setProps({bar: 'foo'});
// expect(wrapper.props().bar).to.equal('foo');
});
it('calls componentDidMount', () => {
sinon.spy(FormNovaPochta.prototype, 'componentDidMount');
const wrapper = mount(<FormNovaPochta apiKey='Test apiKey' />);
expect(FormNovaPochta.prototype.componentDidMount.calledOnce).to.be.true;
FormNovaPochta.prototype.componentDidMount.restore();
});
});
// Static Rendered Markup
// https://github.com/airbnb/enzyme/blob/master/docs/api/render.md
describe('Static Rendered Markup', () => {
it('renders three `.icon-test`s', () => {
const wrapper = render(<FormNovaPochta apiKey='Test apiKey' />);
expect(wrapper.find('select').length).to.equal(3);
});
});
<file_sep>import React, {PropTypes} from 'react';
import ApiNovaPochta from 'yz-react-deliveri-newpochta';
class FormNovaPochta extends React.Component {
constructor(props) {
super(props);
this.Api = new ApiNovaPochta;
this.state = {
listAreas: [],
listCities: [],
listCitiesCurrent: [],
listWarehouses: [],
selectArea: null,
selectCity: null,
selectWarehous: null,
selectCityVal: '',
selectWarehousVal: '',
selectAreaVal: ''
};
this.cbCities = this.cbCities.bind(this);
this.cbWarehouse = this.cbWarehouse.bind(this);
this.cbAreas = this.cbAreas.bind(this);
this.onChangeCity = this.onChangeCity.bind(this);
this.onChangeWarehous = this.onChangeWarehous.bind(this);
this.onChangeArea = this.onChangeArea.bind(this);
this.getCitiesOfArea = this.getCitiesOfArea.bind(this);
this.apiKey = props.apiKey;
this.stylesNP = this.stylesNP.bind(this);
this.s = this.stylesNP();
this.result = this.props.cb;
}
stylesNP() {
return {
container: {
margin: '0 auto',
padding: '0 0 40px',
maxWidth: '380px'
},
select: {
marginTop: '20px',
display: 'block',
boxSizing: 'border-box',
padding: '10px 16px',
width: '100%',
height: '46px',
outline: '0',
border: '1px solid #ccc',
borderRadius: '10px',
background: '#fff',
boxShadow: 'inset 0 1px 1px rgba(0, 0, 0, 0.075)',
color: '#616161',
fontSize: '18px',
lineHeight: '1.333',
transition: 'border-color ease-in-out 0.15s, box-shadow ease-in-out 0.15s'
}
}
}
componentDidMount() {
this.Api.getAreas(this.cbAreas, this.apiKey);
}
componentDidUpdate() {
let res = {
selectArea: this.state.selectArea.Description,
selectCity: this.state.selectCity.Description,
selectWarehous: this.state.selectWarehous.Description,
};
// console.log('componentDidUpdate', this.state);
this.result(res);
}
shouldComponentUpdate() {
if (!this.state.selectArea) {
return false;
}
else if ( !this.state.selectCity ) {
return false;
}
else {
return true
};
}
cbAreas(result) {
let res = [];
result.data.forEach((item)=> {
res.push({
Description: item.Description,
Ref: item.Ref,
AreasCenter: item.AreasCenter
});
});
if (res.length > 0) {
this.setState({
listAreas: res,
selectAreaVal: '1',
selectArea: res[1],
listWarehouses: []
});
this.Api.getCities(this.cbCities, this.apiKey);
}
}
cbCities(result) {
let res = [];
result.data.forEach((item)=> {
res.push({
Description: item.Description,
DescriptionRu: item.DescriptionRu,
Ref: item.Ref,
Area: item.Area
});
});
if (res.length > 0) {
let selectCities = this.getCitiesOfArea(res, this.state.selectArea);
this.setState({
listCities: res,
listCitiesCurrent: selectCities,
selectCity: selectCities[0],
selectCityVal: '0',
selectWarehousVal: '0',
});
if (this.state.selectArea) {
this.Api.getWarehouses(
this.cbWarehouse, this.apiKey, {"CityName": this.getCitiesOfArea(res, this.state.selectArea)[0].Description});
}
}
}
cbWarehouse(result) {
let space = [{
Ref: '-',
Description: '- - - - - - - - - - - - - - - - '
}];
let res = [];
result.data.forEach((item)=> {
res.push({
Ref: item.Ref,
Description: item.Description
});
});
let warehousVal = this.state.selectWarehousVal;
let warehous = res.length>0 ? res[warehousVal] : space;
this.setState(
{
listWarehouses: res,
selectWarehous: warehous
});
}
getCitiesOfArea(listCities, area) {
return listCities.filter((i) => area.Ref === i.Area)
}
onChangeArea(e) {
let value = e.target.value;
let selectArea = this.state.listAreas[parseInt(value)];
let selectCity = this.getCitiesOfArea(this.state.listCities, selectArea);
if (selectCity.length > 0) {
this.setState({
selectArea: selectArea,
selectCity: selectCity[0],
listCitiesCurrent: selectCity,
selectAreaVal: value,
selectCityVal: '0',
selectWarehousVal: '0'
});
this.Api.getWarehouses(
this.cbWarehouse,
this.apiKey,
{"CityName": selectCity[0].Description});
} else {
let space = [{
Ref: '-',
Description: '- - - - - - - - - - - - - - - - '
}];
this.setState({
selectArea: selectArea,
selectCity: space[0],
selectWarehous: space[0],
listCitiesCurrent: space,
listWarehouses: ['- - - - - - - - - - - - - - - - '],
selectAreaVal: value,
selectCityVal: '0',
selectWarehousVal: '0',
});
}
}
onChangeCity(e) {
let value = e.target.value;
this.setState({
selectCity: this.state.listCitiesCurrent[parseInt(value)],
selectCityVal: value,
selectWarehousVal: '0'
});
this.Api.getWarehouses(
this.cbWarehouse,
this.apiKey,
{"CityName": this.state.listCitiesCurrent[parseInt(value)].Description});
}
onChangeWarehous(e) {
let warehousVal = e.target.value;
let warehous = typeof parseInt(warehousVal) === typeof 1 ? this.state.listWarehouses[warehousVal] : '';
this.setState(
{
selectWarehousVal: warehousVal,
selectWarehous: warehous
});
}
render() {
return (
<div style={this.s.container}>
<select style={this.s.select}
name="areas"
onChange={ this.onChangeArea }
value={this.state.selectAreaVal}
>
{ this.state.listAreas.map((i, ind) => ( <option value={ind} key={ind}> {i.Description} </option> )) }
</select>
<select style={this.s.select}
name="cities"
onChange={ this.onChangeCity }
value={this.state.selectCityVal}
>
{ this.state.listCitiesCurrent.map((i, ind) => ( <option value={ind} key={ind}>{i.Description}</option> )) }
</select>
<select style={this.s.select}
name="warehouses"
onChange={ this.onChangeWarehous }
>
{ this.state.listWarehouses.map((i, ind) => ( <option value={ind} key={ind}>{i.Description}</option> )) }
</select>
</div>
)
}
}
FormNovaPochta.propTypes = {
apiKey: PropTypes.string.isRequired,
};
export default FormNovaPochta;
<file_sep># Модуль в РАЗРАБОТКЕ | 0e209ce73d0659a05c8fb360c9f50bb3d99fc30d | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | zhukyuri/z-react-delivery-newpochta-form | 77896cbe57a78bc9505c8fc181c91b0e191bac09 | f2302576c39335136d3668a3ac8613d127c9fe18 |
refs/heads/master | <file_sep>var app = require('http').createServer(handler)
, io = require('socket.io').listen(app)
, fs = require('fs')
app.listen(8070);
var serialPort = '/dev/tty.usbmodem1421';
var arduino = require('./firmataConnector').start(serialPort);
var prestate = true;
var crosstime = 0;
var pretime = 0;
var phasetime = 0;
function handler (req, res) {
fs.readFile(__dirname + '/index.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
io.sockets.on('connection', function (socket) {
socket.on('message', function (msg) {
console.log(msg);
})
socket.on('disconnect', function () {
console.log('client disconnected: ' + socket.id);
})
});
arduino.on('connection', function () {
console.log("successfully connected to Arduino!");
arduino.analogRead(arduino.A0, function(val) {
console.log(val);
});
arduino.pinMode(6, arduino.OUTPUT);
arduino.pinMode(8, arduino.INPUT);
arduino.digitalRead(8, function(val){
console.log(val);
});
});
<file_sep>three_phase_relay
=================
TCNJ Senior Project
<NAME>
<NAME>
<NAME>
<NAME>
<file_sep>#include <SoftwareSerial.h>
#include <TinyGPS.h> // Special version for 1.0
TinyGPS gps;
SoftwareSerial nss(6, 255); // Yellow wire to pin 6
void setup() {
Serial.begin(115200);
nss.begin(4800);
Serial.println("Reading GPS");
}
void loop() {
bool newdata = false;
unsigned long start = millis();
while (millis() - start < 8) { // Update every 5 seconds
if (feedgps()){
newdata = true;
}
}
if (newdata) {
gpsdump(gps);
}
}
// Get and process GPS data
void gpsdump(TinyGPS &gps) {
float flat, flon;
unsigned long age, date, time, fix_age;
gps.f_get_position(&flat, &flon, &age);
gps.get_datetime(&date, &time, &fix_age);
int year;
byte month, day, hour, minute, second, hundredths;
gps.crack_datetime(&year, &month, &day, &hour, &minute, &second, &hundredths, &fix_age);
Serial.print(flat, 4); Serial.print(", ");
Serial.println(flon, 4);
Serial.print(hour); Serial.print(":"); Serial.print(minute);Serial.print(":");Serial.println(second);
}
// Feed data as it becomes available
bool feedgps() {
while (nss.available()) {
if (gps.encode(nss.read()))
return true;
}
return false;
}
<file_sep>
#include <SoftwareSerial.h>
#include <TinyGPS.h> // Special version for 1.0
TinyGPS gps;
SoftwareSerial nss(6, 255); // Yellow wire to pin 6
void setup() {
Serial.begin(115200);
nss.begin(4800);
Serial.println("Reading GPS");
}
void loop() {
while (nss.available()) {
if (gps.encode(nss.read()))
gpsdump(gps);
}
}
// Get and process GPS data
void gpsdump(TinyGPS &gps) {
unsigned long age, date, time, fix_age;
gps.get_datetime(&date, &time, &fix_age);
int year;
byte month, day, hour, minute, second, hundredths, ms, ns, us;
gps.crack_datetime(&year, &month, &day, &hour, &minute, &second, &hundredths, &ms, &ns, &us, &fix_age);
char buffer[32];
sprintf(buffer, "%02d:%02d:%02d:%02d:%02d:%02d:%02d", hour, minute, second, hundredths, ms, ns, us);
Serial.println(buffer);
}
<file_sep>int relay=53;
int cross=24;
bool state;
bool prestate=0;
void setup() {
pinMode(relay,OUTPUT);
pinMode(cross,INPUT);
// Serial.begin(9600);
}
void loop() {
state=digitalRead(cross);
if(state!=prestate){
// Serial.println(millis());
}
digitalWrite(relay,!state);
prestate=state;
}
<file_sep>#include <WiFi.h>
#include <WiFiClient.h>
#include <WiFiServer.h>
#include <SPI.h>
char ssid[] = "SteveAndTimECE"; // your network SSID (name)
char pass[] = "<PASSWORD>"; // your network password
int keyIndex = 0; // your network key Index number (needed only for WEP)
int voltageReading = 0;
int relay=6;
int cross=8;
int peakpin=A0;
int peak;
int peak_max=0;
int phase_sum=0;
int phase_avg = 0;
int pretime=0;
int phasetime;
int crosstime;
bool state;
bool prestate=0;
String HTTP_req;
int newVoltage = 0;
int status = WL_IDLE_STATUS;
WiFiServer server(80);
void setup()
{
Serial.begin(115200); // initialize serial communication
pinMode(peakpin,INPUT);
pinMode(relay,OUTPUT);
pinMode(cross,INPUT);
// attempt to connect to Wifi network:
while ( status != WL_CONNECTED) {
Serial.print("Attempting to connect to Network named: ");
Serial.println(ssid); // print the network name (SSID);
// Connect to WPA/WPA2 network. Change this line if using open or WEP network:
status = WiFi.begin(ssid, pass);
// wait 10 seconds for connection:
//delay(10000);
}
server.begin(); // start the web server on port 80
printWifiStatus();
}
void loop()
{
WiFiClient client = server.available(); // try to get client
createWebPage(client);
Serial.println(phase_avg);
getData();
}
// send the state of the switch to the web browser
void getData()
{
//set up to run for 1 second
int startTime = millis();
int endTime = startTime;
//resetting values
int i = 1;
peak_max = 0;
pretime = micros();
phase_sum = 0;
phase_avg = 0;
while ((endTime - startTime) <= 1000) {
//read peak and phasetime
peak=analogRead(peakpin);
newVoltage=peak*0.4295+29.934;
state=digitalRead(cross);
if(state!=prestate){
crosstime=micros();
phasetime=crosstime-pretime;
}
//steve's thing
digitalWrite(relay,!state);
//sets values for next iteration
prestate=state;
pretime=crosstime;
//find max peak in second
if (newVoltage > peak_max) {
peak_max = newVoltage;
}
//only do a few readings for phase b/c Arduino ints are small
if (i < 2) {
//calculate phase time value
if (phasetime > 5000) {
phase_avg = phasetime;
i++;
}
}
endTime = millis();
}
}
void createWebPage (WiFiClient client) {
if (client) { // got client?
boolean currentLineIsBlank = true;
while (client.connected()) {
if (client.available()) { // client data available to read
char c = client.read(); // read 1 byte (character) from client
HTTP_req += c; // save the HTTP request 1 char at a time
// last line of client request is blank and ends with \n
// respond to client only after last line received
if (c == '\n' && currentLineIsBlank) {
// send a standard http response header
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println("Connection: keep-alive");
client.println();
// AJAX request for switch state
if (HTTP_req.indexOf("ajax_switch") > -1) {
// read switch state and send appropriate paragraph text
GetSwitchState(client);
}
else { // HTTP request for web page
// send web page - contains JavaScript with AJAX calls
client.println("<!DOCTYPE html>");
client.println("<html>");
client.println("<head>");
client.println("<title>Arduino Web Page</title>");
client.println("<script>");
client.println("function GetSwitchState() {");
client.println("nocache = \"&nocache=\"+ Math.random() * 1000000;");
client.println("var request = new XMLHttpRequest();");
client.println("request.onreadystatechange = function() {");
client.println("if (this.readyState == 4) {");
client.println("if (this.status == 200) {");
client.println("if (this.responseText != null) {");
client.println("document.getElementById(\"switch_txt\").innerHTML = this.responseText;");
client.println("}}}}");
client.println("request.open(\"GET\", \"ajax_switch\" + nocache, true);");
client.println("request.send(null);");
client.println("setTimeout('GetSwitchState()', 1000);");
client.println("}");
client.println("</script>");
client.println("</head>");
client.println("<body onload=\"GetSwitchState()\">");
client.println("<h1>Smart Three Phase Power System Status</h1>");
client.println("<p id=\"switch_txt\">Loading data...</p>");
client.println("<a href=\"http://tcnjsmart.weebly.com\">TCNJ SMART Home Page</a>");
client.println("</body>");
client.println("</html>");
}
// display received HTTP request on serial port
Serial.print(HTTP_req);
HTTP_req = ""; // finished with request, empty string
break;
}
// every line of text received from the client ends with \r\n
if (c == '\n') {
// last character on line of received text
// starting new line with next character read
currentLineIsBlank = true;
}
else if (c != '\r') {
// a text character was received from client
currentLineIsBlank = false;
}
} // end if (client.available())
} // end while (client.connected())
delay(1); // give the web browser time to receive the data
client.stop(); // close the connection
} // end if (client)
}
void GetSwitchState(WiFiClient cl){
cl.println("Peak: ");
cl.println(peak_max);
cl.println(" V");
cl.println("Phase: ");
cl.println(phase_avg);
cl.println(" ms");
}
void printWifiStatus() {
// print the SSID of the network you're attached to:
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
// print your WiFi shield's IP address:
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
// print the received signal strength:
long rssi = WiFi.RSSI();
Serial.print("signal strength (RSSI):");
Serial.print(rssi);
Serial.println(" dBm");
// print where to go in a browser:
Serial.print("To see this page in action, open a browser to http://");
Serial.println(ip);
}
<file_sep>#include <WiFi.h>
#include <WiFiClient.h>
#include <WiFiServer.h>
#include <SPI.h>
char ssid[] = "SteveAndTimECE"; // your network SSID (name)
char pass[] = "<PASSWORD>"; // your network password
int keyIndex = 0; // your network key Index number (needed only for WEP)
int voltageReading = 0;
int relay=6;
int cross=8;
int peakpin=A0;
int peak;
int pretime=0;
int phasetime;
int crosstime;
bool state;
bool prestate=0;
String HTTP_req;
int status = WL_IDLE_STATUS;
WiFiServer server(80);
void setup()
{
Serial.begin(115200); // initialize serial communication
pinMode(peakpin,INPUT);
pinMode(relay,OUTPUT);
pinMode(cross,INPUT);
// attempt to connect to Wifi network:
while ( status != WL_CONNECTED) {
Serial.print("Attempting to connect to Network named: ");
Serial.println(ssid); // print the network name (SSID);
// Connect to WPA/WPA2 network. Change this line if using open or WEP network:
status = WiFi.begin(ssid, pass);
// wait 10 seconds for connection:
//delay(10000);
}
server.begin(); // start the web server on port 80
printWifiStatus();
}
void loop()
{
WiFiClient client = server.available(); // try to get client
if (client) { // got client?
boolean currentLineIsBlank = true;
while (client.connected()) {
if (client.available()) { // client data available to read
char c = client.read(); // read 1 byte (character) from client
HTTP_req += c; // save the HTTP request 1 char at a time
// last line of client request is blank and ends with \n
// respond to client only after last line received
if (c == '\n' && currentLineIsBlank) {
// send a standard http response header
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println("Connection: keep-alive");
client.println();
// AJAX request for switch state
if (HTTP_req.indexOf("ajax_switch") > -1) {
// read switch state and send appropriate paragraph text
GetSwitchState(client);
}
else { // HTTP request for web page
// send web page - contains JavaScript with AJAX calls
client.println("<!DOCTYPE html>");
client.println("<html>");
client.println("<head>");
client.println("<title>Arduino Web Page</title>");
client.println("<script>");
client.println("function GetSwitchState() {");
client.println("nocache = \"&nocache=\"+ Math.random() * 1000000;");
client.println("var request = new XMLHttpRequest();");
client.println("request.onreadystatechange = function() {");
client.println("if (this.readyState == 4) {");
client.println("if (this.status == 200) {");
client.println("if (this.responseText != null) {");
client.println("document.getElementById(\"switch_txt\").innerHTML = this.responseText;");
client.println("}}}}");
client.println("request.open(\"GET\", \"ajax_switch\" + nocache, true);");
client.println("request.send(null);");
client.println("setTimeout('GetSwitchState()', 1);");
client.println("}");
client.println("</script>");
client.println("</head>");
client.println("<body onload=\"GetSwitchState()\">");
client.println("<h1>Arduino AJAX Switch Status</h1>");
client.println(
"<p id=\"switch_txt\">Switch state: Not requested...</p>");
client.println("</body>");
client.println("</html>");
}
// display received HTTP request on serial port
Serial.print(HTTP_req);
HTTP_req = ""; // finished with request, empty string
break;
}
// every line of text received from the client ends with \r\n
if (c == '\n') {
// last character on line of received text
// starting new line with next character read
currentLineIsBlank = true;
}
else if (c != '\r') {
// a text character was received from client
currentLineIsBlank = false;
}
} // end if (client.available())
} // end while (client.connected())
delay(1); // give the web browser time to receive the data
client.stop(); // close the connection
} // end if (client)
}
// send the state of the switch to the web browser
void GetSwitchState(WiFiClient cl)
{
peak=analogRead(peakpin);
state=digitalRead(cross);
if(state!=prestate){
crosstime=micros();
phasetime=crosstime-pretime;
}
digitalWrite(relay,!state);
prestate=state;
pretime=crosstime;
//Serial.println(phasetime);
cl.println("Peak Value");
cl.println(peak);
cl.println("Phase Time");
cl.println(phasetime);
}
void printWifiStatus() {
// print the SSID of the network you're attached to:
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
// print your WiFi shield's IP address:
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
// print the received signal strength:
long rssi = WiFi.RSSI();
Serial.print("signal strength (RSSI):");
Serial.print(rssi);
Serial.println(" dBm");
// print where to go in a browser:
Serial.print("To see this page in action, open a browser to http://");
Serial.println(ip);
}
| 57ae76f79bcc520bca242b6212e340cd587c0623 | [
"JavaScript",
"C++",
"Markdown"
] | 7 | JavaScript | davehand/three_phase_relay | 747209d3eb97f2734c09d1894aaa1d4421a7c2ed | 40a99a995e6bb5e5f54cc544cab0a40b45facfc7 |
refs/heads/master | <repo_name>srivatsav789/ScreeningTest<file_sep>/ProgrammingQuestion.py
# 7.11,8,9:00,9:15,14:30,15:00
'''
floor - 7
room_no - 11
max_people - 8
free slots - (9:00,9:15) , (14:30,15:00)
'''
#strptime('15:30','%H:%M')
'''
input -> Given n team members with the floor on which they work and the time they want to meet
data -> list of conference rooms identified by their floor and room number as a decimal number, maximum number of people it fits and pairs of times they are open
'''
from datetime import datetime
import collections
def parse_txt_make_ds(file_path : str):
with open(file_path) as f :
dictionary = {}
all_rooms = f.read().split("\n")
for room in all_rooms :
floor_room = room.split(",")[0]
room = room.replace(f"{floor_room}," , "")
rest_stats = room.split(",")
max_capacity = int(rest_stats[0])
timings = rest_stats[1:]
new_timings = []
if len(timings) > 2 :
for i in range(0,len(timings),2):
new_timings.append((datetime.strptime(timings[i],'%H:%M') , datetime.strptime(timings[i+1],'%H:%M')))
else :
new_timings.append(((datetime.strptime(timings[0],'%H:%M') , (datetime.strptime(timings[1],'%H:%M')))))
dictionary[floor_room] = {"max_capacity" : max_capacity , "Timings" : new_timings}
#dictionary = sort_dict(dictionary)
return dictionary
def sort_dict(dictionary : dict):
new_dict = {}
for item , stats in dictionary.items():
new_dict[float(item)] = stats
od = collections.OrderedDict(sorted(new_dict.items()))
dict_ = {}
for item , stats in od.items():
dict_[str(item)] = stats
return dict_
# Test case
# 5,8,10:30,11:30
# 5 members , 8th floor , Timing
#test_case = input()
#test_case = "5,8,10:30,11:30"
def parse_input(test_case : str):
all_stats = test_case.split(",")
size = int(all_stats[0])
floor = int(all_stats[1])
timings = (datetime.strptime(all_stats[2],'%H:%M') , datetime.strptime(all_stats[3],'%H:%M'))
return {"size" : size , "floor" : floor , "timings" : timings}
#input_stats = parse_input("5,8,10:30,11:30")
def produce_output(test_case : str , room_file_path : str):
rooms_dictionary = parse_txt_make_ds(room_file_path)
input_stats = parse_input(test_case)
possibilities = []
for item , stats in rooms_dictionary.items():
if stats['max_capacity'] >= input_stats['size']:
for time1 , time2 in stats['Timings']:
if time1.time() <= input_stats['timings'][0].time() and time2.time() >= input_stats['timings'][1].time():
possibilities.append(item)
else :
continue
current_best = None
output = None
for pos in possibilities :
floor , room = pos.split(".")
floor , room = int(floor) , int(room)
if current_best is None :
current_best = abs(floor - input_stats["floor"])
output = str(floor) + "." + str(room)
else :
current = abs(floor - input_stats["floor"])
if current < current_best :
current_best = current
output = str(floor) + "." + str(room)
return output
'''
Extra Point work !
def extra_point(test_case : str , room_file_path : str):
rooms_dictionary = parse_txt_make_ds(room_file_path)
input_stats = parse_input(test_case)
possibilities = []
possible_rooms = []
for item , stats in rooms_dictionary.items():
if stats['max_capacity'] > input_stats['size']:
possible_rooms.append(item)
make_poss_room_dict = {}
for pos_room in possible_rooms :
make_poss_room_dict[pos_room] = rooms_dictionary[pos_room]["Timings"]
start_time = input_stats["timings"][0]
end_time = input_stats["timings"][1]
for floor_room , timings in make_poss_room_dict.keys():
for time in range(0 , len(timings) , 2):
''' | 60d9567976c1601ff45354e55d685f0b7c8f72fe | [
"Python"
] | 1 | Python | srivatsav789/ScreeningTest | 17abf6131438ae2bdcc3d32452fb08224be0e744 | 024875e550412dd2dfc510ca56603cd425ed1085 |
refs/heads/master | <repo_name>benpetrosky/shoe-store<file_sep>/app.rb
require('sinatra')
require('sinatra/reloader')
require('sinatra/activerecord')
also_reload('lib/**/*.rb')
require('./lib/brand')
require('./lib/store')
require('pry')
require("pg")
get("/") do
erb(:index)
end
get("/stores/new") do
@stores = Store.all()
erb(:stores)
end
get("/stores") do
@stores = Store.all()
erb(:stores)
end
post('/stores') do
name = params.fetch("name")
Store.create(:name => name)
@stores = Store.all()
erb(:stores)
end
get("/brands/new") do
@brands = Brand.all()
erb(:brands)
end
post('/brands') do
name = params.fetch("name")
price = params.fetch("price").to_i
Brand.create(:name => name, :price => price)
@brands = Brand.all()
erb(:brands)
end
get("/stores/:id") do
id = params.fetch("id").to_i
@store = Store.find(id)
@brands = Brand.all()
@store_brands = @store.brands()
erb(:store)
end
delete('/store_delete/:id') do
id = params.fetch("id").to_i
store = Store.find(id)
store.delete()
@stores = Store.all()
erb(:stores)
end
patch('/store_update/:id') do
id = params.fetch("id").to_i
name = params.fetch("name", "")
brand_ids = params.fetch("brand_ids", "")
@brands = Brand.all()
@store = Store.find(id)
@store_brands = @store.brands()
if name != ""
@store.update(:name => name)
end
if brand_ids != ""
brand_ids.each() do |brand_id|
brand = Brand.find(brand_id)
@store_brands = @store.brands.push(brand)
end
end
erb(:store)
end
<file_sep>/spec/spec_helper.rb
ENV['RACK_ENV'] = 'test'
require("rspec")
require("pg")
require("sinatra/activerecord")
require("./lib/brand")
require("./lib/store")
RSpec.configure do |config|
config.after(:each) do
Store.all().each do |store|
store.destroy()
end
Brand.all().each do |brand|
brand.destroy()
end
end
end
<file_sep>/spec/store_spec.rb
require("spec_helper")
describe(Store) do
it("validates presence of name") do
store = Store.new({:name => ""})
expect(store.save()).to(eq(false))
end
it("assures that a store name entry is unique in the database") do
store1 = Store.create({:name => "sams super shoe store"})
store2 = Store.new({:name => "sams super shoe store"})
expect(store2.save()).to(eq(false))
end
it("ensures the length of the store name is no more than 100 characters") do
store = Store.new({:name => "a".*(101)})
expect(store.save()).to(eq(false))
end
it("Capitalizes the first letter of every word in a store name") do
store = Store.create({:name => "super shoe store for men"})
expect(store.name()).to(eq("Super Shoe Store For Men"))
end
describe('#brands') do
it('each store can have many brands') do
store = Store.create({:name => "shoe mart"})
brand1 = store.brands.create({:name => 'nike'})
brand2 = store.brands.create({:name => 'addidas'})
expect(store.brands()).to(eq([brand1, brand2]))
end
end
end
<file_sep>/README.md
# _Shoe Stores Database_
#### _catalogs shoe brands and stores, .05.12.2017_
#### By _<NAME>_
## Description
_Allows user to catalog shoe brand names and shoe stores into a database. The user can then categorize which shoe brands are at a store. Store names and brand names cannot be repeated in the database._
## Setup/Installation Requirements
Clone this repository on your desktop
In your terminal:
cd into the project directory
run bundle
run postgres
open new terminal and make sure you are in the project directory
run app.rb
in the browswer of your choice, go to the local host provided
## Known Bugs
_There are no known bugs._
## Support and contact details
_If you have any suggestions please feel free to contribute to the code._
## Technologies Used
ActiveRecord
Ruby
sinatra
### License
This software is licensed under the MIT License.
Copyright (c) 2017 **_<NAME>_**
<file_sep>/spec/brand_spec.rb
require("spec_helper")
describe(Brand) do
it("validates presence of name") do
brand = Brand.new({:name => ""})
expect(brand.save()).to(eq(false))
end
it("assures that a brand name entry is unique in the database") do
brand1 = Brand.create({:name => "addidas"})
brand2 = Brand.new({:name => "addidas"})
expect(brand2.save()).to(eq(false))
end
it("Capitalizes the first letter of every word in a brand name") do
brand = Brand.create({:name => "nike"})
expect(brand.name()).to(eq("Nike"))
end
it("ensures the length of the brand name is no more than 100 characters") do
brand = Brand.new({:name => "a".*(101)})
expect(brand.save()).to(eq(false))
end
describe('#stores') do
it('each brand can have many stores') do
brand = Brand.create({:name => "nike"})
store1 = brand.stores.create({:name => 'shoe mart'})
store2 = brand.stores.create({:name => 'shoe depot'})
expect(brand.stores()).to(eq([store1, store2]))
end
end
end
| 96e944e742c19e40aae5d7e4185f2cdcaecb4c59 | [
"Markdown",
"Ruby"
] | 5 | Ruby | benpetrosky/shoe-store | 49a63edef0dce5992f4fe686e0f60d8e14603725 | bac614d1ff72275e644d495c8f89d8ad285de3dd |
refs/heads/master | <repo_name>atshudy/ATM<file_sep>/cs521/src/model/test_address.py
import unittest
from cs521.src.model.address import Address
__author__ = 'ATshudy'
class TestAccount(unittest.TestCase):
address = None
def setUp(self):
self.address = Address("<NAME>", "800 commonwealth Ave", "Boston", "MA", "02215")
def test_get_name(self):
self.assertEqual(self.address.get_name(), "<NAME>", "FALIED to get the name in the address")
def test_set_name(self):
self.address.set_name("<NAME>")
self.assertEqual(self.address.get_name(), "<NAME>", "FALIED to change the name in the address")
def test_get_street(self):
self.assertEqual(self.address.get_street(), "800 commonwealth Ave", "FALIED to get the street in the address")
def test_set_street(self):
self.address.set_street("80 commonwealth Ave")
self.assertEqual(self.address.get_street(), "80 commonwealth Ave", "FALIED to change the street in the address")
def test_get_city(self):
self.assertEqual(self.address.get_city(), "Boston", "FALIED to get the city in the address")
def test_set_city(self):
self.address.set_city("Providence")
self.assertEqual(self.address.get_city(), "Providence", "FALIED to change the city in the address")
def test_get_state(self):
self.assertEqual(self.address.get_state(), "MA", "FALIED to get the state in the address")
def test_set_state(self):
self.address.set_city("RI")
self.assertEqual(self.address.get_city(), "RI", "FALIED to change the state in the address")
def test_get_zip_code(self):
self.assertEqual(self.address.get_zip_code(), "02215", "FALIED to get the zip code in the address")
def test_set_zip_code(self):
self.address.set_zip_code("01122")
self.assertEqual(self.address.get_zip_code(), "01122", "FALIED to change the zip code in the address")
<file_sep>/cs521/src/model/test_db_manager.py
import unittest
from cs521.src.model.bank import Bank
from cs521.src.model.checking_account import CheckingAccount
from cs521.src.model.savings_account import SavingsAccount
from cs521.src.model.db_manager import BankDB
from cs521.src.model.account import Account
__author__ = 'ATshudy'
class TestAccounts(unittest.TestCase):
bank = Bank()
acct1 = CheckingAccount(200.0)
acct2 = SavingsAccount(550.00)
test_database = "TestBank.db"
def setUp(self):
print("*** Starting setUp ***\n")
self.bank.set(1234, self.acct1)
self.bank.set(1111, self.acct2)
print(self.bank)
print("*** Finished setUp ***\n")
def tearDown(self):
print("*** Starting tearDown ***\n")
bankDB = BankDB(self.test_database)
bankDB.delete_account(1234)
bankDB.delete_account(1111)
bankDB.close_db()
self.bank.clear()
print("*** Finished tearDown ***\n")
def test_add_accounts_db(self):
print("*** Starting test_add_accounts_db ***\n")
bankDB = BankDB(self.test_database)
acct = self.bank.get(1234)
acct1 = self.bank.get(1111)
# add the account from the dict to the database
bankDB.add_account(1234, acct)
bankDB.add_account(1111, acct1)
print(bankDB.get_all_accounts())
self.assertEqual(bankDB.get_all_accounts(), [(1111, 'Savings Account', 550.0, None), (1234, 'Checking Account', 200.0, None)])
bankDB.close_db()
print("*** Finished test_add_accounts_db ***\n")
def test_update_accounts_db(self):
print("*** Starting test_update_accounts_db ***\n")
bankDB = BankDB(self.test_database)
acct = self.bank.get(1234)
acct1 = self.bank.get(1111)
bankDB.add_account(1234, acct)
bankDB.add_account(1111, acct1)
self.assertEqual(bankDB.get_all_accounts(), [(1111, 'Savings Account', 550.0, None), (1234, 'Checking Account', 200.0, None)])
# get the account from the database
listItem = bankDB.get_account(1234)
acct = Account(listItem)
acct.deposit(150.0)
# add the updated acct to the database
bankDB.update_account(1234,acct)
print(bankDB.get_account(1234))
self.assertEqual(bankDB.get_all_accounts(), [(1111, 'Savings Account', 550.0, None), (1234, 'Checking Account', 350.0, None)])
bankDB.close_db()
print("*** Finished test_update_accounts_db ***\n")
def test_add_transactionsdb(self):
print("*** Starting test_add_transactionsdb ***\n")
bankDB = BankDB(self.test_database)
acct = self.bank.get(1234)
acct1 = self.bank.get(1111)
bankDB.add_account(1234, acct)
bankDB.add_account(1111, acct1)
bankDB.add_transactions(1234, "deposited an initial off $200")
bankDB.add_transactions(1111, "deposited an initial off $550")
print("*** Finished test_add_transactionsdb ***\n")
def test_delete_transactions_db(self):
print("*** Starting test_delete_transactions_db ***\n")
bankDB = BankDB(self.test_database)
bankDB.delete_transaction_for_account(1234)
bankDB.delete_transaction_for_account(1111)
print("*** Finished test_delete_transactions_db ***\n")<file_sep>/cs521/src/model/account.py
from cs521.src.model.address import Address
__author__ = 'ATshudy'
class Account():
__balance = None
__accountType = None
CHECKING_TYPE = 1
SAVINGS_TYPE = 2
def __init__(self, listItem=None, accountType=1 , balance=0.0):
"""
:param list: This is a tuple that is used when accessing the acct from the database
:param accountType: CHECKING=1 or SAVINGS=2 [default is CHECKING]
:param balance: The initial balance when the accoun is open [default is 0.0]
:return: an Account object
"""
if not listItem:
self.__balance = balance
self.__accountType = accountType
if isinstance(listItem, Account):
self.__balance = listItem.__balance
self.__accountType = listItem.__accountType
elif isinstance(listItem, list):
balance = float(listItem[0][2])
self.set_balance(balance)
if listItem[0][1] == 'Checking Account':
self.__accountType = self.CHECKING_TYPE
else:
self.__accountType = self.SAVINGS_TYPE
def get_balance(self):
"""
getter method
:return: the __balance member variable
"""
return self.__balance
def set_balance(self, balance):
"""
setter method
:param balance: A new balance is added to the existing balance
:return: nothing is returned
"""
self.__balance = balance
def get_account_type(self):
"""
:return: 1=CHECKING or 2=SAVINGS
"""
return self.__accountType;
def get_account_type_str(self):
"""
:return: "Checking Account" or "Savings Account" as a string
"""
if self.__accountType == self.CHECKING_TYPE:
return "Checking Account"
else:
return "Savings Account"
def withdraw(self, amount):
"""
:param amount: the amount to withdraw from account
:return:
"""
self.set_balance(self.get_balance() - amount)
def deposit(self, amount):
"""
:param amount: the amount to deposit in the account
:return:
"""
self.set_balance(self.get_balance() + amount)
def __str__(self):
"""
:return: the account type and balance as a string
"""
if self.__accountType == 1:
return ("Checking Account:Balance "+str(self.get_balance()))
else:
return ("Savings Account:Balance "+str(self.get_balance()))<file_sep>/cs521/src/model/savings_account.py
from cs521.src.model.account import Account
__author__ = 'ATshudy'
class SavingsAccount(Account):
'''
This class inherits for the account class. The savings account sets the type of the account.
'''
__SAVINGS = 2
def __init__(self, balance=0.0):
"""
Initilizes a savings account object
:param balance: the starting balance for the new account [default: 0.0]
:return: A Savings account object
"""
super().__init__( None, self.__SAVINGS, balance)
<file_sep>/cs521/src/model/address.py
__author__ = 'ATshudy'
class Address:
'''
This class is the accounts address that is used for the account.
This is an option when creating an account
'''
__name = None
__street = None
__city = None
__state = None
__zip_code = None
def __init__(self, name, street, city, state, zipCode):
'''
Initializes the address object
:param name:
:param street:
:param city:
:param state:
:param zipCode:
:return:
'''
self.__name = name
self.__street = street
self.__city = city
self.__state = state
self.__zipCode = zipCode
def get_name(self):
'''
getter method for the name of an address object
:return: the name as a string
'''
return self.__name
def set_name(self, name):
'''
setter method for setting the name of an address object
:param name:
:return: None
'''
self.__name = name
def get_street(self):
'''
getter method for the street of the address object
:return: the street as a string
'''
return self.__street
def set_street(self, street):
'''
setter method for setting the street of an address object
:param street:
:return: None
'''
self.__street = street
def get_city(self):
'''
getter method for the city of the address object
return the city as a string
'''
return self.__city
def set_city(self, city):
'''
setter method for the city of the address object
:param city:
:return: None
'''
self.__city = city
def get_state(self):
'''
getter method for the state of the address object
:return: the state as a string
'''
return self.__state
def set_state(self, state):
'''
setter method for the state of the address object
:param state:
:return: the state as a string
'''
self.__state = state
def get_zip_code(self):
'''
getter method for the zip code in the address object
:return: the zip code as a string
'''
return self.__zipCode
def set_zip_code(self, zipCode):
'''
setter method for the zip code in the address object
:param zipCode:
:return: None
'''
self.__zipCode = zipCode
def __str__(self):
'''
used to print the object
:return: a string
'''
return self.get_name()<file_sep>/cs521/src/view/MainWnd.py
from tkinter import *
import tkinter.simpledialog as simpledialog
from cs521.src.controller.transactions_controller import TransactionController
__author__ = 'ATshudy'
class MainWnd(Frame):
__CHECKING_ACCOUNT_TYPE = 1
__SAVINGS_ACCOUNT_TYPE = 2
# declared a dist to hold user session information
__session = {'loggedIn' : False, 'pin' : None}
__controller = TransactionController();
def __init__(self, parent):
Frame.__init__(self, parent)
self.parentWnd = parent
self.menuBar = Menu(self.parentWnd)
self.parentWnd.config(menu=self.menuBar)
self.fileMenu = Menu(self.menuBar,tearoff=0)
self.fileMenu.add_command(label="Create Account",command=self.create_account)
self.fileMenu.add_command(label="Delete Account",command=self.on_delete_account)
self.fileMenu.add_command(label="View Transaction Log",command=self.on_log_transactions)
self.fileMenu.add_command(label="Log out",command=self.logout)
self.menuBar.add_cascade(label="File",menu=self.fileMenu)
self.fileMenu.add_separator()
self.fileMenu.add_command(label="Exit", command=self.on_exit)
self.inputVar = StringVar()
self.topFrame = Frame(self.parentWnd)
self.centerFrame = Frame(self.parentWnd)
self.bottomFrame = Frame(self.parentWnd)
self.centerFrameLeft = Frame(self.centerFrame)
self.centerFrameCenter = Frame(self.centerFrame, bd=1, relief=SUNKEN)
self.centerFrameRight = Frame(self.centerFrame)
self.bottomFrame.pack(side="bottom", fill="both", expand=True)
self.topFrame.pack(side="top", fill="both", expand=False)
self.centerFrame.pack(fill="both", expand=True, padx=5, pady=5)
self.centerFrameLeft.pack(side="left", fill="both", expand=True)
self.centerFrameCenter.pack(side="left", expand=False)
self.centerFrameRight.pack(side="left", fill="both",expand=True)
# add a vertical scroll bar to the text area
self.inputVar = StringVar()
self.displayText = StringVar()
self.textAreaTxt = StringVar()
self.input = Entry(self.topFrame, textvariable=self.inputVar).pack(side="bottom", padx=5, pady=5)
self.textArea = Text(self.topFrame, height="7", width=40, wrap=WORD)
self.textArea.insert(END, "Welcome, enter your pin number")
self.textArea.pack(padx=15, pady=15)
self.btn1Label = StringVar()
self.btn2Label = StringVar()
self.btn3Label = StringVar()
self.btn4Label = StringVar()
self.btn5Label = StringVar()
self.btn6Label = StringVar()
self.btn7Label = StringVar()
self.btn8Label = StringVar()
self.btn9Label = StringVar()
self.btn0Label = StringVar()
self.enterLabel = StringVar()
self.cancelLabel = StringVar()
self.withdrawLabel = StringVar()
self.depositLabel = StringVar()
self.decimalLabel = StringVar()
self.statusTxt = StringVar()
self.initialize_ui()
def on_enter_click(self):
if self.__session['loggedIn'] == False:
self.textArea.delete(1.0, END)
inputTxt = self.inputVar.get()
if self.__controller.account_exists(int(inputTxt)):
self.__session['loggedIn'] = True
self.__session['pin'] = int(inputTxt)
self.textArea.insert(END, "to continue enter an amount and Press\n withdraw or deposit\n")
else:
self.statusTxt.set("ERROR: pin does not match an checking account on file")
self.textArea.insert(END, "Please, re-enter your pin number or create an account")
self.inputVar.set("")
self.statusTxt.set("You have successfully logged in to your account. Your balance is :"+repr(self.__controller.get_account_balance(self.__session['pin'])))
def on_cancel_click(self):
self.inputVar.set("")
self.statusTxt.set("Transaction Canceled")
def on_withdraw_click(self):
inputTxt = self.inputVar.get()
if inputTxt == "":
self.statusTxt.set("Input Text is empty, Please enter amount in the input field")
return
self.__controller.withdraw_from_account(self.__session['pin'], float(inputTxt))
self.inputVar.set("")
self.statusTxt.set("Current Balance : "+repr(self.__controller.get_account_balance(self.__session['pin'])))
def on_deposit_click(self):
inputTxt = self.inputVar.get()
if inputTxt == "":
self.statusTxt.set("Input Text is empty, Please enter amount in the input field")
return
self.__controller.credit_account(self.__session['pin'], float(inputTxt))
self.inputVar.set("")
self.statusTxt.set("Current Balance : "+repr(self.__controller.get_account_balance(self.__session['pin'])))
def on_click_numpad(self, buttonLabel):
value = str(buttonLabel.get())
self.inputVar.set(self.inputVar.get()+value)
def on_log_transactions(self):
if self.__session['loggedIn'] == False:
self.statusTxt.set("User not Logged In, Please login with a valid pin number")
return
pin = self.__session['pin']
TransactionController.print_all_user_transactions(pin)
def on_delete_account(self, pin=None):
if pin is None:
pin = self.__session['pin']
self.__session['loggedIn'] = False
self.__session['pin'] = None
self.__controller.delete_account(pin)
self.textArea.delete(1.0, END)
self.textArea.insert(END, "Welcome, enter your pin number")
self.statusTxt.set("Enter your pin number")
def create_account(self):
name = simpledialog.askstring("Name", "Enter the name on the account")
if not name:
return
street = simpledialog.askstring("Street", "Enter your street address")
if not street:
return
city = simpledialog.askstring("city", "Enter your city")
if not city:
return
state = simpledialog.askstring("state", "Enter your state")
if not state:
return
zipCode = simpledialog.askstring("zip", "Enter your zip code")
if not zipCode:
return
pin = simpledialog.askstring("pin", "Enter your 4 digit pin number")
if not pin:
return
accountType = simpledialog.askinteger("Account Type", "Enter 1 for checking and 2 for savings")
if not accountType:
return
if accountType == self.__CHECKING_ACCOUNT_TYPE:
self.__controller.create_new_checking_account(name, street, city, state, zipCode, pin)
else:
self.__controller.create_new_savings_account(name, street, city, state, zipCode, pin)
if self.__controller.account_exists(pin):
self.__session['loggedIn'] = True
self.__session['pin'] = pin
self.textArea.delete(1.0, END)
self.textArea.insert(END, "Welcome\n\n, would like like to\n Deposit or Withdraw from your account")
self.statusTxt.set("SUCCESSFUL new account created Current Balance : "+repr(self.__controller.get_account_balance(self.__session['pin'])))
else:
self.__session['loggedIn'] = False
self.__session['pin'] = None
self.statusTxt.set("ERROR: Could not create a new account with pin")
def logout(self):
self.__session['loggedIn'] = False
self.__session['pin'] = None
self.textArea.delete(1.0, END)
self.textArea.insert(END, "Welcome, enter your pin number")
self.statusTxt.set("Enter your pin number")
def on_exit(self):
self.logout()
self.parentWnd.quit()
def initialize_ui(self):
self.btn1Label.set("1")
self.btn2Label.set("2")
self.btn3Label.set("3")
self.btn4Label.set("4")
self.btn5Label.set("5")
self.btn6Label.set("6")
self.btn7Label.set("7")
self.btn8Label.set("8")
self.btn9Label.set("9")
self.btn0Label.set("0")
self.enterLabel.set("Enter")
self.cancelLabel.set("Cancel")
self.withdrawLabel.set("Withdraw")
self.depositLabel.set("Deposit")
self.decimalLabel.set(".")
self.button1 = Button(self.centerFrameCenter, width=12, height=2, textvariable=self.btn1Label, command=lambda: self.on_click_numpad(self.btn1Label)).grid(row=0, column=0)
self.button2 = Button(self.centerFrameCenter, width=12, height=2, textvariable=self.btn2Label, command=lambda: self.on_click_numpad(self.btn2Label)).grid(row=0, column=1)
self.button3 = Button(self.centerFrameCenter, width=12, height=2, textvariable=self.btn3Label, command=lambda: self.on_click_numpad(self.btn3Label)).grid(row=0, column=2)
self.button4 = Button(self.centerFrameCenter, width=12, height=2, textvariable=self.btn4Label, command=lambda: self.on_click_numpad(self.btn4Label)).grid(row=1, column=0)
self.button5 = Button(self.centerFrameCenter, width=12, height=2, textvariable=self.btn5Label, command=lambda: self.on_click_numpad(self.btn5Label)).grid(row=1, column=1)
self.button6 = Button(self.centerFrameCenter, width=12, height=2, textvariable=self.btn6Label, command=lambda: self.on_click_numpad(self.btn6Label)).grid(row=1, column=2)
self.button7 = Button(self.centerFrameCenter, width=12, height=2, textvariable=self.btn7Label, command=lambda: self.on_click_numpad(self.btn7Label)).grid(row=2, column=0)
self.button8 = Button(self.centerFrameCenter, width=12, height=2, textvariable=self.btn8Label, command=lambda: self.on_click_numpad(self.btn8Label)).grid(row=2, column=1)
self.button9 = Button(self.centerFrameCenter, width=12, height=2, textvariable=self.btn9Label, command=lambda: self.on_click_numpad(self.btn9Label)).grid(row=2, column=2)
self.button0 = Button(self.centerFrameCenter, width=12, height=2, textvariable=self.btn0Label, command=lambda: self.on_click_numpad(self.btn0Label)).grid(row=3, column=1)
self.enterBtn = Button(self.centerFrameCenter, textvariable=self.enterLabel, command=self.on_enter_click, width=12, height=2).grid(row=3, column=2)
self.cancelBtn = Button(self.centerFrameCenter, textvariable=self.cancelLabel, command=self.on_cancel_click, width=12, height=2).grid(row=3, column=0)
self.withdrawBtn = Button(self.centerFrameCenter, textvariable=self.withdrawLabel, command=self.on_withdraw_click, width=12, height=2).grid(row=5, column=1)
self.depositBtn = Button(self.centerFrameCenter, textvariable=self.depositLabel, command=self.on_deposit_click, width=12, height=2).grid(row=5, column=2)
self.decimal = Button(self.centerFrameCenter, textvariable=self.decimalLabel, command=lambda: self.on_click_numpad(self.decimalLabel), width=12, height=2).grid(row=5, column=0)
# create a static text field and put it in the window and
self.statusTxt.set("Enter your pin number")
self.statisLabel = Label(self.bottomFrame, textvariable=self.statusTxt).pack()
def main_function():
parentWnd = Tk()
# set the title and window size
# create a window object
parentWnd.title("Automatic Teller Machine (ATM)")
parentWnd.geometry("650x450")
parentWnd.resizable(width=FALSE, height=FALSE)
app = MainWnd(parentWnd)
app.mainloop()
if __name__ == '__main__':
main_function()
<file_sep>/cs521/src/model/bank.py
from cs521.src.model.account import Account
__author__ = 'ATshudy'
class Bank(dict):
"""
The Bank class extents the built-in class dict.
The methods override some of dict methods and it uses the super method to call super class methods
This class creates a bank object and it holds bank accounts. Each account is associated with a pin number.
the pin number is the key and account is the value. Therefore, you can only have one account for each pin number.
"""
def __init__(self, *args):
"""
:param args: means a variable number of parameters. No parameters are accepted
:param kw: means a variable number of key value pairs as parameters. No parameters are accepted
:return: a dict object
"""
super().__init__(*args)
self.itemlist = super(Bank,self).keys()
def set(self, key, *values):
# if self.contains_key(key):
# raise Exception("Account exists for pin number "+str(key)+", close the account or create a new one")
# else:
self[key] = values
def get( self, key ):
return self[key][0]
def __iter__(self):
return iter(self.itemlist)
def keys(self):
return self.itemlist
def values(self):
return [self[key] for key in self]
def itervalues(self):
return (self[key] for key in self)
def __str__(self):
ret_str = ""
for d in self.keys():
ret_str += ""+str(d)
for v in self[d]:
ret_str += ","+str(v)
ret_str += "\n"
return ret_str
def contains_key(self, key):
for k in self.keys():
if k == key:
return True
return False
def contains_value(self, item):
return super(Bank, self).__contains__(self, item)<file_sep>/cs521/src/controller/atm_back_ground_process.py
import os
import time
from threading import Thread
__author__ = 'ATshudy'
class ATMThread(Thread):
'''
Class that load the transactionLog.txt file in notepad
'''
def run(self):
os.system('notepad.exe TransactionLog.txt')
<file_sep>/cs521/src/controller/atm_exception.py
__author__ = 'ATshudy'
# DEFINITIONS
class AtmException (Exception):
error_description = "Unknown ATM Exception was thrown."
def __str__(self, exception=error_description):
self.error_description = exception
return self.error_description<file_sep>/cs521/src/model/test_accounts.py
import unittest
from cs521.src.model.bank import Bank
from cs521.src.model.checking_account import CheckingAccount
from cs521.src.model.savings_account import SavingsAccount
from cs521.src.model.address import Address
__author__ = 'ATshudy'
class TestAccounts(unittest.TestCase):
bank = Bank()
acct1 = CheckingAccount(200.0)
acct2 = SavingsAccount(550.00)
def setUp(self):
print("*** Starting setUp ***\n")
self.bank.set(1234, self.acct1)
self.bank.set(1111, self.acct2)
print(self.bank)
print("*** Finished setUp ***\n")
def tearDown(self):
print("*** Starting tearDown ***\n")
self.bank.clear()
print("*** Finished tearDown ***\n")
def test_credit_account(self):
print("*** Starting test_credit_account ***\n")
self.acct1 = self.bank.get(1234)
self.acct1.deposit(100.00)
self.assertEqual(self.acct1.get_balance(), 300.00)
self.acct1.deposit(15.00)
self.assertEqual(self.acct1.get_balance(), 315.00)
print ("Finished: crediting the account")
print("current balance in Checking account is "+str(self.acct1.get_balance()))
print ("String: withdrawing from account")
self.acct1.withdraw(50.00)
self.assertEqual(self.acct1.get_balance(), 265.00)
self.acct1.withdraw(30.00)
self.assertEqual(self.acct1.get_balance(), 235.00)
print("current balance in Checking account is "+str(self.acct1.get_balance()))
print ("Finished: withdrawing the account\n")
print()
print("The current accounts in the bank are\n")
print(self.bank)
print("*** Finished test_credit_account ***\n")
def test_does_pin_number_exist(self):
print("*** Starting test_does_pin_number_exist ***\n")
self.assertEqual(self.bank.contains_key(1234), True)
self.assertEqual(self.bank.contains_key(1222), False)
print("*** Finished test_does_pin_number_exist ***\n")
def test_new_account_with_addresses(self):
print("*** Starting test_new_account_with_addresses ***\n")
addr1 = Address("<NAME>", "800 commonwealth Ave", "Boston", "MA", "02215")
self.acctAddr1 = SavingsAccount(100.0)
self.bank.set(1112, self.acctAddr1, addr1)
addr2 = Address("<NAME>", "880 commonwealth Ave", "Boston", "MA", "02215")
self.acctAddr2 = CheckingAccount(50.00)
self.bank.set(2222, self.acctAddr2, addr2)
print(self.bank)
print("*** Finished test_new_account_with_addresses ***\n")
<file_sep>/cs521/src/model/checking_account.py
from cs521.src.model.account import Account
__author__ = 'ATshudy'
class CheckingAccount(Account):
'''
This class inherits for the account class. The checking account sets the type of the account.
'''
__CHECKING = 1
def __init__(self, balance=0.0):
"""
Initilizes a checking account
:param balance: the starting balance for the new account [default: 0.0]
:return: A Checking account object
"""
super().__init__(None, self.__CHECKING, balance)
<file_sep>/cs521/src/model/db_manager.py
import sqlite3
import datetime
__author__ = 'ATshudy'
class BankDB:
'''
This is the database class.
'''
database_name = "bank.db" # name of the sqlite database file
table_accounts = "table_accounts" # name of the table to hold account information
table_transactions_audit = "table_transactions_audit" # name of the table to log all transactions
def __init__(self, dbName=None):
"""
Initializes a SQL database.
:param dbName: Is an optional parameter. This is the database name.
Default database name is the member variable database_name.
:return: contructor
"""
if dbName is not None:
self.conn = sqlite3.connect(dbName)
else:
self.conn = sqlite3.connect(self.database_name)
self.db_cursor = self.conn.cursor()
self.create_tables()
def create_tables (self):
"""
creates the table_accounts and the transactions tables ONLY if they do not exist
table_accounts example record :
id primary key (automatically generated)
pin_num 1112,
account_type Savings Account,
account_balance 100.0,
address "Allen Tshudy", "800 commonwealth Ave", "Boston", "MA", "02215"
table_transactions_audit example record :
id primary key (automatically generated)
pin_num 1112,
DETAILS "deposit - 20.00",
TRX_DATE "11/11/2015 at 8:54p",
:return: None
"""
# run SQL create table command only if the tables do not exists
self.conn.execute('''CREATE TABLE IF NOT EXISTS '''+self.table_accounts+'''
(pin_num INTEGER PRIMARY KEY NOT NULL,
account_type TEXT NOT NULL,
account_balance REAL,
address CHAR(50));''')
self.conn.execute('''CREATE TABLE IF NOT EXISTS '''+self.table_transactions_audit+'''
(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
pin_num INTEGER NOT NULL,
details CHAR(50) NOT NULL,
trx_date TEXT);''')
self.conn.commit()
def add_account(self, pin, account, address=None):
accountType = account.get_account_type_str()
balance = account.get_balance()
# Calls the execute method that will insert a record
self.conn.execute("INSERT INTO "+self.table_accounts+"(pin_num, account_type, account_balance, address) "
"VALUES (?, ?, ?, ?)", (pin, accountType, balance, address))
self.conn.commit()
def delete_account(self, pin):
"""
:param pin: the pin number to access the account to be deleted
:return:
"""
# Calls the execute method that will delete the record
self.conn.execute("DELETE FROM "+self.table_accounts+" WHERE pin_num=%d" % pin,)
self.conn.commit()
# Calls the method to delete all the recorded transactions for the deleted account
self.delete_transaction_for_account(pin)
def get_account(self, pin):
"""
:param pin: the pin number to access the account to be deleted
:return:
"""
# Calls the execute method that will delete the record
self.db_cursor.execute("SELECT * FROM "+self.table_accounts+" WHERE pin_num=%d" % pin,)
results = self.db_cursor.fetchall()
return results
def update_account(self, pin, account, address=None):
"""
:param pin:
:param account:
:param address:
:return:
"""
accountType = account.get_account_type_str()
balance = account.get_balance()
# Calls the execute method that will insert a record
self.conn.execute("UPDATE "+self.table_accounts+" SET account_type=?, account_balance=?, address=? WHERE pin_num=?", ( accountType, balance, address, pin))
self.conn.commit()
def get_all_accounts(self):
"""
:return: all the account in the table_accounts
"""
# Calls the execute method that will insert a record
self.db_cursor.execute("SELECT * FROM "+self.table_accounts)
results = self.db_cursor.fetchall()
return results
def add_transactions(self, pin, details):
"""
:param pin: the pin number used in the where clause
:return: all the records that are associated with pin number
"""
# Calls the execute method that will insert a record
now = datetime.datetime.now().strftime("%I:%M%p on %B %d, %Y")
self.conn.execute("INSERT INTO "+self.table_transactions_audit+"(pin_num, details, trx_date) "
"VALUES (?, ?, ?)", (pin, details, now))
self.conn.commit()
def get_all_transactions(self, pin):
"""
:param pin: the pin number used in the where clause
:return: all the records that are associated with pin number
"""
# Calls the execute method that will return all records for account with pin number
self.db_cursor.execute("SELECT * FROM "+self.table_transactions_audit+" WHERE pin_num=%d" % pin,)
results = self.db_cursor.fetchall()
return results
def delete_transaction_for_account(self, pin):
"""
:param pin: the pin number to access the account to be deleted
:return:
"""
# Calls the execute method that will delete the record
self.conn.execute("DELETE FROM "+self.table_transactions_audit+" WHERE pin_num=%d" % pin,)
self.conn.commit()
def close_db(self):
self.conn.close()<file_sep>/cs521/src/controller/transactions_controller.py
from cs521.src.model.bank import Bank
from cs521.src.model.address import Address
from cs521.src.model.checking_account import CheckingAccount
from cs521.src.model.savings_account import SavingsAccount
from cs521.src.model.account import Account
from cs521.src.model.db_manager import BankDB
from cs521.src.controller.atm_exception import AtmException
from cs521.src.controller.atm_back_ground_process import ATMThread
__author__ = 'ATshudy'
class TransactionController:
bank = None
def __init__(self):
"""
initilizes a singleton bank object to be used
"""
if self.bank is None:
self.bank = Bank()
def withdraw_from_account(self, pin, amount):
"""
:param pin: pin number to access the account from the bank
:param amount: the amount to withdraw from the account
:return: None
precondition: - user must enter an amount before processing the withdraw.
"""
bankDB = BankDB()
try:
acct = self.bank.get(pin)
# get the account from the database
listItem = bankDB.get_account(int(pin))
acct = Account(listItem)
acct.withdraw(amount)
# update the dict
self.bank.set(pin, acct)
# updated the database
bankDB.update_account(pin,acct)
acct = self.bank.get(pin)
bankDB.add_transactions(pin, "User "+str(pin)+" withdrew "+str(amount)+" from "+acct.get_account_type_str()+ "current balance is : "+str(acct.get_balance()))
finally:
bankDB.close_db()
def credit_account(self, pin, amount):
"""
:param pin: pin number to access the account from the bank
:param amount: the amount to credit from the account
:return:
precondition: - user must enter an amount before processing the credit(deposit).
"""
bankDB = BankDB()
try:
acct = self.bank.get(pin)
# get the account from the database
listItem = bankDB.get_account(int(pin))
acct = Account(listItem)
acct.deposit(amount)
# update the dict
self.bank.set(pin, acct)
# updated the database
bankDB.update_account(pin,acct)
acct = self.bank.get(pin)
bankDB.add_transactions(pin, "User "+str(pin)+" deposited "+str(amount)+" into "+acct.get_account_type_str()+ "current balance is : "+str(acct.get_balance()))
finally:
bankDB.close_db()
def get_account_balance(self, pin):
"""
:param pin: pin number to access the account from the bank
:return: the current balance in the account
"""
acct = Account(self.bank.get(pin))
return acct.get_balance()
def create_new_savings_account(self, name, street, city, state, zipCode, pin):
"""
Creates a new saving account
:param name: the name associated with the new account
:param street: street used for the address
:param city: city used for the address
:param state: state used for the address
:param zipCode: zip code used for the address
:param pin: the pin number associated with the account
:return: None
"""
address = Address(name, street, city, state, zipCode)
acct = SavingsAccount(0.0)
self.bank.set(pin, acct, address)
bankDB = BankDB()
try:
bankDB.add_account(pin, acct)
bankDB.add_transactions(pin, "Created a new "+acct.get_account_type_str()+" for user "+str(pin))
finally:
bankDB.close_db()
def create_new_checking_account(self, name, street, city, state, zipCode, pin):
"""
Creates a new checking account
:param name: the name associated with the new account
:param street: street used for the address
:param city: city used for the address
:param state: state used for the address
:param zipCode: zip code used for the address
:param pin: the pin number associated with the account
:return: None
"""
address = Address(name, street, city, state, zipCode)
acct = CheckingAccount(0.0)
self.bank.set(pin, acct, address)
bankDB = BankDB()
try:
bankDB.add_account(pin, acct)
bankDB.add_transactions(pin, "Created a new "+acct.get_account_type_str()+" for user "+str(pin))
finally:
bankDB.close_db()
@staticmethod
def print_all_user_transactions(pin):
'''
selects all the audits made by an account and saves the information to a file.
then spawns a thread to load the file into nodepad to display to the user.
:param pin: pin number to access the account from the bank
:return: None
Precondidtion: Only the current logged in users account will be viewed.
'''
bankDB = BankDB()
try:
auditData = bankDB.get_all_transactions(int(pin))
finally:
bankDB.close_db()
# using a context manger to automatically close the file
with open("TransactionLog.txt", "w") as text_file:
for irow in range(len(auditData)):
line = '{} : {} : {}'.format(auditData[irow][1], auditData[irow][2], auditData[irow][3])
text_file.write(line+"\n")
# create a thread to launch notepad and load the transaction log file
thread = ATMThread()
# this will kill the thread when the main app exits.
thread.setDaemon(True)
thread.start()
def account_exists(self, pin):
'''
checks to see if the accounts exists.
:param pin: pin number to access the account from the bank
:return: True or False
'''
bankDB = BankDB()
try:
acct = bankDB.get_account(int(pin))
finally:
bankDB.close_db()
# if it's not in the database check memory
if acct.__len__() == 0:
return self.bank.contains_key(pin)
else: # found it in the database so load account into memory
self.bank.set(pin, acct)
return True
def delete_account(self, pin):
'''
deletes an account from the database
:param pin: pin number to access the account from the bank
:return: None
precondition: only the current logged in user will be deleted.
'''
bankDB = BankDB()
try:
bankDB.delete_account(int(pin))
self.bank.pop(pin)
except Exception:
raise AtmException("User account does not exist or you are not logged in!")
finally:
bankDB.close_db() | 0325f33e668970d338fe5ca325de1f12e7d72759 | [
"Python"
] | 13 | Python | atshudy/ATM | 12451f63a1bc03b066b6a3833e00bc883b4f6cd5 | e2b8e05dff45c9abec4c01af1bfd1d7a327c8241 |
refs/heads/master | <repo_name>abhishekkumardwivedi/flatpak-app<file_sep>/ipc/zmqbus/src/files/source/hwserver.c
// Hello World server
#include <zmq.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <assert.h>
int main (void)
{
// Socket to talk to clients
void *context = zmq_ctx_new ();
void *responder = zmq_socket (context, ZMQ_REP);
int rc = zmq_bind (responder, "tcp://*:5555");
assert (rc == 0);
while (1) {
char buffer [10];
zmq_recv (responder, buffer, 10, 0);
printf ("Received Hello\n");
sleep (1); // Do some ’work’
zmq_send (responder, "World", 5, 0);
}
return 0;
}
<file_sep>/socket/src/files/bin/socket.sh
echo "----- socket app --------"
echo "---- server running ---------"
echo --- to check for two way communication override run command with below -----
echo --command=client
/app/bin/server
<file_sep>/ipc/shmem/src/files/bin/shmem.sh
echo --- shmem recv ----
echo --- to run send override run command with --command=send ---
echo --- you can run two applications with overriden command for shmem b/w two ---
echo --- or simpley run send command at system console ---
/app/bin/recv
<file_sep>/README.md
# Let's have required SDK and Runtime ----
flatpak remote-add --from gnome https://sdk.gnome.org/gnome.flatpakrepo
flatpak remote-list -d
flatpak remote-ls -d gnome
sudo flatpak install gnome org.gnome.Sdk//3.24
sudo flatpak install gnome org.gnome.Platform//3.24
flatpak list -d
# Install apps from remote ------
sudo flatpak remote-add --no-gpg-verify apps https://github.com/abhishekkumardwivedi/flatpak-app/tree/master/repo
sudo flatpak install apps com.permissive.audio
# Others -----
flatpak build-update-repo --title="Flatpak sample apps"
# Run an app ------
flatpak run com.permissive.audio
| e7a568e0471a884d8e9c6992340b7b8a956592c1 | [
"Markdown",
"C",
"Shell"
] | 4 | C | abhishekkumardwivedi/flatpak-app | ab0167942985a5c9ca59b71de34e8da45023a0e0 | 4fb36ca8eb251e809897bc9f19542b643564906c |
refs/heads/main | <file_sep>const express = require('express')
const app = express()
const bodyParser = require("body-parser");
const port = 8080
const studentArray = require('./InitialData');
const localStudentArray = [...studentArray];
let maxId = localStudentArray.length;
app.use(express.urlencoded());
// Parse JSON bodies (as sent by API clients)
app.use(express.json());
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
// your code goes here
app.get("/api/student", (req,res) => {
res.send(localStudentArray);
})
app.get("/api/student/:id", (req,res) => {
const idToSearch = req.params.id;
const matched = localStudentArray.filter(
(student) => student.id === Number(idToSearch)
);
if(matched.length == 0){
res.sendStatus(404);
}else{
res.send(matched[0]);
}
});
const isNulllOrUndefined = (vol) => vol === null || vol === undefined;
app.post("/api/student", (req,res) => {
const newStudent = req.body;
const {name, currentClass, division } = newStudent;
if(isNulllOrUndefined(name) || isNulllOrUndefined(currentClass) || isNulllOrUndefined(division)){
res.sendStatus(400);
}else {
const newId = maxId + 1;
maxId = newId;
newStudent.id = newId;
newStudent.currentClass = Number(currentClass);
localStudentArray.push(newStudent);
res.send({ id: newId});
}
});
app.put("/api/student/:id", (req,res) => {
const idToSearch = req.params.id;
const update = req.body;
const {name, currentClass, division } = update;
const matchedIdx = localStudentArray.findIndex(
(student) => student.id === Number(idToSearch)
);
if(matchedIdx === -1){
res.sendStatus(400);
} else{
if(isNulllOrUndefined(name) && isNulllOrUndefined(currentClass) && isNulllOrUndefined(division) ) {
res.sendStatus(400);
}else {
if(!isNulllOrUndefined(name)) {
localStudentArray[matchedIdx].name = name;
res.sendStatus(200);
}
if(!isNulllOrUndefined(currentClass)) {
localStudentArray[matchedIdx].currentClass = Number(currentClass);
res.sendStatus(200);
}
if(!isNulllOrUndefined(division)) {
localStudentArray[matchedIdx].division = division;
res.sendStatus(200);
}
res.sendStatus(200);
}
}
});
app.delete("/api/student/:id", (req,res) => {
const idToSearch = req.params.id;
const matchedIdx = localStudentArray.findIndex(
(student) => student.id === Number(idToSearch)
);
if(matchedIdx === -1){
res.sendStatus(404);
} else{
localStudentArray.splice(matchedIdx , 1);
res.sendStatus(200);
}
});
app.listen(port, () => console.log(`App listening on port ${port}!`))
module.exports = app; | 736fbbf28a63e3da61f52e4acd58e58c75b03ba0 | [
"JavaScript"
] | 1 | JavaScript | ankitanigam51/Backend-Assignments---School-Administration | c2fef5bed9a7b93f016790823bb90df33298dd68 | f99ec73ff836937db050b11d961b1668f2a64e52 |
refs/heads/master | <repo_name>timdamra/jest-test-boilerplate<file_sep>/__tests__/subtract.test.js
const subtract = require('../subtract');
test.only('should subtract 2 numbers', () => {
const result = subtract(2, 1);
expect(result).toBe(1);
});
<file_sep>/__tests__/sum.test.js
const sum = require('../sum');
test('should return sum of 2 numbers', () => {
const result = sum(2, 3);
expect(result).not.toBe(2);
});
| ab64faffe47ecde0231d636b9c83f58d07d54393 | [
"JavaScript"
] | 2 | JavaScript | timdamra/jest-test-boilerplate | da491027d4ea8862ff82bcbfe3f413d725d52afe | 985e8e0bc6636b4dd18fc3ff5684aeeab5f5a58c |
refs/heads/master | <repo_name>wklieber/pi-services<file_sep>/pi/modules/services/src/main/java/pi/HelloWorldResource.java
/*
* Copyright (c) 2015, <NAME>. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package pi;
import com.codahale.metrics.annotation.Timed;
import com.google.common.base.Optional;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import java.util.concurrent.atomic.AtomicLong;
/**
* Created by wklieber on 08.03.2015.
*/
@Path("/hello-world")
@Produces(MediaType.APPLICATION_JSON)
public class HelloWorldResource {
private final String template;
private final String defaultName;
private final AtomicLong counter;
public HelloWorldResource(String template, String defaultName) {
this.template = template;
this.defaultName = defaultName;
this.counter = new AtomicLong();
}
@GET
@Timed
public Saying sayHello(@QueryParam("name") Optional<String> name) {
final String value = String.format(template, name.or(defaultName));
return new Saying(counter.incrementAndGet(), value);
}
}
<file_sep>/pi/modules/services/src/main/java/pi/tools/processexecutor/ProcessExecutorSettings.java
/*
* Copyright (c) 2015, <NAME>. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package pi.tools.processexecutor;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* specify setting for starting an external process
*
* @author <NAME>
*/
public class ProcessExecutorSettings {
/**
* environmenVariables for the new proces.
* if null, system defaults of this vm is used (System.getEnv())
*/
private Map<String, String> env;
/**
* working directory for the new process. May be null
*
* @param text
*/
private String workDir;
/**
* optional text-prefix for each redirected text line in the console.
* This is useful to determin the output of each process.
* for the error an [ERR] prefix is added.
* if null, nothing is appended - even no error prefix
*/
private String outputPrefix;
/**
* the program to execute
*/
private String command;
/**
* addional argurments for the command.
* Note: must be really arguments. E.g. linux pipes are not supported (ls -lah | grep /home will fail)
*/
private List<String> args;
/**
* stream the get the program output. if null, data is logged to the console
*/
private OutputStream outputStream;
/**
* param command the command to execute, e.g. dir or ls
*
* @param args optional set some arguments passing to the command to execute
*/
public ProcessExecutorSettings(String command, String... args) {
this.command = command;
if (args != null) {
List<String> list = getArgs();
for (int i = 0; i < args.length; i++) {
String arg = args[i];
list.add(arg);
}
}
}
public Map<String, String> getEnv() {
return env;
}
public void setEnv(Map<String, String> env) {
this.env = env;
}
public String getWorkDir() {
return workDir;
}
public void setWorkDir(String workDir) {
this.workDir = workDir;
}
public String getOutputPrefix() {
return outputPrefix;
}
public void setOutputPrefix(String outputPrefix) {
this.outputPrefix = outputPrefix;
}
public String getCommand() {
return command;
}
public void setCommand(String command) {
this.command = command;
}
public List<String> getArgs() {
if (args == null) args = new ArrayList<String>();
return args;
}
public void setArgs(List<String> args) {
this.args = args;
}
public OutputStream getOutputStream() {
return outputStream;
}
public void setOutputStream(OutputStream outputStream) {
this.outputStream = outputStream;
}
/**
* return a human readable string containing the command and all arguments as beeing executed
*/
public String printCommandLine() {
StringBuilder str = new StringBuilder();
str.append(command);
for (String arg : args) {
str.append(" ");
str.append(arg);
}
return str.toString();
}
public String toString() {
return "ProcessExecutorSettings{" +
"env=" + env +
", workDir='" + workDir + '\'' +
", outputPrefix='" + outputPrefix + '\'' +
", command='" + command + '\'' +
", args=" + args +
", outputStream=" + outputStream +
'}';
}
}
<file_sep>/pi/modules/services/src/main/java/pi/HelloWorldConfiguration.java
/*
* Copyright (c) 2015, <NAME>. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package pi;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.dropwizard.Configuration;
import org.hibernate.validator.constraints.NotEmpty;
/**
* Created by wklieber on 08.03.2015.
*/
public class HelloWorldConfiguration extends Configuration {
@NotEmpty
private String template;
@NotEmpty
private String defaultName = "Stranger";
@JsonProperty
public String getTemplate() {
return template;
}
@JsonProperty
public void setTemplate(String template) {
this.template = template;
}
@JsonProperty
public String getDefaultName() {
return defaultName;
}
@JsonProperty
public void setDefaultName(String name) {
this.defaultName = name;
}
}
<file_sep>/pi/modules/services/pom.xml
<?xml version="1.0"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>wklieber.pi.service</groupId>
<artifactId>pi-parent</artifactId>
<version>1.0-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<artifactId>pi-services</artifactId>
<packaging>jar</packaging>
<name>PI Services</name>
<url>http://klieber.info</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<build>
<extensions>
<extension>
<groupId>org.apache.maven.wagon</groupId>
<artifactId>wagon-ftp</artifactId>
<version>1.0-beta-2</version>
</extension>
<extension>
<groupId>org.apache.maven.wagon</groupId>
<artifactId>wagon-ssh</artifactId>
<version>1.0-beta-6</version>
</extension>
<extension>
<groupId>org.apache.maven.wagon</groupId>
<artifactId>wagon-webdav</artifactId>
<version>1.0-beta-2</version>
</extension>
</extensions>
<plugins>
<!--<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.16</version>
<configuration>
<!– invoke a listener to inform when testing starts and when finished –>
<properties>
<property>
<name>listener</name>
<value>at.knowcenter.kdapp.TestListener</value>
</property>
</properties>
</configuration>
</plugin>-->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>1.6</version>
<configuration>
<createDependencyReducedPom>true</createDependencyReducedPom>
<filters>
<filter>
<artifact>*:*</artifact>
<excludes>
<exclude>META-INF/*.SF</exclude>
<exclude>META-INF/*.DSA</exclude>
<exclude>META-INF/*.RSA</exclude>
</excludes>
</filter>
</filters>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<transformers>
<transformer
implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/>
<transformer
implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
<mainClass>pi.HelloWorldApplication</mainClass>
</transformer>
</transformers>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>2.4</version>
<configuration>
<archive>
<manifest>
<addDefaultImplementationEntries>true</addDefaultImplementationEntries>
</manifest>
</archive>
</configuration>
</plugin>
<!-- do not deploy the war on the local jetty - causes errors when started
from an othe folder -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.7</version>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-install-plugin</artifactId>
<version>2.3.1</version>
<!--<configuration>
<skip>true</skip>
</configuration>-->
</plugin>
<!--plugin>
<groupId>org.mortbay.jetty</groupId>
<artifactId>maven-jetty-plugin</artifactId>
<version>6.1.26</version>
<configuration>
<scanIntervalSeconds>10</scanIntervalSeconds>
<stopKey>foo</stopKey>
<stopPort>9999</stopPort>
<connectors>
<connector implementation="org.mortbay.jetty.nio.SelectChannelConnector">
<port>8888</port>
</connector>
</connectors>
</configuration>
<executions>
<execution>
<id>start-jetty</id>
<goals>
<goal>run</goal>
</goals>
<configuration>
<scanIntervalSeconds>0</scanIntervalSeconds>
<daemon>true</daemon>
</configuration>
</execution>
<execution>
<id>skip-install-jetty</id>
<phase>install</phase>
<configuration>
<skip>true</skip>
</configuration>
</execution>
<execution>
<id>stop-jetty</id>
<goals>
<goal>stop</goal>
</goals>
</execution>
</executions>
</plugin-->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>com.pi4j</groupId>
<artifactId>pi4j-core</artifactId>
<version>${pi4j.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons.io.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>net.sf.opencsv</groupId>
<artifactId>opencsv</artifactId>
<version>${opencsv.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>io.dropwizard</groupId>
<artifactId>dropwizard-core</artifactId>
<version>${dropwizard.version}</version>
<scope>compile</scope>
</dependency>
</dependencies>
</project><file_sep>/pi/modules/services/src/test/resources/wklieber/start_service.sh
#!/bin/sh
cd ~/git/pi-services
git pull
cd pi/modules/services
mvn clean package
java -jar target/pi-services-1.0-SNAPSHOT.jar server default-configuration.yml
<file_sep>/pi/modules/services/src/main/java/pi/tools/processexecutor/ProcessExecutorResult.java
/*
* Copyright (c) 2015, <NAME>. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package pi.tools.processexecutor;
/**
* @author <NAME>
*/
public class ProcessExecutorResult {
private Process process;
private Thread threadOut;
private Thread threadErr;
protected ProcessExecutorResult(Process process, Thread threadOut, Thread threadErr) {
this.process = process;
this.threadOut =threadOut;
this.threadErr=threadErr;
}
public Process getProcess() {
return process;
}
/** wait until process finished and all output is written to the streams */
public int waitFor() throws InterruptedException {
int ret = process.waitFor();
threadOut.join();
threadErr.join();
return ret;
}
public String toString() {
return "ProcessExecutorResult{" +
"process=" + process +
'}';
}
}
<file_sep>/pi/pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>wklieber.pi.service</groupId>
<artifactId>pi-parent</artifactId>
<name>Pi Service parent</name>
<description>PI Services</description>
<url>http://maven.apache.org</url>
<version>1.0-SNAPSHOT</version>
<packaging>pom</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<jersey.version>1.18.1</jersey.version>
<jetty-version>6.1.26</jetty-version>
<cleaner-version>1.0-SNAPSHOT</cleaner-version>
<jsp-version>6.1.14</jsp-version>
<servlet-api-version>2.4</servlet-api-version>
<apache.commons.version>1.5</apache.commons.version>
<derby-version>10.10.1.1</derby-version>
<dropwizard.version>0.8.0</dropwizard.version>
<pi4j.version>1.1-SNAPSHOT</pi4j.version>
<commons.io.version>2.4</commons.io.version>
<dropwizard.redirect.version>0.2.0</dropwizard.redirect.version>
<opencsv.version>2.3</opencsv.version>
<log4j.version>1.2.14</log4j.version>
<junit.version>4.11</junit.version>
</properties>
<scm>
<developerConnection>scm:svn:https://svn.</developerConnection>
<connection>scm:svn:https://svn.</connection>
<url>https://svn.</url>
</scm>
<modules>
<module>modules/services</module>
</modules>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<extensions>
<extension>
<groupId>org.apache.maven.wagon</groupId>
<artifactId>wagon-ftp</artifactId>
<version>1.0-beta-2</version>
</extension>
<extension>
<groupId>org.apache.maven.wagon</groupId>
<artifactId>wagon-ssh</artifactId>
<version>1.0-beta-6</version>
</extension>
<extension>
<groupId>org.apache.maven.wagon</groupId>
<artifactId>wagon-webdav</artifactId>
<version>1.0-beta-2</version>
</extension>
</extensions>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>2.8</version>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>oss-snapshots-repo</id>
<name>Sonatype OSS Maven Repository</name>
<url>https://oss.sonatype.org/content/groups/public</url>
<snapshots>
<enabled>true</enabled>
<updatePolicy>always</updatePolicy>
</snapshots>
</repository>
<repository>
<id>kc_external</id>
<name>Know-Center external Maven Repository</name>
<layout>default</layout>
<url>https://nexus.know-center.tugraz.at/content/groups/public</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
</repositories>
<distributionManagement>
<repository>
<id>kc_external</id>
<name>KC Repository</name>
<url>dav:https://nexus.know-center.tugraz.at/content/repositories/releases</url>
</repository>
<snapshotRepository>
<id>kc_external</id>
<name>KC Repository</name>
<url>dav:https://nexus.know-center.tugraz.at/content/repositories/snapshots</url>
</snapshotRepository>
</distributionManagement>
</project><file_sep>/pi/modules/services/src/main/java/pi/PiCameraResource.java
/*
* Copyright (c) 2015, <NAME>. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package pi;
import com.codahale.metrics.annotation.Timed;
import org.apache.commons.io.IOUtils;
import pi.tools.processexecutor.ProcessExecutor;
import pi.tools.processexecutor.ProcessExecutorResult;
import pi.tools.processexecutor.ProcessExecutorSettings;
import javax.inject.Singleton;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.*;
import java.util.concurrent.atomic.AtomicLong;
/**
* Created by wklieber on 08.03.2015.
*/
@Path("/pi")
@Produces(MediaType.APPLICATION_JSON)
@Singleton
public class PiCameraResource {
private final AtomicLong imageCaputureCounter;
public PiCameraResource() {
this.imageCaputureCounter = new AtomicLong();
}
@GET
@Timed
@Path("/image/capture")
@Produces("image/png")
public Response capture() throws Exception {
// use the command line tool "raspistill".
//try {
String id = String.valueOf(imageCaputureCounter.incrementAndGet());
String fileName = "/tmp/image-" + id + "-" + System.currentTimeMillis() + ".png";
executeCaptureCommand(fileName);
InputStream inputStream = new FileInputStream(fileName);
byte[] imageData = IOUtils.toByteArray(inputStream);
executeDeleteImageCommand(fileName);
// uncomment line below to send non-streamed
return Response.ok(imageData).build();
// uncomment line below to send streamed
// return Response.ok(new ByteArrayInputStream(imageData)).build();
/*} catch (Exception e) {
String msg = e.toString();
throw new WebApplicationException(msg);
}*/
}
private void executeCaptureCommand(String fileName) throws InterruptedException {
//-o, --output : Output filename <filename> (to write to stdout, use '-o -'). If not specified, no file is saved
//-e, --encoding : Encoding to use for output file (jpg, bmp, gif, png)
//-t, --timeout : Time (in ms) before takes picture and shuts down (if not specified, set to 5s) minimum 30ms, setting to 0 waits forever
//-q, --quality : Set jpeg quality <0 to 100>
String[] args = new String[]{"-o", fileName, "-e", "png"};
ProcessExecutor executor = new ProcessExecutor();
ProcessExecutorSettings settings = new ProcessExecutorSettings("raspistill", args);
ByteArrayOutputStream out = new ByteArrayOutputStream();
settings.setOutputStream(out);
ProcessExecutorResult result = executor.start(settings);
Process process = result.getProcess();
int ret = result.waitFor();
if(ret != 0) {
throw new UnsupportedOperationException("error executing image capture command line tool 'raspistill'. " +
"return code was " + ret + ", Console output: '" + out.toString() + "'");
}
}
/**
* delete captured file from raspberry after reading.
*/
private void executeDeleteImageCommand(String fileName) throws InterruptedException {
String[] args = new String[]{"-rf", fileName};
ProcessExecutor executor = new ProcessExecutor();
ProcessExecutorSettings settings = new ProcessExecutorSettings("rm", args);
ByteArrayOutputStream out = new ByteArrayOutputStream();
settings.setOutputStream(out);
ProcessExecutorResult result = executor.start(settings);
Process process = result.getProcess();
int ret = result.waitFor();
if(ret != 0) {
String message = "error deleting image file '" + fileName +
"'. Return code was " + ret + ", Console output: '" + out.toString() + "'";
System.err.println(message);
}
}
}
<file_sep>/README.md
# pi-services
Raspberry pi experimenting stuff for java
| 6f7728810e9ddb36866a4406300cde20db9cffea | [
"Markdown",
"Java",
"Maven POM",
"Shell"
] | 9 | Java | wklieber/pi-services | 3611c77b3e8eb7b8bc62c917c61ae845b055f853 | 4b372b5fb1a8c102aac80080551f53886a2d71a6 |
refs/heads/master | <file_sep>class Play < ApplicationRecord
belongs_to :user
belongs_to :game
has_many :moves
enum result: %i[inprogress winner loser draw]
enum role: %i[single creator invited]
before_create :generate_goal
CHARS = %w[1 2 3 4 5 6 7 8 9 0]
LENGTH = 4
def generate_goal
self.goal = ''
while goal.length != LENGTH do
char = CHARS.sample
self.goal += char unless goal.include?(char)
end
end
end
<file_sep>class User < ApplicationRecord
include Clearance::User
has_many :plays
has_many :games, through: :plays
def winner_of?(game)
play = plays.find_by game: game
play.winner?
end
end
<file_sep>require 'rails_helper'
RSpec.describe Move, type: :model do
describe "validation" do
subject { build :move }
it "is invalid without request" do
subject.request = nil
expect(subject).not_to be_valid
end
it { is_expected.to be_valid }
it "is invalid unless request has 4 digits" do
subject.request = '123'
expect(subject).not_to be_valid
subject.request = '12345'
expect(subject).not_to be_valid
end
it "is invalid unless all digits are unique" do
subject.request = '1233'
expect(subject).not_to be_valid
end
end
describe "generate_response" do
it "creates response automatically" do
play = create :play, memory: '1234'
move = play.moves.create request: '1234'
expect(move.response).to eq '44'
end
it do
play = create :play, memory: '1234'
move = play.moves.create request: '1230'
expect(move.response).to eq '33'
end
it do
play = create :play, memory: '1234'
move = play.moves.create request: '5678'
expect(move.response).to eq '00'
end
it do
play = create :play, memory: '1234'
move = play.moves.create request: '3201'
expect(move.response).to eq '31'
end
end
end
<file_sep>require 'rails_helper'
RSpec.describe "moves/new", type: :view do
before(:each) do
assign(:move, Move.new(
:play => nil,
:request => "MyString",
:response => "MyString"
))
end
it "renders new move form" do
render
assert_select "form[action=?][method=?]", moves_path, "post" do
assert_select "input[name=?]", "move[play_id]"
assert_select "input[name=?]", "move[request]"
assert_select "input[name=?]", "move[response]"
end
end
end
<file_sep>class Game < ApplicationRecord
has_many :plays
has_many :users, through: :plays
enum state: %i[created canceled accepted rejected waiting playing aborted finished expired]
before_validation :generate_join_code
def generate_join_code
self.join_code = SecureRandom.base58(3).downcase
end
end
<file_sep>class ApplicationController < ActionController::Base
include Clearance::Controller
protect_from_forgery with: :exception
before_action :login
private
def login
unless signed_in?
user = User.create email: "<EMAIL>", password: '123'
sign_in(user)
end
end
end
<file_sep>require 'rails_helper'
RSpec.describe "plays/edit", type: :view do
before(:each) do
@play = assign(:play, Play.create!(
:user => nil,
:game => nil,
:memory => "MyString",
:role => 1,
:result => 1
))
end
it "renders the edit play form" do
render
assert_select "form[action=?][method=?]", play_path(@play), "post" do
assert_select "input[name=?]", "play[user_id]"
assert_select "input[name=?]", "play[game_id]"
assert_select "input[name=?]", "play[memory]"
assert_select "input[name=?]", "play[role]"
assert_select "input[name=?]", "play[result]"
end
end
end
<file_sep>FactoryBot.define do
factory :move do
association(:play)
request "1234"
response nil
end
end
<file_sep>require 'rails_helper'
RSpec.describe "plays/new", type: :view do
before(:each) do
assign(:play, Play.new(
:user => nil,
:game => nil,
:memory => "MyString",
:role => 1,
:result => 1
))
end
it "renders new play form" do
render
assert_select "form[action=?][method=?]", plays_path, "post" do
assert_select "input[name=?]", "play[user_id]"
assert_select "input[name=?]", "play[game_id]"
assert_select "input[name=?]", "play[memory]"
assert_select "input[name=?]", "play[role]"
assert_select "input[name=?]", "play[result]"
end
end
end
<file_sep>require 'rails_helper'
RSpec.describe Play, type: :model do
it "generates goal when created" do
play = create :play
expect(play.goal).not_to be_nil
expect(play.goal.size).to eq 4
end
end
<file_sep>FactoryBot.define do
factory :game do
state 1
join_code "MyString"
end
end
<file_sep>class CreateMoves < ActiveRecord::Migration[5.1]
def change
create_table :moves do |t|
t.belongs_to :play, foreign_key: true
t.string :request
t.string :response
t.timestamps
end
end
end
<file_sep>json.extract! play, :id, :user_id, :game_id, :goal, :role, :result, :created_at, :updated_at
json.url play_url(play, format: :json)
<file_sep>FactoryBot.define do
factory :play do
association(:user)
association(:game)
goal nil
role 1
result 1
end
end
<file_sep>class Move < ApplicationRecord
belongs_to :play
validates :request, presence: true, length: { is: 4 }
validate :request_must_have_unique_chars
before_create :generate_response
def request_must_have_unique_chars
return if request.nil?
errors.add :request, :unique unless request_unique_chars_count == 4
end
def generate_response
guessed, correct = [0, 0]
request.each_char do |digit|
guessed += 1 if play.goal.include?(digit)
correct += 1 if play.goal.index(digit) == request.index(digit)
end
self.response = "#{guessed}#{correct}"
end
def request_unique_chars_count
request.chars.to_a.uniq.size
end
def finishing?
response == '44'
end
end
<file_sep>class PagesController < ApplicationController
def home
end
def single
end
def multiuser
end
end
<file_sep>require 'rails_helper'
RSpec.describe PagesController, type: :controller do
describe "GET #home" do
it "returns http success" do
get :home
expect(response).to have_http_status(:success)
end
end
describe "GET #single" do
it "returns http success" do
get :single
expect(response).to have_http_status(:success)
end
end
describe "GET #multiuser" do
it "returns http success" do
get :multiuser
expect(response).to have_http_status(:success)
end
end
end
<file_sep>require 'rails_helper'
RSpec.describe "moves/show", type: :view do
before(:each) do
@move = assign(:move, Move.create!(
:play => nil,
:request => "Request",
:response => "Response"
))
end
it "renders attributes in <p>" do
render
expect(rendered).to match(//)
expect(rendered).to match(/Request/)
expect(rendered).to match(/Response/)
end
end
<file_sep>Rails.application.routes.draw do
root 'pages#home'
get 'pages/single'
get 'pages/multiuser'
resources :moves
resources :plays
resources :games
resources :users
end
<file_sep>json.extract! move, :id, :play_id, :request, :response, :created_at, :updated_at
json.url move_url(move, format: :json)
| d9e47d06ebde1d4c652ba0524935e793131542f1 | [
"Ruby"
] | 20 | Ruby | garshyn/bulls | 01721c657972db24ed0cd403bb9d8b1cb86ebd2a | 6883ebd6ac6987726018b383cd014ab4f8cb3180 |
refs/heads/master | <file_sep># hp_characters_visualization
Harry Potter characters visualization
<file_sep>##### Insert line after a specific position #####
# for i in range(1,8):
# with open("data_hp%d.txt" % i,"r+") as in_file:
# buf = in_file.readlines()
# with open("data_hp%d.txt" % i,"w") as out_file:
# for line in buf:
# if(line == "Draco\n"):
# line = line + "Malfoy\n"
# out_file.write(line)
###### Append at the end of the file #####
for i in range(1,8):
with open("data_hp%d.txt" % i,"a+") as f:
f.write("\Professor <NAME>\n")
##### Replace into same line #####
# for i in range(5,8):
# with open("data_hp%d.txt" % i,"r+") as in_file:
# buf = in_file.readlines()
# with open("data_hp%d.txt" % i,"w") as out_file:
# for line in buf:
# if(line == "Draco\n"):
# line = "Draco Malfoy\n"
# out_file.write(line)
# elif(line != "Malfoy\n"):
# out_file.write(line)
# for i in range(2,8):
# with open("data_hp%d.txt" % i,"r+") as in_file:
# buf = in_file.readlines()
# with open("data_hp%d.txt" % i,"w") as out_file:
# for line in buf:
# if(line == "McGonagall\n"):
# line = "Professor McGonagall\n"
# out_file.write(line)
# elif(line != "McGonagall\n"):
# out_file.write(line)
# for i in range(3,8):
# with open("data_hp%d.txt" % i,"r+") as in_file:
# buf = in_file.readlines()
# with open("data_hp%d.txt" % i,"w") as out_file:
# for line in buf:
# if(line == "<NAME>\n"):
# continue
# # line = "<NAME>\n"
# # out_file.write(line)
# out_file.write(line)
<file_sep>import csv
import nltk
import codecs
import time
# nodes - names with count
names = {}
updated_names = {}
# edges
relationships = {}
# name list in a whole chapter
entity_names = []
# chapter
chapter = []
# Count names occurence in a chapter
def countnames(entity_names):
for temp in entity_names:
if any(temp in s for s in name_set):
# if temp in name_set:
if temp in names:
names[temp] += 1
else:
names[temp] = 1
return names
def extract_name_entities(chapter, entity_names):
# for sent in nltk.sent_tokenize(chapter):
for sent in chapter:
# ne_chunk: a classifier-based named entity recognizer
# pos_tag: processes a sequence of words, and attaches a part of speech tag to each word
# word_tokenize: tokenize text into words
for chunk in nltk.ne_chunk(nltk.pos_tag(nltk.word_tokenize(sent))):
if hasattr(chunk, 'label') and chunk.label()=="PERSON":
name = [child[0] for child in chunk]
if any("Professor" in w for w in name):
name.pop(0)
new_name = name
entity_names.append(' '.join(new_name))
elif any("Uncle" in w for w in name):
name.pop(0)
new_name = name
entity_names.append(' '.join(new_name))
elif any("Aunt" in w for w in name):
name.pop(0)
new_name = name
entity_names.append(' '.join(new_name))
else:
entity_names.append(' '.join(name))
# print("\nnames in chapter\n", entity_names)
return entity_names
def hp_relations(chapter, entity_names, updated_names):
key = list(updated_names.keys())
for block in chapter:
for name1 in entity_names:
if (name1 not in key) or (name1 not in block):
continue
for name2 in entity_names:
if (name2 not in key) or (name2 not in block):
continue
if name1 == name2:
continue
if name1 not in relationships:
relationships[name1]={}
elif name2 not in relationships[name1]:
relationships[name1][name2] = 1
else:
relationships[name1][name2] += 1
return relationships
# Union the same name
def unionname(names):
for kv in names.items():
name = kv[0]
value = kv[1]
edited = False
if (name == '') or (len(name) < 3):
continue
for dic_new_kv in list(updated_names.items()):
dic_new_name = dic_new_kv[0]
dic_new_value = dic_new_kv[1]
if name in dic_new_name:
updated_names[dic_new_name] = dic_new_value + value
edited = True
elif dic_new_name in name:
updated_names[name] = value + dic_new_value
del updated_names[dic_new_name]
edited = True
if not edited:
updated_names[name] = value
return updated_names
# Save as new csv file
def save_node_and_edge(names, relationships):
with open('nodes.csv', 'w') as csv_file:
writer = csv.writer(csv_file)
for key in names:
writer.writerow([key, names[key]])
with open('edges.csv', 'w') as csv_file:
writer = csv.writer(csv_file)
for key1 in relationships:
for key2 in relationships[key1]:
writer.writerow([key1, key2, relationships[key1][key2]])
print("\nFinish!!!\n")
# --------------------------------------- Read files ---------------------------------------- #
t = time.process_time()
for i in range(1, 8):
# with codecs.open("data_hp%d.txt" % i, "r") as hp_name:
# name_set = hp_name.readlines()
# name_set = [j.strip() for j in name_set]
# print ("HP_names", name_set, "\n")
with codecs.open("hp_characters.txt", "r") as hp_name:
name_set = hp_name.readlines()
name_set = [j.strip() for j in name_set]
# print ("HP_names", name_set, "\n")
with codecs.open("hp%d.txt" % i, "r") as hp:
hp_content = [j.strip() for j in hp.readlines()]
print("-------------------------- Book %d --------------------------" %i)
print("Chapter 1")
for sen in hp_content:
if "Chapter" in sen and sen != "Chapter 1":
print(sen)
entity_names = extract_name_entities(chapter, entity_names);
names = countnames(entity_names)
updated_names = unionname(names)
relationships = hp_relations(chapter, entity_names, updated_names)
chapter[:] = []
entity_names[:] = []
else:
chapter.append(sen)
print("\noccurence of names\n", updated_names)
print("\nrelationships: ", relationships)
save_node_and_edge(names, relationships)
print("Process in ", time.process_time()-t, " secs")
| 066fe17007272e28121dcd47b18d22243f9e1b25 | [
"Markdown",
"Python"
] | 3 | Markdown | yourSylvia/hp_characters_visualization | 0b136c0b3e6ff4401aa263d1fb83d13f0a5daa9c | 60a100fb8bf9feabff8155f69f4e2596420ed74c |
refs/heads/main | <file_sep>-- phpMyAdmin SQL Dump
-- version 5.0.2
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Oct 27, 2020 at 04:01 AM
-- Server version: 10.4.14-MariaDB
-- PHP Version: 7.4.10
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `mercury`
--
-- --------------------------------------------------------
--
-- Table structure for table `makanan`
--
CREATE TABLE `makanan` (
`ID_Makanan` int(3) NOT NULL,
`Nama_Makanan` varchar(35) NOT NULL,
`Harga` int(7) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `makanan`
--
INSERT INTO `makanan` (`ID_Makanan`, `Nama_Makanan`, `Harga`) VALUES
(11, '<NAME>', 10000),
(12, '<NAME>', 11000),
(13, '<NAME>', 11000),
(14, '<NAME>', 11000),
(15, '<NAME>', 5000),
(16, '<NAME>', 5000),
(17, 'Waffle', 7000),
(18, '<NAME>', 8000),
(19, 'Indomie ', 3500),
(20, 'Indomie Double', 7000),
(21, '<NAME>', 12000),
(22, 'Americano', 10000),
(23, 'Moccacino', 15000),
(24, 'Espresso', 10000),
(25, 'Flat White', 15000),
(26, 'Cafe Latte', 12000),
(27, 'Vanilla Latte', 15000),
(28, 'Virgin Mojito', 20000),
(29, 'Dalgona Coffee', 16000),
(30, 'Soda Gembira', 8000);
-- --------------------------------------------------------
--
-- Table structure for table `transaksi`
--
CREATE TABLE `transaksi` (
`ID_Transaksi` int(3) NOT NULL,
`ID_Makanan` int(3) NOT NULL,
`Jumlah` int(3) NOT NULL,
`Total_Harga` int(10) NOT NULL,
`Tanggal` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `transaksi`
--
INSERT INTO `transaksi` (`ID_Transaksi`, `ID_Makanan`, `Jumlah`, `Total_Harga`, `Tanggal`) VALUES
(1, 11, 2, 20000, '2019-08-15 12:31:46'),
(2, 12, 2, 22000, '2020-10-26 12:32:44'),
(3, 11, 2, 30000, '2020-10-26 12:51:33'),
(4, 11, 2, 20000, '2018-04-19 02:16:57'),
(5, 13, 2, 22000, '2018-05-24 16:16:57'),
(6, 13, 2, 22000, '2020-08-26 02:26:28');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `makanan`
--
ALTER TABLE `makanan`
ADD PRIMARY KEY (`ID_Makanan`);
--
-- Indexes for table `transaksi`
--
ALTER TABLE `transaksi`
ADD PRIMARY KEY (`ID_Transaksi`),
ADD KEY `ID_Makanan` (`ID_Makanan`),
ADD KEY `ID_Makanan_2` (`ID_Makanan`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `makanan`
--
ALTER TABLE `makanan`
MODIFY `ID_Makanan` int(3) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=31;
--
-- AUTO_INCREMENT for table `transaksi`
--
ALTER TABLE `transaksi`
MODIFY `ID_Transaksi` int(3) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=45;
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 */;
| 1405697fb2ff173ed3ca2258701d33869bce88dc | [
"SQL"
] | 1 | SQL | DeMrTypo/RestaurantService-Using-HibernateORM | 9e8d1647c4cbc6b2d9116dbfb58494faa45c0ba4 | 5b912a5c379496ea406116cf0e9abe5b3f026caa |
refs/heads/main | <repo_name>jyotiiiii/passing-props<file_sep>/src/App.js
import { useState } from 'react';
import GraphContainer from './GraphContainer';
import './App.css';
import Table from './Table';
import InfoPanel from './InfoPanel';
const students = {
nodes: [
{ id: 1, name: 'Wasif', age: 21, email: '<EMAIL>' },
{ id: 2, name: 'Ali', age: 19, email: '<EMAIL>' },
{ id: 3, name: 'Saad', age: 16, email: '<EMAIL>' },
{ id: 4, name: 'Asad', age: 25, email: '<EMAIL>' }
],
links: [
{ source: 1, target: 2 },
{ source: 1, target: 3 },
{ source: 1, target: 4 }
]
};
function App() {
const [tableRowIdHighlighted, setTableRowIdHighlighted] = useState(
undefined
);
const onNodeMouseOut = () => {
setTableRowIdHighlighted(undefined);
};
const onNodeMouseOver = (nodeId) => {
setTableRowIdHighlighted(String(nodeId))
}
const student = students.nodes.find(element => String(element.id) === tableRowIdHighlighted)
const studentsWithColorInformation = {
...students,
nodes: students.nodes.map(student => {
if (
String(student.id) === tableRowIdHighlighted
) {
return {
...student,
color: 'black'
}
} else {
return student
}
}),
}
return (
<div className='App'>
<GraphContainer
data={studentsWithColorInformation}
onNodeMouseOver={onNodeMouseOver}
onNodeMouseOut={onNodeMouseOut}
/>
<InfoPanel student={student} />
<Table
data={students.nodes}
onNodeMouseOver={onNodeMouseOver}
onNodeMouseOut={onNodeMouseOut}
tableRowIdHighlighted={tableRowIdHighlighted}
/>
</div>
);
}
export default App;
<file_sep>/src/Table.js
import './Table.css';
const Table = ({ data, tableRowIdHighlighted, onNodeMouseOver, onNodeMouseOut }) => {
const header = Object.keys(data[0]);
return (
<div>
<h1 className='title'>All data</h1>
<table className='students'>
<tbody>
<tr>
{header.map((key, index) => (
<th key={index}>{key.toUpperCase()}</th>
))}
</tr>
{data.map((student, index) => {
// Work out which row is activated based on the id
const isThisStudentHighlighted = String(student.id) === tableRowIdHighlighted;
const onMouseOver = () => {
onNodeMouseOver(student.id)
}
return (
<tr id={isThisStudentHighlighted ? "highlighted" : ""} key={student.id}
onMouseOver={onMouseOver} onMouseOut={onNodeMouseOut}
>
<td>{student.id}</td>
<td>{student.name}</td>
<td>{student.age}</td>
<td>{student.email}</td>
</tr>
);
})}
</tbody>
</table>
</div>
);
};
export default Table;
<file_sep>/src/InfoPanel.js
import './InfoPanel.css';
const InfoPanel = ({ student }) => {
return (
<div>
<table className='info'>
<tbody>
<tr>
<th>Information</th>
</tr>
<tr>{student?.id}</tr>
<tr>{student?.name}</tr>
<tr>{student?.age}</tr>
<tr>{student?.email}</tr>
</tbody>
</table>
</div>
);
};
export default InfoPanel;
| 50b51c07c417ed5e0853780943c09c4d6816d9bc | [
"JavaScript"
] | 3 | JavaScript | jyotiiiii/passing-props | 758f8bfa8c5c8c591172c27f5e03383771a8fb98 | d65691ee22a5dcdb3ea377309ed88fdfda42678e |
refs/heads/main | <file_sep>//
// CreateViewController.swift
// morta
//
// Created by unkonow on 2020/10/24.
//
import UIKit
import Loaf
import RealmSwift
class CreateViewController: UIViewController {
var delegrate: UIViewController!
var mode: ModeType!
var routineItem:RoutineItem!
@IBOutlet weak var textField: UITextField!
@IBOutlet weak var navigationBarItem: UINavigationItem!
@IBOutlet weak var deleteBtn: UIButton!
// @IBOutlet weak var deleteBtnConstraint: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
switch mode {
case .create:
navigationBarItem.title = "ルーティーン作成"
deleteBtn.isEnabled = false
deleteBtn.tintColor = .darkGray
deleteBtn.frame = CGRect(x: 0, y: 0, width: 0, height: 0)
// deleteBtnConstraint.constant = 0
case .edit:
navigationBarItem.title = "ルーティーン編集"
deleteBtn.isEnabled = true
deleteBtn.tintColor = .red
// deleteBtnConstraint.constant = 32
textField.text = routineItem.title
case .none: break
}
self.textField.becomeFirstResponder()
}
enum ModeType{
case create
case edit
}
@IBAction func delete(){
let alert: UIAlertController = UIAlertController(title: "消去", message: "ルーティーンを消去してもいいですか?", preferredStyle: UIAlertController.Style.alert)
let defaultAction: UIAlertAction = UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler:{
(action: UIAlertAction!) -> Void in
let realm = try! Realm()
let routineItemIndex = self.routineItem.index
try! realm.write{
realm.delete(self.routineItem)
}
let routine = realm.objects(RoutineItem.self)
print(routine)
guard let routineLast = routine.sorted(byKeyPath: "index", ascending: true).last else {
self.deletedDialogDismiss()
return
}
if (routineLast.index + 1) == routineItemIndex{
self.deletedDialogDismiss()
return
}else{
try! realm.write({
for index in routineItemIndex...routineLast.index - 1{
routine[index - 1].index -= 1
}
})
}
self.dismiss(animated: true, completion: nil)
(self.delegrate as! HomeViewController).routineView.reloadData()
Loaf("消去しました!", state: .success, sender: self.delegrate).show(.short)
})
let cancelAction: UIAlertAction = UIAlertAction(title: "キャンセル", style: UIAlertAction.Style.cancel, handler:{
(action: UIAlertAction!) -> Void in
})
alert.addAction(cancelAction)
alert.addAction(defaultAction)
present(alert, animated: true, completion: nil)
}
func deletedDialogDismiss(){
self.dismiss(animated: true, completion: nil)
(self.delegrate as! HomeViewController).routineView.reloadData()
Loaf("消去しました!", state: .success, sender: self.delegrate).show(.short)
}
@IBAction func cancel(){
self.dismiss(animated: true, completion: nil)
}
@IBAction func done(){
if textField.text == ""{
Loaf("1文字以上入力してください",state: .error, location: .top, sender: self).show(.custom(0.8))
}else{
var sucsessMsg = ""
switch mode {
case .create:
create()
sucsessMsg = "追加しました!"
case .edit:
if textField.text == routineItem.title{
self.dismiss(animated: true, completion: nil)
return
}
update()
sucsessMsg = "アップデートしました!"
default:
break
}
self.dismiss(animated: true, completion: nil)
(delegrate as! HomeViewController).routineView.reloadData()
Loaf(sucsessMsg, state: .success, sender: delegrate).show(.short)
}
}
func update(){
let realm = try! Realm()
try! realm.write({
routineItem.title = textField.text!
})
}
func create(){
let realm = try! Realm()
let lastIndex = realm.objects(RoutineItem.self).sorted(byKeyPath: "index", ascending: true).last?.index
let ri = RoutineItem()
ri.title = textField.text!
ri.index = (lastIndex ?? 0) + 1
try! realm.write({
realm.add(ri)
})
}
}
<file_sep>//
// RoutineItem.swift
// morta
//
// Created by unkonow on 2020/10/25.
//
import Foundation
import RealmSwift
class RoutineItem: Object{
@objc dynamic var title: String? = ""
@objc dynamic var index = 100
}
<file_sep>//
// HomeViewController.swift
// morta
//
// Created by unkonow on 2020/10/24.
//
import UIKit
import RealmSwift
import Loaf
import LSDialogViewController
class HomeViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var delegrate: UIViewController!
private var routine:Results<RoutineItem>!
private var realm:Realm!
private var timeLimitTextField: UITextField!
private var datePicker: UIDatePicker!
private var demoMode = false
@IBOutlet weak var routineView: UITableView!
@IBOutlet weak var aleartLabel: UILabel!
@IBOutlet weak var getupLabel: UILabel!
@IBOutlet weak var homeLabel: UILabel!
@IBOutlet weak var routineLabel: UILabel!
@IBOutlet weak var resumeButton: UIButton!
@IBOutlet weak var aleartSwitch: UISwitch!
override func viewDidLoad() {
super.viewDidLoad()
realm = try! Realm()
//
// for i in 1...10{
// let item = RoutineItem()
// item.title = "hey!" + String(i)
// item.index = i
// try! realm.write({
// realm.add(item)
// })
// }
aleartSwitch.isHidden = true
routine = realm.objects(RoutineItem.self)
self.view.backgroundColor = .backgroundColor
self.routineView.backgroundColor = .white
self.routineView.layer.cornerRadius = 13
aleartLabel.textColor = .tabbarColor
getupLabel.textColor = .tabbarColor
homeLabel.textColor = .tabbarColor
routineLabel.textColor = .textColor
routineView.backgroundColor = .backgroundSubColor
let nib = UINib(nibName: "RoutineTableViewCell", bundle: nil)
routineView.register(nib, forCellReuseIdentifier: "cell")
routineView.delegate = self
routineView.dataSource = self
routineView.allowsSelection = false
routineView.separatorStyle = .none
let footerCell: UITableViewCell = routineView.dequeueReusableCell(withIdentifier: "tableFooterCell")!
let footerView: UIView = footerCell.contentView
routineView.tableFooterView = footerView
let headerCell: UITableViewCell = routineView.dequeueReusableCell(withIdentifier: "tableHeaderCell")!
let headerView: UIView = headerCell.contentView
routineView.tableHeaderView = headerView
let isSwitch = UserDefaults.standard.bool(forKey: "isAleartSwitch")
switchChange(bool: isSwitch)
routineView.isEditing = true
// let isBeenHome = UserDefaults.standard.bool(forKey: "isBeenHome")
let isBeenTutorial = UserDefaults.standard.bool(forKey: "isBeenTutorial")
if isBeenTutorial {
// if !isBeenHome{
// UserDefaults.standard.set(true, forKey: "isBeenHome")
// }
} else {
self.fst()
demoMode = true
// let vc = self.storyboard?.instantiateViewController(withIdentifier: "TutorialViewController") as? TutorialViewController
// vc?.modalPresentationStyle = .overFullScreen
// self.present(vc!, animated: true, completion: nil)
UserDefaults.standard.set(true, forKey: "isBeenTutorial")
}
}
func fst(){
createRoutine(title: "起床", index: 1)
createRoutine(title: "歯を磨く", index: 2)
createRoutine(title: "朝ごはんを食べる", index: 3)
}
private func createRoutine(title:String, index: Int){
let realm = try! Realm()
let ri = RoutineItem()
ri.title = title
ri.index = index
try! realm.write({
realm.add(ri)
})
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
(self.view.viewWithTag(2525))?.removeFromSuperview()
var aramTime = UserDefaults.standard.integer(forKey: "ararmTime")
if aramTime == nil {
let calendar = Calendar(identifier: .gregorian)
var aramClock = calendar.dateComponents([.year, .month, .day, .hour, .minute, .second], from: Date())
aramClock.minute! = 0
aramClock.hour! = 6
UserDefaults.standard.set(calendar.date(from: aramClock)?.timeIntervalSince1970, forKey: "ararmTime")
aramTime = Int(calendar.date(from: aramClock)!.timeIntervalSince1970)
}
let calendar = Calendar.current
let date = Date(timeIntervalSince1970: TimeInterval(aramTime))
let hour = calendar.component(.hour, from: date)
let min = calendar.component(.minute, from: date)
aleartLabel.text = String(hour).leftPadding(toLength: 2, withPad: "0") + ":" + String(min).leftPadding(toLength: 2, withPad: "0")
let isSuspension = UserDefaults.standard.bool(forKey: "isSuspension")
if !isSuspension{
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
self.resume()
}
UserDefaults.standard.set(true, forKey: "isSuspension")
}
let now = calendar.dateComponents([.hour, .minute, .second], from: Date())
let diff = calendar.dateComponents([.second], from: now, to: Calendar.current.dateComponents(in: TimeZone.current, from: date))
if now.hour! == hour{
if now.minute! > min{
demoMode = false
resumeButton.setTitle("再開する", for: .normal)
}
}else if now.hour! > hour{
demoMode = false
resumeButton.setTitle("再開する", for: .normal)
}else{
resumeButton.setTitle("デモ", for: .normal)
demoMode = true
}
let today = calendar.component(.day, from: Date())
let lastdate = realm.objects(Ranking.self).sorted(byKeyPath: "date", ascending: true).last?.date
if lastdate != nil{
let lastday = calendar.component(.day, from:lastdate!)
if lastday == today{
demoMode = true
resumeButton.setTitle("デモ", for: .normal)
}
}
}
@IBAction func edit(){
let vc = storyboard?.instantiateViewController(withIdentifier: "TimePickerViewController") as! TimePickerViewController
// vc.modalTransitionStyle = .coverVertical
vc.modalPresentationStyle = .overFullScreen
vc.deleglate = self
let backView = UIView()
backView.frame = CGRect(x: 0, y: -100, width: self.view.frame.width, height: 10000)
backView.backgroundColor = UIColor(hex: "000000", alpha: 0.3)
backView.tag = 2525
self.view.addSubview(backView)
self.present(vc, animated: true, completion: nil)
// self.presentDialogViewController(vc, animationParttern: .slideBottomBottom, completion: { () -> Void in })
}
@IBAction func resume(){
let vc = self.storyboard?.instantiateViewController(withIdentifier: "RTAViewController") as? RTAViewController
vc?.modalPresentationStyle = .overFullScreen
vc?.isDEMO = demoMode
self.present(vc!, animated: true, completion: nil)
}
@IBAction func create(){
// delegrate.performSegue(withIdentifier: "toCreate", sender: nil)
let vc = storyboard?.instantiateViewController(withIdentifier: "CreateViewController") as? CreateViewController
vc?.delegrate = self
vc?.mode = .create
self.present(vc!, animated: true, completion: nil)
}
@IBAction func switchChanged(_ sender: UISwitch) {
switchChange(bool: sender.isOn)
}
func switchChange(bool:Bool){
aleartSwitch.isOn = bool
UserDefaults.standard.set(bool, forKey: "isAleartSwitch")
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.routine.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = routineView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! RoutineTableViewCell
cell.indexPath = indexPath
cell.indexLabel.text = String(indexPath.row + 1) + "."
cell.titleLabel.text = self.routine.filter("index == \(indexPath.row + 1)")[0].title
cell.editBtn.addTarget(self,action: #selector(self.cellClicked(_ :)),for: .touchUpInside)
cell.editBtn.tag = indexPath.row + 1
return cell
}
@objc func cellClicked(_ sender: UIButton){
print(sender.tag)
let vc = storyboard?.instantiateViewController(withIdentifier: "CreateViewController") as? CreateViewController
vc?.delegrate = self
vc?.mode = .edit
vc?.routineItem = self.routine.filter("index == \(sender.tag)")[0]
self.present(vc!, animated: true, completion: nil)
}
func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
return .none
}
func tableView(_ tableView: UITableView, shouldIndentWhileEditingRowAt indexPath: IndexPath) -> Bool {
return false
}
func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
return true
}
func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
if sourceIndexPath == destinationIndexPath{
return
}
try! realm.write {
let sourceObject = self.routine.filter("index == \(sourceIndexPath.row + 1)")[0]
let destinationObject = self.routine.filter("index == \(destinationIndexPath.row + 1)")[0]
print(sourceObject)
print(destinationObject)
let destinationObjectOrder = destinationObject.index
if sourceIndexPath.row < destinationIndexPath.row {
// up2down
print(sourceIndexPath.row...destinationIndexPath.row )
for index in sourceIndexPath.row...destinationIndexPath.row {
let object = self.routine.filter("index == \(index + 1)")[0]
object.index -= 1
}
} else {
// down2up
for index in (destinationIndexPath.row..<sourceIndexPath.row).reversed() {
let object = self.routine.filter("index == \(index + 1)")
print(index,object)
object[0].index += 1
}
}
sourceObject.index = destinationObjectOrder
tableView.reloadData()
}
}
}
<file_sep>//
// TutorialViewController.swift
// morta
//
// Created by unkonow on 2020/11/03.
//
import UIKit
import Lottie
class TutorialViewController: UIViewController {
@IBOutlet weak var backView: UIView!
private var backAnimationView: AnimationView!
override func viewDidLoad() {
super.viewDidLoad()
// backView.isHidden = true
self.backViewChange(name: "blueBackView")
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
self.backViewChange(name: "orangeBackView")
}
}
func backViewChange(name:String){
backView.subviews.forEach{$0.removeFromSuperview()}
backAnimationView = AnimationView(name: name)
backAnimationView.frame = self.view.frame
backAnimationView.loopMode = .loop
backAnimationView.contentMode = .scaleAspectFit
backAnimationView.animationSpeed = 0.2
backAnimationView.play()
self.backView.addSubview(backAnimationView)
}
}
<file_sep>//
// AramStatus.swift
// morta
//
// Created by unkonow on 2020/10/30.
//
import Foundation
public enum AramStatusType: String{
case end = "end"
case stop = "stop"
}
<file_sep>//
// Ranking.swift
// morta
//
// Created by unkonow on 2020/11/03.
//
import Foundation
import RealmSwift
class Ranking: Object{
@objc dynamic var date: Date? = Date()
@objc dynamic var time: Int = 0
dynamic var routineList = List<RoutineItem>()
}
<file_sep>//
// ViewController.swift
// morta
//
// Created by unkonow on 2020/10/24.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var fragmentView: UIView!
@IBOutlet weak var tabbar: UIView!
@IBOutlet weak var homeBtn: UIButton!
@IBOutlet weak var rankingBtn: UIButton!
private var nowFragmentsType: FragmentsType!
private var homeVC: HomeViewController!
private var rankingVC: RankingViewController!
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .backgroundColor
// let appDelegate:AppDelegate = UIApplication.shared.delegate as! AppDelegate
// appDelegate.baseVC = self
tabbar.backgroundColor = .tabbarColor
tabbar.layer.cornerRadius = 17
homeBtn.imageView?.frame.size = CGSize(width: 20, height: 20)
homeVC = storyboard?.instantiateViewController(withIdentifier: "HomeViewController") as? HomeViewController
homeVC.delegrate = self
rankingVC = storyboard?.instantiateViewController(withIdentifier: "RankingViewController") as? RankingViewController
fragmentsChange(type: .home)
}
enum FragmentsType {
case home
case ranking
}
func fragmentsChange(type: FragmentsType){
if nowFragmentsType == type{
return
}else{
switch type {
case .home:
homeBtn.setBackgroundImage(UIImage(named: "homeIcon"), for: .normal)
rankingBtn.setBackgroundImage(UIImage(named: "listIconDisable"), for: .normal)
remove(viewController: rankingVC)
add(viewController: homeVC)
case .ranking:
homeBtn.setBackgroundImage(UIImage(named: "homeIconDisable"), for: .normal)
rankingBtn.setBackgroundImage(UIImage(named: "listIcon"), for: .normal)
remove(viewController: homeVC)
add(viewController: rankingVC)
default:return
}
nowFragmentsType = type
}
}
@IBAction func home(){
fragmentsChange(type: .home)
}
@IBAction func ranking(){
fragmentsChange(type: .ranking)
}
// MARK: - Child VC Operation Methods
private func add(viewController: UIViewController) {
// addChild(viewController)
// view.addSubview(viewController.view)
fragmentView.addSubview(viewController.view)
// viewController.view.frame = view.bounds
viewController.view.frame.size = fragmentView.frame.size
viewController.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
viewController.didMove(toParent: self)
}
private func remove(viewController: UIViewController) {
viewController.willMove(toParent: nil)
viewController.view.removeFromSuperview()
viewController.removeFromParent()
}
}
<file_sep>//
// RankingItem.swift
// morta
//
// Created by unkonow on 2020/11/03.
//
import Foundation
<file_sep>//
// RoutineTableViewCell.swift
// morta
//
// Created by unkonow on 2020/10/24.
//
import UIKit
class RoutineTableViewCell: UITableViewCell {
var indexPath:IndexPath?
@IBOutlet weak var indexLabel: UILabel!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var editBtn: UIButton!
override func awakeFromNib() {
super.awakeFromNib()
titleLabel.textColor = .textColor
indexLabel.textColor = .textColor
self.backgroundColor = .backgroundSubColor
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
<file_sep>//
// UIColor+.swift
// morta
//
// Created by unkonow on 2020/10/24.
//
import Foundation
import UIKit
extension UIColor{
static let backgroundColor = ldColor(light: UIColor(hex: "#F0F0F0"), dark: UIColor(hex: "#252E40"))
static let backgroundSubColor = ldColor(light: UIColor(hex: "#FFFFFF"), dark: UIColor(hex: "#313B50"))
static let clockBackgroundColor = ldColor(light: UIColor(hex: "#DDDDDD"), dark: UIColor(hex: "232B3B"))
static let tabbarColor = ldColor(light: UIColor(hex: "#1AC0C6"), dark: UIColor(hex: "#1AC0C6"))
static let textColor = ldColor(light: UIColor(hex: "#134E6F"), dark: UIColor(hex: "#dee0e6"))
static func ldColor(light:UIColor,dark:UIColor) -> UIColor{
if #available(iOS 13.0, *) {
return UIColor { (traits) -> UIColor in
return traits.userInterfaceStyle == .dark ?
dark:
light
}
}else{
return light
}
}
}
<file_sep># Morta(モルタ)
**冬の寒い時期、目は覚めるけど布団から出れないあなたへ。**
Morning Routine RTA.
<img src="https://i.imgur.com/Fsp7AKn.png" height=500 />
<img src="https://i.imgur.com/9FniYCD.png" height=500 />
<img src="https://i.imgur.com/jms4JH6.png" height=500 />
<img src="https://i.imgur.com/eJ4TCpz.png" height=500 />
<file_sep>//
// ExistsAlertViewController.swift
// morta
//
// Created by unkonow on 2020/11/03.
//
import UIKit
class ExistsAlertViewController: UIViewController {
var delegate: RTAViewController!
@IBOutlet weak var backView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
backView.backgroundColor = .backgroundColor
backView.layer.cornerRadius = 15
}
@IBAction func exit(){
delegate.dismissDialog()
}
}
<file_sep>//
// TimePickerViewController.swift
// morta
//
// Created by unkonow on 2020/11/02.
//
import UIKit
import Loaf
class TimePickerViewController: UIViewController, UIAdaptivePresentationControllerDelegate {
@IBOutlet weak var backView: UIView!
@IBOutlet weak var pickerView: UIDatePicker!
var deleglate: HomeViewController!
override func viewDidLoad() {
super.viewDidLoad()
self.backView.backgroundColor = .backgroundColor
self.backView.layer.cornerRadius = 13
self.view.backgroundColor = .none
let unixtime: TimeInterval = TimeInterval(UserDefaults.standard.integer(forKey: "ararmTime"))
let date = Date(timeIntervalSince1970: unixtime)
self.pickerView.date = date
}
func presentationControllerDidAttemptToDismiss(_ presentationController: UIPresentationController) {
dismiss(animated: true)
}
@IBAction func done(){
UserDefaults.standard.set(Int(pickerView.date.timeIntervalSince1970), forKey: "ararmTime")
self.dismissCalled()
}
@IBAction func cancel(){
self.dismissCalled()
}
func dismissCalled(){
self.dismiss(animated: true, completion: nil)
deleglate.viewWillAppear(true)
}
}
<file_sep>//
// RTAItem.swift
// morta
//
// Created by unkonow on 2020/10/27.
//
import UIKit
import Lottie
class RTAItem: UIView {
@IBOutlet weak var checkBoxView: UIView!
@IBOutlet weak var topLineView: UIView!
@IBOutlet weak var bottomLineView: UIView!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var timerLabel: UILabel!
private var nocheckView: UIImageView!
private var animationView: AnimationView!
private var isChecked = false
var positionType:PositionType!
convenience init(position: PositionType) {
self.init(frame: CGRect.zero)
self.positionType = position
switch positionType {
case .top:
topLineView.isHidden = true
topLineView.backgroundColor = .red
case .bottom:
bottomLineView.isHidden = true
case .content:
break
case .alone:
topLineView.isHidden = true
bottomLineView.isHidden = true
case .none:
break
}
}
override init(frame: CGRect) {
super.init(frame: frame)
loadNib()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
loadNib()
}
func checkAnimation(){
if isChecked{
return
}
isChecked = true
DispatchQueue.main.asyncAfter(deadline: .now() + 0.7) {
self.nocheckView.removeFromSuperview()
}
self.animationView.play{ finished in
if finished{
print("finished")
}
}
}
func back(){
reset()
}
func reset(){
for subview in checkBoxView.subviews{
subview.removeFromSuperview()
}
timerLabel.isHidden = true
isChecked = false
checkBoxView.backgroundColor = .none
titleLabel.textColor = .textColor
animationView = AnimationView(name: "check-animation")
animationView.frame = CGRect(x: 0, y: 0, width: checkBoxView.bounds.width, height: checkBoxView.bounds.height)
animationView.loopMode = .playOnce
animationView.contentMode = .scaleAspectFit
animationView.animationSpeed = 1.5
nocheckView = UIImageView(image: UIImage(named: "no-check"))
nocheckView.frame = CGRect(x: 0, y: 0, width: checkBoxView.bounds.width, height: checkBoxView.bounds.height)
nocheckView.contentMode = .scaleAspectFill
checkBoxView.addSubview(nocheckView)
checkBoxView.addSubview(animationView)
}
enum PositionType {
case top
case content
case bottom
case alone
}
func loadNib() {
if let view = Bundle(for: type(of: self)).loadNibNamed(String(describing: type(of: self)), owner: self, options: nil)?.first as? UIView {
view.frame = self.bounds
view.backgroundColor = .none
reset()
self.addSubview(view)
}
}
}
<file_sep>//
// RankingViewController.swift
// morta
//
// Created by unkonow on 2020/10/24.
//
import UIKit
import SwiftyMenu
import RealmSwift
class RankingViewController: UIViewController, SwiftyMenuDelegate, UITableViewDelegate, UITableViewDataSource {
let sortItems: [SwiftyMenuDisplayable] = [SortType.new.rawValue, SortType.rank.rawValue]
var realm:Realm!
var rankings: Results<Ranking>!
private var sortType:SortType = .new
@IBOutlet private weak var dropDownMenu: SwiftyMenu!
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var rankingLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .backgroundColor
rankingLabel.textColor = .tabbarColor
realm = try! Realm()
switch sortType {
case .new:
rankings = realm.objects(Ranking.self).sorted(byKeyPath: "date", ascending: true)
case .rank:
rankings = realm.objects(Ranking.self).sorted(byKeyPath: "time", ascending: true)
default:break
}
dropDownMenu.delegate = self
dropDownMenu.items = sortItems
dropDownMenu.selectedIndex = 0
dropDownMenu.placeHolderText = SortType.new.rawValue
tableView.backgroundColor = .backgroundSubColor
tableView.separatorStyle = .none
tableView.layer.cornerRadius = 15
tableView.delegate = self
tableView.dataSource = self
let nib = UINib(nibName: "RankingTableViewCell", bundle: nil)
tableView.register(nib, forCellReuseIdentifier: "cell")
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
tableView.reloadData()
}
enum SortType:String {
case new = "新規順"
case rank = "ランク順"
}
func swiftyMenu(_ swiftyMenu: SwiftyMenu, didSelectItem item: SwiftyMenuDisplayable, atIndex index: Int) {
sortType = SortType(rawValue: String(sortItems[index].displayableValue))!
switch sortType {
case .new:
rankings = realm.objects(Ranking.self).sorted(byKeyPath: "date", ascending: true)
case .rank:
rankings = realm.objects(Ranking.self).sorted(byKeyPath: "time", ascending: true)
default:break
}
tableView.reloadData()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return rankings.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! RankingTableViewCell
cell.dateLabel.text = date2String(rankings[indexPath.row].date!)
let (h,m,s) = seconds2HMS(seconds: rankings[indexPath.row].time)
cell.timeLabel.text = String(h) + "時間" + String(m) + "分" + String(s) + "秒"
cell.backgroundColor = .backgroundSubColor
cell.rankView.backgroundColor = .none
cell.timeLabel.textColor = .textColor
cell.timeLabel.textColor = .textColor
let rank = realm.objects(Ranking.self).sorted(byKeyPath: "time", ascending: true).index(of: rankings[indexPath.row])!
cell.rankView.subviews.forEach({$0.removeFromSuperview()})
if rank < 3{
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: cell.rankView.frame.width, height: cell.rankView.frame.height))
imageView.image = UIImage(named: "rank\(rank + 1)")
cell.rankView.addSubview(imageView)
}else{
let label = UILabel(frame: CGRect(x: 0, y: 0, width: cell.rankView.frame.width, height: cell.rankView.frame.height))
label.text = String(rank + 1)
label.textAlignment = .center
cell.rankView.addSubview(label)
}
return cell
}
func date2String(_ date:Date) -> String{
let f = DateFormatter()
f.dateFormat = "MM月dd日"
return f.string(from: date)
}
func seconds2HMS(seconds : Int) -> (Int, Int, Int) {
return (seconds / 3600, (seconds % 3600) / 60, (seconds % 3600) % 60)
}
}
extension String: SwiftyMenuDisplayable {
public var retrievableValue: Any {
return self
}
public var displayableValue: String {
return self
}
public var retrivableValue: Any {
return self
}
}
<file_sep>//
// RTAViewController.swift
// morta
//
// Created by unkonow on 2020/10/26.
//
import UIKit
import AudioToolbox
import RealmSwift
class RTAViewController: UIViewController {
@IBOutlet weak var clockBackView: UIView!
@IBOutlet weak var clockLabel: UILabel!
@IBOutlet weak var rtaScrollView: UIScrollView!
@IBOutlet weak var suspensionLabel: UIButton!
@IBOutlet weak var gestureImageView: UIImageView!
@IBOutlet weak var guestureBackView: UIView!
private var rtaIndex = -1
private var rtaItems:[RTAItem] = []
private var isMoving = false
private var routines: Results<RoutineItem>!
private var gestureType: GestureType = .yet
private var aramClock: DateComponents!
private var calendar: Calendar!
private var elapsedTime: String = ""
private var timer: Timer!
var isDEMO: Bool = false
private var startDate: DateComponents!
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .backgroundColor
self.rtaScrollView.backgroundColor = .backgroundSubColor
self.rtaScrollView.layer.cornerRadius = 15
self.clockBackView.backgroundColor = .clockBackgroundColor
self.clockBackView.layer.cornerRadius = 15
self.clockLabel.textColor = .textColor
self.guestureBackView.backgroundColor = .none
calendar = Calendar.current
let aramTime = UserDefaults.standard.integer(forKey: "ararmTime")
let date = Date(timeIntervalSince1970: TimeInterval(aramTime))
aramClock = Calendar.current.dateComponents(in: TimeZone.current, from: date)
clockLabel.text = "Loading..."
startDate = calendar.dateComponents([.year, .month, .day, .hour, .minute, .second], from: Date())
let realm = try! Realm()
routines = realm.objects(RoutineItem.self).sorted(byKeyPath: "index", ascending: true)
let lastindex = routines.last?.index
let today = calendar.component(.day, from: Date())
let lastdate = realm.objects(Ranking.self).sorted(byKeyPath: "date", ascending: true).last?.date
if lastdate != nil{
let lastday = calendar.component(.day, from:lastdate!)
if lastday == today{
let vc = storyboard?.instantiateViewController(withIdentifier: "ExistsAlertViewController") as! ExistsAlertViewController
vc.modalPresentationStyle = .overFullScreen
vc.delegate = self
self.presentDialogViewController(vc, animationPattern: .fadeInOut, completion: { () -> Void in })
}
}
for item in routines{
var positionType:RTAItem.PositionType!
if item.index == 1{
if item.index == lastindex{
positionType = .alone
}else{
positionType = .top
}
}else if item.index == lastindex{
positionType = .bottom
}else{
positionType = .content
}
let view2 = RTAItem(position: positionType)
view2.titleLabel.text = item.title
view2.frame = CGRect(x: 0, y: 60*(item.index - 1), width: Int(self.rtaScrollView.frame.width - 30), height: 60)
self.rtaScrollView.addSubview(view2)
rtaItems.append(view2)
}
rtaScrollView.contentSize = CGSize(width: 30, height: 60 * (routines.last?.index ?? 0))
rtaScrollView.showsHorizontalScrollIndicator = false
start()
}
enum GestureType {
case next
case back
case yet
}
override func touchesBegan(_ touches: Set<UITouch>,with event: UIEvent?){
if touchedView(touches: touches, view: guestureBackView){
isMoving = true
return
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
if isMoving{
let x = touches.first?.location(in: guestureBackView).x
let scWidth = UIScreen.main.bounds.size.width
if x! > scWidth - 130{
if x! > scWidth - 100{
return
}
if case .next = gestureType{}else{
AudioServicesPlaySystemSound( 1519 )
gestureType = .next
gestureImageView.image = UIImage(named: "gestureIconNext")
}
}else if x! < 130{
if x! < 70{
return
}
if case .back = gestureType{}else{
AudioServicesPlaySystemSound( 1519 )
gestureType = .back
gestureImageView.image = UIImage(named: "gestureIconBack")
}
}
else{
if case .yet = gestureType{}else{
gestureImageView.image = UIImage(named: "gestureIcon")
gestureType = .yet
}
}
gestureImageView.center.x = x!
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
if isMoving{
switch gestureType {
case .next:
UIView.animate(withDuration: 0.3, delay: 0.3, options: .curveEaseInOut, animations: {
self.gestureImageView.center.x = self.view.center.x
}, completion: {finished in
self.gestureImageView.image = UIImage(named: "gestureIcon")
self.isMoving = false
})
next()
case .back:
UIView.animate(withDuration: 0.3, delay: 0.3, options: .curveEaseInOut, animations: {
self.gestureImageView.center.x = self.view.center.x
}, completion: {finished in
self.gestureImageView.image = UIImage(named: "gestureIcon")
self.isMoving = false
})
back()
case .yet:
UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseInOut, animations: {
self.gestureImageView.center.x = self.view.center.x
}, completion: {finished in
self.gestureImageView.image = UIImage(named: "gestureIcon")
self.isMoving = false
})
}
}
}
func next(){
if rtaIndex >= rtaItems.count - 1{
AudioServicesPlaySystemSound( 1102 )
}else{
AudioServicesPlaySystemSound( 1519 )
self.rtaIndex += 1
print("rtaindex",self.rtaIndex)
let rtaItem = rtaItems[self.rtaIndex]
rtaItem.checkAnimation()
rtaItem.timerLabel.text = elapsedTime
rtaItem.timerLabel.isHidden = false
if rtaIndex == (routines.last!.index - 1){
print("LAST")
end()
}
nowIndexCenter(index: self.rtaIndex)
}
}
func back(){
if rtaIndex < 0{
AudioServicesPlaySystemSound( 1102 )
}else{
AudioServicesPlaySystemSound( 1519 )
rtaItems[self.rtaIndex].back()
nowIndexCenter(index: self.rtaIndex)
self.rtaIndex -= 1
}
}
func start(){
print("=========START============")
timer = Timer(timeInterval: 1,
target: self,
selector: #selector(timeCheck),
userInfo: nil,
repeats: true)
RunLoop.main.add(timer, forMode: .default)
}
func stop(){
}
func end(){
if isDEMO{
let vc = storyboard?.instantiateViewController(withIdentifier: "ResultViewController") as! ResultViewController
vc.modalPresentationStyle = .overFullScreen
vc.delegate = self
self.presentDialogViewController(vc, animationPattern: .fadeInOut, completion: { () -> Void in })
vc.timeLabel.text = elapsedTime
vc.rankingLabel.text = "デモ"
}else{
let realm = try! Realm()
let ranking = Ranking()
ranking.date = Date()
routines.forEach{ranking.routineList.append($0)}
var now = calendar.dateComponents([.year, .month, .day, .hour, .minute, .second], from: Date())
now.year = aramClock.year
now.month = aramClock.month
now.day = aramClock.day
let diff = calendar.dateComponents([.second], from: self.aramClock, to: now)
ranking.time = Int(diff.second!)
try! realm.write({
realm.add(ranking)
})
let rank = realm.objects(Ranking.self).filter("time < \(ranking.time)").count + 1
let vc = storyboard?.instantiateViewController(withIdentifier: "ResultViewController") as! ResultViewController
vc.modalPresentationStyle = .overFullScreen
vc.delegate = self
self.presentDialogViewController(vc, animationPattern: .fadeInOut, completion: { () -> Void in })
vc.timeLabel.text = elapsedTime
vc.rankingLabel.text = String(rank) + "位"
}
}
func dismissDialog(){
dismissDialogViewController(.fadeInOut)
}
@objc func timeCheck(){
if isDEMO{
let now = calendar.dateComponents([.year, .month, .day, .hour, .minute, .second], from: Date())
let diff = calendar.dateComponents([.hour,.minute,.second], from: startDate, to: now)
clockLabel.text = String(diff.hour!).leftPadding(toLength: 2, withPad: "0") + ":" + String(diff.minute!).leftPadding(toLength: 2, withPad: "0") + ":" + String(diff.second!).leftPadding(toLength: 2, withPad: "0")
elapsedTime = clockLabel.text!
}else{
var now = calendar.dateComponents([.year, .month, .day, .hour, .minute, .second], from: Date())
now.year = aramClock.year
now.month = aramClock.month
now.day = aramClock.day
let diff = calendar.dateComponents([.hour,.minute,.second], from: self.aramClock, to: now)
clockLabel.text = String(diff.hour!).leftPadding(toLength: 2, withPad: "0") + ":" + String(diff.minute!).leftPadding(toLength: 2, withPad: "0") + ":" + String(diff.second!).leftPadding(toLength: 2, withPad: "0")
elapsedTime = clockLabel.text!
}
}
func secs2str(_ second: Int) -> String{
return String(second / 60).leftPadding(toLength: 2, withPad: "0") + ":" + String(second % 60).leftPadding(toLength: 2, withPad: "0")
}
func touchedView(touches: Set<UITouch>, view:UIView)->Bool{
for touch: AnyObject in touches {
let t: UITouch = touch as! UITouch
if t.view?.tag == view.tag {
return true
} else {
return false
}
}
return false
}
@IBAction func exit(){
self.dismiss(animated: true, completion: nil)
self.timer.invalidate()
}
func nowIndexCenter(index: Int){
self.rtaScrollView.setContentOffset(CGPoint(x: 0, y: 60*(index / 2)), animated: true)
}
}
<file_sep>//
// ResultViewController.swift
// morta
//
// Created by unkonow on 2020/11/03.
//
import UIKit
class ResultViewController: UIViewController {
var delegate: RTAViewController!
@IBOutlet weak var backView: UIView!
@IBOutlet weak var timeLabel: UILabel!
@IBOutlet weak var rankingLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
backView.backgroundColor = .backgroundColor
backView.layer.cornerRadius = 15
}
@IBAction func eixt(){
delegate.dismissDialog()
delegate.dismiss(animated: true, completion: nil)
}
}
<file_sep>//
// RankingTableViewCell.swift
// morta
//
// Created by unkonow on 2020/11/03.
//
import UIKit
class RankingTableViewCell: UITableViewCell {
@IBOutlet weak var dateLabel: UILabel!
@IBOutlet weak var timeLabel: UILabel!
@IBOutlet weak var rankView: UIView!
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| e9a9363e72423db09c120a06de344df97cb12d46 | [
"Swift",
"Markdown"
] | 18 | Swift | hirossan4049/Morta | 3d1801613c6433ad291c91b739284f31b869c661 | d341ae15f738757f8fc254e9c347d064a1e44267 |
refs/heads/master | <file_sep># the-epic-music-player
This is a very small Operating System Project which uses Shell script commands to play songs available on Ubuntu system.
This script uses mpg123 command of mpg123 audio player.
To install mpg123 Audio Player use command:
sudo apt-get install mpg123
<file_sep>#!/bin/bash
maindirectory=$HOME
if [ -e songs.txt ]; then
rm songs.txt
else
echo >> songs.txt
fi
OIFS="$IFS"
IFS=$'\n'
for file in `find /home -type f -name "*.mp3" 2>&1 | grep -v "Permission denied"`
do
echo "$file" >> songs.txt
done
IFS="$OIFS"
echo "************************************"
echo "*** Welcome to Epic Music Player ***"
echo "************************************"
echo
echo "Here is the list of songs available in your PC:"
echo
aa="a"
i=1;
while read -r line
do
name="$line"
echo -n "$i. "
echo "$name" | sed -r "s/.+\/(.+)\..+/\1/"
i=$[ $i +1 ]
done < "songs.txt"
pfList(){
cd $maindirectory
echo -n "Enter song number to play: "
read sn
i=1
while read -r line
do
name="$line"
if [ $sn -eq $i ]; then
aa=$name
cd "$( dirname "${aa}" )"
echo "Press CTRL+C to stop playing a song."
mpg123 -C "$aa" | sed -r "s/.+\/(.+)\..+/\1/"
break
fi
i=$[ $i +1 ]
done < $1
}
searchSongByName(){
cd $maindirectory
if [ -e sresults.txt ]; then
rm sresults.txt
else
echo >> sresults.txt
fi
echo -n "Enter song name to search: "
read sn
echo $sn
i=1
OIFS="$IFS"
IFS=$'\n'
for file in ` find /home -type f -iname "*.mp3" -a -iname "*$sn*" 2>&1 | grep -v "Permission denied"`
do
echo "$file" >> sresults.txt
done
IFS="$OIFS"
i=1;
while read -r line
do
name="$line"
echo -n "$i. "
echo "$name" | sed -r "s/.+\/(.+)\..+/\1/"
i=$[ $i +1 ]
done < "sresults.txt"
pfList "sresults.txt"
}
while true
do
echo
echo "MENU:"
echo "1. Play a song from above list"
echo "2. Search a song by name"
echo "3. Exit"
echo
echo -n "Enter choice: "
read choice
case $choice in
1) pfList "songs.txt";;
2) searchSongByName;;
3) exit;;
*) exit;;
esac
echo
done
| 0ebed1f4782e35b4cb9fed8026dc628160b09bc0 | [
"Markdown",
"Shell"
] | 2 | Markdown | 10aditya/the-epic-music-player | f90f1c5cee87e33da004e2b11ef171f622d1c317 | 531523ef271619ea0a122cd62ebd04becc20981f |
refs/heads/master | <file_sep>#!/bin/sh
portfolio_top=`pwd`
ln -svf $portfolio_top/.bash_aliases ~
ln -svf $portfolio_top/.gitconfig ~
ln -svf $portfolio_top/.gitignore ~
ln -svf $portfolio_top/.vimrc ~
<file_sep>/usr/lib/vmware-tools/bin32/vmware-user-loader --blockFd 3
<file_sep>gconftool -s /apps/gksu/save-to-keyring -t bool true
<file_sep>gconftool -s /apps/metacity/general/button_layout -t string "menu:minimize,maximize,close"
<file_sep>sudo apt-get install gnustep gnustep-devel menu wmaker
<file_sep>localpath=`pwd`
vi -c 'so %' $localpath/getscript.vba
tar zxvf $localpath/vimball.tar.gz -C ~/.vim
cp $localpath/GetLatestVimScripts.dat ~/.vim/GetLatest/
vi -c 'GLVS'
#input GLVS to get lastest vim scripts
cp -r ~/.vim/EnhancedCommentify-2.3/* ~/.vim/
rm -r ~/.vim/EnhancedCommentify-2.3
sed -i 's/F4/F12/' ~/.vim/plugin/qbuf.vim
<file_sep>cd
rm -r Documents/ Music/ Public/ Pictures/ Videos/ Templates/
<file_sep>EXEC := runme
OBJS += \
main.o
$(EXEC): $(OBJS)
cc -o $@ $^
clean:
rm -f *.o $(EXEC)
<file_sep>#===================start of my .bashrc=====================#
#if [ -f ~/.bash_aliases ]; then
# source ~/.bash_aliases
#fi
#================start of my .bash_aliases==================#
if [ -d ~/bin ]; then
export PATH=~/bin:$PATH
fi
if [ -d /opt/google/chrome ]; then
export PATH=/opt/google/chrome:$PATH
fi
export EDITOR=vi
export LESS_TERMCAP_mb=$'\E[01;36m'
export LESS_TERMCAP_md=$'\E[01;36m'
export LESS_TERMCAP_me=$'\E[0m'
export LESS_TERMCAP_se=$'\E[0m'
export LESS_TERMCAP_so=$'\E[01;43;34m'
export LESS_TERMCAP_ue=$'\E[0m'
export LESS_TERMCAP_us=$'\E[01;36m'
alias agi='sudo apt-get install'
alias ag='sudo apt-get'
alias acs='apt-cache search'
alias ac='apt-cache'
alias ls='ls --color -F'
alias la='ls -A'
alias ll='ls -l'
alias le='less'
alias grep='grep --color=auto --exclude-dir=.git --exclude-dir=.svn'
alias mydate='date "+%Y-%m-%d %H:%M:%S"'
alias gpmstart='sudo gpm -m /dev/misc/psaus -t ps2'
alias svnmodi="svn status | grep '^ \?' | awk '{print $2}'"
alias svnadd="svn status | grep '^ \??' | awk '{print $2}' |xargs svn add"
alias svncmit="svn commit -m ' '"
alias gdb='gdb -silent -tui'
alias cm="./configure && make"
alias cmi="./configure && make && sudo make install"
alias mcm='make clean && make'
alias vial='vi ~/.bash_aliases'
alias gvi='gvim'
alias si='wine /home/cidana/.wine/drive_c/Program\ Files/Source\ Insight\ 3/Insight3.exe & '
alias s="sdcv"
alias cpgl="cp ~/my_stuff/GetLatestVimScripts.dat ~/.vim/GetLatest/"
alias fixqbuf="sed -i 's/F4/F12/' ~/.vim/plugin/qbuf.vim"
ANDROID_SDK_PATH=~/android-sdk-linux_86
if [ -d ${ANDROID_SDK_PATH} ]; then
export PATH=${ANDROID_SDK_PATH}/platforms/android-1.5/tools:${ANDROID_SDK_PATH}/tools:$PATH
fi
# ANDROID_NDK_PATH=~/android-ndk-1.6_r1
# if [ -d ${ANDROID_SDK_PATH} ]; then
# export PATH=${ANDROID_NDK_PATH}/build/prebuilt/linux-x86/arm-eabi-4.2.1/bin:$PATH
# fi
alias emu15='emulator @android-1.5&'
alias emu16='emulator @android-1.6&'
alias emu20='emulator @android-2.0&'
alias emu201='emulator @android-2.0.1&'
alias emu21='emulator @android-2.1&'
alias ads='adb shell'
alias adk='adb kill-server'
alias add='adb devices'
alias adl='adb logcat'
alias adu='adb uninstall com.cidana.jplayer'
alias gvim='LANG="zh_CN.UTF-8" LOCALE="zh_CN.UTF-8" gvim'
#================end of my .bash_aliases==================#
<file_sep>sudo update-alternatives --install "/usr/bin/java" "java" "/opt/jdk1.6.0_20/bin/java" 1
<file_sep>sudo apt-get install stardict sdcv
sudo tar jxf stardict-langdao-ec-gb-2.4.2.tar.bz2 -C /usr/share/stardict/dic/
<file_sep># opengl without x11
sudo apt-get install mesa-common-dev libgl1-mesa-dev libglu1-mesa-dev freeglut3-dev
# with x11
sudo apt-get install libx11-dev libxxf86vm-dev
| 45e8c6cd2b62417e89f8f3b3355842210e9d228b | [
"Makefile",
"Shell"
] | 12 | Shell | artisdom/fuddle | 795cae0be8c9755bd6af262f59c4c096ac1850bc | 678174e8ae8cb574e88150b382c0c71fce73994f |
refs/heads/master | <repo_name>neuroradiology/SeeShell<file_sep>/README.md
# SeeShell
Example code for working with the SeeShell API. The api is ideal for more complex automation tasks, when a "linear" macro is not sufficient. The API allows you to control all Kantu functions from your favorite programming or scripting language. Note that some "ready to run" VBS and Powershell sample scripts are automatically installed with Kantu. Youn find them in the folder "This PC"/documents/kantu/api
Documentation: https://a9t9.com/SeeShell/docs
API: https://a9t9.com/SeeShell/docs#api
FAQ: https://a9t9.com/SeeShell/docs#faq
Kantu separates the linear website flow logic (the screenshot scripts) and the programming/scripting logic with this Scripting API. So for tasks like condidtional statements, use the API Scripting Interface. The PLAY command always returns detailed status and error information, and use can use this to base your IF/THEN/ELSE decisions on:
~~~~
IntegerReturnValue = objSeeShell.Play ("Macro1.see")
if IntegerReturnValue = 1 then
'Do something
MsgBox "OK!"
else
'error, do something else, like running another Kantu macro.
IntegerReturnValue = objSeeShell.Play ("Macro2.see")
end if
~~~~
Technically, the API is implemented as a Windows COM interface. So while this example uses the VBS/Visual Basic syntax, you can use the SeeShell COM object from any programming or scripting language on Windows.
<file_sep>/Loop/Load list of URLs/readme.md
This macro demos:
1. Load data with ReadCSV
2. Use the {{$COL1}} value in the Open command
3. Start the macro with LOOP => Kantu navigates to all URLs in the URLlist.txt file<file_sep>/C# Visual Studio/README.md
# Kantu C# API Demo
Visual Studio demo for runtime loading of the Kantu COM library.
Late-binding to COM objects as in this demo means that you do *not* have to add a reference to the COM library to your .NET project.
You can download the "Visual Studio C# Demo.zip" ZIP file directly. It contains the complete sample project.
<file_sep>/Java/README.md
<h1>Java - Kantu API Demo App</h1>
The test app connects to the Kantu API COM interface to start Kantu, run a macro,
log the return code and then close Kantu.
API documentation: https://a9t9.com/kantu/docs#api
## Prerequisites
- Kantu PRO or Kantu PRO Trial - https://a9t9.com/download
- JDK 1.8
- JAVA_HOME environment variable must be set and point to JDK folder,
(for example C:\Program Files\Java\jdk1.8.0_152)
## How to build
Execute command file `build.cmd`
## How to start
Execute command file `run.cmd`
## Java COM Bridge (https://sourceforge.net/projects/jacob-project/)
* Java library jacob v1.14.3
* Native libraries downloaded into dist/dlls
All artifacts can be found here http://central.maven.org/maven2/net/sf/jacob-project/jacob/1.14.3/
<file_sep>/C# Visual Studio/Visual Studio C# Demo/KantuAPIDemo/Form1.cs
using System;
using System.Windows.Forms;
namespace KantuDemo.ComForm
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private string myScript;
private void button1_Click(object sender, EventArgs e)
{
int i;
myScript = textBox1.Text;
// Instanciate Kantu COM object
var myType = Type.GetTypeFromProgID("Kantu");
dynamic myKantu = Activator.CreateInstance(myType);
textBoxLog.Text = "Starting Kantu Browser\r\n";
//open the Kantu Browser. With myKantu.open(FALSE) you can connect to an already open instance
i = myKantu.open(true);
if (i < 0) textBoxLog.Text += "Kantu Open Error: " + i.ToString() + " Text: " + myKantu.getLastError() + "\r\n";
myKantu.echo("Hello from the C# app: "+myScript);
textBoxLog.Text += "Start Script\r\n";
//Now we run the script - note that the .xkts extension is required
i = myKantu.play(myScript);
if (i < 0)
{
textBoxLog.Text += "Script Replay Error: " + i.ToString() + " Text: " + myKantu.getLastError() + "\r\n";
}
else
{
textBoxLog.Text += "Script completed - OK\r\n";
}
myKantu.echo("Done");
textBoxLog.Text += "Closing Kantu Browser...\r\n";
myKantu.close();
}
}
}
| d98e7c11ee80d62b1172fb4e1601378157ff0014 | [
"Markdown",
"C#"
] | 5 | Markdown | neuroradiology/SeeShell | 0210772550fde3a098545f4a0b098604ac9207d7 | a4c944480b651ede3ffcaca65cdbd970c3d48f11 |
refs/heads/master | <repo_name>MNoorFawi/large-data-processing-with-command-line<file_sep>/README.md
Large Data Processing at the Command Line
================
[Processing Large Data using compression, data.table and the command line](https://github.com/MNoorFawi/Large-Data-Processing-with-Command-Line)
========================================================================
### here we are going to see different ways for processing big data using R and command line
first we will generate the data and writing it to disk
``` r
set.seed(13)
x <- matrix(rnorm(1e7), ncol = 10)
write.table(x, file = 'large_file.txt', sep = ",",
row.names = FALSE, col.names = FALSE)
```
our first way to read such large data is to read a compressed version of it
``` r
system("cp large_file.txt large-compressed.txt")
system('gzip large-compressed.txt')
system.time(
uncomp <- read.table('large_file.txt', sep = ',')
)
## user system elapsed
## 17.23 0.30 17.64
system.time(
comp <- read.table('large-compressed.txt.gz', sep = ',')
)
## user system elapsed
## 9.34 0.03 9.44
```
a big difference in time need to execute both reading commands
and yet there's another great tool to read such large files **DATA.TABLE**
``` r
library(data.table)
system.time(
funcomp <- fread('large_file.txt', sep = ',')
)
## user system elapsed
## 0.50 0.07 3.47
system.time(
fcomp <- fread('< large-compressed.txt.gz gzip -d', sep = ',')
# gzip -d is a command line tool to unzip gzip files
)
## user system elapsed
## 0.41 0.05 0.12
```
### there's almost no difference between freading compressed or uncompressed data
### and both ways are better than regular read.table even with compressed data.
##### data.table::fread also supports some command line functionalities which we're going to explore later on.
for example
``` r
# we can exclude any rows with a negative value
positive_only <- fread(
"< large-compressed.txt.gz cat | gzip -d | grep -v '-'",
sep = ',')
# get the number of rows, which will be a data.table object
fread('< large-compressed.txt.gz cat | gzip -d | wc -l')
fread('< large_file.txt wc -l')
## V1
## 1: 1000000
```
Data Processing with Command Line Tools
=======================================
### the command line has very useful tools that are great in dealing with large and even very big data and parallelism as well.
### to get the full benefits from the command line we need to have some tools installed first:
- if we're using Windows we need to setup cygwin tools, gnuwin/awk, etc..
- other tools like "**csvkit**" which has great functionalities to deal with data we can install it using **pip install csvkit**
- there's also a great toolbox for doing data science with the command line which is **DataScienceToolbox** developed by **<NAME>** author of the great book "*Data Science at the Command Line*" we can either install his magnificent virtual environment or download the tools git clone <https://github.com/jeroenjanssens/data-science-at-the-command-line.git> and put their folder in the path \#\#\#\# then we can use these tools in Windows using cygwin terminal or Git Bash.
let's get down to business first, I want to compare between the time need to read and extract only the rows with all positive values using Command Line and R
``` r
# we have "comp" variable which took almost 25 minuts to get read
system.time(
comp[-which(comp < 0, arr.ind=TRUE)[,1],]
)
## user system elapsed
## 0.57 0.03 0.60
# add this time to the time needed to read it
```
#### using the command line
``` r
time < large-compressed.txt.gz cat |
gzip -d | grep -v '-' > output.txt
#$ real 0m2.124s
```
**such a huge difference**.
#### now it's time to explore more tools and to see what else we can do with the command line
``` r
# here we read the zipped file then we exclude any negative value then we choose only the rows where columns 7 is greater than or equal to 2 and column 5 is greater than 1 then we get the number of rows
< large-compressed.txt.gz cat | gzip -d |
grep -v '-' |
awk -F, '($7 >= 2) && ($5 > 1)' |
wc -l
#$ 21
# here we read the data and get the rows that have any negative value
# then we select rows where column 1 >= 2 or column 2 < 0
# and return columns 3, 4, 5+6, 7*8 and naming the columns a, b, c, d
# and showing the first 10 rows including the header with a nice look
< large-compressed.txt.gz cat | gzip -d | grep '-' |
awk -F, '($1 >= 2) || ($2 < 0) {print $3","$4","$5+$6","$7*$8}' |
header -a a,b,c,d | head | csvlook
```
| a | b | c | d |
|--------|--------|--------|--------|
| 0.263 | 0.248 | -0.079 | 0.280 |
| 0.605 | 0.902 | 0.549 | 0.207 |
| -1.124 | 0.853 | 1.471 | -0.183 |
| -0.578 | -0.462 | 0.760 | 0.706 |
| -1.108 | -0.396 | 1.091 | 0.115 |
| 0.939 | -0.342 | -2.619 | 0.042 |
| -2.101 | 2.659 | -4.484 | -0.141 |
| 0.922 | -0.570 | -1.287 | -1.327 |
| 1.069 | -1.227 | 1.076 | -0.296 |
``` r
# we can also write the output to a file then read it with R and do our analysis on it being much smaller
< large-compressed.txt.gz cat | gzip -d |
grep -v '-' |
awk -F, '($7 >= 2) && ($5 > 1)' > smaller_file.csv
#fread('smaller_file.csv', sep = ',')
# we can also use the functionality of SQL within command line
< large-compressed.txt.gz cat | gzip -d |
csvcut -c 7,8,9,10 | header -a g,h,i,j |
csvsql --query 'SELECT SUM(g) AS sum_a, AVG(h) AS mean_h, MIN(i) AS min_i, MAX(j) AS max_j FROM stdin'
#$ sum_a,mean_h,min_i,max_j
#$ 604.6188991213197,-0.0003848574020195104,-4.98809626002303,4.68823847832136
```
as we saw, **Command Line** can be of very great use when it comes to processing large files. and we can combine it with the analytical power of R to gain better performance. for example we can preprocess data in command line then reading the processed data in R and do our analysis. finally I want to recommend reading <https://www.datascienceatthecommandline.com/> book ...
<file_sep>/full_code.sh
time < large-compressed.txt.gz cat |
gzip -d | grep -v '-' > output.txt
#$ real 0m2.124s
< large-compressed.txt.gz cat | gzip -d |
grep -v '-' |
awk -F, '($7 >= 2) && ($5 > 1)' |
wc -l
#$ 21
< large-compressed.txt.gz cat | gzip -d | grep '-' |
awk -F, '($1 >= 2) || ($2 < 0) {print $3","$4","$5+$6","$7*$8}' |
header -a a,b,c,d | head | csvlook
< large-compressed.txt.gz cat | gzip -d |
grep -v '-' |
awk -F, '($7 >= 2) && ($5 > 1)' > smaller_file.csv
< large-compressed.txt.gz cat | gzip -d |
csvcut -c 7,8,9,10 | header -a g,h,i,j |
csvsql --query 'SELECT SUM(g) AS sum_a, AVG(h) AS mean_h, MIN(i) AS min_i, MAX(j) AS max_j FROM stdin'
| c98b8604515e9ebef9053b7761a05808ad67e261 | [
"Markdown",
"Shell"
] | 2 | Markdown | MNoorFawi/large-data-processing-with-command-line | 856bb1677aad72ebe9a9d9f33c3a288b6bfc9375 | 80f828b470f083cf75406e0fbbf8115eecb0903b |
refs/heads/master | <repo_name>Sheiki1/CDMX009-cipher<file_sep>/src/index.js
import cipher from "./cipher.js" ;
let cleanButton = document.getElementById("clean");//llamando a cleanButton
cleanButton.onclick = clean;//llamando a cleanButton
let copyButton=document.getElementById("copy");
copyButton.onclick = copy;
document.addEventListener('DOMContentLoaded', function () {
let checkbox = document.querySelector('#switch-label');
checkbox.addEventListener('change', function () {
if (checkbox.checked) {
document.getElementById("text").addEventListener("input", getValue);
function getValue() {
let cipherText = document.getElementById("text");//llamar el texto del input
let text = cipherText.value;//guardar el valor del texto en una variable
let cipherKey = document.getElementById("key");//llamar el numero del input
let offset = parseInt(cipherKey.value);//guardar el valor del numero en una variable
let concatenarCharacters = cipher.decode(offset,text);//llamar la funcion de encode
let element = document.getElementById("result");
element.innerHTML = concatenarCharacters.toString();
}
console.log('Checked');
} else {
document.getElementById("text").addEventListener("input", getValue);
function getValue() {
let cipherText = document.getElementById("text");//llamar el texto del input
let text = cipherText.value;//guardar el valor del texto en una variable
let cipherKey = document.getElementById("key");//llamar el numero del input
let offset = parseInt(cipherKey.value);//guardar el valor del numero en una variable
let concatenarCharacters = cipher.encode(offset,text);//llamar la funcion de encode
let element = document.getElementById("result");
element.innerHTML = concatenarCharacters.toString();
}
console.log('Not checked');
}
});
});
function clean (){//funcion para cuando se presione el boton limpiar se limpie el div de resultado
document.getElementById("text").value=" ";//se pone un div vacio
}
function copy(){
let copyText = document.getElementById("result");
copyText.select();
copyText.setSelectionRange(0, 99999)
document.execCommand("copy");
}
<file_sep>/docs/index.js
import cipher from "./cipher.js" ;
let encodeButton = document.getElementById("cipher");//llamando a encodeButton
encodeButton.onclick = encode1;//llamando a encodeButton
let decodeButton = document.getElementById("decipher");//llamando a decodeButton
decodeButton.onclick = decode1;//llamando a decodeButton
let cleanButton = document.getElementById("clean");//llamando a cleanButton
cleanButton.onclick = clean;//llamando a cleanButton
let copyButton=document.getElementById("copy");
copyButton.onclick = copy;
function encode1(){//funcion para cuando se presione el boton encode1 se realicen estas operaciones
let cipherText = document.getElementById("text");//llamar el texto del input
let text = cipherText.value;//guardar el valor del texto en una variable
let cipherKey = document.getElementById("key");//llamar el numero del input
let offset = parseInt(cipherKey.value);//guardar el valor del numero en una variable
let concatenarCharacters = cipher.encode(offset,text);//llamar la funcion de encode
let element = document.getElementById("result");//llamar el div de resultado
element.innerHTML = concatenarCharacters.toString();//poner en el div el resultado final
}
function decode1(){//funcion para cuando se presione el boton decode1 se realicen estas operaciones
let cipherText = document.getElementById("text");//llamar el texto del input
let text = cipherText.value;//guardar el valor del texto en una variable
let cipherKey = document.getElementById("key");//llamar el numero del input
let offset = parseInt(cipherKey.value);//guardar el valor del numero en una variable
let concatenarCharacters = cipher.decode(offset,text);//llamar la funcion de decode
let element = document.getElementById("result");//llamar el div de resultado
element.innerHTML = concatenarCharacters.toString();//poner en el div el resultado final
}
function clean (){//funcion para cuando se presione el boton limpiar se limpie el div de resultado
document.getElementById("text").value=" ";//se pone un div vacio
}
function copy(){
let copyText = document.getElementById("result");
copyText.select();
copyText.setSelectionRange(0, 99999)
document.execCommand("copy");
}
console.log(cipher);
| a4a396c8ab979e66fda89ac7c90b0939bb09a376 | [
"JavaScript"
] | 2 | JavaScript | Sheiki1/CDMX009-cipher | c3927f0cf1ea6d6c376b7da415e0b0a5d5d51b27 | eaf67a1ecb0062e0e0e79e05270b9f171da8618a |
refs/heads/master | <file_sep>namespace WindowsFormsApplication3
{
internal class inversoGrupal
{
public string cifrar(string palabra, string resul)
{
for (int i = palabra.Length - 1; i >= 0; i--)
{
resul += palabra[i];
}
return resul;
}
public string concatenarCadena(int indice,string s1, string resultado)
{
while (indice < s1.Length)
{
resultado += s1[indice];
indice++;
}
return resultado;
}
public string cifrado(int grupo,int indice,string texto, string result) {
if ((indice + grupo) < texto.Length)
{
return cifrado(grupo, indice + grupo,texto,result +""+ cifrar(texto.Substring(indice, indice + grupo),""));
}
return concatenarCadena(indice, texto, result);
}
}
}<file_sep>using System.Threading;
using System;
using System.Windows.Forms;
namespace JuegoDeLaVida
{
public static class Program
{
private static Mutex mutex;
[STAThread]
public static void Main()
{
if (PrevInstance())
{
Application.Exit();
return;
}
Application.Run(new MainForm());
}
/// <summary>
/// Determina si existe alguna instancia previa del programa corriendo
/// </summary>
public static bool PrevInstance()
{
//Obtengo el nombre del ensamblado donde se encuentra ésta función
string NombreAssembly = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;
//Nombre del mutex según Tipo (visibilidad)
string mutexName = "Global\\" + NombreAssembly;
bool newMutexCreated = false;
try
{
//Abro/Creo mutex con nombre único
mutex = new Mutex(false, mutexName, out newMutexCreated);
if (newMutexCreated)
{
//Se creó el mutex, NO existe instancia previa
return false;
}
else
{
//El mutex ya existía, Libero el mutex
mutex.Close();
return true;
}
}
catch (Exception)
{
return false;
}
}
}
}<file_sep>namespace WindowsFormsApplication3
{
internal class cifrado
{
public int buscarCaracterEnAlfabeto(char c, string alfabeto)
{
for (int i = 0; i < alfabeto.Length; i++)
{
if (alfabeto[i] == c)
return i;
}
return 0;
}
//abcdefghijklmnñopqrstuvwxyz 27
private char cifrarLetra(char c, string alfabeto, int desplazamiento)
{
int pos = buscarCaracterEnAlfabeto(c, alfabeto);
if (pos > 0)
pos = pos + desplazamiento;
else
return c;
if (pos >= alfabeto.Length)
pos = pos - alfabeto.Length;
return alfabeto[pos];
}
public string cifrarPalabra(string result, string palabra, string alfabeto, int desplazamiento)
{
for (int i = 0; i < palabra.Length; i++)
{
result += cifrarLetra(palabra[i], alfabeto, desplazamiento);
}
return result;
}
}
}<file_sep>using System.Collections.Generic;
using System.Drawing;
namespace JuegoDeLaVida
{
public static class Extensiones
{
public static void Add(this IList<Point> a, int X, int Y)
{
a.Add(new Point(X, Y));
}
}
}
<file_sep>using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
public class BitmapLocker
{
public enum ColorChannel : int { RED = 2, GREEN = 1, BLUE = 0, ALPHA = 3 }
#region Fields
private int RowSizeBytes;
private byte[] PixBytes;
private BitmapData BitmapData;
#endregion
#region Public Methods
// Lock the bitmap's data.
public void LockBitmap(Bitmap bm, bool ReadOnly = false)
{
// Lock the bitmap data.
Rectangle bounds = new Rectangle(0, 0, bm.Width, bm.Height);
BitmapData = bm.LockBits(bounds, ReadOnly ? ImageLockMode.ReadOnly : ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);
RowSizeBytes = BitmapData.Stride;
// Allocate room for the data.
int total_size = BitmapData.Stride * BitmapData.Height;
PixBytes = new byte[total_size + 1];
// Copy the data into the g_PixBytes array.
Marshal.Copy(BitmapData.Scan0, PixBytes, 0, total_size);
}
public void UnlockBitmap(Bitmap bm)
{
// Copy the data back into the bitmap.
int total_size = BitmapData.Stride * BitmapData.Height;
Marshal.Copy(PixBytes, 0, BitmapData.Scan0, total_size);
// Unlock the bitmap.
bm.UnlockBits(BitmapData);
// Release resources.
PixBytes = null;
BitmapData = null;
}
public Color GetPixel(int x, int y)
{
return Color.FromArgb(PixBytes[GetArrayPos(x, y, ColorChannel.ALPHA)],
PixBytes[GetArrayPos(x, y, ColorChannel.RED)],
PixBytes[GetArrayPos(x, y, ColorChannel.GREEN)],
PixBytes[GetArrayPos(x, y, ColorChannel.BLUE)]);
}
public void SetPixel(int x, int y, Color c)
{
PixBytes[GetArrayPos(x, y, ColorChannel.RED)] = c.R;
PixBytes[GetArrayPos(x, y, ColorChannel.GREEN)] = c.G;
PixBytes[GetArrayPos(x, y, ColorChannel.BLUE)] = c.B;
PixBytes[GetArrayPos(x, y, ColorChannel.ALPHA)] = c.A;
}
public int GetArrayPos(int x, int y, ColorChannel c)
{
return Convert.ToInt32((RowSizeBytes * y + x * 4) + c);
}
#endregion
}
<file_sep>namespace WindowsFormsApplication3
{
internal class inverso
{
public string cifrar(string palabra, string resul) {
for (int i = palabra.Length - 1; i >= 0; i--) {
resul += palabra[i];
}
return resul;
}
}
}<file_sep>namespace WindowsFormsApplication3
{
internal class descifrado
{
private int buscarCaracterEnAlfabeto(char c, string alfabeto)
{
for (int i = 0; i < alfabeto.Length; i++)
{
if (alfabeto[i] == c)
return i;
}
return 0;
}
//abcdefghijklmnñopqrstuvwxyz 27
private char descifrarLetra(char c, string alfabeto, int desplazamiento)
{
int pos = buscarCaracterEnAlfabeto(c, alfabeto) - desplazamiento;
if (pos < 0)
pos = alfabeto.Length + pos;
return alfabeto[pos];
}
public string descifrarPalabra(string result, string palabra, string alfabeto, int desplazamiento)
{
for (int i = 0; i < palabra.Length; i++)
{
result += descifrarLetra(palabra[i], alfabeto, desplazamiento);
}
return result;
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication3
{
public partial class Form1 : Form
{ inverso c = new inverso();
cifrado c1 = new cifrado();
inversoGrupal ig = new inversoGrupal();
// descifrado c2 = new descifrado();
public Form1()
{
Console.WriteLine(ig.cifrado(3, 0, "holc", ""));
InitializeComponent();
}
private void textoPlano_KeyUp(object sender, KeyEventArgs e)
{
transposicion.Text = c.cifrar(textoPlano.Text, "");
cesarbox.Text = c1.cifrarPalabra("", textoPlano.Text, "aábcdeéfghiíjklmnñoópqrstuúüvwxyz", Decimal.ToInt32(numericUpDown1.Value));
tia.Text = ig.cifrado(Decimal.ToInt32(grupo.Value), 0, textoPlano.Text, "");
}
private void numericUpDown1_MouseClick(object sender, MouseEventArgs e)
{
cesarbox.Text = c1.cifrarPalabra("", textoPlano.Text, "aábcdeéfghiíjklmnñoópqrstuúüvwxyz", Decimal.ToInt32(numericUpDown1.Value));
}
private void numericUpDown1_KeyUp(object sender, KeyEventArgs e)
{
cesarbox.Text = c1.cifrarPalabra("", textoPlano.Text, "aábcdeéfghiíjklmnñoópqrstuúüvwxyz", Decimal.ToInt32(numericUpDown1.Value));
}
private void numericUpDown1_MouseCaptureChanged(object sender, EventArgs e)
{
cesarbox.Text = c1.cifrarPalabra("", textoPlano.Text, "aábcdeéfghiíjklmnñoópqrstuúüvwxyz", Decimal.ToInt32(numericUpDown1.Value));
}
private void numericUpDown1_ValueChanged(object sender, EventArgs e)
{
cesarbox.Text = c1.cifrarPalabra("", textoPlano.Text, "aábcdeéfghiíjklmnñoópqrstuúüvwxyz", Decimal.ToInt32(numericUpDown1.Value));
}
private void grupo_ValueChanged(object sender, EventArgs e)
{
tia.Text = ig.cifrado(Decimal.ToInt32(grupo.Value), 0, textoPlano.Text, "");
}
}
}
| af65badf5d0b8313244936e49b3109bf3a7dd486 | [
"C#"
] | 8 | C# | GasgaLopezAdriana/disor | f382e5c51a720e32687ae5735e8eb2710fa794e7 | 85a374c7995f1d90cbd0db64bc80415fd44e876c |
refs/heads/master | <repo_name>hardik9193/Omisego-Reactjs-jsonparser<file_sep>/src/components/Editor/Editor.js
import React, { Component } from 'react';
import JSONInput from 'react-json-editor-ajrm';
import locale from 'react-json-editor-ajrm/locale/en';
import { Row, Col , Button } from 'reactstrap';
import _ from 'lodash';
let flattenObjectArray = [];
class Editor extends Component {
state = {
inputJson : null,
outputJson : null,
flatJsonArray : []
}
parseJson = () => {
flattenObjectArray = [];
let { inputJson } = this.state;
this.flattenObject(inputJson);
this.setState({ outputJson : this.unflatten(flattenObjectArray)});
}
flattenObject = (ob) => {
var toReturn = {};
for (var i in ob) {
if (!ob.hasOwnProperty(i)) continue;
if ((typeof ob[i]) == 'object' && ob[i] !== null) {
var flatObject = this.flattenObject(ob[i]);
if(Object.keys(flatObject).length > 0) {
flattenObjectArray.push(flatObject);
}
} else {
toReturn[i] = ob[i];
}
}
return toReturn;
}
unflatten = ( array, parent, tree ) => {
tree = typeof tree !== 'undefined' ? tree : [];
parent = typeof parent !== 'undefined' ? parent : { id: null };
var children = _.filter( array, (child) => { return child.parent_id === parent.id; });
if( !_.isEmpty( children ) ){
if( parent.id === null ){
tree = children;
}else{
parent['children'] = children;
}
_.each( children, ( child ) => { this.unflatten( array, child ) } );
}
return tree;
}
render() {
return (
<div className="json-wrapper">
<Row>
<Col md="6">
<div className="heading-title">Input (editable field)</div>
<JSONInput
id='json_editor_input'
locale={locale}
height='500px'
onChange={ (e) => { this.setState({ inputJson : e.jsObject}) }}
/>
</Col>
<Col md="6">
<div className="heading-title">Output</div>
<JSONInput
id='json_editor_output'
locale={locale}
height='500px'
placeholder={this.state.outputJson ? this.state.outputJson : null }
viewOnly
/>
</Col>
</Row>
<div className="row">
<div className="col-md-12 btn-col">
<Button color="primary" onClick={ this.parseJson }>Submit</Button>
</div>
</div>
</div>
);
}
}
export default Editor; | 92721f58da1ef8065e39b569b4d7d1083d63e51c | [
"JavaScript"
] | 1 | JavaScript | hardik9193/Omisego-Reactjs-jsonparser | 98ea9e547032a75cbdd96fa0c7d9135459715504 | d991397ed5832c443336bde6f0337ff9d3200e9c |
refs/heads/master | <file_sep>/**
* Very simple screen sharing app using WebRTC.
*
* Room == Session
* Floor == RTCMultiConn's Room/Channel concept (not data channel)
*
* FF (Hosting):
* media.getusermedia.screensharing.enabled = true
* media.getusermedia.screensharing.allowed_domains + app domain or ip
* Chrome (Hosting):
* install plugin by clicking the prompted link.
*
* @author <NAME> 02.09.2015
*/
(function(){
window.app = window.app || {};
$(function domReady(){
$('#more-peers').click(function openMorePeers(){
window.open(location.href);
});
/*==================== Setup signaling channel ====================*/
var primus = Primus.connect('/primus');
var $tag = $('#my-status');
primus.on('open', function onOpen(){
console.log('online!');
$tag.html('online');
$tag.addClass('label-green').removeClass('label-red');
});
primus.on('end', function onClose(){
console.log('offline.');
$tag.html('offline');
$tag.removeClass('label-green').addClass('label-red');
});
primus.on('reconnect', function onRetry(){
console.log('retrying...');
$tag.html('reconnecting...');
$tag.removeClass('label-green label-red');
});
/*=========== Create RTC conn (pick a appname/floor) & signaling channel adapter ===========*/
var onMessageCallbacks = {};
var rtc = new RTCMultiConnection('ShareScreen.io');
rtc.skipLogs();
rtc.media.min(1280,720);
$('#peerid').html(['peer:', rtc.userid].join(' '));
primus.on('data', function onMessage(data){
if (data.sender == rtc.userid) return;
//console.log('[signal received]', data);
if (onMessageCallbacks[data.channel]) {
onMessageCallbacks[data.channel](data.message);
}
//mark dropped peer
if(data.message.left){
//console.log(data);
rtc.remove(data.message.userid);
//hack based on 4065 openSignalingChannel - onmessage (fixing the host left problem)
delete rtc.sessionDescriptions[data.message.sessionid];
rtc.numberOfSessions--;
}
});
rtc.openSignalingChannel = function (config) {
var channel = config.channel || this.channel;
onMessageCallbacks[channel] = config.onmessage;
if (config.onopen) setTimeout(config.onopen, 1000);
return {
send: function (message) {
primus.write({
sender: rtc.userid,
channel: channel,
message: message
});
},
channel: channel
};
};
// Upon getting local OR remote media stream
rtc.onstream = function(e) {
if(e.type == 'local'){
console.log('[local stream ready]');
}
else {
if (rtc.isInitiator) return;
console.log('[remote stream added]', e.type, e);
}
//delete e.mediaElement;
$('#screen').attr('src', URL.createObjectURL(e.stream));
};
/* TBI: list available rooms, BUG::onNewSession might not fire for previousely onlined client -- fixed*/
var rooms = {};
rtc.onNewSession = function(s) {
console.log('[room info]', s); //upon receiving room info (up, left...)
if(s.left){
// if(!rooms[s.sessionid]){
// rtc.refresh(); //reset the connection.
// return;
// }
delete rooms[s.sessionid];
return;
}
else rooms[s.sessionid] = s.userid;
};
rtc.connect();
/*========================= Hook up UI controls =========================*/
$roomId = $('#roomId');
function showStatus(roomId){
$('#controlbar-start').hide();
$('#status').html(roomId);
$('#controlbar-end').show();
}
function hideStatus(){
$('#controlbar-start').show();
$('#controlbar-end').hide();
$('#screen').stop();
}
hideStatus();
//A. Host
$('#host').click(function hostScreenShare(){
var perspectiveRoom = $roomId.val() || 'default-room';
if(rooms[perspectiveRoom]){
return alert('Room [' + perspectiveRoom + '] exists, please use other names...');
}
// List peer users for host
// [hack 3355 updateSocket(), 3932 connection.remove() + onPeersChanged]
var $peers = $('#peers');
function renderPeers(){
$peers.empty();
var count = 0;
for (var pid in rtc.peers) {
if (pid == rtc.userid) continue;
$peers.append('<li>' + '<i class="icon-' + rtc.peers[pid].userinfo.browser + '"></i> ' + pid + '</li>');
count ++;
}
if(count){
$('#screen').removeClass('unit-100').addClass('unit-70');
$peers.prepend('<li style="list-style:none;">Participants <span class="badge badge-green right">'+ count +'</span></li>');
}else
$('#screen').removeClass('unit-70').addClass('unit-100');
}
rtc.onPeersChanged = function(){
renderPeers();
};
// Customize what to share:
rtc.session = {
//video:true,
//audio:true,
screen: true,
oneway: true
};
rtc.autoCloseEntireSession = true;
rtc.interval = 5000;
//rtc.transmitRoomOnce = true; --> need to send sd & roomid to server!
// since previousely onlined peers won't get the sd from roomid
var sd = rtc.open(perspectiveRoom);
//http://bit.ly/webrtc-screen-extension
if(rtc.UA.isChrome)
rtc.DetectRTC.screen.getChromeExtensionStatus(function(status){
if (status == 'not-installed')
showStatus('Error: ' + 'you need to install <a target="_blank" href="http://bit.ly/webrtc-screen-extension">webrtc-screen-extension</a> or use Firefox');
else
showStatus('Hosting: ' + perspectiveRoom);
});
else
showStatus('<span class="label label-outline label-blue"><i class="fa fa-bullhorn"></i> Hosting</span> ' + perspectiveRoom);
//now when the host starts [> the stream, the broadcasting begins.
//we use the default room-id broadcasting mech here, ignoring returned sd.
window.rtc = rtc;
});
//B. Join
$('#join').click(function joinScreenShare(){
var targetRoom = $roomId.val() || 'default-room';
if(!rooms[targetRoom]){
return alert('Room [' + targetRoom + '] not available...');
}
rtc.join(targetRoom);
showStatus('<span class="label label-outline label-yellow"><i class="fa fa-slideshare"></i> Watching</span> ' + targetRoom);
});
//C. Drop
$('#stop').click(function onStop(){
rtc.leave();
location.reload(false);
});
});
})();<file_sep>/**
* This is a simple WebRTC peer tracker (just relaying messages)
*/
var Primus = require('primus'),
path = require('path'),
colors = require('colors');
var primus = Primus.createServer(function onConnect(spark /*peer*/){
//Protocol:: Just broadcast the messages out: (without peer records)
spark.on('data', function onMessage(data){
primus.write(data);
console.log(['peer', spark.id.yellow, '(', data.sender, ') ==>'.grey, 'all @', new Date()].join(' '));
//console.dir(data);
});
}, {
//Options::
port: 5000,
transformer: 'websockets'
});
//Client Lib:: Save the client api into a lib file.
primus.save(path.join(__dirname, '..', 'client', 'js', 'primus.js'));
//Logs:: simple client on/off logging.
primus.on('connection', function onPeerOnline(spark){
console.log(['peer', spark.id.yellow, spark.address.ip, 'online'.green].join(' '));
console.time(spark.id);
});
primus.on('disconnection', function onPeerOffline(spark){
console.log(['peer', spark.id.yellow, 'offline'.red].join(' '));
console.timeEnd(spark.id);
}); | 65301932872a257c18b91932fca76da1c3a93eeb | [
"JavaScript"
] | 2 | JavaScript | YetFix/WebRTC-peer-tracker | c1d91647af3cb7465ba057e9a5164d3c288e0e07 | 29ac5575914a07f58a45a137d65fd2f5f3ce30da |
refs/heads/master | <file_sep>$(document).ready(function(){
$(".owl-carousel").owlCarousel({
items: 1,
loop: true,
margin: 20,
navText: ["",""],
mouseDrag: false,
dots: true,
nav: true,
responsiveClass:true,
responsive:{
0: {
nav:false
},
700: {
nav: true
},
1000:{
dots: false,
items: 2
}
}
});
});<file_sep>const modal = document.getElementById("myModal");
const burger = document.getElementById("navToggle");
const closeBtn = document.getElementsByClassName("modal__header-close")[0];
const logo = document.getElementById("logo");
const btnModalPw = document.querySelector('#btnmodal__pw');
const btnModalEmail = document.querySelector('#btnmodal__email');
const btnModalTel = document.querySelector('#btnmodal__tel');
const btnPw = document.querySelector('.btn__pw');
const btnEmail = document.querySelector('.btn__email');
const btnTel = document.querySelector('.btn__tel');
const btnModalClosePw = document.querySelector('.btnmodal-close-pw');
const btnModalCloseEmail = document.querySelector('.btnmodal-close-email');
const btnModalCloseTel = document.querySelector('.btnmodal-close-tel');
const signUp = document.getElementById('signup');
const logIn = document.getElementById('login');
const loginLink = document.getElementById('loginlink');
const signupLink = document.getElementById('signuplink');
const pwModal = document.getElementById('pwModal');
const showModal = document.getElementById('forgot__password');
const pwCloseBtn = document.getElementsByClassName('pwmodal__header-close')[0];
const input = document.querySelector(".pwmodal__input");
const phoneNum = document.querySelector(".phone__num");
const btnModalInputNewTel = document.querySelector('.btnmodal__input-old-tel');
const btnModalInputOldTel = document.querySelector('.btnmodal__input-new-tel');
function showPwModal(event) {
event.preventDefault();
if (event.target = showModal) {
pwModal.classList.add('show-pwmodal');
document.getElementsByTagName("body")[0].style.overflow = 'hidden';
}
}
function closePwModal() {
pwModal.classList.remove('show-pwmodal');
document.getElementsByTagName("body")[0].style.overflow = 'scroll';
document.getElementsByTagName("body")[0].style.overflowX = 'hidden';
}
let runSign = e => {
e.preventDefault();
logIn.style.display = 'none';
loginLink.classList.remove('actives');
signUp.style.display = 'block';
signupLink.classList.add('actives');
}
let runLogin = e => {
e.preventDefault();
signUp.style.display = 'none';
signupLink.classList.remove('actives');
logIn.style.display = 'block';
loginLink.classList.add('actives');
}
function closeBtnModal() {
logo.style.opacity = '1';
burger.style.display = 'block';
modal.classList.remove('show-modal');
document.getElementsByTagName("body")[0].style.overflow = 'scroll';
document.getElementsByTagName("body")[0].style.overflowX = 'hidden';
}
function openBurger() {
logo.style.opacity = '0';
burger.style.display = 'none';
modal.style.display = 'flex';
modal.classList.add('show-modal');
document.getElementsByTagName("body")[0].style.overflow = 'hidden';
}
function showBtnModalPw(event) {
event.preventDefault();
btnModalPw.classList.add('show-btnmodal');
document.getElementsByTagName("body")[0].style.overflow = 'hidden';
}
function showBtnModalEmail(event) {
event.preventDefault();
btnModalEmail.classList.add('show-btnmodal');
document.getElementsByTagName("body")[0].style.overflow = 'hidden';
}
function showBtnModalTel(event) {
event.preventDefault();
btnModalTel.classList.add('show-btnmodal');
document.getElementsByTagName("body")[0].style.overflow = 'hidden';
}
// Password
function setCursorPosition(pos, elem) {
elem.focus();
if (elem.setSelectionRange) elem.setSelectionRange(pos, pos);
else if (elem.createTextRange) {
let range = elem.createTextRange();
range.collapse(true);
range.moveEnd("character", pos);
range.moveStart("character", pos);
range.select()
}
}
function mask(event) {
let matrix = "(___) ___ __ __",
i = 0,
def = matrix.replace(/\D/g, ""),
val = this.value.replace(/\D/g, "");
if (def.length >= val.length) val = def;
this.value = matrix.replace(/./g, function (a) {
return /[_\d]/.test(a) && i < val.length ? val.charAt(i++) : i >= val.length ? "" : a
});
if (event.type == "blur") {
if (this.value.length == 2) this.value = ""
} else setCursorPosition(this.value.length, this)
};
function init () {
if (phoneNum) {
phoneNum.addEventListener("input", mask, false);
phoneNum.addEventListener("focus", mask, false);
phoneNum.addEventListener("blur", mask, false);
}
if (btnModalInputNewTel) {
btnModalInputNewTel.addEventListener("input", mask, false);
btnModalInputNewTel.addEventListener("focus", mask, false);
btnModalInputNewTel.addEventListener("blur", mask, false);
}
if (btnModalInputOldTel) {
btnModalInputOldTel.addEventListener("input", mask, false);
btnModalInputOldTel.addEventListener("focus", mask, false);
btnModalInputOldTel.addEventListener("blur", mask, false);
}
if (input) {
input.addEventListener("input", mask, false);
input.addEventListener("focus", mask, false);
input.addEventListener("blur", mask, false);
}
if (burger) {
burger.addEventListener('click', openBurger);
}
if (closeBtn) {
closeBtn.addEventListener('click', closeBtnModal);
}
if (showModal) {
showModal.addEventListener('click', showPwModal);
}
if (pwCloseBtn) {
pwCloseBtn.addEventListener('click', closePwModal);
}
if (signupLink) {
signupLink.addEventListener('click', runSign);
}
if (loginLink) {
loginLink.addEventListener('click', runLogin);
}
if (btnPw) {
btnPw.addEventListener('click', showBtnModalPw);
}
if (btnEmail) {
btnEmail.addEventListener('click', showBtnModalEmail);
}
if (btnTel) {
btnTel.addEventListener('click', showBtnModalTel);
}
if (btnModalClosePw) {
btnModalClosePw.addEventListener('click', () => {
btnModalPw.classList.remove('show-btnmodal');
document.getElementsByTagName("body")[0].style.overflow = 'auto';
document.getElementsByTagName("body")[0].style.overflowX = 'hidden';
});
}
if (btnModalCloseEmail) {
btnModalCloseEmail.addEventListener('click', () => {
btnModalEmail.classList.remove('show-btnmodal');
document.getElementsByTagName("body")[0].style.overflow = 'auto';
document.getElementsByTagName("body")[0].style.overflowX = 'hidden';
});
}
if (btnModalCloseTel) {
btnModalCloseTel.addEventListener('click', () => {
btnModalTel.classList.remove('show-btnmodal');
document.getElementsByTagName("body")[0].style.overflow = 'auto';
document.getElementsByTagName("body")[0].style.overflowX = 'hidden';
});
}
}
init();<file_sep><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>HomeBarber</title>
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="owlcarousel/owl.carousel.css">
<link rel="stylesheet" href="owlcarousel/owl.theme.default.css">
</head>
<body>
<div class="group__wrap">
<header class="header">
<div class="navbar">
<div class="container">
<div class="navbar-wrap">
<a class="logo" href="index.html" id="logo">
HOME<b>BARBER</b>
</a>
<div class="nav" id="nav">
<a class="nav__link" href="#">Blog</a>
<a class="nav__link hide__link" href="./stylist.html">
<div class="nav__link-stylist-icon">
<img class="nav__icon" src="./images/Vector.png" alt="#">
</div>
<div class="nav__link-stylist-text">
BECOME STYLIST
</div>
</a>
<a href="registration.html" class="nav__link-login">
<img src="./images/icons/login.svg" alt="login">
</a>
</div>
<button class="burger" type="button" id="navToggle">
<img class="burger__icon" src="./images/icons/burger.svg" alt="">
</button>
</div>
</div>
</div>
</header>
<section class="intro">
<div class="container">
<div class="intro__block">
<div class="intro__block-content">
<div class="intro__block-title">
New experience
<br>in hair style
</div>
<div class="intro__block-text">
Get your hair service, in your Home or Office.
</div>
<div class="block-buttons">
<a href="#"><img src="images/appStore.png"></a>
<a href="#"><img src="images/googolePlay.png"></a>
</div>
</div>
<div class="intro__block-img">
<img class="intro__img-client" src="./images/client.png" alt="barber">
</div>
</div>
</div>
</section>
</div>
<section class="unique">
<div class="container">
<div class="unique__block">
<div class="unique__block-img">
<img src="./images/icons/phone.png" alt="" class="unique__block-image">
</div>
<div class="unique__block-content">
<div class="unique__block-title">
A unique approach to on demand hair services
</div>
<div class="unique__block-img-hide">
<img src="./images/icons/phone.png" alt="" class="unique__block-img-hide-img">
</div>
<div class="unique__block-text">
Our appealing service enables us to connect clients with a mobile hairstylist. No need to head
to the salon, we offer in-home, office or hotel hair services! Whether you need a new and
improved hairstyle or on demand haircuts, our team of professionals will come to you! We will
have you klipped and trimmed in no time.
</div>
<div class="block-buttons">
<a href="#"><img src="images/appStore.png"></a>
<a href="#"><img src="images/googolePlay.png"></a>
</div>
</div>
</div>
</div>
</section>
<section class="service">
<div class="container">
<div class="service__wrap">
<div class="service__title">
How it Works
</div>
<div class="service__content">
<div class="service__content-icon">
<img src="./images/icons/first.svg" alt="1">
</div>
<div class="service__content-block">
<div class="service__content-subtitle">
Select your service
</div>
<div class="service__content-text">
New hair cut needed? Overdue for a new hairstyle? Use our application to access on-demand
haircuts and to get in touch with a mobile hairstylist. Choose the service you need, along
with your hair expert of choice, and we’ll be present wherever you need us.
</div>
</div>
<img class="service__content-img" src="./images/mobiles.png" alt="mobiles">
</div>
</div>
</div>
</section>
<section class="date">
<div class="container">
<div class="date__wrap">
<img class="date__icon" src="./images/icons/second.svg" alt="2">
<div class="date__content">
<div class="date__content-title">
Choose Your Location, Date & Time
</div>
<div class="date__content-text">
Heading out on the town after work? In need of last-minute hair care services? Regardless of
your location, or occasion, we can be there to provide exceptional in-home hair services. Choose
your location, date, and time, and our hair experts will arrive on time to give you an
incredible look.
</div>
</div>
</div>
</div>
</section>
<section class="knock">
<div class="container">
<div class="knock__wrap">
<div class="knock__wrap-left">
<div class="knock__block">
<img src="./images/icons/third.svg" alt="3">
</div>
<div class="knock__content">
<div class="knock__content-title">
Wait for A Knock
</div>
<div class="knock__content-text">
Once your schedule is set, sit back, relax, and await the arrival of your hair expert.
They’ll be there punctually, ready & willing to transform your appearance. Don’t forget to
listen out for that knock!
</div>
</div>
</div>
<div class="knock__wrap-right">
<img src="./images/knock.png" alt="phone">
</div>
</div>
</div>
</section>
<section class="reviews">
<div class="container">
<div class="reviews__title">
Reviews
</div>
<div class="owl-carousel">
<div>
<div class="slider__item">
<div class="slider__content">
<img class="slider__content-photo" src="./images/icons/Max.png" alt="">
<div class="slider__content-name">
Max
</div>
</div>
<div class="slider__text">
Ready to get started with our in-home hair services? Download our app, book your first
appointment, and experience the satisfaction of having a mobile hairstylist come to you!
</div>
</div>
</div>
<div>
<div class="slider__item">
<div class="slider__content">
<img class="slider__content-photo" src="./images/icons/Paul.png" alt="">
<div class="slider__content-name">
Paul
</div>
</div>
<div class="slider__text">
Ready to get started with our in-home hair services? Download our app, book your first
appointment, and experience the satisfaction of having a mobile hairstylist come to you!
</div>
</div>
</div>
<div>
<div class="slider__item">
<div class="slider__content">
<img class="slider__content-photo" src="./images/icons/Max.png" alt="">
<div class="slider__content-name">
Paul
</div>
</div>
<div class="slider__text">
Ready to get started with our in-home hair services? Download our app, book your first
appointment, and experience the satisfaction of having a mobile hairstylist come to you!
</div>
</div>
</div>
<div>
<div class="slider__item">
<div class="slider__content">
<img class="slider__content-photo" src="./images/icons/Paul.png" alt="">
<div class="slider__content-name">
Paul
</div>
</div>
<div class="slider__text">
Ready to get started with our in-home hair services? Download our app, book your first
appointment, and experience the satisfaction of having a mobile hairstylist come to you!
</div>
</div>
</div>
</div>
</div>
</section>
<section class="interactive"
style="background: url('./images/appimage.png');background-size: cover;background-repeat: no-repeat;">
<div class="container">
<div class="interactive__content">
<div class="interactive__content-title logo">
HOME<b>BARBER</b>
</div>
<div class="interactive__content-subtitle">
Download HomeBarber
<br>end become best hair stylist
<br>in your area
</div>
<div class="interactive__content-text">
Ready to get started with our in-home hair services? Download our app, book your first appointment,
and experience the satisfaction of having a mobile hairstylist come to you!
</div>
<div class="block-buttons special_btn">
<a href="#"><img src="images/appStore.png"></a>
<a href="#"><img src="images/googolePlay.png"></a>
</div>
</div>
</div>
</section>
<footer class="footer">
<div class="container">
<div class="contacts">
<a href="#" class="contacts__title logo">
HOME<b>BARBER</b>
</a>
<div class="contacts__links">
<div class="contacts__links-title">About Us</div>
<a href="#">Company</a>
<a href="#">Contact Us</a>
<a href="#">iOS App</a>
<a href="#">Android App</a>
</div>
<div class="contacts__links-second">
<div class="contacts__links-title">FAQs and Policies</div>
<a href="#">FAQs</a>
<a href="#">Privacy</a>
<a href="#">Terms of use</a>
</div>
<div class="contacts__links-social">
<div class="contacts__links-title">Follow Us</div>
<div class="contacts__links-social-icon">
<a href="#"><img src="./images/icons/icon-fb.svg" alt="facebook"></a>
<a href="#"><img src="./images/icons/icon-tw.svg" alt="twitter"></a>
<a href="#"><img src="./images/icons/icon-ins.svg" alt="instagram"></a>
</div>
</div>
</div>
</div>
</footer>
<!-- Modal -->
<div id="myModal" class="modal">
<div class="modal__wrap">
<div class="container">
<div class="modal__header">
<div class="modal__header-logo">
HOME<b>BARBER</b>
</div>
<div class="modal__header-close">×</div>
</div>
</div>
</div>
<div class="modal__content">
<div class="container">
<div class="modal-content">
<a class="modal-content-links" href="#">Login</a>
<a class="modal-content-links" href="#">Registation</a>
<a class="modal-content-links" href="#">Company</a>
<a class="modal-content-links" href="#">Contact Us</a>
</div>
</div>
</div>
<button type="button" class="modal__button">
<div class="nav__link-stylist-icon">
<img class="nav__icon" src="./images/Vector.png" alt="#">
</div>
<a class="div" href="stylist.html">
BECOME STYLIST
</a>
</button>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"
integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script src="owlcarousel/owl.carousel.min.js"></script>
<script src="./js/slider.js"></script>
<script src="./js/app.js"></script>
</body>
</html><file_sep># homebarber
https://bogdone15.github.io/homebarber/
<p>The home page has active navigation. When you click on "Become Stylist" you will be taken to the corresponding page.</p>
<p>
When you click on the registration icon, you go to this page, where there is an active "Back" button, which returns to the previous page, Tabs (Login and Registration), as well as the Forget password link
, when clicked, a modal window opens with a phone check. When entering a number, a standard mask is automatically generated. When you click on the Send button,
there is a transfer to the page with the verification of the phone, where you need to enter the code from the message. The code is entered with automatic jumping over Input</p>
<p>When you click on Tab with registration, you can go to the page with the registration of the master and registration of the client</p>
| 381b5ae8f2c0a9188730df126789c4c88abff941 | [
"JavaScript",
"HTML",
"Markdown"
] | 4 | JavaScript | BogDone15/homebarber | 4643c2a893f0c5a143ccf0e51e93e9b90c59b7d8 | 9346ef4c6f271618dc1419819e8219f69fb72d29 |
refs/heads/master | <file_sep>package com.monochromeroad.grails.plugins.xwiki;
import org.xwiki.rendering.block.XDOM;
import org.xwiki.rendering.parser.ParseException;
import org.xwiki.rendering.parser.Parser;
import org.xwiki.rendering.syntax.Syntax;
import org.xwiki.rendering.syntax.SyntaxFactory;
import org.xwiki.rendering.transformation.Transformation;
import java.io.*;
/**
* Wiki Text Renderer using XWiki Rendering Engine.
*
* @author <NAME>
*/
public class XWikiRenderer {
private XWikiConfigurationProvider configurationProvider;
private SyntaxFactory syntaxFactory;
private XWikiParserFactory parserFactory;
private XDOMBuilder xdomBuilder = new XDOMBuilder();
private XDOMTransformationManager xdomTransformationManager;
private XDOMWriter xdomWriter;
/**
* Renders a source text using XWiki Rendering Engine.
*
* @param source source text reader
* @param writer output writer
* @param inputSyntax inputSyntax
* @param outputSyntax outputSyntax
* @param transformations transform parameters
*/
public void render(Reader source, Writer writer,
CharSequence inputSyntax, CharSequence outputSyntax, Transformation ...transformations) {
Syntax inputSyntaxObj = getSyntax(inputSyntax);
Syntax outputSyntaxObj = getSyntax(outputSyntax);
Parser parser = parserFactory.getParser(inputSyntaxObj);
XDOM xdom = xdomBuilder.build(source, parser);
xdomTransformationManager.transform(xdom, parser, transformations);
xdomWriter.write(xdom, outputSyntaxObj, writer);
}
/**
* Renders a source text using XWiki rendering engine and default syntax.
*
* @param source source text reader
* @param writer output writer
* @param transformations transform parameters
*/
public void render(Reader source, Writer writer, Transformation ...transformations) {
String inputSyntax = configurationProvider.getDefaultInputSyntax();
String outputSyntax = configurationProvider.getDefaultOutputSyntax();
render(source, writer, inputSyntax, outputSyntax, transformations);
}
/**
* Renders a source text using XWiki rendering engine and default syntax.
*
* @param source source text reader
* @param writer output writer
* @param inputSyntax inputSyntax
* @param outputSyntax outputSyntax
* @param transformations transform parameters
*/
public void render(
CharSequence source, Writer writer,
CharSequence inputSyntax, CharSequence outputSyntax, Transformation ...transformations) {
render(new StringReader(source.toString()), writer, inputSyntax, outputSyntax, transformations);
}
/**
* Renders a source text using XWiki rendering engine and default syntax.
*
* @param source source text reader
* @param writer output writer
* @param transformations transform parameters
*/
public void render(CharSequence source, Writer writer, Transformation...transformations) {
render(new StringReader(source.toString()), writer, transformations);
}
/**
* Returns rendered text from XWiki Rendering.
*
* @param source source text reader
* @param inputSyntax inputSyntax
* @param outputSyntax outputSyntax
* @param transformations transform parameters
* @return a rendered result
*/
public String render(Reader source, String inputSyntax, String outputSyntax, Transformation ...transformations) {
Writer writer = new StringWriter();
render(source, writer, inputSyntax, outputSyntax, transformations);
return writer.toString();
}
/**
* Returns rendered text from XWiki Rendering using default input syntax and default output syntax.
*
* @param source a source text
* @param transformations transform parameters
* @return a rendered result
*/
public String render(Reader source, Transformation ...transformations) {
String inputSyntax = configurationProvider.getDefaultInputSyntax();
String outputSyntax = configurationProvider.getDefaultOutputSyntax();
return render(source, inputSyntax, outputSyntax, transformations);
}
/**
* Returns rendered text from XWiki Rendering.
*
* @param source a source text
* @param inputSyntax inputSyntax
* @param outputSyntax outputSyntax
* @param transformations transform parameters
* @return a rendered result
*/
public String render(CharSequence source,
String inputSyntax, String outputSyntax, Transformation ...transformations) {
return render(new StringReader(source.toString()), inputSyntax, outputSyntax, transformations);
}
/**
* Returns rendered text from XWiki Rendering using default input syntax and default output syntax.
*
* @param source a source text
* @param transformations transform parameters
* @return a rendered result
*/
public String render(CharSequence source, Transformation ...transformations) {
String inputSyntax = configurationProvider.getDefaultInputSyntax();
String outputSyntax = configurationProvider.getDefaultOutputSyntax();
return render(source, inputSyntax, outputSyntax, transformations);
}
void setTransformationManager(XDOMTransformationManager transformationManager) {
this.xdomTransformationManager = transformationManager;
}
void setWriter(XDOMWriter writer) {
this.xdomWriter = writer;
}
void setSyntaxFactory(SyntaxFactory syntaxFactory) {
this.syntaxFactory = syntaxFactory;
}
void setParserFactory(XWikiParserFactory parserFactory) {
this.parserFactory = parserFactory;
}
void setConfigurationProvider(XWikiConfigurationProvider configurationProvider) {
this.configurationProvider = configurationProvider;
}
private Syntax getSyntax(Object id) {
try {
return syntaxFactory.createSyntaxFromIdString(id.toString());
} catch (ParseException e) {
throw new IllegalArgumentException("Invalid Syntax ID: " + id, e);
}
}
}
<file_sep>package com.monochromeroad.grails.plugins.xwiki.artefact;
import com.monochromeroad.grails.plugins.xwiki.macro.GrailsMacro;
import org.codehaus.groovy.grails.commons.ArtefactHandlerAdapter;
public class XwikiMacroArtefactHandler extends ArtefactHandlerAdapter {
public static final String TYPE = "XwikiMacro";
public XwikiMacroArtefactHandler() {
super(TYPE, GrailsXwikiMacroClass.class, DefaultGrailsXwikiMacroClass.class, null);
}
public boolean isArtefactClass(Class clazz) {
return clazz != null && GrailsMacro.class.isAssignableFrom(clazz);
}
}
<file_sep>/**
* 11/10/20
*
* Copyright (c) 2011 Monochromeroad
*/
package com.monochromeroad.grails.plugins.xwiki;
import org.xwiki.rendering.block.Block;
import org.xwiki.rendering.block.RawBlock;
import org.xwiki.rendering.syntax.Syntax;
import org.xwiki.rendering.transformation.AbstractTransformation;
import org.xwiki.rendering.transformation.TransformationContext;
import org.xwiki.rendering.transformation.TransformationException;
public class TestTransformation extends AbstractTransformation {
private String parameter;
private int priority;
public TestTransformation(String parameter, int priority) {
this.parameter = parameter;
this.priority = priority;
}
public void transform(
Block block, TransformationContext transformationContext) throws TransformationException {
block.addChild(new RawBlock(parameter, Syntax.XHTML_1_0));
}
public int getPriority() {
return this.priority;
}
}
<file_sep>package com.monochromeroad.grails.plugins.xwiki;
import org.xwiki.rendering.syntax.Syntax;
import java.util.ArrayList;
import java.util.List;
public class XWikiConfigurationProvider {
// TODO import from a configuration file
// private Map<String, String> config = new HashMap<String, String>();
public String getDefaultInputSyntax() {
return Syntax.XWIKI_2_1.toIdString();
}
public String getDefaultOutputSyntax() {
return Syntax.XHTML_1_0.toIdString();
}
public List<String> getDefaultTransformations() {
List<String> transformations = new ArrayList<String>();
transformations.add("macro");
return transformations;
}
}
<file_sep># XWiki Rendering Framework Grails Integration #
This Grails plugin allows you to convert texts using XWiki Rendering Framework.
[XWiki Rendering Framework](http://rendering.xwiki.org/xwiki/bin/view/Main/WebHome)
The plugin's reference documentation is [here](http://literalice.github.com/grails-xwiki-rendering/).
<file_sep>package com.monochromeroad.grails.plugins.xwiki;
import org.xwiki.rendering.block.XDOM;
import org.xwiki.rendering.parser.Parser;
import org.xwiki.rendering.transformation.Transformation;
import org.xwiki.rendering.transformation.TransformationContext;
import org.xwiki.rendering.transformation.TransformationException;
import java.util.Collections;
import java.util.NavigableSet;
import java.util.TreeSet;
class XDOMTransformationManager {
private NavigableSet<Transformation> defaultTransformations = new TreeSet<Transformation>();
XDOM transform(XDOM xdom, Parser parser, Transformation ...transformations) {
TransformationContext context = new TransformationContext(xdom, parser.getSyntax());
NavigableSet<Transformation> transformationList = getTransformationList(transformations);
try {
for(Transformation transformation : transformationList) {
transformation.transform(xdom, context);
}
} catch (TransformationException e) {
throw new IllegalStateException(e);
}
return xdom;
}
void addDefaultTransformation(Transformation transformation) {
defaultTransformations.add(transformation);
}
private NavigableSet<Transformation> getTransformationList(Transformation ...transformations) {
NavigableSet<Transformation> transformationList =
new TreeSet<Transformation>(defaultTransformations);
Collections.addAll(transformationList, transformations);
return transformationList;
}
}
<file_sep>package com.monochromeroad.grails.plugins.xwiki.macro;
import org.apache.commons.lang.StringUtils;
import org.xwiki.component.descriptor.ComponentDescriptor;
import org.xwiki.component.descriptor.DefaultComponentDescriptor;
import org.xwiki.component.phase.InitializationException;
import org.xwiki.properties.BeanManager;
import org.xwiki.rendering.block.Block;
import org.xwiki.rendering.macro.AbstractMacro;
import org.xwiki.rendering.macro.Macro;
import org.xwiki.rendering.macro.MacroExecutionException;
import org.xwiki.rendering.transformation.MacroTransformationContext;
import java.util.List;
import java.util.Map;
/**
* XWiki Macro Runner in a Grails System
*/
public class GenericGrailsMacro extends AbstractMacro<Object> {
public static GenericGrailsMacro getInstance(Map<String, Object> config, BeanManager beanManager) {
String macroName = (String)config.get("macroName");
String macroFullName = "Grails Macro " + StringUtils.capitalize(macroName);
GrailsMacro macroImpl = (GrailsMacro)config.get("macroImpl");
Boolean inlineSupport = (Boolean)config.get("inlineSupport");
Class parametersBeanClass = (Class)config.get("parametersBeanClass");
GenericGrailsMacro macro =
new GenericGrailsMacro(macroName, macroFullName,
macroImpl, beanManager, parametersBeanClass, inlineSupport);
try {
macro.initialize();
} catch (InitializationException e) {
throw new IllegalStateException(e);
}
return macro;
}
private GrailsMacro macroImpl;
private String macroName;
private Boolean inlineSupport = false;
private GenericGrailsMacro(String macroName, String macroFullName , GrailsMacro macroImpl,
BeanManager beanManager, Class parametersBeanClass, Boolean inlineSupport) {
super(macroFullName, macroImpl.toString(), parametersBeanClass);
this.macroName = macroName;
this.macroImpl = macroImpl;
this.beanManager = beanManager;
this.inlineSupport = inlineSupport;
}
public boolean supportsInlineMode() {
return inlineSupport;
}
public List<Block> execute(Object parameters, String content, MacroTransformationContext context) throws MacroExecutionException {
return macroImpl.execute(parameters, content, context);
}
public String getMacroName() {
return macroName;
}
public ComponentDescriptor createDescriptor() {
DefaultComponentDescriptor<Macro> macroDescriptor =
new DefaultComponentDescriptor<Macro>();
macroDescriptor.setImplementation(GenericGrailsMacro.class);
macroDescriptor.setRoleType(Macro.class);
macroDescriptor.setRoleHint(this.macroName);
return macroDescriptor;
}
}
<file_sep>package com.monochromeroad.grails.plugins.xwiki;
import org.xwiki.rendering.block.XDOM;
import org.xwiki.rendering.parser.ParseException;
import org.xwiki.rendering.parser.Parser;
import java.io.Reader;
/**
* XWiki XDOM Builder
*
* @author <NAME>
*/
class XDOMBuilder {
/**
* Builds XDOM Tree from a source text reader.
*
* @param source source text reader
* @param parser wiki text parser
* @return the built XDOM
*/
public XDOM build(Reader source, Parser parser) {
try {
return parser.parse(source);
} catch (ParseException e) {
throw new IllegalStateException(e);
}
}
}
<file_sep>package com.monochromeroad.grails.plugins.xwiki;
import org.xwiki.component.manager.ComponentManager;
import org.xwiki.rendering.syntax.SyntaxFactory;
import org.xwiki.rendering.transformation.Transformation;
import java.util.List;
public class XWikiRendererConfigurator {
public static void initialize(XWikiRenderer renderer,
XWikiConfigurationProvider configurationProvider, ComponentManager componentManager) {
XWikiComponentRepository componentRepository = new XWikiComponentRepository(componentManager);
renderer.setConfigurationProvider(configurationProvider);
renderer.setParserFactory(new XWikiParserFactory(componentRepository));
renderer.setSyntaxFactory(getSyntaxFactory(componentRepository));
XDOMTransformationManager transformationManager =
createTransformationManager(componentRepository, configurationProvider);
renderer.setTransformationManager(transformationManager);
renderer.setWriter(new XDOMWriter(componentRepository));
}
private static XDOMTransformationManager createTransformationManager(
XWikiComponentRepository componentRepository, XWikiConfigurationProvider configurationProvider) {
XDOMTransformationManager manager = new XDOMTransformationManager();
List<String> defaultTransformations = configurationProvider.getDefaultTransformations();
for (String transformation : defaultTransformations) {
manager.addDefaultTransformation(
componentRepository.lookupComponent(Transformation.class, transformation));
}
return manager;
}
private static SyntaxFactory getSyntaxFactory(XWikiComponentRepository componentRepository) {
return componentRepository.
lookupComponent(SyntaxFactory.class);
}
}
<file_sep>package com.monochromeroad.grails.plugins.xwiki;
import org.xwiki.component.manager.ComponentLookupException;
import org.xwiki.component.manager.ComponentManager;
public class XWikiComponentRepository {
private final ComponentManager componentManager;
public XWikiComponentRepository(ComponentManager componentManager) {
this.componentManager = componentManager;
}
public <T> T lookupComponent(Class<T> componentClass) {
try {
return componentManager.getInstance(componentClass);
} catch (ComponentLookupException e) {
throw new IllegalStateException(e);
}
}
public <T> T lookupComponent(Class<T> componentClass, String parameter) {
try {
return componentManager.getInstance(componentClass, parameter);
} catch (ComponentLookupException e) {
throw new IllegalStateException(e);
}
}
}
| 8751f6d85c025b213a470baaff3c77b2f1281d14 | [
"Markdown",
"Java"
] | 10 | Java | jvelo/grails-xwiki-rendering | 4b9ccb8e03e8b1de9e29e0b48feb4208e45b892b | 2d352122cb7f5366af27b1b6f17ecd21dc0a3d07 |
refs/heads/main | <file_sep>import {
TYPE_CURSOS_SET_CEP,
TYPE_CURSOS_SET_CEP_LOGRADOURO,
TYPE_CURSOS_SET_CEP_LOGRADOURO_COMPLEMENTO,
TYPE_USUARIO_SET_CPF,
TYPE_USUARIO_SET_DATA_NASC,
TYPE_USUARIO_SET_EMAIL,
TYPE_USUARIO_SET_ENDERECO,
TYPE_USUARIO_SET_ID_USUARIO_MOCK,
TYPE_USUARIO_SET_NOME,
TYPE_USUARIO_SET_NUMERO,
TYPE_USUARIO_SET_SENHA,
} from "../actions/usuario";
const INITIAL_STATE = {
lista: [],
cpf: "",
isCpfValido: true,
cep: null,
isCepValido: true,
endereco: null,
isEnderecoValido: true,
numero: null,
isNumeroValido: true,
_idUsuario: "",
dataNasc: "",
isDataNascValido: true,
nomeUsuario: "",
isNomeUsuarioValido: true,
email: "",
isEmailValido: true,
senha: "",
isSenhaValido: true,
redireciona: false,
listaIdTarefa: [],
};
export const usuarioReducer = (state = INITIAL_STATE, action) => {
switch (action.type) {
case TYPE_USUARIO_SET_NOME:
return {
...state,
nomeUsuario: action.value,
isNomeUsuarioValido: action.isValido,
};
case TYPE_USUARIO_SET_CPF:
return { ...state, cpf: action.value, isCpfValido: action.isValido };
case TYPE_USUARIO_SET_DATA_NASC:
return {
...state,
dataNasc: action.value,
isDataNascValido: action.isValido,
};
case TYPE_USUARIO_SET_EMAIL:
return { ...state, email: action.value, isEmailValido: action.isValido };
case TYPE_USUARIO_SET_SENHA:
return { ...state, senha: action.value, isSenhaValido: action.isValido };
case TYPE_CURSOS_SET_CEP_LOGRADOURO_COMPLEMENTO:
return {
...state,
cep: action.value,
endereco: action.logradouro,
numero: action.complemento,
isCepValido: action.isCepValido,
isEnderecoValido: action.isEnderecoValido,
isNumeroValido: action.isNumeroValido,
};
case TYPE_CURSOS_SET_CEP_LOGRADOURO:
return {
...state,
cep: action.value,
endereco: action.logradouro,
isCepValido: action.isCepValido,
isEnderecoValido: action.isEnderecoValido,
};
case TYPE_CURSOS_SET_CEP:
return {
...state,
cep: action.value,
isCepValido: action.isCepValido,
};
case TYPE_USUARIO_SET_ENDERECO:
return {
...state,
endereco: action.value,
isEnderecoValido: action.isValido,
};
case TYPE_USUARIO_SET_NUMERO:
return {
...state,
numero: action.value,
isNumeroValido: action.isValido,
};
case TYPE_USUARIO_SET_ID_USUARIO_MOCK: // uso temporario, e nao será necessário conforme implementacao da rota de login no servidor
return {
...state,
_idUsuario: action.value,
};
default:
return state;
}
};
<file_sep>import React from "react";
import { connect } from "react-redux";
import { bindActionCreators } from "redux";
import {
limparFormularioTarefas,
salvarTarefa,
setDataFim,
setDataInicio,
setNomeTarefa,
} from "../../actions/tarefa";
const FormularioTarefas = (props) => {
const {
nomeTarefa,
dataInicio,
dataFim,
idUsuario, // a receber, apos requisicao especifica ao servidor
setNomeTarefa,
setDataInicio,
setDataFim,
isNomeTarefaValido,
isDataInicioValido,
isDataFimValido,
salvarTarefa,
limparFormularioTarefas,
_id,
} = props;
return (
<div className="border-right pl-3 pr-3 pt-4">
<h3 className="border-bottom">Cadastro de Tarefas</h3>
<form>
<div
className={`form-group ${
!isNomeTarefaValido ? "errorInput" : ""
} row pt-4`}
>
<label htmlFor="nomeTarefa" className="col-sm-3 col-form-label">
*Nome:
</label>
<div className="col-sm-7">
<input
type="string"
className={`form-control`}
id="nomeTarefa"
value={nomeTarefa}
onChange={setNomeTarefa}
/>
</div>
</div>
<div
className={`form-group ${
!isDataInicioValido ? "errorInput" : ""
} row pt-2 `}
>
<label htmlFor="dataInicio" className="col-sm-3 col-form-label">
*Início:
</label>
<div className="col-sm-6">
<input
type="date"
name="startDate"
id="dataInicio"
value={dataInicio}
onChange={setDataInicio}
/>
</div>
</div>
<div
className={`form-group ${
dataFim < dataInicio && dataFim !== "" ? "errorInput" : ""
} row `}
>
<label htmlFor="dataFim" className="col-sm-3 col-form-label">
Conclusão:
</label>
<div className="col-sm-6">
<input
type="date"
name="endDate"
id="dataFim"
value={dataFim}
onChange={setDataFim}
/>
</div>
</div>
<div className="form-group row">
<button
className="btn btn-primary ml-3 mb-3"
disabled={
!(
isNomeTarefaValido &&
isDataInicioValido &&
isDataFimValido &&
(dataInicio < dataFim || dataFim === "") &&
nomeTarefa &&
dataInicio
)
}
onClick={(e) =>
salvarTarefa(e, {
isNomeTarefaValido,
nomeTarefa,
isDataInicioValido,
dataInicio,
isDataFimValido,
dataFim,
idUsuario,
_id,
})
}
>
{_id ? "Atualizar" : "Adicionar"}
</button>
<button
className="btn btn-secondary ml-3 mb-3"
type="button"
onClick={limparFormularioTarefas}
>
Limpar
</button>
</div>
</form>
</div>
);
};
const mapStoreToProps = (store) => ({
isNomeTarefaValido: store.tarefas.isNomeTarefaValido,
nomeTarefa: store.tarefas.nomeTarefa,
isDataInicioValido: store.tarefas.isDataInicioValido,
dataInicio: store.tarefas.dataInicio,
isDataFimValido: store.tarefas.isDataFimValido,
dataFim: store.tarefas.dataFim,
idUsuario: store.usuarios._idUsuario, // temporario, para armazenar idUsuario a ser inscrito conforme se registrem tarefas
_id: store.tarefas._id,
});
const mapActionToProps = (dispatch) =>
bindActionCreators(
{
setNomeTarefa,
setDataInicio,
setDataFim,
salvarTarefa,
limparFormularioTarefas,
},
dispatch
);
const conectado = connect(mapStoreToProps, mapActionToProps)(FormularioTarefas);
export { conectado as FormularioTarefas };
<file_sep>import React from "react";
import { FormularioUsuario } from "./Formulario";
export class FuncoesFormUsuario extends React.Component {
render() {
return (
<div className="row border-bottom">
<FormularioUsuario />
</div>
);
}
}
<file_sep>import React from "react";
import { connect } from "react-redux";
import { bindActionCreators } from "redux";
import {
salvarUsuario,
setCep,
setCpf,
setDataNasc,
setEmail,
setEndereco,
setNomeUsuario,
setNumero,
setSenha,
} from "../../actions/usuario";
const FormularioUsuario = (props) => {
const {
nomeUsuario,
isNomeUsuarioValido,
setNomeUsuario,
dataNasc,
isDataNascValido,
setDataNasc,
email,
isEmailValido,
setEmail,
senha,
isSenhaValido,
setSenha,
cep,
isCepValido,
setCep,
endereco,
numero,
isEnderecoValido,
isNumeroValido,
setEndereco,
setNumero,
cpf,
isCpfValido,
setCpf,
salvarUsuario,
isPublic,
} = props;
return (
<div className="cadastroScreen">
{isPublic ? (
<div className=" pt-5 pb-5 ">
<h1>Esqueça como é se esquecer</h1>
<p className="col-sm-5 pt-4 pb-3 ">
O gerenciador de tarefas é uma poderosa ferramenta para incrementar
a produtivdade, sem perder o foco naquilo que importa.
</p>
<div className={`form-group row `}>
<div className="col-sm-6">
<input
type="string"
className={`form-control`}
value={email}
onChange={setEmail}
placeholder="Email"
id="email"
/>
</div>
<div className="">
<button
className="btn btn-primary ml-3 mr-3 mb-3"
onClick={(e) =>
salvarUsuario(e, {
cpf,
cep,
endereco,
numero,
dataNasc,
nomeUsuario,
email,
senha,
isNomeUsuarioValido,
isDataNascValido,
isEmailValido,
isSenhaValido,
isPublic,
})
}
>
Registrar
</button>
</div>
</div>
</div>
) : (
<div>
<h3 className={`border-bottom pt-4 pl-4 `}>
Formulario de cadastro de Usuario
</h3>
<form className={`border-bottom pt-3 pr-3 pl-3 `}>
<div
className={`form-group ${
!isNomeUsuarioValido ? "errorInput" : ""
} row `}
>
<label htmlFor="nomeUsuario" className="col-sm-3 col-form-label">
Nome*:
</label>
<div className="col-sm-6">
<input
type="string"
className={`form-control`}
id="nomeUsuario"
value={nomeUsuario}
onChange={setNomeUsuario}
/>
</div>
</div>
<div
className={`form-group ${!isCpfValido ? "errorInput" : ""} row `}
>
<label htmlFor="cpfUsuario" className="col-sm-3 col-form-label">
CPF:
</label>
<div className="col-sm-6">
<input
type="number"
className={`form-control`}
id="cpfUsuario"
placeholder="12345678901"
value={cpf}
onChange={setCpf}
/>
</div>
</div>
<div
className={`form-group ${
!isDataNascValido ? "errorInput" : ""
} row `}
>
<label htmlFor="nascimento" className="col-sm-3 col-form-label">
Data de nascimento*:
</label>
<div className="col-sm-6">
<input
type="date"
value={dataNasc}
onChange={setDataNasc}
id="dataNasc"
/>
</div>
</div>
<div
className={`form-group ${
!isEmailValido ? "errorInput" : ""
} row `}
>
<label htmlFor="email" className="col-sm-3 col-form-label">
Email*:
</label>
<div className="col-sm-6">
<input
type="string"
className={`form-control`}
value={email}
onChange={setEmail}
id="email"
/>
</div>
</div>
<div
className={`form-group ${
!isSenhaValido ? "errorInput" : ""
} row `}
>
<label htmlFor="senha" className="col-sm-3 col-form-label">
Senha*:
</label>
<div className="col-sm-6">
<input
type="password"
className={`form-control`}
value={senha}
onChange={setSenha}
id="senha"
/>
</div>
</div>
<div className={`form-group ${!isCepValido ? "" : ""} row `}>
<label htmlFor="cep" className="col-sm-3 col-form-label">
CEP:
</label>
<div className="col-sm-6 mb-3">
<input
type="number"
className={`form-control`}
placeholder="12345678"
value={cep}
onChange={setCep}
id="cep"
/>
</div>
</div>
<div className={`form-group ${!isEnderecoValido ? "" : ""} row `}>
<label htmlFor="logradouro" className="col-sm-3 col-form-label">
Endereço:
</label>
<div className="col-sm-6">
<input
type="string"
className={`form-control`}
value={endereco}
onChange={setEndereco}
id="endereco"
/>
</div>
</div>
<div className={`form-group ${!isNumeroValido ? "" : ""} row `}>
<label
htmlFor="numeroEndereco"
className="col-sm-3 col-form-label"
>
Complemento:
</label>
<div className="col-sm-6">
<input
type="string"
className={`form-control`}
value={numero}
onChange={setNumero}
id="numero"
/>
</div>
</div>
<div className="row d-flex justify-content-center">
<button
className="btn btn-primary ml-3 mr-3 mb-3"
disabled={
!(
isNomeUsuarioValido &&
isDataNascValido &&
isEmailValido &&
isSenhaValido &&
nomeUsuario &&
dataNasc &&
email &&
senha
)
}
onClick={(e) =>
salvarUsuario(e, {
cpf,
cep,
endereco,
numero,
dataNasc,
nomeUsuario,
email,
senha,
isNomeUsuarioValido,
isDataNascValido,
isEmailValido,
isSenhaValido,
})
}
>
Adicionar
</button>
</div>
</form>
</div>
)}
</div>
);
};
const mapStoreToProps = (store) => ({
cpf: store.usuarios.cpf,
isCpfValido: store.usuarios.isCpfValido,
cep: store.usuarios.cep,
isCepValido: store.usuarios.isCepValido,
endereco: store.usuarios.endereco,
isEnderecoValido: store.usuarios.isEnderecoValido,
numero: store.usuarios.numero,
isNumeroValido: store.usuarios.isNumeroValido,
_idUsuario: store.usuarios._idUsuario,
dataNasc: store.usuarios.dataNasc,
isDataNascValido: store.usuarios.isDataNascValido,
nomeUsuario: store.usuarios.nomeUsuario,
isNomeUsuarioValido: store.usuarios.isNomeUsuarioValido,
email: store.usuarios.email,
isEmailValido: store.usuarios.isEmailValido,
senha: store.usuarios.senha,
isSenhaValido: store.usuarios.isSenhaValido,
listaIdTarefa: store.usuarios.listaIdTarefa,
});
const mapActionToProps = (dispatch) =>
bindActionCreators(
{
setNomeUsuario,
setDataNasc,
setEmail,
setSenha,
setCep,
setEndereco,
setNumero,
setCpf,
salvarUsuario,
},
dispatch
);
const conectado = connect(mapStoreToProps, mapActionToProps)(FormularioUsuario);
export { conectado as FormularioUsuario };
<file_sep>import "bootstrap/dist/css/bootstrap.min.css";
import "bootstrap/dist/js/bootstrap.min.js";
import "font-awesome/css/font-awesome.min.css";
import "jquery/dist/jquery.min.js";
import React from "react";
import ReactDOM from "react-dom";
import { Provider } from "react-redux";
import { BrowserRouter } from "react-router-dom";
import { applyMiddleware, createStore } from "redux";
import { persistReducer, persistStore } from "redux-persist";
import { PersistGate } from "redux-persist/integration/react";
import storage from "redux-persist/lib/storage";
import thunk from "redux-thunk";
import { App } from "./App";
import "./index.css";
import reducers from "./reducers";
const createStoreWithMiddleware = applyMiddleware(thunk)(createStore);
const storeWithMiddleware = createStoreWithMiddleware(reducers);
const persistConfig = {
key: "root",
storage,
};
const persistedReducer = persistReducer(persistConfig, reducers);
let store = createStore(persistedReducer);
let persistor = persistStore(store);
ReactDOM.render(
<React.StrictMode>
<BrowserRouter>
<Provider store={storeWithMiddleware}>
<PersistGate loading={null} persistor={persistor}>
<App />
</PersistGate>
</Provider>
</BrowserRouter>
</React.StrictMode>,
document.getElementById("root")
);
<file_sep>import React from "react";
import { LoginUsuario } from "../components/cadastro/Login";
export class LoginScreen extends React.Component {
render() {
return (
<div className="container homeScreen">
<LoginUsuario />
</div>
);
}
}
<file_sep>import React from "react";
import { Route, Switch } from "react-router-dom";
import { Menu } from "./components/Menu";
import { CadastroScreen } from "./screens/CadastroUsuario";
import { HomeScreen } from "./screens/Home";
import { LoginScreen } from "./screens/Login";
import { TarefaScreen } from "./screens/Tarefas";
export class App extends React.Component {
render() {
return (
<div className="container">
<Menu />
<Switch>
<Route path="/cadastro" component={CadastroScreen} />
<Route path="/tarefas" component={TarefaScreen} />
<Route path="/login" component={LoginScreen} />
<Route path="/" component={HomeScreen} />
</Switch>
</div>
);
}
}
<file_sep>import axios from "axios";
import swal from "sweetalert";
export const TYPE_TAREFA_GET_LISTA = "TYPE_TAREFA_GET_LISTA";
export const TYPE_TAREFA_SET_NOME_TAREFA = "TYPE_TAREFA_SET_NOME_TAREFA";
export const TYPE_TAREFA_SET_DATA_INICIO = "TYPE_TAREFA_SET_DATA_INICIO";
export const TYPE_TAREFA_SET_DATA_FIM = "TYPE_TAREFA_SET_DATA_FIM";
export const TYPE_TAREFA_LIMPAR_FORM = "TYPE_TAREFA_LIMPAR_FORM";
export const TYPE_TAREFA_SELECIONAR_TAREFA = "TYPE_TAREFA_SELECIONAR_TAREFA";
const URL = "http://localhost:3201/api/tarefas/";
// o ideal seria fazer uma request à API, enviando _idUsuario, a fim de receber uma lista de listas a partir da URL inserida (URL + _idUsuario)
//para isso, na API, deve-se criar nova rota e criar middleware específicos para a tarefa de selecionar listas que possuam campo _idUsuario valido (usando find())
export const getTarefas = () => {
return async (dispatch) => {
try {
const response = await axios.get(URL);
if (response && response.data) {
dispatch({
type: TYPE_TAREFA_GET_LISTA,
value: response.data,
});
}
} catch (e) {
console.log(e);
swal(
"Erro!",
"Não foi possível listar tarefas, tente novamente mais tarde!",
"error"
);
}
};
};
export const setNomeTarefa = (e) => {
const value = e?.target?.value;
let isValido = true;
if (!value || value.length < 3) {
isValido = false;
}
return {
type: TYPE_TAREFA_SET_NOME_TAREFA,
value: value,
isValido: isValido,
};
};
export const setDataInicio = (e) => {
const value = e?.target?.value;
let isValido = true;
if (!value) {
isValido = false;
}
return {
type: TYPE_TAREFA_SET_DATA_INICIO,
value: value,
isValido: isValido,
};
};
export const setDataFim = (e) => {
const value = e?.target?.value;
let isValido = true;
if (!value) {
isValido = false;
}
return {
type: TYPE_TAREFA_SET_DATA_FIM,
value: value,
isValido: isValido,
};
};
export const limparFormularioTarefas = () => {
return {
type: TYPE_TAREFA_LIMPAR_FORM,
};
};
export const selecionarTarefa = (tarefa) => {
return {
type: TYPE_TAREFA_SELECIONAR_TAREFA,
value: tarefa,
};
};
export const salvarTarefa = (evento, formulario) => {
return async (dispatch) => {
try {
const {
isNomeTarefaValido,
nomeTarefa,
isDataInicioValido,
dataInicio,
isDataFimValido,
dataFim,
idUsuario,
_id,
} = formulario;
if (evento) {
evento.preventDefault();
}
if (
!(
isNomeTarefaValido &&
isDataInicioValido &&
isDataFimValido &&
(dataInicio < dataFim || dataFim === "") &&
nomeTarefa &&
dataInicio
)
) {
swal("Ops!", "favor preencher todos os campos", "error");
return;
}
const body = {
idUsuario,
nomeTarefa,
dataInicio,
dataFim,
};
if (_id) {
await axios.put(URL + _id, body);
} else {
await axios.post(URL, body);
}
dispatch(getTarefas());
dispatch(limparFormularioTarefas());
swal(
"Parabéns!",
`Tarefa ${_id ? "atualizada" : "salva"} com sucesso!`,
"success"
);
} catch (e) {
console.log(e);
swal(
"Erro!",
"Não foi possível salvar tarefa, tente novamente mais tarde!",
"error"
);
}
};
};
export const excluirTarefa = (_id) => {
return async (dispatch) => {
console.log("a");
try {
if (!_id) {
swal("Erro!", "Identificação da tarefa não informada!", "error");
return;
}
const result = await swal({
title: "Tem certeza?",
text: "Após deletado, a tarefa não poderá ser restaurada",
icon: "warning",
buttons: true,
dangerMode: true,
});
if (result) {
console.log(URL + _id);
await axios.delete(URL + _id);
dispatch(getTarefas());
swal("Parabéns!", "Tarefa deletada com sucesso", "success");
}
} catch (e) {
console.log(e);
swal(
"Erro!",
"Não foi possível excluir tarefa, tente novamente mais tarde!",
"error"
);
}
};
};
<file_sep>const express = require("express");
module.exports = (server) => {
const routes = express.Router();
server.use("/api", routes);
const { UsuarioService } = require("../services/cadastroUsuario");
UsuarioService.register(routes, "/usuario");
const { TarefaService } = require("../services/tarefas");
TarefaService.register(routes, "/tarefas");
};
<file_sep>import React, { useEffect } from "react";
import { connect } from "react-redux";
import { bindActionCreators } from "redux";
import {
excluirTarefa,
getTarefas,
selecionarTarefa,
} from "../../actions/tarefa";
const ListagemTarefas = (props) => {
const {
listaTarefas,
getTarefas,
excluirTarefa,
selecionarTarefa,
_idUsuario,
} = props;
useEffect(() => {
getTarefas();
}, [getTarefas]);
const exibirLinhas = () => {
const tarefas = listaTarefas || [];
return tarefas.map((tarefa) => (
<tr key={tarefa._id}>
<td>{tarefa.nomeTarefa}</td>
<td>{`${
tarefa.dataInicio === null ? "" : tarefa.dataInicio.substring(0, 10)
}`}</td>
<td>{`${
tarefa.dataFim === null ? "" : tarefa.dataFim.substring(0, 10)
}`}</td>
<td>
<button
className="btn btn-success ml-2"
onClick={(_) => selecionarTarefa(tarefa)}
>
<i className="fa fa-check"></i>
</button>
<button
className="btn btn-danger ml-2"
onClick={(_) => excluirTarefa(tarefa._id)}
>
<i className="fa fa-trash-o"></i>
</button>
</td>
</tr>
));
};
return (
<div className="border-right pl-2 pr-2 pt-3">
<h3 className="b">Lista de Tarefas</h3>
<table className="table table-striped">
<thead>
<tr>
<th>Nome</th>
<th>Data Início</th>
<th>Data Término</th>
<th></th>
</tr>
</thead>
<tbody>{exibirLinhas()}</tbody>
<div>{console.log(_idUsuario)}</div>
</table>
</div>
);
};
const mapStoreToProps = (store) => ({
listaTarefas: store.tarefas.lista,
_idUsuario: store.usuarios._idUsuario,
});
const mapActionToProps = (dispatch) =>
bindActionCreators(
{
excluirTarefa,
selecionarTarefa,
getTarefas,
},
dispatch
);
const conectado = connect(mapStoreToProps, mapActionToProps)(ListagemTarefas);
export { conectado as ListagemTarefas };
<file_sep>const nodeRestful = require("node-restful");
const schema = new nodeRestful.mongoose.Schema({
data: { type: Date, required: true },
nome: { type: String, required: true },
email: { type: String, required: true },
senha: { type: String, required: true },
cpf: { type: String, required: false, default: "123.456.789-XX" },
cep: { type: String, required: false, default: "12345-67" },
endereco: { type: String, required: false, default: "Avenida Brasil" },
numero: { type: String, required: false, default: "01" },
});
exports.UsuarioSchema = nodeRestful.model("contatos", schema);
<file_sep>import React from "react";
import { FuncoesFormUsuario } from "../components/cadastro/Funcoes";
export class CadastroScreen extends React.Component {
render() {
return (
<div className="container">
<FuncoesFormUsuario />
</div>
);
}
}
<file_sep>const nodeRestful = require("node-restful");
const schema = new nodeRestful.mongoose.Schema({
idUsuario: { type: String, required: true },
nomeTarefa: { type: String, required: true },
dataInicio: { type: Date, required: true },
dataFim: { type: Date, required: false, default: null },
});
exports.TarefaSchema = nodeRestful.model("tarefa", schema);
<file_sep>import axios from "axios";
import { cpf } from "cpf-cnpj-validator";
import swal from "sweetalert";
export const TYPE_USUARIO_SET_NOME = "TYPE_USUARIO_SET_NOME";
export const TYPE_USUARIO_SET_CPF = "TYPE_USUARIO_SET_CPF";
export const TYPE_USUARIO_SET_DATA_NASC = "TYPE_USUARIO_SET_DATA_NASC";
export const TYPE_USUARIO_SET_EMAIL = "TYPE_USUARIO_SET_EMAIL";
export const TYPE_USUARIO_SET_SENHA = "TYPE_USUARIO_SET_SENHA";
export const TYPE_CURSOS_SET_CEP_LOGRADOURO_COMPLEMENTO =
"TYPE_CURSOS_SET_CEP_LOGRADOURO_COMPLEMENTO";
export const TYPE_CURSOS_SET_CEP_LOGRADOURO = "TYPE_CURSOS_SET_CEP_LOGRADOURO";
export const TYPE_CURSOS_SET_CEP = "TYPE_CURSOS_SET_CEP";
export const TYPE_USUARIO_SET_ENDERECO = "TYPE_USUARIO_SET_ENDERECO";
export const TYPE_USUARIO_SET_NUMERO = "TYPE_USUARIO_SET_NUMERO";
export const TYPE_USUARIO_SET_ID_USUARIO_MOCK =
"TYPE_USUARIO_SET_ID_USUARIO_MOCK";
const URL = "http://localhost:3201/api/usuario/";
const URLcep = "https://viacep.com.br/ws/";
export const setNomeUsuario = (e) => {
const value = e?.target?.value;
let isValido = true;
if (!value || value.length < 3) {
isValido = false;
}
return {
type: TYPE_USUARIO_SET_NOME,
value: value,
isValido: isValido,
};
};
export const setCpf = (e) => {
const value = e?.target?.value;
let isValido = false;
if (value && cpf.isValid(value)) {
isValido = true; // ordem invertida
}
return {
type: TYPE_USUARIO_SET_CPF,
value: value,
isValido: isValido,
};
};
export const setDataNasc = (e) => {
const value = e?.target?.value;
// alternativa: utilizar moment para manipular as datas em questao
console.log(value);
const valueAno = parseInt(value.substring(0, 4));
console.log(valueAno);
const valueMes = parseInt(value.substring(5, 7));
const valueDia = parseInt(value.substring(8, 10));
const hoje = new Date();
const hojeAno = hoje.getFullYear();
console.log(hojeAno);
const hojeMes = hoje.getMonth();
const hojeDia = hoje.getDate();
let isValido = true;
if (
!value ||
valueAno + 12 > hojeAno ||
(valueAno + 12 === hojeAno && valueMes > hojeMes) ||
(valueAno + 12 === hojeAno && valueMes === hojeMes && valueDia > hojeDia)
) {
isValido = false;
}
return {
type: TYPE_USUARIO_SET_DATA_NASC,
value: value,
isValido: isValido,
};
};
export const setEmail = (e) => {
const value = e?.target?.value;
let isValido = true;
if (
!value ||
value.length < 5 ||
!value.includes("@") ||
!value.includes(".")
) {
isValido = false;
}
return {
type: TYPE_USUARIO_SET_EMAIL,
value: value,
isValido: isValido,
};
};
export const setSenha = (e) => {
const value = e?.target?.value;
let isValido = true;
if (!value || value.length < 6) {
// opcao: exigir tambem caracteres especiais
isValido = false;
}
return {
type: TYPE_USUARIO_SET_SENHA,
value: value,
isValido: isValido,
};
};
export const setCep = (evento) => {
return async (dispatch) => {
try {
const value = evento?.target?.value;
if (value.length === 8) {
try {
console.log("a");
const response = await axios
.get(URLcep + value + "/json/")
.then((response) => {
// alternativa: switch case
if (response.data.logradouro && response.data.complemento) {
dispatch({
type: TYPE_CURSOS_SET_CEP_LOGRADOURO_COMPLEMENTO,
cep: value,
logradouro: response.data.logradouro,
complemento: response.data.complemento,
isCepValido: true,
isEnderecoValido: true,
isNumeroValido: true,
});
} else {
if (response.data.logradouro && !response.data.complemento) {
dispatch({
type: TYPE_CURSOS_SET_CEP_LOGRADOURO,
cep: value,
logradouro: response.data.logradouro,
isCepValido: true,
isEnderecoValido: true,
});
} else {
dispatch({
type: TYPE_CURSOS_SET_CEP,
cep: value,
isCepValido: true,
});
}
}
});
} catch (e) {
console.log(e);
}
}
} catch (e) {
console.log(e);
}
};
};
export const setEndereco = (e) => {
const value = e?.target?.value;
let isValido = true;
if (!value || value.length < 3) {
isValido = false;
}
return {
type: TYPE_USUARIO_SET_ENDERECO,
value: value,
isValido: isValido,
};
};
export const setNumero = (e) => {
const value = e?.target?.value;
let isValido = true;
if (!value) {
isValido = false;
}
return {
type: TYPE_USUARIO_SET_NUMERO,
value: value,
isValido: isValido,
};
};
export const redirecionaTarefa = () => {
window.location = "/tarefas"; // para aplicações mobile, substituir por método equivalente que seja compatível
};
// o ideal seria fazer uma request à API, enviando email+senha, a fim de receber um parametro de retorno (como _idUsuario), para poder selecionar a lista de tarefas apenas do usuario em questao
//para isso, na API, deve-se criar nova rota e criar middleware específicos para a tarefa de login (usando find() ou findOne())
export const loginUsuario = (evento, formularioLogin) => {
return async (dispatch) => {
try {
const { email, isEmailValido, senha, isSenhaValido } = formularioLogin;
if (evento) {
evento.preventDefault();
}
let idMock = email + senha; // uma alternativa seria codificar a combinacao email+senha usando um algorito codificador, como base64 (existe módulo npm que pode auxiliar nisso), para enviar essa combinação para o servidor
return {
type: TYPE_USUARIO_SET_ID_USUARIO_MOCK,
value: idMock,
};
} catch (e) {
console.log(e);
}
};
};
export const salvarUsuario = (evento, formulario) => {
return async (dispatch) => {
try {
const {
cpf,
cep,
endereco,
numero,
dataNasc,
nomeUsuario,
email,
senha,
isNomeUsuarioValido,
isDataNascValido,
isEmailValido,
isSenhaValido,
isPublic,
} = formulario;
if (evento) {
evento.preventDefault();
}
if (isPublic) {
dispatch(setEmail(evento));
window.location = "/cadastro";
return;
}
if (
!(
isNomeUsuarioValido &&
isDataNascValido &&
isEmailValido &&
isSenhaValido
)
) {
swal("Ops!", "Favor preencher todos os campos corretamente", "error");
return;
}
const body = {
cpf,
cep,
endereco,
numero,
data: dataNasc,
nome: nomeUsuario,
email,
senha,
};
console.log("a");
await axios.post(URL, body);
swal("Parabéns!", "Cadastro salvo com sucesso", "success");
setTimeout(() => {
window.location = "/home";
}, 2500);
} catch (e) {
console.log(e);
swal(
"Erro!",
"Não foi possível salvar cadastro, tente novamente mais tarde!",
"error"
);
}
};
};
<file_sep># APP de Tasks
Para instalar:
```
git clone https://github.com/Andrei-Araujo/Tasks.git
cd Tasks
npm i
```
Para executar:
- Executar servidor
1) ```cd api```
2) ```npx nodemon```
- Executar client
1) ```cd site```
2) ```npm start```
- Para executar o projeto completo, executar servidor e client a partir de instâncias distintas da linha de comando
<file_sep>const express = require("express");
const cors = require("./cors");
const port = 3201;
const server = express();
server.use(express.urlencoded({ extended: true }));
server.use(express.json());
server.use(cors);
server.listen(port, () => console.log(`Servidor no ar na porta ${port}`));
module.exports = server;
<file_sep>require("./configs/db");
console.log("Conectado");
const server = require("./configs/server");
const routes = require("./configs/routes");
routes(server);
<file_sep>import React from "react";
import { connect } from "react-redux";
import { bindActionCreators } from "redux";
import {
loginUsuario,
redirecionaTarefa,
setEmail,
setSenha,
} from "../../actions/usuario";
const LoginUsuario = (props) => {
const {
email,
isEmailValido,
setEmail,
senha,
isSenhaValido,
setSenha,
loginUsuario,
_idUsuario, // a receber, apos requisicao especifica ao servidor
} = props;
return (
<div className="loginScreen">
<div>
<h3 className={`border-bottom pt-4 `}>Login de Usuario</h3>
<form className={`border-bottom pt-3 pr-3 pl-3 `}>
<div
className={`form-group ${!isEmailValido ? "errorInput" : ""} row `}
>
<label htmlFor="email" className="col-sm-3 col-form-label">
Email*:
</label>
<div className="col-sm-6">
<input
type="string"
className={`form-control`}
value={email}
onChange={setEmail}
id="email"
/>
</div>
</div>
<div
className={`form-group ${!isSenhaValido ? "errorInput" : ""} row `}
>
<label htmlFor="senha" className="col-sm-3 col-form-label">
Senha*:
</label>
<div className="col-sm-6">
<input
type="password"
className={`form-control`}
value={senha}
onChange={setSenha}
id="senha"
/>
</div>
</div>
<div className="row d-flex justify-content-center">
<button
className="btn btn-primary ml-3 mr-3 mb-3"
disabled={!(isEmailValido && isSenhaValido && email && senha)}
onClick={(e) => {
loginUsuario(e, {
email,
senha,
isEmailValido,
isSenhaValido,
});
redirecionaTarefa();
}}
>
Adicionar
</button>
</div>
</form>
</div>
</div>
);
};
const mapStoreToProps = (store) => ({
email: store.usuarios.email,
isEmailValido: store.usuarios.isEmailValido,
senha: store.usuarios.senha,
isSenhaValido: store.usuarios.isSenhaValido,
_idUsuario: store.usuarios._idUsuario,
});
const mapActionToProps = (dispatch) =>
bindActionCreators(
{
setEmail,
setSenha,
loginUsuario,
},
dispatch
);
const conectado = connect(mapStoreToProps, mapActionToProps)(LoginUsuario);
export { conectado as LoginUsuario };
| 25e5f5b21c41792473080c86e826462cf56232b7 | [
"JavaScript",
"Markdown"
] | 18 | JavaScript | Andrei-Araujo/Tasks | 711a5f9ff43664225c475f5755fb7044b88f1171 | d54385aae158e41241108f20247fd95b298d68c0 |
refs/heads/master | <file_sep># GeneratedEye
Uses: Numpy, Caseman's Noise (https://github.com/caseman/noise), math, random, and PIL
(with a few other random libraries thrown in for experimentation).
Program to automatically generate a random eye using fractal simplex noise.
There are some color options that generate multiple brownian noise flowfields in order to color the eye.
Some black and white images are added as well, as I wasn't very succcessful in finding a good way to color the generated eye, but
I have been working on some other flowfields to devise a way to color.
Similarly, if interested, Inconvergent has a very interesting coloring method, but seeing as this program is already a bit bloated
(takes a while to run and generate the multiple fields even with multiprocessing), I'll leave this as something to think about for anyone
who might seek to pick this up and build on it.
https://github.com/inconvergent/sand-spline
Out10.png is also somewhat edited in photoshop to increase the colors and change them around a little bit to see what could be with
some improvements to coloring and flowfields.
<file_sep># -*- coding: utf-8 -*-
"""
Created on Mon Jan 15 15:36:14 2018
@author: Reuben
"""
import noise
import numpy as np
import matplotlib.pyplot as plt
from math import atan2, cos, sin, pi, radians, floor
import random
from sklearn.preprocessing import normalize
from PIL import Image
from scipy.ndimage.filters import gaussian_filter
randStart = 10000*random.random()
def brownnoise(x, y, scl):
scl = 1/scl
x+=randStart
y+=randStart
n = noise.snoise2(x*scl, y*scl, octaves=8, lacunarity=2.5)
n+=1
n/=2
return n
def dist(x0, y0, x1, y1):
return abs( ((x1-x0)**2 + (y1-y0)**2)**.5)
def lerp(x0, x1, n):
n = max(min(1, n), 0)
return (1-n)*x0 + n*x1
#BELOW FUNCTION: Thanks to http://robotics.usc.edu/~ampereir/wordpress/?p=626
#To save matplotlib to an image, usually just better to use PIL And NP
def SaveFigureAsImage(fileName,fig=None,**kwargs):
''' Save a Matplotlib figure as an image without borders or frames.
Args:
fileName (str): String that ends in .png etc.
fig (Matplotlib figure instance): figure you want to save as the image
Keyword Args:
orig_size (tuple): width, height of the original image used to maintain
aspect ratio.
'''
fig_size = fig.get_size_inches()
w,h = fig_size[0], fig_size[1]
fig.patch.set_alpha(0)
if 'orig_size' in kwargs: # Aspect ratio scaling if required
w,h = kwargs['orig_size']
w2,h2 = fig_size[0],fig_size[1]
fig.set_size_inches([(w2/w)*w,(w2/w)*h])
fig.set_dpi((w2/w)*fig.get_dpi())
a=fig.gca()
a.set_frame_on(False)
a.set_xticks([]); a.set_yticks([])
plt.axis('off')
plt.xlim(0,h); plt.ylim(w,0)
fig.savefig(fileName, transparent=True, bbox_inches='tight', \
pad_inches=0)
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def mult(self, m):
self.x *=m
self.y *=m
def heading(self):
return atan2(self.y, self.x)
def copy(self):
return Vector(self.x, self.y)
def fromAngle(a):
return Vector(cos(a), sin(a))
def lerp(v0, v1, n):
n = max(min(1, n), 0)
x = (1-n)*v0.x+n*v1.x
y = (1-n)*v0.y+n*v1.y
return Vector(x, y)
class Particle:
def __init__(self, x, y):
self.loc = Vector(x, y)
self.angle = atan2(y, x)
self.loc.y *= 1-np.random.normal(0, .02, 1)[0].item()
self.loc.x*=1-np.random.normal(0, .02, 1)[0].item()
theta = pi/2
self.lowerbound = (self.angle-theta)
self.upperbound = (self.angle+theta)
self.destination = Vector.fromAngle(self.angle)
self.destination.mult(.11)
self.destination.x *=1- np.random.normal(0, .1, 1)[0].item()
self.destination.y *=1- np.random.normal(0, .1, 1)[0].item()
def update(self, bn, pic):
radius = 400
ploc = self.loc.copy()
w = pic.shape[0]-1
h = pic.shape[1]-1
max0 = bn.shape[0]
repetitions = int(w/10)
for i in range(repetitions):
ploc = Vector.lerp(self.loc, self.destination, i/repetitions)
indx = max(min(max0-1, floor(ploc.x*(max0/2)+(max0/2))), 0)
indy = max(min(max0-1, floor(ploc.y*(max0/2)+(max0/2))), 0)
lerpval = bn[indx,indy].item()
d = dist(ploc.x, ploc.y, 0, 0)
result = Vector.fromAngle(lerp(self.lowerbound, self.upperbound, lerpval))
result.mult(d)
result.x = max(min(w, result.x * radius + w/2), 0)
result.y = max(min(h, result.y * radius + h/2), 0)
spike = abs(abs((d-.55))-.25)
pic[round(result.x), round(result.y)] += (spike*.001+.001)**4
#TO-DO: Do something with result, place it in an array, somehow save values
if __name__ == "__main__":
pics = []
result = np.zeros((1000, 1000, 3))
for j in range(3):
W = 1000
H = 1000
pic = np.zeros((W, H))
bn = np.zeros((1000, 1000))
it = np.nditer(bn, flags=['multi_index'], op_flags=['writeonly'])
randStart = random.random() * 10000
while not it.finished:
it[0] = brownnoise(it.multi_index[1], it.multi_index[0], 10000)
#TO DO : Experiment with changing this back to 1000, and why it becomes alll fuzzy
it.iternext()
rands = random.random()*100000
particles = [Particle(cos(brownnoise(1000-i+rands, i+rands, 1500)*2*pi*20), sin(brownnoise(1000-i+rands, i+rands, 1500)*2*pi*20)) for i in range(100000)]
for p in particles:
p.update(bn, pic)
# pic = normalize(pic)
#pic *= 255.0/pic.max()
pic *= 1/pic.max()
#pic = gaussian_filter(pic, sigma=3)
pics.append(pic)
# plt.figure(figsize=(10, 10), dpi=100)
# plt.imshow(pic, cmap="gist_gray")
# SaveFigureAsImage('out'+str(10+j)+'.png',plt.gcf(), orig_size=(W-1, H-1))
print("Finished")
result[..., 0] = pics[0]*255
result[..., 1] = pics[1]*255
result[..., 2] = (pics[2]/40)*255
print("Done")
im = Image.fromarray(np.uint8(result))
im.save('eye.png')
| 5598753247e0c3d2a084e3d3fd0b1cd3aed5aca7 | [
"Markdown",
"Python"
] | 2 | Markdown | SeanceDog/GeneratedEye | c85be79953fe470a402fa4b8ffc76df44f612ee9 | 3f1f61594acbc476cea9b757637897b39b750289 |
refs/heads/master | <repo_name>TooKirill/DiscordBot<file_sep>/config.py
TOKEN = '<PASSWORD>' # в кавычках
POST_ID = 669218821344591885 # без кавычек
ROLES = {
'😀': 669216309237776406,
'💯': 669216469732556804
}
EXCROLES = []
MAX_ROLES_PER_USER = 1<file_sep>/README.md
Бот для Discord сервера с возможностью игрокам сомостоятельно выбрать себе роль в специальном канале.
| 6c73b979f0f42a9885e791d7e7daf71082f00146 | [
"Markdown",
"Python"
] | 2 | Python | TooKirill/DiscordBot | 3f4ff18c1c9ff4c9d0955b7bf7fc53eec8715f47 | d7129df4fb3255748927e13a7e7324bbe2fd4c4f |
refs/heads/master | <repo_name>AmitThakkar/GettingStartedWithBrowserify<file_sep>/app/src/components/product/product.main.js
/**
* Created by <NAME> on 02/05/15.
*/
(function (ng) {
'use strict';
var exports = module.exports;
exports.moduleName = 'angular-amd.product';
try {
exports.module = ng.module(exports.moduleName);
} catch(e) {
exports.module = ng.module(exports.moduleName, []);
}
exports.routes = [
{
url: '/products',
templateUrl: 'src/components/product/_product{{now}}.html',
controller: 'ProductController',
controllerAs: 'productController',
deps: ['src/components/product/product.controller{{now}}.js']
}
];
})(angular);<file_sep>/README.md
#Getting Started with Browserify
This repository contains Browserify demo.
1. `gulp dev` pr `gulp`.
2. <file_sep>/app/src/components/home/home.service.js
/**
* Created by amitthakkar on 02/05/15.
*/
(function (ng) {
'use strict';
var homeApp = ng.module(require('./home.main.js').moduleName);
homeApp.service("HomeService", [function () {
this.getName = function() {
return "Home Service";
};
}]);
})(angular);<file_sep>/app/src/components/product/product.controller.js
/**
* Created by <NAME> on 02/05/15.
*/
(function (ng) {
'use strict';
var productApp = ng.module(require('./product.main.js').moduleName);
productApp.controller("ProductController", [function () {
var productController = this;
productController.page = "Product Page";
}]);
})(angular);<file_sep>/app/src/components/home/home.controller.js
/**
* Created by <NAME> on 02/05/15.
*/
(function (ng, require) {
'use strict';
var homeApp = ng.module(require('./home.main.js').moduleName);
require('./home.service.js');
homeApp.controller('HomeController', ['HomeService', function (HomeService) {
var homeController = this;
homeController.page = 'Home Page ' + HomeService.getName();
}]);
})(angular, require);<file_sep>/app/src/angular-amd.js
/**
* Created by <NAME> on 01/05/15.
*/
(function (require, window) {
'use strict';
var config = require('./config');
var ng = window.angular;
var $script = window.$script;
var addDynamicBehaviourSupportToModule = function (internalModule) {
internalModule.config(['$controllerProvider', '$provide', '$compileProvider', function ($controllerProvider, $provide, $compileProvider) {
internalModule.controller = function (name, constructor) {
$controllerProvider.register(name, constructor);
return (this);
};
internalModule.service = function (name, constructor) {
$provide.service(name, constructor);
return (this);
};
internalModule.factory = function (name, factory) {
$provide.factory(name, factory);
return (this);
};
internalModule.value = function (name, value) {
$provide.value(name, value);
return (this);
};
internalModule.constant = function (name, value) {
$provide.constant(name, value);
return (this);
};
internalModule.directive = function (name, factory) {
$compileProvider.directive(name, factory);
return (this);
};
}]);
};
var routes = [];
ng.forEach(config.internalModuleObjects, function (internalModuleObject) {
routes = routes.concat(internalModuleObject.routes);
addDynamicBehaviourSupportToModule(internalModuleObject.module);
});
var angularAMD = ng.module(config.mainAppModule, config.dependModules);
angularAMD.config(['$routeProvider', function ($routeProvider) {
var loadDependencies = function ($q, deps) {
var deferred = $q.defer();
$script(deps, function (error) {
if (error) {
deferred.reject(error);
} else {
deferred.resolve('Success');
}
});
return deferred.promise;
};
ng.forEach(routes, function (route) {
if (route.deps) {
if (!route.resolve) {
route.resolve = {};
}
route.resolve.deps = ['$q', function ($q) {
return loadDependencies($q, route.deps);
}];
}
$routeProvider.when(route.url, route)
});
$routeProvider.otherwise({
redirectTo: config.DEFAULT_URL
});
}]);
require('../../temp/environment.config')
})(require, window);<file_sep>/gulpfile.js
/**
* Created by <NAME> on 04/05/15.
*/
(function (require) {
'use strict';
var gulp = require('gulp'),
browserify = require('gulp-browserify'),
uglify = require('gulp-uglify'),
gulpif = require('gulp-if'),
open = require('gulp-open'),
runSequence = require('run-sequence'),
livereload = require('gulp-livereload'),
notify = require('gulp-notify'),
minifyHTML = require('gulp-minify-html'),
inject = require('gulp-inject'),
rename = require('gulp-rename'),
replace = require('gulp-replace'),
rimraf = require('rimraf'),
gulpNgConfig = require('gulp-ng-config');
var isDevelopmentEnvironment = false,
projectName = 'AngularAMD with Browserify',
sound = 'Frog',
srcFolder = 'app/src/',
destFolder = 'build/src/',
temp = 'temp/',
javascriptTasks = [
{
taskName: 'angular-amd',
srcFiles: [srcFolder + 'angular-amd.js'],
dest: destFolder
},
{
taskName: 'home.javascript',
srcFiles: [srcFolder + 'components/home/home.controller.js'],
dest: destFolder + 'components/home'
},
{
taskName: 'product.javascript',
srcFiles: [srcFolder + 'components/product/product.controller.js'],
dest: destFolder + 'components/product'
}
],
htmlTasks = [
{
taskName: 'home.html',
srcFiles: [srcFolder + 'components/home/_home.html'],
dest: destFolder + 'components/home/'
},
{
taskName: 'product.html',
srcFiles: [srcFolder + 'components/product/_product.html'],
dest: destFolder + 'components/product/'
}
],
now = '-' + Date.now(),
environment = 'production',
renameFunction = function (path) {
path.basename += now;
};
gulp.task('config.json', function () {
return gulp.src(srcFolder + 'environment.config.json')
.pipe(gulpNgConfig('angular-amd', {
createModule: false,
wrap: '(function(angular) {<%= module %>})(angular);',
environment: environment
}))
.pipe(gulp.dest(temp));
});
gulp.task('index.html', function () {
return gulp.src(srcFolder + '../index.html')
.pipe(inject(gulp.src(destFolder + 'angular-amd*.js', {read: false}), {relative: true}))
.pipe(gulpif(!isDevelopmentEnvironment, minifyHTML()))
.pipe(gulp.dest('./build/'))
.pipe(gulpif(isDevelopmentEnvironment, livereload()));
});
gulp.task('assets', function () {
return gulp.src('app/assets/**/*')
.pipe(gulp.dest('build/assets'));
});
gulp.task('clear', function (callback) {
rimraf('./build', callback);
});
gulp.task('clear.temp', function (callback) {
rimraf(temp, callback);
});
gulp.task('setDevEnvironment', function () {
isDevelopmentEnvironment = true;
});
var taskNames = [];
javascriptTasks.forEach(function (javascriptTask) {
taskNames.push(javascriptTask.taskName);
gulp.task(javascriptTask.taskName, function () {
return gulp.src(javascriptTask.srcFiles)
.pipe(browserify())
.pipe(replace('{{now}}', now))
.pipe(gulpif(!isDevelopmentEnvironment, uglify()))
.pipe(rename(renameFunction))
.pipe(gulp.dest(javascriptTask.dest))
.pipe(gulpif(isDevelopmentEnvironment, livereload()))
.pipe(gulpif(isDevelopmentEnvironment, notify({
title: projectName,
message: javascriptTask.taskName + ' task executed',
sound: sound
})));
});
});
htmlTasks.forEach(function (htmlTask) {
taskNames.push(htmlTask.taskName);
gulp.task(htmlTask.taskName, function () {
return gulp.src(htmlTask.srcFiles)
.pipe(gulpif(!isDevelopmentEnvironment, minifyHTML()))
.pipe(rename(renameFunction))
.pipe(gulp.dest(htmlTask.dest))
.pipe(gulpif(isDevelopmentEnvironment, livereload()));
})
});
gulp.task('browserify', function (callback) {
runSequence('config.json', taskNames, 'index.html', 'assets', callback);
});
gulp.task('open', function () {
var options = {
url: 'http://localhost:63342/AngularAMD-with-Browserify/build/'
};
gulp.src('./build/index.html')
.pipe(open('', options));
});
gulp.task('watch', function () {
livereload.listen();
gulp.watch(srcFolder + '../index.html', ['index.html']);
gulp.watch(srcFolder + '*.js', ['angular-amd']);
gulp.watch(srcFolder + 'shared/*.js', ['angular-amd']);
gulp.watch(srcFolder + 'components/**/*.main.js', ['angular-amd']);
gulp.watch(srcFolder + 'components/home/*.html', ['home.html']);
gulp.watch(srcFolder + 'components/product/*.html', ['product.html']);
gulp.watch(srcFolder + 'components/home/*.js', ['home.javascript']);
gulp.watch(srcFolder + 'components/product/*.js', ['product.javascript']);
});
gulp.task('dev', function (callback) {
environment = 'development';
runSequence('clear', 'clear.temp', 'setDevEnvironment', 'browserify', 'open', 'watch', callback);
});
gulp.task('qa', function (callback) {
environment = 'qa';
runSequence('clear', 'clear.temp', 'browserify', 'clear.temp', callback);
});
gulp.task('default', function (callback) {
runSequence('clear', 'clear.temp', 'browserify', 'clear.temp', callback);
});
})(require);<file_sep>/app/src/config.js
/**
* Created by <NAME> on 02/05/15.
*/
(function (require, module) {
require('./shared/js-libs');
require('./shared/angular-libs');
var MAIN_APP_MODULE = "angular-amd";
var exports = module.exports;
var externalModules = [
'ngRoute'
];
// If your module have route configuration then push module main file to moduleMainFiles.
var moduleMainFiles = [
require('./components/home/home.main'),
require('./components/product/product.main')
];
// If your module have not route configuration then don't neet push module to internalModuleObjects.
var withoutRouteMainFiles = [
require('./shared/common.main')
];
var internalModules = [];
var internalModuleObjects = [];
moduleMainFiles.forEach(function (moduleMainFile) {
internalModules.push(moduleMainFile.moduleName);
internalModuleObjects.push(moduleMainFile);
});
withoutRouteMainFiles.forEach(function (withoutRouteMainFile) {
internalModules.push(withoutRouteMainFile.moduleName);
});
exports.mainAppModule = MAIN_APP_MODULE;
exports.dependModules = externalModules.concat(internalModules);
exports.internalModuleObjects = internalModuleObjects;
exports.DEFAULT_URL = "/home";
})(require, module);<file_sep>/app/src/shared/common.main.js
/**
* Created by <NAME> on 02/05/15.
*/
(function (ng, module) {
'use strict';
var exports = module.exports;
exports.moduleName = 'angular-amd.common';
try {
exports.module = ng.module(exports.moduleName);
} catch(e) {
exports.module = ng.module(exports.moduleName, []);
}
})(angular, module); | 72a6d74161414d9ea8600a823c77f1c3624abb1e | [
"JavaScript",
"Markdown"
] | 9 | JavaScript | AmitThakkar/GettingStartedWithBrowserify | a46aa24e2128ed41e759dd65ceaa2a4543ef7d1d | 13051e5afd097b2fe83fe0e0d8c879020baba4b2 |
refs/heads/master | <repo_name>kevgathuku/crispy-octo-adventure<file_sep>/algos-clj/README.md
# algos-clj
Implementing some algorithms in Clojure
## Algorthims Implemented
- Merge Sort
References:
- [Recursive merge solition](https://gist.github.com/baabelfish/6573984)
- [Recursive loop solution](https://gist.github.com/egri-nagy/512998bd8482fc49947b)
<file_sep>/java/linearSearch.java
import java.util.Arrays;
class Scratch {
public static void main(String[] args) {
int[] unsorted = { 19, 64, 5, 9, 12 };
Scratch sc = new Scratch();
sc.selectionSort(unsorted);
sc.linearSearch(unsorted, 9);
}
public void selectionSort(int[] lst) {
int len = lst.length;
for (int i = 0; i < len; i++) {
int smallestIndex = i;
// Start with the current item as the smallest
int smallest = lst[i];
// Find the actual smallest item starting from position i
for (int j = i; j < len; j++) {
if (lst[j] < smallest) {
smallest = lst[j]; // save the actual smallest number
smallestIndex = j; // save position of smallest item
}
}
int temp = lst[i]; // save the number in the current position
lst[i] = smallest; // set the smallest in the correct position
lst[smallestIndex] = temp; // set the current number in the smallest position
}
System.out.println(Arrays.toString(lst));
}
public void linearSearch(int[] lst, int needle) {
int len = lst.length;
for (int i = 0; i < len; i++) {
if (lst[i] == needle) {
System.out.println("found needle! It is at position " + i);
return;
}
}
System.out.println("the element is not in the array");
return;
}
}
<file_sep>/README.md
Learning some algorithms from [Microsoft: DEV285x](https://courses.edx.org/courses/course-v1:Microsoft+DEV285x+2T2018/course/)
<file_sep>/java/bubbleSort.java
import java.util.Arrays;
class Scratch {
public static void main(String[] args) {
int[] unsorted = { 19, 64, 5, 9, 12 };
Scratch sc = new Scratch();
sc.bubbleSort(unsorted);
}
public void bubbleSort(int[] lst) {
int len = lst.length;
boolean swapped;
do {
swapped = false;
for (int i = 0; i < len - 1; i++) {
if (lst[i] > lst[i + 1]) {
int temp = lst[i];
lst[i] = lst[i + 1];
lst[i + 1] = temp;
swapped = true;
} else {
// no swapping to do
// swapped variable remains false and loop ends
}
}
} while (swapped == true);
System.out.println(Arrays.toString(lst));
}
}
| 51aa35c4e4d9b65b459b7ac6a5cf314d9fd7aa29 | [
"Markdown",
"Java"
] | 4 | Markdown | kevgathuku/crispy-octo-adventure | 0fbdca9550cba04b56164f53cd3348c75213fbb4 | 227565e5922683d3b75802b966f35fbe79a332d0 |
refs/heads/master | <file_sep>package circularchess.shared;
import java.io.Serializable;
public class Piece implements Serializable {
private static final long serialVersionUID = -863457807648943094L;
public enum Type {
KING('K', 1000), QUEEN('Q', 9), ROOK('R', 5), KNIGHT('N', 3), BISHOP(
'B', 3), PAWN('P', 1);
public char type;
public double value;
Type(char c, double v) {
type = c;
value = v;
}
public String toString() {
return String.valueOf(type);
}
public boolean equals(Type t) {
return t != null && type == t.type;
}
}
public Type type;
public boolean white;
@SuppressWarnings("unused")
private Piece() {
}
public Piece(Type type, boolean white) {
this.type = type;
this.white = white;
}
public String toString() {
String str = type.toString();
if (!white)
str = str.toLowerCase();
return str;
}
public double value() {
return white ? type.value : -type.value;
}
}<file_sep>package circularchess.client;
import circularchess.shared.Game;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.ChangeHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.user.client.Random;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.RadioButton;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
public class OnlineTwoPlayerPopup extends PopupPanel implements ValueChangeHandler, ChangeHandler,ClickHandler {
boolean flag = false;
Game game;
int color=0;
final RadioButton rb0,rb1,rb2;
final TextBox txt;
final Button start;
private StartListener callback;
OnlineTwoPlayerPopup(Game game, StartListener callback){
this.game = game;
this.callback = callback;
VerticalPanel panel = new VerticalPanel();
Label label = new Label("Share this code with a friend to play, or enter their code here");
panel.add(label);
txt = new TextBox();
txt.setText(generateCode());
txt.addChangeHandler(this);
panel.add(txt);
rb0 = new RadioButton("color", "Random");
rb0.setValue(true);
rb0.addValueChangeHandler(this);
panel.add(rb0);
rb1 = new RadioButton("color", "White");
rb1.addValueChangeHandler(this);
panel.add(rb1);
rb2 = new RadioButton("color", "Black");
rb2.addValueChangeHandler(this);
panel.add(rb2);
start = new Button("Start");
start.addClickHandler(this);
panel.add(start);
setWidget(panel);
}
private String generateCode(){
int x = Math.abs(Random.nextInt());
x = x - x % 3 + color;
String str = Integer.toString(x,36);
int sum = 0;
for(int i=0; i<str.length(); i++){
sum += Integer.parseInt(str.substring(i,i+1), 36);
}
String check = Integer.toString(sum % 36,36);
return check + str;
}
private int parseCode(){
String code = txt.getText();
int checkSum = Integer.parseInt(code.substring(0,1),36);
String str = code.substring(1);
int sum = 0;
for(int i=0; i<str.length(); i++){
sum += Integer.parseInt(str.substring(i,i+1), 36);
}
sum = sum % 36;
if(sum != checkSum)
return -1;
else
return Integer.parseInt(str, 36) % 3;
}
@Override
public void onValueChange(ValueChangeEvent event) {
if(rb0.getValue())
color = 0;
else if(rb1.getValue())
color = 1;
else if(rb2.getValue())
color = 2;
txt.setText(generateCode());
flag = false;
}
@Override
public void onChange(ChangeEvent event) {
color = parseCode();
if(color == 0)
rb0.setValue(true);
else if(color == 2)
rb1.setValue(true);
else if(color == 1)
rb2.setValue(true);
flag = true;
start.setEnabled(color != -1);
}
@Override
public void onClick(ClickEvent event) {
String code = txt.getText();
if (color == 0)
{
int x = Integer.parseInt(code.substring(1),36);
if(x % 6 < 3)
flag = !flag;
}
else if(color == 1)
flag = !flag;
callback.onStart(true,true,flag,!flag,code);
hide();
}
}
<file_sep>Circular Chess
==============
A browser based implementation of [Circular Chess](http://en.wikipedia.org/wiki/Circular_chess). Rules are the same as regular chess except that castling and en passant are not allowed. Also, pieces cannot make a "null move" by going all the way around the circle to return to their starting position.
This project uses [GWT](http://www.gwtproject.org/) to compile to a JavaScript, mostly canvas-based, UI.
It is hosted at [circular-chess.appspot.com](circular-chess.appspot.com) thanks to [App Engine](https://cloud.google.com/appengine/docs).<file_sep>package circularchess.client;
public interface StartListener {
public void onStart(boolean whiteHuman, boolean blackHuman, boolean whiteAuth, boolean blackAuth, String id);
}
<file_sep>package circularchess.client;
import com.google.gwt.user.client.ui.TextArea;
public class TextPopup extends ShowPopupPanel {
final TextArea ta;
public TextPopup(String text, int lines) {
super(true);
ta = new TextArea();
ta.setCharacterWidth(80);
ta.setVisibleLines(lines);
ta.setText(text);
setWidget(ta);
ta.setSelectionRange(0,text.length());
}
@Override
public void onShow() {
ta.setFocus(true);
ta.setSelectionRange(0,ta.getText().length());
}
}
<file_sep>package circularchess.client;
import java.util.HashMap;
import circularchess.shared.*;
import com.google.gwt.canvas.client.Canvas;
import com.google.gwt.canvas.dom.client.Context2d;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.gwt.dom.client.ImageElement;
import com.google.gwt.event.dom.client.*;
import com.google.gwt.media.client.Audio;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.VerticalPanel;
/**
* Entry point classes define <code>onModuleLoad()</code>.
*/
public class CircularChess implements EntryPoint, MoveListener, StartListener {
private static final int pollRate = 1000;
private static final int refreshRate = 25;
private static final int canvasWidth = 600;
private static final int canvasHeight = 600;
private static final double RING_WIDTH = 50;
private static final double INNER_RADIUS = 100;
private static final double CELL_ANGLE = 2 * Math.PI / 16;
private boolean online = false;
private final HashMap<String, Image> images = new HashMap<String, Image>();
private Canvas canvas;
private Context2d ctx;
Game game;
private NetworkManager networkManager;
private FlexTable moveText;
private Audio illegalMoveAudio, moveAudio, gameOverAudio;
private int boardOrientation = 4;
public VerticalPanel whiteLost, blackLost;
public void onModuleLoad() {
HorizontalPanel panel = new HorizontalPanel();
Image img;
for (Piece.Type type : Piece.Type.values()) {
String key = type.toString();
String lowerKey = key.toLowerCase();
img = new Image("images/white-" + lowerKey + ".svg");
images.put(key, img);
img.setVisible(false);
RootPanel.get().add(img);
img = new Image("images/black-" + lowerKey + ".svg");
images.put(lowerKey, img);
img.setVisible(false);
RootPanel.get().add(img);
}
VerticalPanel vpanel = new VerticalPanel();
panel.add(vpanel);
canvas = Canvas.createIfSupported();
canvas.setWidth(canvasWidth + "px");
canvas.setCoordinateSpaceWidth(canvasWidth);
canvas.setHeight(canvasHeight + "px");
canvas.setCoordinateSpaceHeight(canvasHeight);
ctx = canvas.getContext2d();
ctx.translate(canvasWidth / 2.0, canvasHeight / 2.0);
vpanel.add(canvas);
HorizontalPanel buttonPanel = new HorizontalPanel();
Button pgnButton = new Button("Show PGN", new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
final TextPopup popup = new TextPopup(game.toPGN(),13);
showPopup(popup);
}
});
buttonPanel.add(pgnButton);
Button fenButton = new Button("Show FEN", new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
final TextPopup popup = new TextPopup(game.toFEN(),1);
showPopup(popup);
}
});
buttonPanel.add(fenButton);
vpanel.add(buttonPanel);
moveText = new FlexTable();
moveText.addStyleName("moveText");
panel.add(moveText);
whiteLost = new VerticalPanel();
panel.add(whiteLost);
blackLost = new VerticalPanel();
panel.add(blackLost);
RootPanel.get().add(panel);
newGame();
illegalMoveAudio = Audio.createIfSupported();
illegalMoveAudio.setSrc("audio/illegal-move.mp3");
moveAudio = Audio.createIfSupported();
moveAudio.setSrc("audio/move.mp3");
gameOverAudio = Audio.createIfSupported();
gameOverAudio.setSrc("audio/game-over.mp3");
initHandlers();
// setup timer
final Timer timer = new Timer() {
public void run() {
redraw();
}
};
timer.scheduleRepeating(refreshRate);
}
int mode = 0;
int[] selected;
int mouseX, mouseY;
public void initHandlers() {
canvas.addMouseDownHandler(new MouseDownHandler() {
public void onMouseDown(MouseDownEvent event) {
mouseX = event.getRelativeX(canvas.getElement());
mouseY = event.getRelativeY(canvas.getElement());
selected = getCoords(mouseX, mouseY);
mode = 1;
}
});
canvas.addMouseMoveHandler(new MouseMoveHandler() {
public void onMouseMove(MouseMoveEvent event) {
mouseX = event.getRelativeX(canvas.getElement());
mouseY = event.getRelativeY(canvas.getElement());
}
});
canvas.addMouseUpHandler(new MouseUpHandler() {
public void onMouseUp(MouseUpEvent event) {
mode = 0;
mouseX = event.getRelativeX(canvas.getElement());
mouseY = event.getRelativeY(canvas.getElement());
Piece p = game.board[selected[0]][selected[1]];
if (p != null) {
int[] target = getCoords(mouseX, mouseY);
int r = (selected[0] / 8) * 2 - 1;
if (p.type == Piece.Type.PAWN
&& ((game.whiteToMove
&& (target[0] == 7 || target[0] == 8) && selected[0]
- r == target[0])
|| (!game.whiteToMove
&& (target[0] == 0 || target[0] == 15) && selected[0]
+ r == target[0]))) {
final PromotedPopup popup = new PromotedPopup(images, game, selected,
target);
popup.setPopupPositionAndShow(new PopupPanel.PositionCallback() {
public void setPosition(int offsetWidth, int offsetHeight) {
int left = (Window.getClientWidth() - offsetWidth) / 3;
int top = (Window.getClientHeight() - offsetHeight) / 3;
popup.setPopupPosition(left, top);
}
});
} else {
Move m = new Move(selected[0], selected[1], target[0],
target[1]);
game.attemptMove(m);
selected[0] = selected[1] = -1;
}
}
}
});
}
public void log(String str) {
RootPanel.get().add(new Label(str));
}
private void redraw() {
ctx.clearRect(-canvasWidth / 2.0, -canvasHeight / 2.0, canvasWidth,
canvasHeight);
ctx.setStrokeStyle("#000000");
for (int i = 0; i < 16; i++) {
for (int j = 0; j < 4; j++) {
// draw board
if ((i + j) % 2 == 0) {
ctx.setFillStyle("#EEEEEE");
} else {
ctx.setFillStyle("#999999");
}
ctx.beginPath();
double innerRad = INNER_RADIUS + j * RING_WIDTH;
double outerRad = INNER_RADIUS + (j + 1) * RING_WIDTH;
ctx.moveTo(Math.cos(i * CELL_ANGLE) * innerRad,
Math.sin(i * CELL_ANGLE) * innerRad);
ctx.lineTo(Math.cos(i * CELL_ANGLE) * outerRad,
Math.sin(i * CELL_ANGLE) * outerRad);
ctx.arcTo(
Math.cos((i + 0.5) * CELL_ANGLE) * outerRad
/ Math.cos(CELL_ANGLE / 2.0),
Math.sin((i + 0.5) * CELL_ANGLE) * outerRad
/ Math.cos(CELL_ANGLE / 2.0),
Math.cos((i + 1.0) * CELL_ANGLE) * outerRad,
Math.sin((i + 1.0) * CELL_ANGLE) * outerRad, outerRad);
ctx.lineTo(Math.cos((i + 1.0) * CELL_ANGLE) * innerRad,
Math.sin((i + 1.0) * CELL_ANGLE) * innerRad);
ctx.arcTo(
Math.cos((i + 0.5) * CELL_ANGLE) * innerRad
/ Math.cos(CELL_ANGLE / 2),
Math.sin((i + 0.5) * CELL_ANGLE) * innerRad
/ Math.cos(CELL_ANGLE / 2),
Math.cos(i * CELL_ANGLE) * innerRad,
Math.sin(i * CELL_ANGLE) * innerRad, innerRad);
ctx.closePath();
ctx.fill();
ctx.stroke();
}
}
for (int i = 0; i < 16; i++) {
for (int j = 0; j < 4; j++) {
double midRad = INNER_RADIUS + (j + 0.5) * RING_WIDTH;
Piece p = game.board[i][j];
if (p != null) {
Image img = images.get(p.toString());
ImageElement imgElem = (ImageElement) img.getElement().cast();
if (i == selected[0] && j == selected[1] && mode == 1) {
ctx.drawImage(imgElem, mouseX - imgElem.getWidth() / 2.0
- canvasWidth / 2.0, mouseY - imgElem.getHeight()
/ 2.0 - canvasHeight / 2.0);
} else {
ctx.drawImage(
imgElem,
Math.cos((i + boardOrientation + 0.5) * CELL_ANGLE) * midRad
- imgElem.getWidth() / 2.0,
Math.sin((i + boardOrientation + 0.5) * CELL_ANGLE) * midRad
- imgElem.getHeight() / 2.0);
}
}
}
}
}
public int[] getCoords(double x, double y) {
x -= canvasWidth / 2.0;
y -= canvasHeight / 2.0;
int[] coords = { -1, -1 };
double theta = (Math.atan2(y, x) + 2 * Math.PI) % (2 * Math.PI);
double radius = Math.sqrt(x * x + y * y);
if(radius < INNER_RADIUS || radius > INNER_RADIUS + 4*RING_WIDTH)
return coords;
coords[1] = (int) ((radius - INNER_RADIUS)/RING_WIDTH);
coords[0] = (((int) (theta/CELL_ANGLE)) - boardOrientation + 16) % 16;
return coords;
}
@Override
public void onMove(Move move) {
if(online)
networkManager.sendMove(move);
if(game.whiteToMove){
moveText.setText(game.moves, 2, move.toString());
}
else{
moveText.setText(game.moves, 0, game.moves + ".");
moveText.setText(game.moves, 1, move.toString());
}
if(move.captures != null){
if(move.captures.white)
whiteLost.add(createImage(move.captures.toString().charAt(0)));
else
blackLost.add(createImage(move.captures.toString().charAt(0)));
}
if(game.result != Game.Result.ONGOING){
gameOverAudio.load();
gameOverAudio.play();
final ResultPopup popup = new ResultPopup(this);
popup.setPopupPositionAndShow(new PopupPanel.PositionCallback() {
public void setPosition(int offsetWidth, int offsetHeight) {
int left = (Window.getClientWidth() - offsetWidth) / 3;
int top = (Window.getClientHeight() - offsetHeight) / 3;
popup.setPopupPosition(left, top);
}
});
}
else{
moveAudio.load();
moveAudio.play();
}
}
public void newGame(){
game = new Game();
selected = new int[] { -1, -1 };
moveText.removeAllRows();
game.setMoveListener(this);
whiteLost.clear();
blackLost.clear();
final MainPopup popup = new MainPopup(game, this);
popup.setPopupPositionAndShow(new PopupPanel.PositionCallback() {
public void setPosition(int offsetWidth, int offsetHeight) {
int left = (Window.getClientWidth() - offsetWidth) / 3;
int top = (Window.getClientHeight() - offsetHeight) / 3;
popup.setPopupPosition(left, top);
}
});
}
@Override
public void onIllegalMove(Move move) {
illegalMoveAudio.load();
illegalMoveAudio.play();
}
@Override
public void onStart(boolean whiteHuman, boolean blackHuman,
boolean whiteAuth, boolean blackAuth, String id) {
if(!whiteHuman || !whiteAuth)
boardOrientation = 12;
else
boardOrientation = 4;
game.whiteHuman = whiteHuman;
game.blackHuman = blackHuman;
game.whiteAuth = whiteAuth;
game.blackAuth = blackAuth;
online = !(whiteAuth && blackAuth);
if (online) {
networkManager = new NetworkManager(this, id);
networkManager.scheduleRepeating(pollRate);
}
game.start();
}
public Image createImage(char c){
switch(c){
case 'K': return new Image("images/white-k.svg");
case 'Q': return new Image("images/white-q.svg");
case 'R': return new Image("images/white-r.svg");
case 'B': return new Image("images/white-b.svg");
case 'N': return new Image("images/white-n.svg");
case 'P': return new Image("images/white-p.svg");
case 'k': return new Image("images/black-k.svg");
case 'q': return new Image("images/black-q.svg");
case 'r': return new Image("images/black-r.svg");
case 'b': return new Image("images/black-b.svg");
case 'n': return new Image("images/black-n.svg");
case 'p': return new Image("images/black-p.svg");
}
return null;
}
public void showPopup(final ShowPopupPanel popup){
popup.setPopupPositionAndShow(new PopupPanel.PositionCallback() {
public void setPosition(int offsetWidth, int offsetHeight) {
int left = (Window.getClientWidth() - offsetWidth) / 3;
int top = (Window.getClientHeight() - offsetHeight) / 3;
popup.setPopupPosition(left, top);
}
});
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
@Override
public void execute() {
popup.onShow();
}
});
}
}
<file_sep>package circularchess.client;
import circularchess.shared.Game;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.VerticalPanel;
public class OnePlayerPopup extends PopupPanel {
Game game;
public OnePlayerPopup(final Game game, final StartListener callback) {
super(false, true);
this.game = game;
VerticalPanel panel = new VerticalPanel();
Button random = new Button("Random", new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
boolean flag = true;
if (Math.random() < 0.5)
flag = !flag;
callback.onStart(flag, !flag, true, true, "");
hide();
}
});
panel.add(random);
Button white = new Button("White", new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
callback.onStart(true, false, true, true, "");
hide();
}
});
panel.add(white);
Button black = new Button("Black", new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
callback.onStart(false, true, true, true, "");
hide();
}
});
panel.add(black);
setWidget(panel);
}
}
<file_sep>package circularchess.server;
import static com.googlecode.objectify.ObjectifyService.ofy;
import circularchess.client.ChessService;
import circularchess.shared.Game;
import circularchess.shared.Move;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.googlecode.objectify.ObjectifyService;
/**
* The server-side implementation of the RPC service.
*/
@SuppressWarnings("serial")
public class ChessServiceImpl extends RemoteServiceServlet implements
ChessService {
static {
ObjectifyService.register(Game.class);
}
@Override
public void sendMove(String id, Move move) throws IllegalArgumentException {
Game game = ofy().load().type(Game.class).id(id).now();
if (game == null) {
game = new Game();
game.id = id;
}
if (game.isLegal(move))
game.move(move);
else
throw new IllegalArgumentException();
ofy().save().entity(game).now();
}
@Override
public Move getMove(String id, int halfMove) {
Game game = ofy().load().type(Game.class).id(id).now();
if (game != null && halfMove < game.history.size())
return game.history.get(halfMove);
else
return null;
}
}
| 56db06ee845654e99069e59108e53df720c43af6 | [
"Markdown",
"Java"
] | 8 | Java | lotrf3/circular-chess | d0eb9adbe127aa140a27ec7f480d82a49355fb63 | a56a901fd721efb7cb2f3856bae3f1b4fb9fdd77 |
refs/heads/main | <file_sep>using System;
using System.Windows.Forms;
namespace CefFormStartPosition
{
public partial class Form1 : Form
{
public Form1()
{
// It seems to be important that this form is larger than the dialog it launches
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
new BrowserDialog().ShowDialog(this);
}
private void button2_Click(object sender, EventArgs e)
{
for (int i = 0; i < 50; i++)
{
new BrowserDialog().ShowDialog(this);
}
}
}
}<file_sep>using System;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using CefSharp.WinForms;
namespace CefFormStartPosition
{
public partial class BrowserDialog : Form
{
public BrowserDialog()
{
InitializeComponent();
// Removing this line will cause the dialog to consistently render correctly
StartPosition = FormStartPosition.CenterParent;
InitializeCefSharp();
Task.Run(() =>
{
Thread.Sleep(1000);
Action closeAction = Close;
Invoke(closeAction);
});
}
private void InitializeCefSharp()
{
Uri indexUri = new Uri(Path.Combine(new FileInfo(Assembly.GetExecutingAssembly().Location).Directory.FullName, "index.html"));
ChromiumWebBrowser chromiumWebBrowser = new ChromiumWebBrowser(indexUri.AbsoluteUri);
Controls.Add(chromiumWebBrowser);
}
}
}
| 6dc47ede44f5802908cb51a2ec8ad6f3e16cdd5d | [
"C#"
] | 2 | C# | ohlookitsben/cefformstartposition | deea37cb14b8ea664b5c49ec5323656df4ccf7bd | e726614c1baf18d04bf6ef6469bb9574de056a0d |
refs/heads/master | <file_sep># python-aio2gis
A Python library for accessing the 2gis API (http://api.2gis.ru) powered with [asyncio](https://docs.python.org/3/library/asyncio.html).
## Usage
### Example
import asyncio
from aio2gis.client import API
@asyncio.coroutine
def get_projects_list():
api = API('api-key')
response = yield from api.project_list()
print(response)
loop = asyncio.get_event_loop()
loop.run_until_complete(get_projects_list())
## Contributing
If you want to contribute, follow the [pep8](http://www.python.org/dev/peps/pep-0008/) guideline.
<file_sep>class DgisError(Exception):
"""2Gis API error"""
def __init__(self, code, message, error_code):
self.code = code
self.message = message
self.error_code = error_code
def __str__(self):
return self.message
<file_sep>from .binder import bind_api
class API:
def __init__(self, key, host='catalog.api.2gis.ru', version='1.3', register_views=True, loop=None):
"""2GIS API client
Parameters::
key : user API key
host : base URL for queries
version : API version for working
register_views : should library send information to stats server about a firm profile viewing
loop : optional event loop
"""
self.key = key
self.host = host
self.version = version
self.register_views = register_views
self.loop = loop
"""Projects lists
http://api.2gis.ru/doc/firms/list/project-list/
"""
project_list = bind_api(
path='/project/list',
allowed_param=[],
)
"""List of the project cities
http://api.2gis.ru/doc/firms/list/city-list/
"""
city_list = bind_api(
path='/city/list',
allowed_param=['where', 'project_id']
)
def rubricator(self, **kwargs):
"""Rubrics search
http://api.2gis.ru/doc/firms/list/rubricator/
"""
# `show_children' parameter must be an integer
kwargs['show_children'] = int(kwargs.pop('show_children', False))
return self._rubricator(**kwargs)
_rubricator = bind_api(
path='/rubricator',
allowed_param=['where', 'id', 'parent_id', 'show_children', 'sort'],
)
def search(self, **kwargs):
"""Firms search
http://api.2gis.ru/doc/firms/searches/search/
"""
point = kwargs.pop('point', False)
if point:
kwargs['point'] = '%s,%s' % point
bound = kwargs.pop('bound', False)
if bound:
kwargs['bound[point1]'] = bound[0]
kwargs['bound[point2]'] = bound[1]
filters = kwargs.pop('filters', False)
if filters:
for k, v in filters.items():
kwargs['filters[%s]' % k] = v
return self._search(**kwargs)
_search = bind_api(
path='/search',
allowed_param=['what', 'where', 'point', 'radius', 'bound', 'page', 'pagesize', 'sort', 'filters'],
)
def search_in_rubric(self, **kwargs):
"""Firms search in rubric
http://api.2gis.ru/doc/firms/searches/searchinrubric/
"""
point = kwargs.pop('point', False)
if point:
kwargs['point'] = '%s,%s' % point
bound = kwargs.pop('bound', False)
if bound:
kwargs['bound[point1]'] = bound[0]
kwargs['bound[point2]'] = bound[1]
filters = kwargs.pop('filters', False)
if filters:
for k, v in filters.items():
kwargs['filters[%s]' % k] = v
return self._search_in_rubric(**kwargs)
_search_in_rubric = bind_api(
path='/searchinrubric',
allowed_param=['what', 'where', 'point', 'radius', 'bound', 'page', 'pagesize', 'sort', 'filters'],
)
"""Firm filials
http://api.2gis.ru/doc/firms/searches/firmsbyfilialid/
"""
firms_by_filial_id = bind_api(
path='/firmsByFilialId',
allowed_param=['firmid', 'page' 'pagesize'],
)
"""Adverts search
http://api.2gis.ru/doc/firms/searches/adssearch/
"""
ads_search = bind_api(
path='/ads/search',
allowed_param=['what', 'where', 'format', 'page', 'pagesize'],
)
"""Firm profile
http://api.2gis.ru/doc/firms/profiles/profile/
"""
profile = bind_api(
path='/profile',
allowed_param=['id', 'hash'],
register_views=True,
)
def geo_search(self, **kwargs):
"""Geo search
http://api.2gis.ru/doc/geo/search/
"""
if 'types' in kwargs:
kwargs['types'] = ','.join(kwargs['types'])
bound = kwargs.pop('bound', False)
if bound:
kwargs['bound[point1]'] = bound[0]
kwargs['bound[point2]'] = bound[1]
return self._geo_search(**kwargs)
_geo_search = bind_api(
path='/geo/search',
allowed_param=['q', 'types', 'radius', 'limit', 'project', 'bound', 'format'],
)
"""Information about a geo object"""
geo_get = bind_api(
path='/geo/search',
allowed_param=['id', ],
)
<file_sep>import os
import asyncio
from aio2gis.client import API
try:
key = os.environ['DGIS_KEY']
except KeyError:
raise RuntimeError('Add an environment variable DGIS_KEY with 2gis API key')
@asyncio.coroutine
def test_projects_list():
api = API(key)
response = yield from api.project_list()
assert response['response_code'] == '200'
assert response['api_version'] == api.version
print(response)
loop = asyncio.get_event_loop()
loop.run_until_complete(test_projects_list())
<file_sep># -*- coding: utf-8 -*-
import json
import asyncio
from urllib import parse
import aiohttp
from .exceptions import DgisError
__all__ = ('bind_api',)
def __init__(self, api):
self.api = api
@asyncio.coroutine
def execute(self, *args, **kwargs):
# Build GET parameters for query
parameters = {}
# Both positional
for idx, arg in enumerate(args):
if arg is None:
continue
try:
parameters[self.allowed_param[idx]] = arg
except IndexError:
raise ValueError('Too many parameters supplied')
# And keyword parameters
for key, arg in kwargs.items():
if arg is None:
continue
if key in parameters:
raise ValueError('Multiple values for parameter %s supplied' % key)
parameters[key] = arg
parameters.update({
'key': self.api.key,
'version': self.api.version,
'output': 'json',
})
url = parse.urlunparse(['http', self.api.host, self.path, None, parse.urlencode(parameters), None])
response = yield from aiohttp.request('GET', url, loop=self.api.loop)
body = yield from response.read_and_close()
# Can't use `read_and_close(decode=True)` because of a https://github.com/KeepSafe/aiohttp/issues/18
body = json.loads(body.decode('utf-8'))
if body['response_code'] != '200':
raise DgisError(int(body['response_code']), body['error_message'], body['error_code'])
# Register view if required
if self.register_views and self.api.register_views:
response = yield from aiohttp.request('GET', body['register_bc_url'], loop=self.api.loop)
if (yield from response.read_and_close()) == '0':
raise DgisError(404, 'View registration cannot be processed', 'registerViewFailed')
return body
def bind_api(**config):
properties = {
'path': config['path'],
'method': config.get('method', 'GET'),
'allowed_param': config['allowed_param'],
'register_views': config.get('register_views', False),
'__init__': __init__,
'execute': execute,
}
cls = type('API%sMethod' % config['path'].title().replace('/', ''), (object,), properties)
def _call(api, *args, **kwargs):
return cls(api).execute(*args, **kwargs)
return _call
<file_sep># -*- coding: utf-8 -*-
"""
python-aio2gis
============
A Python library for accessing the 2gis API via asyncio interface
"""
from setuptools import setup, find_packages
setup(
name='aio2gis',
version='0.0.1',
author='svartalf',
author_email='<EMAIL>',
url='https://github.com/svartalf/python-aio2gis',
description='asyncio-powered 2gis library for Python',
long_description=__doc__,
license='BSD',
packages=find_packages(),
install_requires=('aiohttp', ),
# test_suite='tests',
classifiers=(
'Development Status :: 1 - Planning',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Topic :: Software Development :: Libraries',
),
)
| 534d801cfb7e6e85dd977c76d942bc07e1c6bc79 | [
"Markdown",
"Python"
] | 6 | Markdown | svartalf/python-aio2gis | 588bdb782df8bae77855a9e2a6acb80cd6c99a80 | 113122bfa796e8c1c596e9f749169fc43ee1ced5 |
refs/heads/master | <repo_name>fernandobejarano/api-real-state-management<file_sep>/MillionAndUp.Models/Models.ValueObject/OwnerDTO.cs
using System;
namespace MillionAndUp.Models.Models.ValueObject
{
public class OwnerDetail
{
public int OwnerId { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public string Photo { get; set; }
public DateTime Birthday { get; set; }
}
public class OwnerReq
{
public string Name { get; set; }
public string Address { get; set; }
public string Photo { get; set; }
public DateTime Birthday { get; set; }
}
}
<file_sep>/MillionAndUp.Api/Controllers/AuthController.cs
using Microsoft.AspNetCore.Mvc;
using MillionAndUp.Cross_Cutting.Auth;
using System;
namespace MillionAndUp.Api.Controllers
{
[ApiController]
public class AuthController : Controller
{
private readonly ITokenService _auth;
public AuthController(ITokenService auth) => this._auth = auth;
[Route("api/[controller]")]
[HttpGet]
public IActionResult Autorization()
{
try
{
return Ok(_auth.CreateToken());
}
catch (Exception)
{
throw;
}
}
}
}
<file_sep>/MillionAndUp.Api/Migrations/20210518162450_InitialCreate.cs
using System;
using Microsoft.EntityFrameworkCore.Migrations;
namespace MillionAndUp.Api.Migrations
{
public partial class InitialCreate : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Owner",
columns: table => new
{
OwnerId = table.Column<int>(type: "INTEGER", nullable: false)
.Annotation("Sqlite:Autoincrement", true),
Name = table.Column<string>(type: "TEXT", nullable: true),
Address = table.Column<string>(type: "TEXT", nullable: true),
Photo = table.Column<string>(type: "TEXT", nullable: true),
Birthday = table.Column<DateTime>(type: "TEXT", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Owner", x => x.OwnerId);
});
migrationBuilder.CreateTable(
name: "Property",
columns: table => new
{
PropertyId = table.Column<int>(type: "INTEGER", nullable: false)
.Annotation("Sqlite:Autoincrement", true),
Name = table.Column<string>(type: "TEXT", nullable: true),
Address = table.Column<string>(type: "TEXT", nullable: true),
Price = table.Column<double>(type: "REAL", nullable: false),
CodeInternal = table.Column<int>(type: "INTEGER", nullable: false),
Year = table.Column<int>(type: "INTEGER", nullable: false),
OwnerId = table.Column<int>(type: "INTEGER", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Property", x => x.PropertyId);
table.ForeignKey(
name: "FK_Property_Owner_OwnerId",
column: x => x.OwnerId,
principalTable: "Owner",
principalColumn: "OwnerId",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
name: "PropertyImage",
columns: table => new
{
PropertyImageId = table.Column<int>(type: "INTEGER", nullable: false)
.Annotation("Sqlite:Autoincrement", true),
IdProperty = table.Column<int>(type: "INTEGER", nullable: false),
File = table.Column<string>(type: "TEXT", nullable: true),
Enable = table.Column<bool>(type: "INTEGER", nullable: false),
PropertyId = table.Column<int>(type: "INTEGER", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_PropertyImage", x => x.PropertyImageId);
table.ForeignKey(
name: "FK_PropertyImage_Property_PropertyId",
column: x => x.PropertyId,
principalTable: "Property",
principalColumn: "PropertyId",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
name: "PropertyTrace",
columns: table => new
{
PropertyTraceId = table.Column<int>(type: "INTEGER", nullable: false)
.Annotation("Sqlite:Autoincrement", true),
DateSale = table.Column<DateTime>(type: "TEXT", nullable: false),
Name = table.Column<string>(type: "TEXT", nullable: true),
Value = table.Column<double>(type: "REAL", nullable: false),
Tax = table.Column<double>(type: "REAL", nullable: false),
PropertyId = table.Column<int>(type: "INTEGER", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_PropertyTrace", x => x.PropertyTraceId);
table.ForeignKey(
name: "FK_PropertyTrace_Property_PropertyId",
column: x => x.PropertyId,
principalTable: "Property",
principalColumn: "PropertyId",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateIndex(
name: "IX_Property_OwnerId",
table: "Property",
column: "OwnerId");
migrationBuilder.CreateIndex(
name: "IX_PropertyImage_PropertyId",
table: "PropertyImage",
column: "PropertyId");
migrationBuilder.CreateIndex(
name: "IX_PropertyTrace_PropertyId",
table: "PropertyTrace",
column: "PropertyId");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "PropertyImage");
migrationBuilder.DropTable(
name: "PropertyTrace");
migrationBuilder.DropTable(
name: "Property");
migrationBuilder.DropTable(
name: "Owner");
}
}
}
<file_sep>/MillionAndUp.Models/Models.Entity/Owner.cs
using System;
using System.Collections.Generic;
namespace MillionAndUp.Models.Models.Entity
{
public class Owner
{
public int OwnerId { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public string Photo { get; set; }
public DateTime Birthday { get; set; }
public ICollection<Property> Propertys { get; set; }
}
}
<file_sep>/MillionAndUp.Models/Models.Entity/Property.cs
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
namespace MillionAndUp.Models.Models.Entity
{
public class Property
{
public int PropertyId { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public double Price { get; set; }
public int CodeInternal { get; set; }
public int Year { get; set; }
[ForeignKey("OwnerId")]
public Owner Owner { get; set; }
public ICollection<PropertyImage> PropertyImages { get; set; }
public ICollection<PropertyTrace> PropertyTraces { get; set; }
}
}
<file_sep>/MillionAndUp.Api/Startup.cs
using AutoMapper;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using MillionAndUp.Bussines;
using MillionAndUp.Cross_Cutting.Auth;
using MillionAndUp.Models.Interfaces;
using MillionAndUp.Models.Mappers;
using MillionAndUp.Persistence;
using Swashbuckle.AspNetCore.SwaggerGen;
using System;
using System.IO;
using System.Reflection;
using System.Text;
namespace MillionAndUp.Api
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
var mapperConfig = new MapperConfiguration(mc =>
{
mc.AddProfile(new MappingProfile());
});
IMapper mapper = mapperConfig.CreateMapper();
services.AddSingleton(mapper);
services.AddDbContext<SqlLiteDbContext>(x => x.UseSqlite(Configuration.GetConnectionString("Sqlite"), x => x.MigrationsAssembly("MillionAndUp.Api")));
services.AddScoped<ITokenService, TokenService>();
services.AddScoped<IOwnerBLL, OwnerBLL>();
services.AddScoped<IPropertyBLL, PropertyBLL>();
services.AddControllers();
services.AddSwaggerGen((Action<SwaggerGenOptions>)(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo()
{
Title = "MillionAndUp.Api",
Version = "v1"
});
Path.Combine(AppContext.BaseDirectory, Assembly.GetExecutingAssembly().GetName().Name + ".xml");
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
{
In = ParameterLocation.Header,
Description = "Please insert JWT with Bearer into field",
Name = "Authorization",
Type = SecuritySchemeType.ApiKey
});
SwaggerGenOptions swaggerGenOptions = c;
OpenApiSecurityRequirement securityRequirement1 = new OpenApiSecurityRequirement();
OpenApiSecurityRequirement securityRequirement2 = securityRequirement1;
OpenApiSecurityScheme key1 = new OpenApiSecurityScheme();
key1.Reference = new OpenApiReference()
{
Type = new ReferenceType?(ReferenceType.SecurityScheme),
Id = "Bearer"
};
string[] strArray = new string[0];
securityRequirement2.Add(key1, strArray);
OpenApiSecurityRequirement securityRequirement3 = securityRequirement1;
swaggerGenOptions.AddSecurityRequirement(securityRequirement3);
byte[] key = Encoding.ASCII.GetBytes("8C136A86-13EF-469F-8B8C-CC6797323C9A");
services.AddAuthentication((Action<AuthenticationOptions>)(x =>
{
x.DefaultAuthenticateScheme = "Bearer";
x.DefaultChallengeScheme = "Bearer";
})).AddJwtBearer((Action<JwtBearerOptions>)(x =>
{
x.RequireHttpsMetadata = false;
x.SaveToken = true;
x.TokenValidationParameters = new TokenValidationParameters()
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = (SecurityKey)new SymmetricSecurityKey(key),
ValidateIssuer = false,
ValidateAudience = false
};
}));
}));
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "MillionAndUp.Api v1"));
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
<file_sep>/MillionAndUp.Api/Controllers/OwnerController.cs
using Microsoft.AspNetCore.Mvc;
using MillionAndUp.Models.Interfaces;
using MillionAndUp.Models.Models.ValueObject;
using System;
using System.Threading.Tasks;
namespace MillionAndUp.Api.Controllers
{
[ApiController]
public class OwnerController : ControllerBase
{
private readonly IOwnerBLL _owner;
public OwnerController(IOwnerBLL owner) => this._owner = owner;
[HttpPost]
[Route("api/CreateOwner")]
public async Task<IActionResult> CreateOwner(OwnerDetail req)
{
try
{
_owner.CreateOwner(req);
return Accepted();
}
catch (Exception)
{
return NotFound();
}
}
[Route("api/ListOwners")]
[HttpGet]
public async Task<IActionResult> ListOwners()
{
try
{
return Ok(_owner.ListOwners());
}
catch (Exception)
{
return NotFound();
}
}
[Route("api/UpdateOwner")]
[HttpPut]
public async Task<IActionResult> UpdateOwner(OwnerDetail req)
{
try
{
_owner.UpdateOwner(req);
return Accepted();
}
catch (Exception)
{
return NotFound();
}
}
}
}
<file_sep>/MillionAndUp.Api/Controllers/PropertyController.cs
using Microsoft.AspNetCore.Mvc;
using MillionAndUp.Models.Interfaces;
using MillionAndUp.Models.Models.ValueObject;
using System;
using System.Threading.Tasks;
namespace MillionAndUp.Api.Controllers
{
[ApiController]
public class PropertyController : ControllerBase
{
private readonly IPropertyBLL _property;
public PropertyController(IPropertyBLL property) => this._property = property;
[HttpPost]
[Route("api/RegisterProperty")]
public async Task<IActionResult> RegisterProperty(PropertyDetail req)
{
try
{
_property.RegisterProperty(req);
return Accepted();
}
catch (Exception)
{
return NotFound();
}
}
[HttpGet]
[Route("api/GetPropertyByOwner")]
public async Task<IActionResult> GetPropertyByOwner(int ownerId)
{
try
{
return Ok((object)this._property.GetPropertyByOwner(ownerId));
}
catch (Exception)
{
return NotFound();
}
}
[HttpPost]
[Route("api/GeneratePropertyTrace")]
public async Task<IActionResult> GeneratePropertyTrace(PropertyTraceDetail req)
{
try
{
_property.GeneratePropertyTrace(req);
return Accepted();
}
catch (Exception)
{
return NotFound();
}
}
[HttpGet]
[Route("api/GetImagesByProperty")]
public async Task<IActionResult> GetImagesByProperty(int PropertyId)
{
try
{
_property.GetImagesByProperty(PropertyId);
return Accepted();
}
catch (Exception)
{
return NotFound();
}
}
[HttpPost]
[Route("api/ListTrace")]
public async Task<IActionResult> ListTrace(int PropertyId)
{
try
{
return Ok((object)this._property.ListTrace(PropertyId));
}
catch (Exception)
{
return NotFound();
}
}
[HttpPut]
[Route("api/ModifyImagesProperty")]
public async Task<IActionResult> ModifyImagesProperty(PropertyImageDetail req)
{
try
{
_property.ModifyImagesProperty(req);
return Ok();
}
catch (Exception)
{
return NotFound();
}
}
}
}
<file_sep>/MillionAndUp.Bussines/PropertyBLL.cs
using AutoMapper;
using MillionAndUp.Models.Interfaces;
using MillionAndUp.Models.Models.Entity;
using MillionAndUp.Models.Models.ValueObject;
using MillionAndUp.Persistence;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace MillionAndUp.Bussines
{
public class PropertyBLL : IPropertyBLL
{
private readonly SqlLiteDbContext _context;
private readonly IMapper _mapper;
public PropertyBLL(SqlLiteDbContext context, IMapper mapper)
{
_context = context;
_mapper = mapper;
}
public async Task RegisterProperty(PropertyDetail req)
{
_context.Property.Add(_mapper.Map<Property>(req));
_context.SaveChanges();
}
public IEnumerable<PropertyDetail> GetPropertyByOwner(int OwnerId)
{
var propertys = _context.Property.Where(x => x.Owner.OwnerId == OwnerId).ToList();
if (propertys.Count <= 0)
return null;
return _mapper.Map<IEnumerable<PropertyDetail>>(propertys);
}
public async Task SaveImagesProperty(IEnumerable<PropertyImageDetail> req)
{
_context.PropertyImage.Add(_mapper.Map<PropertyImage>(req));
_context.SaveChanges();
}
public async Task ModifyImagesProperty(PropertyImageDetail req)
{
var owner = _context.PropertyImage.Where(x => x.Property.PropertyId == req.IdProperty).FirstOrDefault();
owner = _mapper.Map<PropertyImage>(req);
_context.SaveChanges();
}
public IEnumerable<PropertyImageDetail> GetImagesByProperty(int PropertyId)
{
var images = _context.PropertyImage.Where(x => x.Property.PropertyId == PropertyId).ToList();
if (images.Count <= 0)
return null;
return _mapper.Map<IEnumerable<PropertyImageDetail>>(images);
}
public async Task GeneratePropertyTrace(PropertyTraceDetail req)
{
_context.PropertyTrace.Add(_mapper.Map<PropertyTrace>(req));
_context.SaveChanges();
}
public IEnumerable<PropertyTraceDetail> ListTrace(int PropertyId)
{
var trace = _context.PropertyTrace.Where(x => x.Property.PropertyId == PropertyId).ToList();
if (trace.Count <= 0)
return null;
return _mapper.Map<IEnumerable<PropertyTraceDetail>>(trace);
}
}
}
<file_sep>/MillionAndUp.Models/Models.ValueObject/PropertyDTO.cs
using System;
namespace MillionAndUp.Models.Models.ValueObject
{
public class PropertyDetail
{
public string Name { get; set; }
public string Address { get; set; }
public double Price { get; set; }
public int CodeInternal { get; set; }
public int Year { get; set; }
public int OwnerId { get; set; }
}
public class PropertyImageDetail
{
public int IdProperty { get; set; }
public string File { get; set; }
public bool Enable { get; set; }
}
public class PropertyTraceDetail
{
public DateTime DateSale { get; set; }
public string Name { get; set; }
public double Value { get; set; }
public double Tax { get; set; }
public int PropertyId { get; set; }
}
}
<file_sep>/MillionAndUp.Models/Models.Entity/PropertyImage.cs
using System.ComponentModel.DataAnnotations.Schema;
namespace MillionAndUp.Models.Models.Entity
{
public class PropertyImage
{
public int PropertyImageId { get; set; }
public int IdProperty { get; set; }
public string File { get; set; }
public bool Enable { get; set; }
[ForeignKey("PropertyId")]
public Property Property { get; set; }
}
}
<file_sep>/MillionAndUp.Bussines/OwnerBLL.cs
using AutoMapper;
using MillionAndUp.Models.Interfaces;
using MillionAndUp.Models.Models.Entity;
using MillionAndUp.Models.Models.ValueObject;
using MillionAndUp.Persistence;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace MillionAndUp.Bussines
{
public class OwnerBLL : IOwnerBLL
{
private readonly SqlLiteDbContext _context;
private readonly IMapper _mapper;
public OwnerBLL(SqlLiteDbContext context, IMapper mapper)
{
_context = context;
_mapper = mapper;
}
public async Task CreateOwner(OwnerDetail req)
{
_context.Owner.Add(_mapper.Map<Owner>(req));
_context.SaveChanges();
}
public IEnumerable<OwnerDetail> ListOwners()
{
var owners = _context.Owner.ToList();
if (owners.Count <= 0)
return null;
return _mapper.Map<List<OwnerDetail>>(owners);
}
public async Task UpdateOwner(OwnerDetail req)
{
var owner = _context.Owner.Where(x => x.OwnerId == req.OwnerId).FirstOrDefault();
owner = _mapper.Map<Owner>(req);
_context.SaveChanges();
}
}
}
<file_sep>/MillionAndUp.CrossCutting/Auth/TokenService.cs
using Microsoft.IdentityModel.Tokens;
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Text;
namespace MillionAndUp.Cross_Cutting.Auth
{
public class TokenService : ITokenService
{
public string CreateToken()
{
var key = Encoding.ASCII.GetBytes("8C136A86-13EF-469F-8B8C-CC6797323C9A");
var tokenHandler = new JwtSecurityTokenHandler();
var descriptor = new SecurityTokenDescriptor
{
Expires = DateTime.UtcNow.AddHours(1),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
var token = tokenHandler.CreateToken(descriptor);
return tokenHandler.WriteToken(token);
}
}
}
<file_sep>/MillionAndUp.Models/Interfaces/IPropertyBLL.cs
using MillionAndUp.Models.Models.ValueObject;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace MillionAndUp.Models.Interfaces
{
public interface IPropertyBLL
{
Task RegisterProperty(PropertyDetail req);
IEnumerable<PropertyDetail> GetPropertyByOwner(int OwnerId);
Task SaveImagesProperty(IEnumerable<PropertyImageDetail> req);
Task ModifyImagesProperty(PropertyImageDetail req);
IEnumerable<PropertyImageDetail> GetImagesByProperty(int PropertyId);
Task GeneratePropertyTrace(PropertyTraceDetail req);
IEnumerable<PropertyTraceDetail> ListTrace(int PropertyId);
}
}
<file_sep>/MillionAndUp.Models/Interfaces/IOwnerBLL.cs
using MillionAndUp.Models.Models.ValueObject;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace MillionAndUp.Models.Interfaces
{
public interface IOwnerBLL
{
Task CreateOwner(OwnerDetail req);
IEnumerable<OwnerDetail> ListOwners();
Task UpdateOwner(OwnerDetail req);
}
}
<file_sep>/MillionAndUp.Models/Models.Entity/PropertyTrace.cs
using System;
using System.ComponentModel.DataAnnotations.Schema;
namespace MillionAndUp.Models.Models.Entity
{
public class PropertyTrace
{
public int PropertyTraceId { get; set; }
public DateTime DateSale { get; set; }
public string Name { get; set; }
public double Value { get; set; }
public double Tax { get; set; }
[ForeignKey("PropertyId")]
public Property Property { get; set; }
}
}
<file_sep>/MillionAndUp.Models/Mappers/MappingProfile.cs
using AutoMapper;
using MillionAndUp.Models.Models.Entity;
using MillionAndUp.Models.Models.ValueObject;
namespace MillionAndUp.Models.Mappers
{
public class MappingProfile : Profile
{
public MappingProfile()
{
CreateMap<Owner, OwnerDetail>();
CreateMap<OwnerDetail, Owner>();
CreateMap<PropertyDetail, Property>();
CreateMap<Property, PropertyDetail>();
CreateMap<PropertyImage, PropertyImageDetail>();
CreateMap<PropertyImageDetail, PropertyImage>();
CreateMap<PropertyTrace, PropertyTraceDetail>();
CreateMap<PropertyTraceDetail, PropertyTrace>();
}
}
}
<file_sep>/MillionAndUp.Persistence/SqlLiteDbContext.cs
using Microsoft.EntityFrameworkCore;
using MillionAndUp.Models.Models.Entity;
namespace MillionAndUp.Persistence
{
public class SqlLiteDbContext : DbContext
{
public SqlLiteDbContext(DbContextOptions<SqlLiteDbContext> options) : base(options)
{
}
public DbSet<Owner> Owner { get; set; }
public DbSet<Property> Property { get; set; }
public DbSet<PropertyImage> PropertyImage { get; set; }
public DbSet<PropertyTrace> PropertyTrace { get; set; }
}
}
<file_sep>/MillionAndUp.CrossCutting/Auth/ITokenService.cs
namespace MillionAndUp.Cross_Cutting.Auth
{
public interface ITokenService
{
string CreateToken();
}
}
| a88645222aac590ab72d52c072de67ff32032c69 | [
"C#"
] | 19 | C# | fernandobejarano/api-real-state-management | b4632349c5db163b53c31d9f02a57c10cb9e2ec4 | 3158873dd4487dc86036c2125f5cd1ef7a72504f |
refs/heads/master | <repo_name>leperrot/Perrot_Leandre_WEB_TP2_Systeme<file_sep>/Patisserie2.0/src/model/Client.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 model;
/**
*
* @author leperrot
*/
public class Client implements Runnable {
private final String nom;
private final Patisserie patisserie;
private final int CPT = 3;
public Client(String nom, Patisserie patisserie) {
this.nom = nom;
this.patisserie = patisserie;
}
@Override
public void run() {
int cpt = 0;
//while(cpt < CPT) {
while(true){
try {
Gateau g = patisserie.achete();
if(g.equals(Gateau.GATEAU_EMPOISONNE)){
System.out.println("Le client " + nom + " est décédé suite à un gateau pas bon");
return;
}
cpt++;
System.out.println("Le client " + nom + " a acheté son " + cpt + " gateau");
} catch (InterruptedException ex) {
System.out.println("Le client " + nom + " peut acheter un gateau");
}
}
}
}
<file_sep>/Patisserie2.0/src/model/Patisserie.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 model;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
/**c
*
* @author leperrot
*/
public class Patisserie {
private final BlockingQueue<Gateau> gateaux;
private int cpt = 0;
public Patisserie(){
gateaux = new ArrayBlockingQueue(10);
}
public void depose(Gateau g) throws InterruptedException, Exception{
if(cpt == 20) throw new Exception();
gateaux.put(g);
}
public Gateau achete() throws InterruptedException{
if(cpt == 20)
return Gateau.GATEAU_EMPOISONNE;
cpt++;
return gateaux.take();
}
public int getStock(){
return gateaux.size();
}
}
<file_sep>/Patisserie/src/model/Gateau.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 model;
/**
*
* @author leperrot
*/
public class Gateau {
private double prix;
public Gateau(double prix){
this.prix = prix;
}
public double getPrix() {
return prix;
}
public void setPrix(double prix) {
this.prix = prix;
}
}
| 3baaa2351319eccc03dae9c43373e87f222689e4 | [
"Java"
] | 3 | Java | leperrot/Perrot_Leandre_WEB_TP2_Systeme | 86af5ef93be31e1e85f57fb72762c2ea98fa263d | 563ca4f3f9e399e242f357376e2418ce2fa47ffc |
refs/heads/master | <repo_name>amirza495/LIS331-Driver<file_sep>/main/LIS331.cpp
#include "LIS331.h"
// conversion factor LSB/g divide raw value by this to get acceleration in g's
float conversion = 1000.0*5.6;
unsigned int read_axis(byte reg)
{
int data = 0;
data = readRegister(csLIS331, reg+1, 1);
data = data << 8;
data |= readRegister(csLIS331, reg, 1);
return data;
}
float convert_axis(int raw)
{
float value = 0.0;
value = (float) raw/conversion;
return value;
}
void LIS331_init(){
Serial.begin(115200);
// start the SPI library:
SPI_init();
// initalize the chip select pin:
pinMode(csLIS331, OUTPUT);
// give the sensor time to set up:
delay(100);
writeRegister(csLIS331, CTRL_REG1, PWR_MODE_ON | DATA_RATE_400HZ | Z_AXIS_ENABLE | Y_AXIS_ENABLE | X_AXIS_ENABLE);
delay(100);
int test = readRegister(csLIS331, CTRL_REG4, 1);
Serial.println(test, BIN);
}
void LIS331_get_data(LIS331_t *gLIS331Data) {
// zero raw data inputs
gLIS331Data->raw.x = 0;
gLIS331Data->raw.y = 0;
gLIS331Data->raw.z = 0;
// read each axis of data
gLIS331Data->raw.x = read_axis(OUT_X_L);
gLIS331Data->raw.y = read_axis(OUT_Y_L);
gLIS331Data->raw.z = read_axis(OUT_Z_L);
// convert data from LSB to g
gLIS331Data->data.x = convert_axis(gLIS331Data->raw.x);
gLIS331Data->data.y = convert_axis(gLIS331Data->raw.y);
gLIS331Data->data.z = convert_axis(gLIS331Data->raw.z);
}
<file_sep>/main/SPI_Driver.cpp
#include "SPI_Driver.h"
// Start SPI interface
// still must configure chip select pin as OUTPUT
void SPI_init(){
// start SPI
SPI.begin();
// set to MSB first mode
SPI.setBitOrder(MSBFIRST);
}
//Read from a register over SPI
unsigned int readRegister(int cs, byte reg, int len) {
byte inByte = 0; // incoming byte from the SPI
unsigned int result = 0; // result to return
byte dataToSend = reg | READ;
// take the chip select low to select the device:
digitalWrite(cs, LOW);
// send the device the register you want to read:
SPI.transfer(dataToSend);
// send a value of 0 to read the first byte returned:
result = SPI.transfer(0x00);
// decrement the number of bytes left to read:
len--;
// if you still have another byte to read:
if (len > 0) {
// shift the first byte left, then get the second byte:
result = result << 8;
inByte = SPI.transfer(0x00);
// combine the byte you just got with the previous one:
result = result | inByte;
// decrement the number of bytes left to read:
len--;
}
// take the chip select high to de-select:
digitalWrite(cs, HIGH);
// return the result:
return (result);
}
//Sends a write command to SPI device
void writeRegister(int cs, byte reg, byte val) {
// now combine the register address and the command into one byte:
byte data = reg | WRITE;
// take the chip select low to select the device:
digitalWrite(cs, LOW);
SPI.transfer(data); //Send register location
SPI.transfer(val); //Send value to record into register
// take the chip select high to de-select:
digitalWrite(cs, HIGH);
}
<file_sep>/main/SPI_Driver.h
#ifndef SPI_DRIVER_H_
#define SPI_DRIVER_H_
#include <Arduino.h>
#include <SPI.h>
const byte READ = 0b10000000; // SCP1000's read command
const byte WRITE = 0b00000000; // SCP1000's write command
// Start SPI interface
void SPI_init(void);
// read register function
unsigned int readRegister(int cs, byte reg, int len);
// write value to register
void writeRegister(int cs, byte reg, byte val);
#endif
<file_sep>/main/LIS331.h
#ifndef LIS331_H_
#define LIS331_H_
#include "SPI_Driver.h"
#define WHO_AM_I 0x0F
#define CTRL_REG1 0x20
#define CTRL_REG2 0x21
#define CTRL_REG3 0x22
#define CTRL_REG4 0x23
#define CTRL_REG5 0x24
#define HP_FILTER_RESET 0x25
#define REFERENCE 0x26
#define STATUS_REG 0x27
#define OUT_X_L 0x28
#define OUT_X_H 0x29
#define OUT_Y_L 0x2A
#define OUT_Y_H 0x2B
#define OUT_Z_L 0x2C
#define OUT_Z_H 0x2D
// CTRL_REG1 Values
#define PWR_MODE_ON (1 << 5)
#define DATA_RATE_50HZ (1 << 3)
#define DATA_RATE_100HZ (2 << 3)
#define DATA_RATE_400HZ (3 << 3)
#define Z_AXIS_ENABLE (1 << 2)
#define Y_AXIS_ENABLE (1 << 1)
#define X_AXIS_ENABLE (1 << 0)
// CTRL_REG4
#define FS_2g (0 << 4)
#define FS_4g (1 << 4)
#define FS_8g (3 << 4)
const int csLIS331 = 10;
// raw data struct
typedef struct{
int x;
int y;
int z;
}LIS331_raw_data_t;
// calibrated data struct
typedef struct {
float x;
float y;
float z;
}LIS331_data_t;
// sensor data struct
typedef struct{
LIS331_raw_data_t raw;
LIS331_data_t data;
}LIS331_t;
// sensor initialization function
void LIS331_init();
// get data function, returns outputs to global variable
void LIS331_get_data(LIS331_t *gLIS331Data);
#endif
<file_sep>/main/main.ino
#include "LIS331.h"
LIS331_t gLIS331Data;
void setup() {
// put your setup code here, to run once:
LIS331_init();
Serial.println("Initialization Complete");
}
void loop() {
// put your main code here, to run repeatedly:
LIS331_get_data(&gLIS331Data);
//Serial.print("The x accleration is: ");
Serial.print(gLIS331Data.data.x);
Serial.print(",");
//Serial.print("The y accleration is: ");
Serial.print(gLIS331Data.data.y);
Serial.print(",");
//Serial.print("The z accleration is: ");
Serial.print(gLIS331Data.data.z);
Serial.print("\r\n");
delay(10);
}
<file_sep>/README.md
# LIS331-Driver
C SPI driver for LIS331 3-axis accelerometer
<br>
The working driver is on master
A template/tutorial driver is on template if you are interested in learning how the driver was written
| 7a0aaabffa43a900212033db45eb80b55d8ce609 | [
"Markdown",
"C",
"C++"
] | 6 | C++ | amirza495/LIS331-Driver | 59b1d570d45cea81c19d5686f2ab9f24f62fa961 | 378963566a4e842850e12ca85d3bcdfbdf5bbeb8 |
refs/heads/master | <repo_name>thallada/panic-shack<file_sep>/js/sendChat.js
var form = document.getElementById('say-form');
var username = document.getElementById('say-username');
var text = document.getElementById('say-text');
var send = document.getElementById('say-send');
var sending = document.getElementById('say-sending');
var success = document.getElementById('say-success');
var error = document.getElementById('say-error');
function sendChat(e) {
e.preventDefault();
var xhr = new XMLHttpRequest();
var formData = new FormData(form);
xhr.addEventListener('load', function (event) {
console.log(event.target.responseText);
if (event.target.status === 200) {
error.textContent = '';
text.value = '';
success.style.display = 'inline-block';
} else if (event.target.status === 422) {
error.textContent = 'You must give a message to send! (' + event.target.status + ')';
success.style.display = 'none';
} else {
error.textContent = 'Error Sending! (' + event.target.status + ')';
success.style.display = 'none';
}
sending.style.display = 'none';
});
xhr.open('POST', '/chat/');
xhr.send(formData);
sending.style.display = 'inline-block';
}
form.addEventListener('submit', sendChat);
<file_sep>/notify/notify_joins.py
#!/usr/bin/env python
# Read the Minecraft server log and diff it against the server log it saw last. If there any new joins in the diff, send
# a notification.
import codecs
import os
import re
from datetime import datetime
import requests
from secrets import IFTTT_WEBHOOK_KEY_TYLER, IFTTT_WEBHOOK_KEY_KAELAN
LOG_FILENAME = '/srv/minecraft-panic-shack/logs/latest.log'
OLD_LOG_FILENAME = '/srv/minecraft-panic-shack/logs/last-read.log'
USERNAME_BLACKLIST = ['anarchyeight', 'kinedactyl']
IFTTT_EVENT_NAME = 'user_joined_panic_shack'
def read_log(filename):
with codecs.open(filename, encoding='utf-8') as log:
return log.readlines()
def save_log(filename, lines):
with codecs.open(filename, 'w', encoding='utf-8') as log:
log.writelines(lines)
if __name__ == '__main__':
if (datetime.fromtimestamp(os.path.getmtime(LOG_FILENAME)) >
datetime.fromtimestamp(os.path.getmtime(OLD_LOG_FILENAME))):
new_log = read_log(LOG_FILENAME)
old_log = read_log(OLD_LOG_FILENAME)
if new_log[0] != old_log[0]:
# A log rotate occured
old_log = []
if len(new_log) > len(old_log):
for new_line in new_log[len(old_log):]:
match = re.match('[\[][0-9:]+[\]]\s[\[]Server thread/INFO]: (\S+) joined the game', new_line)
if match:
username = match.group(1)
if username not in USERNAME_BLACKLIST:
# IFTTT does not support sharing Applets anymore :(
r = requests.post(
'https://maker.ifttt.com/trigger/{}/with/key/{}'.format(IFTTT_EVENT_NAME,
IFTTT_WEBHOOK_KEY_TYLER),
data={'value1': username})
r = requests.post(
'https://maker.ifttt.com/trigger/{}/with/key/{}'.format(IFTTT_EVENT_NAME,
IFTTT_WEBHOOK_KEY_KAELAN),
data={'value1': username})
save_log(OLD_LOG_FILENAME, new_log)
<file_sep>/js/getMapUpdate.js
var mapUpdateTime = document.getElementById('map-last-updated');
function getHeaderTime () {
mapUpdateTime.textContent = moment(this.getResponseHeader("Last-Modified")).calendar();
}
var oReq = new XMLHttpRequest();
oReq.open("HEAD", "/map/index.html");
oReq.onload = getHeaderTime;
oReq.send();
<file_sep>/chat/minecraft-chat.ini
[uwsgi]
module = wsgi:application
master = true
processes = 2
socket = minecraft-chat.sock
chmod-socket = 664
vacuum = true
die-on-term = true
<file_sep>/js/getLog.js
var output = document.getElementById('server-log');
function reqListener() {
var autoScroll = document.getElementById('auto-scroll');
output.textContent = xhr.responseText;
if (autoScroll.checked) {
output.scrollTop = output.scrollHeight;
}
}
var xhr = new XMLHttpRequest();
xhr.addEventListener('load', reqListener);
xhr.open('GET', '/server.log');
xhr.send();
setInterval(function() {
xhr = new XMLHttpRequest();
xhr.addEventListener('load', reqListener);
xhr.open('GET', '/server.log');
xhr.send();
}, 10000);
<file_sep>/config/overviewerConfig.py
worlds["Death Pit"] = "/srv/minecraft-panic-shack/world"
renders["normalrender"] = {
"world": "Death Pit",
"title": "North",
"rendermode": smooth_lighting,
"dimension": "overworld",
"northdirection": "upper-left",
}
renders["normalrendersouth"] = {
"world": "Death Pit",
"title": "South",
"rendermode": smooth_lighting,
"dimension": "overworld",
"northdirection": "lower-right",
}
renders["normalrenderwest"] = {
"world": "Death Pit",
"title": "West",
"rendermode": smooth_lighting,
"dimension": "overworld",
"northdirection": "upper-right",
}
renders["normalrendereast"] = {
"world": "Death Pit",
"title": "East",
"rendermode": smooth_lighting,
"dimension": "overworld",
"northdirection": "lower-left",
}
renders["nightrender"] = {
"world": "Death Pit",
"title": "Night North",
"rendermode": smooth_night,
"dimension": "overworld",
"northdirection": "upper-left",
}
renders["nightrendersouth"] = {
"world": "Death Pit",
"title": "Night South",
"rendermode": smooth_night,
"dimension": "overworld",
"northdirection": "lower-right",
}
renders["nightrenderwest"] = {
"world": "Death Pit",
"title": "Night West",
"rendermode": smooth_night,
"dimension": "overworld",
"northdirection": "upper-right",
}
renders["nightrendereast"] = {
"world": "Death Pit",
"title": "Night East",
"rendermode": smooth_night,
"dimension": "overworld",
"northdirection": "lower-left",
}
renders["caverender"] = {
"world": "Death Pit",
"title": "Cave North",
"rendermode": cave,
"dimension": "overworld",
"northdirection": "upper-left",
}
renders["caverendersouth"] = {
"world": "Death Pit",
"title": "Cave South",
"rendermode": cave,
"dimension": "overworld",
"northdirection": "lower-right",
}
renders["caverenderwest"] = {
"world": "Death Pit",
"title": "Cave West",
"rendermode": cave,
"dimension": "overworld",
"northdirection": "upper-right",
}
renders["caverendereast"] = {
"world": "Death Pit",
"title": "Cave East",
"rendermode": cave,
"dimension": "overworld",
"northdirection": "lower-left",
}
renders["netherrender"] = {
"world": "Death Pit",
"title": "Nether North",
"rendermode": nether,
"dimension": "nether",
"northdirection": "upper-left",
}
renders["netherrendersouth"] = {
"world": "Death Pit",
"title": "Nether South",
"rendermode": nether,
"dimension": "nether",
"northdirection": "lower-right",
}
renders["netherrenderwest"] = {
"world": "Death Pit",
"title": "Nether West",
"rendermode": nether,
"dimension": "nether",
"northdirection": "upper-right",
}
renders["netherrendereast"] = {
"world": "Death Pit",
"title": "Nether East",
"rendermode": nether,
"dimension": "nether",
"northdirection": "lower-left",
}
outputdir = "/var/www/panic-shack/map/"
<file_sep>/chat/server.py
import logging
import shlex
import subprocess
import unicodedata
from flask import Flask, request
app = Flask(__name__)
@app.before_first_request
def setup_logging():
app.logger.addHandler(logging.StreamHandler())
app.logger.setLevel(logging.INFO)
def sanitize_input(input):
input = "".join(ch for ch in input if unicodedata.category(ch)[0] != "C")
return shlex.quote(input.replace('^', ''))
@app.route('/chat/', methods=['POST'])
def send_chat():
if request.method == 'POST':
if request.form.get('email', None):
return 'Text was entered into honeypot!', 200
if not request.form.get('say-text', None):
return 'No message to send!', 422
if request.form.get('say-username', None):
subprocess.call([
'/usr/bin/screen', '-S', 'mc-panic-shack', '-p', '0', '-X', 'stuff',
'/say [{}]: {}\015'.format(
sanitize_input(request.form['say-username']),
sanitize_input(request.form['say-text']))
])
else:
subprocess.call([
'/usr/bin/screen', '-S', 'mc-panic-shack', '-p', '0', '-X', 'stuff',
'/say {}\015'.format(sanitize_input(request.form['say-text']))
])
return 'Sending chat: ' + request.form.get('say-username', '') + ': ' + request.form['say-text']
if __name__ == "__main__":
app.run(host='0.0.0.0', port="8888")
| a0a9f2173e5392d42e83ba2f034925dfba532a6f | [
"JavaScript",
"Python",
"INI"
] | 7 | JavaScript | thallada/panic-shack | c90cb7d00051b17347ba0c91ecd474cc78c29550 | aaf1bf7728bbb8ebb5b9f268d062a123429d26b5 |
refs/heads/master | <file_sep>//
// MainCollectionViewController.swift
// CourierManagement
//
// Created by <NAME> on 07/10/20.
// Copyright © 2020 <NAME>. All rights reserved.
//
import UIKit
import ZCCoreFramework
import ZCUIFramework
class MainCollectionViewController: UIViewController {
var tiles: [Component] = []
lazy var collectionView: UICollectionView = {
let collectionView = UICollectionView(frame: .zero, collectionViewLayout: collectionViewLayout())
collectionView.register(MainCollectionViewCell.self, forCellWithReuseIdentifier: "CollectionViewCell")
collectionView.backgroundColor = UIColor.init(red: 34/255, green: 36/255, blue: 38/255, alpha: 1)
collectionView.delegate = self
collectionView.dataSource = self
collectionView.translatesAutoresizingMaskIntoConstraints = false
return collectionView
}()
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
}
}
extension MainCollectionViewController{
private func logout() {
ZohoAuth.revokeAccessToken {
(error) in
if error == nil {
//Logout Successfully
LoginHandler.shared.logOut()
}
else {
//Error Occurred
}
}
}
@objc private func logOutPermission(){
let alert = UIAlertController(title: "Permission", message: "YouNeedToLogOut", preferredStyle: .alert)
let logOut = UIAlertAction(title: "yes", style: .default) { _ in
self.logout()
}
let no = UIAlertAction(title: "cancel", style: .cancel, handler: nil)
alert.addAction(no)
alert.addAction(logOut)
self.present(alert, animated: true, completion: nil)
}
}
extension MainCollectionViewController {
private func setupUI() {
self.view.backgroundColor = UIColor.init(red: 34/255, green: 36/255, blue: 38/255, alpha: 1)
self.navigationController?.navigationBar.topItem?.title = "Courier Management"
self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(title: "Logout", style: .plain, target: self, action: #selector(self.logOutPermission))
self.navigationItem.rightBarButtonItem?.tintColor = .black
self.view.addSubview(collectionView)
NSLayoutConstraint.activate([
collectionView.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor),
collectionView.leftAnchor.constraint(equalTo: self.view.leftAnchor),
collectionView.rightAnchor.constraint(equalTo: self.view.rightAnchor),
collectionView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor)
])
}
private func collectionViewLayout() -> UICollectionViewLayout {
let layout = UICollectionViewFlowLayout()
let cellWidthHeightConstant: CGFloat = 120
layout.sectionInset = UIEdgeInsets(top: 40,
left: 40,
bottom: 40,
right: 40)
layout.scrollDirection = .vertical
layout.minimumInteritemSpacing = 10
layout.minimumLineSpacing = 30
layout.itemSize = CGSize(width: cellWidthHeightConstant, height: cellWidthHeightConstant)
return layout
}
private func getComponentViewController(for index:Int){
let component = self.tiles[index]
let vc:UIViewController
switch component.type {
case .form:
vc = ZCUIService.getViewController(forForm: ComponentDetail.init(componentLinkName: component.componentLinkName))
case .report:
vc = ZCUIService.getViewController(forReport: ComponentDetail.init(componentLinkName: component.componentLinkName))
case .page:
vc = ZCUIService.getViewController(forPage: ComponentDetail.init(componentLinkName: component.componentLinkName))
default:
return
}
self.navigationController?.pushViewController(vc, animated: true)
}
}
extension MainCollectionViewController: UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return tiles.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionViewCell", for: indexPath) as! MainCollectionViewCell
cell.titleLabel.text = tiles[indexPath.row].componentLinkName
cell.imgView.image = UIImage.init(named: tiles[indexPath.row].componentLinkName)
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
self.getComponentViewController(for:indexPath.row)
}
}
class MainCollectionViewCell: UICollectionViewCell {
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
setupUI()
}
lazy var roundedBackgroundView: UIView = {
let view = UIView()
view.layer.cornerRadius = 10
view.layer.borderColor = UIColor.systemGray.cgColor
view.layer.borderWidth = 1
view.backgroundColor = UIColor.init(red: 63/255, green: 68/255, blue: 74/255, alpha: 1)
view.translatesAutoresizingMaskIntoConstraints = false
return view
}()
lazy var titleLabel: UILabel = {
let label = UILabel()
label.font = UIFont(name: "HelveticaNeue", size: 14)
label.textColor = .white
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
lazy var imgView : UIImageView = {
let imgView = UIImageView()
imgView.sizeToFit()
imgView.translatesAutoresizingMaskIntoConstraints = false
return imgView
}()
}
extension MainCollectionViewCell {
private func setupUI() {
self.contentView.addSubview(roundedBackgroundView)
roundedBackgroundView.addSubview(titleLabel)
roundedBackgroundView.addSubview(imgView)
// imgView.image = UIImage.init(named: "Screenshot 2020-09-23 at 1.43.49 PM")
NSLayoutConstraint.activate([
roundedBackgroundView.topAnchor.constraint(equalTo: self.contentView.topAnchor, constant: 5),
roundedBackgroundView.bottomAnchor.constraint(equalTo: self.contentView.bottomAnchor, constant: -5),
roundedBackgroundView.leftAnchor.constraint(equalTo: self.contentView.leftAnchor, constant: 5),
roundedBackgroundView.rightAnchor.constraint(equalTo: self.contentView.rightAnchor, constant: -5),
titleLabel.centerXAnchor.constraint(equalTo: roundedBackgroundView.centerXAnchor),
titleLabel.centerYAnchor.constraint(equalTo: roundedBackgroundView.centerYAnchor,constant: 70),
imgView.centerXAnchor.constraint(equalTo: roundedBackgroundView.centerXAnchor),
imgView.centerYAnchor.constraint(equalTo: roundedBackgroundView.centerYAnchor),
imgView.heightAnchor.constraint(equalToConstant: 50),
imgView.widthAnchor.constraint(equalToConstant: 50)
])
}
}
<file_sep>//
// LoginHandler.swift
// CourierManagement
//
// Created by <NAME> on 08/10/20.
// Copyright © 2020 <NAME>. All rights reserved.
//
import UIKit
import ZCCoreFramework
class LoginHandler {
static var shared = LoginHandler()
private var application = Application(appOwnerName: "vigneshkumargt0", appLinkName: "courier-management")
var window:UIWindow?
private var mainVc : MainCollectionViewController?
private init(){ }
func configureCreatorClient(window: UIWindow){
self.window = window
let scope = ["ZohoCreator.meta.READ", "ZohoCreator.data.READ", "ZohoCreator.meta.CREATE", "ZohoCreator.data.CREATE", "aaaserver.profile.READ", "ZohoContacts.userphoto.READ", "ZohoContacts.contactapi.READ"]
let clientID = "1000.S45UAZ5HE09NQU6A9CPKIY3JDNAT0Z"
let clientSecret = "<KEY>"
let urlScheme = "couriermanagement://"
let accountsUrl = "https://accounts.zoho.com" // enter the accounts URL of your respective DC. For eg: EU users use 'https://accounts.zoho.eu'.
ZohoAuth.initWithClientID(clientID, clientSecret: clientSecret, scope: scope, urlScheme: urlScheme, mainWindow: window, accountsURL: accountsUrl)
if ZohoAuth.isUserSignedIn(){
Creator.configure(delegate: self)
guard let window = self.window else { return }
guard let vc = window.rootViewController as? ViewController else{return}
DispatchQueue.main.async {
vc.loginButton.alpha = 0
vc.circularView.alpha = 1
vc.circularView.progressAnimation(duration: 5)
}
self.setUpViewcontroller()
}else{
self.window?.rootViewController = ViewController()
}
}
func logOut(){
guard let window = self.window else { return }
DispatchQueue.main.async {
window.rootViewController = ViewController()
}
}
func login(){
ZohoAuth.getOauth2Token {
(token, error) in
if token == nil {
// Not logged in
self.showLoginScreen()
} else {
// App logged in already.
// Ensure to use the following line of code in your iOS app before you utilize any of Creator SDK’s methods
Creator.configure(delegate: self)
self.setUpViewcontroller()
}
}
}
private func showLoginScreen(){
ZohoAuth.presentZohoSign( in: {
(token, error) in
if token != nil {
// success login
// Ensure to use the following line of code in your iOS app before you utilize any of Creator SDK’s methods
Creator.configure(delegate: self)
self.setUpViewcontroller()
}
if error != nil{
guard let window = self.window else { return }
guard let vc = window.rootViewController as? ViewController else{return}
DispatchQueue.main.async {
vc.circularView.alpha = 0
}
}
})
}
private func setUpViewcontroller(){
self.mainVc = MainCollectionViewController()
ZCAPIService.fetchSectionList(for: application) { (result) in
switch result
{
case .success(let sectionlist):
let components = self.getComponents(sectionlist.sections)
self.mainVc?.tiles = components
case .failure(_):
print("error")
self.mainVc?.tiles = []
}
guard let mainVc = self.mainVc else{return}
DispatchQueue.main.async {
let navVc = UINavigationController(rootViewController: mainVc)
self.window?.rootViewController = navVc
}
}
}
private func getComponents(_ sections:[Section])->[Component]{
var components:[Component] = []
for section in sections{
for component in section.components {
components.append(component)
}
}
return components
}
}
extension LoginHandler: ZCCoreFrameworkDelegate{
func oAuthToken(with completion: @escaping AccessTokenCompletion) {
ZohoAuth.getOauth2Token {
(token, error) in
completion(token, error)
}
}
func configuration() -> CreatorConfiguration {
return CreatorConfiguration(creatorURL: "https://creator.zoho.com") // enter the creator URL of your respective data center (DC). For eg: EU users must use https://creator.zoho.eu
}
}
<file_sep># Uncomment the next line to define a global platform for your project
# platform :ios, '9.0'
target 'CourierManagement' do
# Comment the next line if you don't want to use dynamic frameworks
use_frameworks!
# Pods for CourierManagement
pod 'ZohoAuth'
pod 'ZCCoreFramework'
pod 'ZCUIFramework'
end
<file_sep>//
// SceneDelegate.swift
// CourierManagement
//
// Created by <NAME> on 25/09/20.
// Copyright © 2020 <NAME>. All rights reserved.
//
import UIKit
import ZCCoreFramework
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
guard let window = window else { return }
LoginHandler.shared.configureCreatorClient(window: window)
}
func scene(_ scene: UIScene, openURLContexts URLContexts: Set <UIOpenURLContext> ) {
if let context = URLContexts.first {
let _ = ZohoAuth.handleURL(context.url,
sourceApplication: context.options.sourceApplication,
annotation: context.options.annotation)
}
}
}
//extension SceneDelegate: ZCCoreFrameworkDelegate {
// func oAuthToken(with completion: @escaping AccessTokenCompletion) {
// ZohoAuth.getOauth2Token {
// (token, error) in
// completion(token, error)
// }
// }
// func configuration() -> CreatorConfiguration {
// return CreatorConfiguration(creatorURL: "https://creator.zoho.com") // enter the creator URL of your respective data center (DC). For eg: EU users must use https://creator.zoho.eu
// }
//
// func showLoginScreen() {
// ZohoAuth.presentZohoSign( in: {
// (token, error) in
// if token != nil {
// // success login
// // Ensure to use the following line of code in your iOS app before you utilize any of Creator SDK’s methods
// Creator.configure(delegate: self)
// self.window?.rootViewController = MainViewController()
// }
// })
// }
//
// func logout() {
// ZohoAuth.revokeAccessToken {
// (error) in
// if error == nil {
// //Logout Successfully
// }
// else {
// //Error Occurred
// }
// }
// }
// }
<file_sep>//
// ViewController.swift
// CourierManagement
//
// Created by <NAME> on 25/09/20.
// Copyright © 2020 <NAME>. All rights reserved.
//
import UIKit
import ZCCoreFramework
class ViewController: UIViewController{
lazy var loginButton :UIButton = {
var loginButton = UIButton()
loginButton.layer.cornerRadius = 70
loginButton.setTitle("SignIn", for: .normal)
loginButton.titleLabel?.font = UIFont.systemFont(ofSize: 30, weight: .ultraLight)
loginButton.setTitleColor(.black, for: .normal)
loginButton.backgroundColor = UIColor.init(red: 232/255, green: 232/255, blue: 232/255, alpha: 1)
loginButton.addTarget(self, action: #selector(showLogin), for: .touchUpInside)
loginButton.translatesAutoresizingMaskIntoConstraints = false
return loginButton
}()
lazy var circularView = CircularProgressView()
override func viewDidLoad() {
super.viewDidLoad()
setupLoginView()
}
func setupLoginView(){
self.view.backgroundColor = UIColor.init(red: 110/255, green: 110/255, blue: 110/255, alpha: 1)
self.view.addSubview(circularView)
self.view.addSubview(loginButton)
circularView.center = view.center
NSLayoutConstraint.activate([
loginButton.centerXAnchor.constraint(equalTo: self.view.centerXAnchor),
loginButton.centerYAnchor.constraint(equalTo: self.view.centerYAnchor),
loginButton.heightAnchor.constraint(equalToConstant: 140),
loginButton.widthAnchor.constraint(equalToConstant: 140)
])
circularView.alpha = 0
}
@objc private func showLogin(){
circularView.alpha = 1
LoginHandler.shared.login()
circularView.progressAnimation(duration: 50)
DispatchQueue.main.asyncAfter(deadline: .now()+50) {
self.circularView.alpha = 0
}
}
}
class CircularProgressView: UIView {
private var circleLayer = CAShapeLayer()
private var progressLayer = CAShapeLayer()
var circularView: CircularProgressView!
override init(frame: CGRect) {
super.init(frame: frame)
createCircularPath()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
createCircularPath()
}
func createCircularPath() {
let circularPath = UIBezierPath(arcCenter: CGPoint(x: frame.size.width / 2.0, y: frame.size.height / 2.0), radius: 80, startAngle: -.pi / 2, endAngle: 3 * .pi / 2, clockwise: true)
circleLayer.path = circularPath.cgPath
circleLayer.fillColor = UIColor.clear.cgColor
circleLayer.lineCap = .round
circleLayer.lineWidth = 10.0
circleLayer.strokeColor = UIColor.black.cgColor
progressLayer.path = circularPath.cgPath
progressLayer.fillColor = UIColor.clear.cgColor
progressLayer.lineCap = .round
progressLayer.lineWidth = 5.0
progressLayer.strokeEnd = 0
progressLayer.strokeColor = UIColor.init(red: 232/255, green: 232/255, blue: 232/255, alpha: 1).cgColor
layer.addSublayer(circleLayer)
layer.addSublayer(progressLayer)
}
func progressAnimation(duration: TimeInterval) {
let circularProgressAnimation = CABasicAnimation(keyPath: "strokeEnd")
circularProgressAnimation.duration = duration
circularProgressAnimation.toValue = 1.0
circularProgressAnimation.fillMode = .forwards
circularProgressAnimation.isRemovedOnCompletion = false
progressLayer.add(circularProgressAnimation, forKey: "progressAnim")
}
}
| 482fcbe82a9df7b858e347171fa72296fc8c0d28 | [
"Swift",
"Ruby"
] | 5 | Swift | karankarthic/CourierManagement | 3edf7e8c2d6424e32cdae8f428e7fd57627a831e | e9a13ef8b6ff1e871565379e4c19456dc6f0de5a |
refs/heads/master | <file_sep>import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
long m = scanner.nextLong();
System.out.println(lowestN(m));
}
public static long factorial(int n) {
if (n == 0) {
return 1;
}
return n * factorial(n - 1);
}
public static int lowestN(long m) {
int n = 2;
while (factorial(n) <= m) {
n++;
}
return n;
}
}<file_sep>import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int input = 0;
int intMax = 0;
while (scanner.hasNextInt()) {
input = scanner.nextInt();
if (input == 0) {
break;
}
if (intMax < input) {
intMax = input;
}
}
System.out.println(intMax);
}
}<file_sep>import java.util.ArrayList;
import java.util.Scanner;
class Main {
public static void main(String[] args) {
final Scanner scanner = new Scanner(System.in);
int input = scanner.nextInt();
ArrayList<Integer> list = calculateNum(input);
for (int i = 0; i < input; i++) {
System.out.print(list.get(i) + " ");
}
}
public static ArrayList<Integer> calculateNum(int num) {
ArrayList<Integer> list = new ArrayList<>();
for (int i = 1; i <= num; i++) {
for (int j = 1; j <= i; j++) {
list.add(i);
}
}
return list;
}
}<file_sep>import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void sort(int[] numbers) {
int temp;
for (int i = numbers.length / 2 - 1; i >= 0; i--) {
heapify(numbers, numbers.length, i);
}
for (int i = numbers.length - 1; i > 0; i--) {
temp = numbers[0];
numbers[0] = numbers[i];
numbers[i] = temp;
heapify(numbers, i, 0);
}
}
public static void heapify(int[] arr, int n, int i) {
int max = i;
int left = 2 * i + 1;
int right = 2 * i + 2;
int temp;
if (left < n && arr[left] > arr[max]) {
max = left;
}
if (right < n && arr[right] > arr[max]) {
max = right;
}
if (max != i) {
temp = arr[i];
arr[i] = arr[max];
arr[max] = temp;
heapify(arr, n, max);
}
}
/* Do not change code below */
public static void main(String[] args) {
final Scanner scanner = new Scanner(System.in);
String[] values = scanner.nextLine().split("\\s+");
int[] numbers = Arrays.stream(values)
.mapToInt(Integer::parseInt)
.toArray();
sort(numbers);
Arrays.stream(numbers).forEach(e -> System.out.print(e + " "));
}
}<file_sep>import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
List<Integer> list = new ArrayList<>();
List<Integer> listDist = new ArrayList<>();
String str = scanner.nextLine();
int n = scanner.nextInt();
int minDist = Integer.MAX_VALUE;
int dist;
for (String s : str.split("\\s")) {
list.add(Integer.parseInt(s));
}
for (Integer i : list) {
dist = Math.abs(n - i);
if (dist < minDist) {
listDist.clear();
listDist.add(i);
minDist = dist;
} else if (dist == minDist) {
listDist.add(i);
}
}
Collections.sort(listDist);
listDist.forEach(var -> System.out.print(var + " "));
}
}
<file_sep>class Patient {
String name;
// write your method here
}<file_sep>import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String input = sc.next();
String output = "";
int sum = 1;
for (int i = 0; i < input.length() - 1; i++) {
if (input.charAt(i) == input.charAt(i + 1)) {
sum++;
} else {
output = output + input.charAt(i) + sum;
sum = 1;
}
}
output = output + input.charAt(input.length() - 1) + sum;
System.out.println(output);
}
}<file_sep>import java.util.Scanner;
class Main {
public static void main(String[] args) {
final Scanner scanner = new Scanner(System.in);
final String input = scanner.nextLine();
System.out.println(output(input));
}
static String output(String input) {
final String[] words = input.split(" ");
String biggerWord = words[0];
for (String word : words) {
if (word.length() > biggerWord.length()) {
biggerWord = word;
}
}
return biggerWord;
}
}<file_sep>import java.util.Scanner;
class Main {
public static void main(String[] args) {
final Scanner scanner = new Scanner(System.in);
final String input = scanner.nextLine();
if (isPalindrome(editedString(input))) {
System.out.println("yes");
} else {
System.out.println("no");
}
}
static String editedString(String input) {
String recenica = "";
for (int i = 0; i < input.length(); i++) {
if (input.charAt(i) == ' ') {
recenica += "";
} else {
recenica += input.charAt(i);
}
}
return recenica.toLowerCase();
}
static boolean isPalindrome(String editedString) {
for (int i = 0; i < editedString.length() / 2; i++) {
if (editedString.charAt(i) != editedString.charAt(editedString.length() - 1 - i)) {
return false;
}
}
return true;
}
}<file_sep><h2>Sorting numbers</h2>
<html>
<head></head>
<body>
Implement a method for sorting a given array of integers in the ascending order.
<p>You can use any algorithm for sorting it.</p>
</body>
</html><br><b>Sample Input:</b><br><pre><code class="language-no-highlight">3 1 2</code></pre><br><b>Sample Output:</b><br><pre><code class="language-no-highlight">1 2 3 </code></pre><br><br><br><font color="gray">Memory limit: 256 MB</font><br><font color="gray">Time limit: 8 seconds</font><br><br>
| d7f8934348874e8c006cde1e7c2b8c39dab5ead7 | [
"Java",
"HTML"
] | 10 | Java | djoleK/Readability_Score | 606f869624698367d137646f2065cba7d7cc374c | 9ff6e28f4baf9dae22967e17a0b8fbbe2642c020 |
refs/heads/master | <file_sep>using System;
using DemoLibrary;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace API1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class StartPage : Window
{
#region vars
private int maxNumber = 0;
private int currentNumber = 0;
bool programRunning = false;
#endregion
#region constructor
public StartPage()
{
InitializeComponent();
//make new HTTPS client
APIHelper.NewAPIClient();
//make sure user can't hit next and back button if the button is off
NextBut.IsEnabled = false;
LastPageBut.IsEnabled = false;
}
#endregion
private async void Window_Loaded(object sender, RoutedEventArgs e)
{
try
{
//Get the data model for the api made
var image = await ImageProcessor.LoadImage();
//get the image url and use it as a bitmap for the image source on the page
var imageSource = new Uri(image.Img, UriKind.Absolute);
MainImage.Source = new BitmapImage(imageSource);
//set the number of comics to updated numbers
maxNumber = image.Num;
currentNumber = maxNumber;
//let us go backwards but not forwards
LastPageBut.IsEnabled = true;
}
catch (Exception x)
{
MessageBox.Show(x.Message, "Loading in image failed", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
private async void NextBut_Click(object sender, RoutedEventArgs e)
{
currentNumber++;
ImageModel comic = await ImageProcessor.LoadImage(currentNumber);
Uri imageSource = new Uri(comic.Img);
MainImage.Source = new BitmapImage(imageSource);
if (currentNumber == maxNumber)
{
NextBut.IsEnabled = false;
}
if (!LastPageBut.IsEnabled)
{
LastPageBut.IsEnabled = true;
}
}
/// <summary>
///create a new visual test page and delete the current page
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void NewPageBut_Click(object sender, RoutedEventArgs e)
{
programRunning = true;
VisualProgrammingTest visualProgramming = new VisualProgrammingTest();
visualProgramming.Show();
this.Close();
}
/// <summary>
/// used to go back one comic
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public async void LastPageBut_Click(object sender, RoutedEventArgs e)
{
currentNumber--;
ImageModel comic = await ImageProcessor.LoadImage(currentNumber);
Uri imageSource = new Uri(comic.Img);
MainImage.Source = new BitmapImage(imageSource);
if (currentNumber < 2)
{
LastPageBut.IsEnabled = false;
}
NextBut.IsEnabled = true;
}
private void Window_Closed(object sender, EventArgs e)
{
if (!programRunning)
{
Application.Current.Shutdown();
}
}
}
}
<file_sep>using System.Collections.Generic;
using ExampleWebAPIone.Models.DataModels.DataAccess;
using ExampleWebAPIone.Scripts;
using Xunit;
namespace demoLibrary
{
public class testClass
{
//test that is a yes or no
[Fact]
public void GetListAllPeople_NoValuesGiveListOfPeople()
{
//arrange
int expectedCount = 1;
SQLFunctions functions = new SQLFunctions();
//act
List <CustomersDAO> actualCount = functions.GetAllPeople();
//result(Assert)
Assert.True(expectedCount <= actualCount.Count);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace ExampleWebAPIone.Models.SqlTableModels
{
public class SQLCustomers
{
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace DemoLibrary
{
public static class ImageProcessor
{
public static async Task<ImageModel> LoadImage(int comicNumber = 0)
{
ImageModel DownloadedImage = new ImageModel();
//url for the connection for the connection to the website api
string url = "";
if (comicNumber > 0)
{
url = $"https://xkcd.com/{comicNumber}/info.0.json";
}
else
{
url = "https://xkcd.com/info.0.json";
}
using (HttpResponseMessage response = await APIHelper.APIClient.GetAsync(url))
{
if (response.IsSuccessStatusCode)
{
DownloadedImage = await response.Content.ReadAsAsync<ImageModel>();
return DownloadedImage;
}
else
{
throw new Exception(response.ReasonPhrase);
}
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
namespace DemoLibrary
{
public static class APIHelper
{
//made static to be once per appliaction can also be checked for null
public static HttpClient APIClient { get; set; }
/// <summary>
/// setup for the API client
/// </summary>
public static void NewAPIClient()
{
//intislise client
APIClient = new HttpClient();
//would usually add in for single address
//APIClient.BaseAddress = new Uri("http://webaddress");
//end of usual
APIClient.DefaultRequestHeaders.Accept.Clear();
APIClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
/// <summary>
/// function to check live internet connection
/// </summary>
/// <returns></returns>
public static bool CheckForInternetConnection()
{
try
{
using (var client = new WebClient())
using (client.OpenRead("http://google.com/generate_204"))
return true;
}
catch
{
return false;
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using ExampleWebAPIone.Models;
using ExampleWebAPIone.Models.DataModels.DataAccess;
using ExampleWebAPIone.Models.DataModels.DataInput;
using ExampleWebAPIone.Scripts;
namespace ExampleWebAPIone.Controllers
{
public class PeopleController : ApiController
{
private SQLFunctions sQL;
public PeopleController()
{
sQL = new SQLFunctions();
}
// GET endpoint for the api to return only the
[Route("api/listAllPeople")]
public List<CustomersDAO> GetAllPeople()
{
return sQL.GetAllPeople();
}
[Route("api/AddPerson")]
public bool Post(CustomerDOO val)
{
return sQL.AddPersonToPeople(val);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using DemoLibrary.APIProcessing;
using DemoLibrary.DataModels;
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;
using DemoLibrary;
namespace API1
{
/// <summary>
/// Interaction logic for VisualProgrammingTest.xaml
/// </summary>
public partial class VisualProgrammingTest : Window
{
private List<CheckListDataModel> TrueList;
private List<CheckListDataModel> FalseList;
bool programRunning = false;
public VisualProgrammingTest()
{
InitializeComponent();
APIHelper.NewAPIClient();
}
private async void GetData_Click(object sender, RoutedEventArgs e)
{
if (APIHelper.CheckForInternetConnection())
{
TrueList = new List<CheckListDataModel>();
FalseList = new List<CheckListDataModel>();
clearlists();
var rawData = await SchoolChecklistProcessor.GetCheckListDataAysnc();
foreach (CheckListDataModel x in rawData)
{
if (x.Completed)
{
TrueList.Add(x);
PossativeList.Items.Add(x.Title);
}
else
{
FalseList.Add(x);
NegativeList.Items.Add(x.Title);
}
}
}
else
{
MessageBox.Show("Please make sure you have a active internet connection then retrying", "No internet Connection", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
private void SortDataBut_Click(object sender, RoutedEventArgs e)
{
clearlists();
TrueList = TrueList.OrderBy(x => x.Title).ToList<CheckListDataModel>();
TrueList.ForEach(x => PossativeList.Items.Add(x.Title));
FalseList = FalseList.OrderBy(x => x.Title).ToList<CheckListDataModel>();
FalseList.ForEach(x => NegativeList.Items.Add(x.Title));
}
private void ComicsPageNavBut_Click(object sender, RoutedEventArgs e)
{
programRunning = true;
StartPage startPage = new StartPage();
startPage.Show();
this.Close();
}
private void Window_Closed(object sender, EventArgs e)
{
if (!programRunning)
{
Application.Current.Shutdown();
}
}
/// <summary>
/// clears the UI lists
/// </summary>
private void clearlists()
{
PossativeList.Items.Clear();
NegativeList.Items.Clear();
}
}
}
<file_sep># codex
a place used for storage and testing of code developed for personal usage
<file_sep>using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Data.Linq;
using ExampleWebAPIone.Models;
using System;
using System.Data.Linq.Mapping;
using ExampleWebAPIone.Models.DataModels.DataAccess;
using ExampleWebAPIone.Models.DataModels.DataInput;
namespace ExampleWebAPIone.Scripts
{
public class SQLFunctions
{
private Table<CustomersDAO> incommingCustomers;
private Table<CustomerDOO> outputCustomer;
private DataContext db;
private SqlConnectionStringBuilder sb;
/// <summary>
/// constructor
/// </summary>
public SQLFunctions()
{
setupSQL();
}
/// <summary>
/// used to create linq bewteen this appliaction and the sql server
/// </summary>
private void setupSQL()
{
//setup data base connection
sb = new SqlConnectionStringBuilder();
//server location
sb.DataSource = @"JONATHAN-WATSON\MSSQLSERVER01";
//database on server
sb.InitialCatalog = "DemoDatabase";
//user id (wouldn't reguarly in plane text and inputted or via access token)
sb.UserID = "test";
//users password same as userID
sb.Password = "<PASSWORD>";
//create new local db link
db = new DataContext(sb.ConnectionString);
//set the table model to link the sql
incommingCustomers = db.GetTable<CustomersDAO>();
outputCustomer = db.GetTable<CustomerDOO>();
}
/// <summary>
/// makes an sql qeurey to get all people currently within the table customers on my sql server
/// </summary>
/// <returns></returns>
public List<CustomersDAO> GetAllPeople()
{
IQueryable<CustomersDAO> custQuery = from cust in incommingCustomers select cust;
return GetPeople(custQuery);
}
/// <summary>
/// function made to get people from query into a list of person datamodel type
/// </summary>
/// <param name="query"></param>
/// <returns></returns>
private List<CustomersDAO> GetPeople(IQueryable<CustomersDAO> query)
{
List<CustomersDAO> people = new List<CustomersDAO>();
foreach (CustomersDAO cust in query)
{
people.Add(cust);
}
return people;
}
/// <summary>
/// class that attempts to add a person object taken from a post request and add them in to the
/// uses standard c# commiaction setup with stored procedure to do this
/// </summary>
/// <param name="incommingPerson"></param>
/// <returns>if successful or not </returns>
public bool AddPersonToPeople(CustomerDOO incommingPerson)
{
//create connection object(to be setup in config file in future)
SqlConnection connection = new SqlConnection(sb.ConnectionString);
//create blank sql command
SqlCommand cmd = new SqlCommand()
{
Connection = connection,
CommandText = "SPaddNewCustomer"
};
connection.Open();
using (connection)
{
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("email", incommingPerson.Email)
{
Direction = System.Data.ParameterDirection.Input,
DbType = System.Data.DbType.String
});
cmd.Parameters.Add(new SqlParameter("firstName", incommingPerson.FirstName)
{
Direction = System.Data.ParameterDirection.Input,
DbType = System.Data.DbType.String
});
cmd.Parameters.Add(new SqlParameter("lastName", incommingPerson.LastName)
{
Direction = System.Data.ParameterDirection.Input,
DbType = System.Data.DbType.String
});
cmd.Parameters.Add(new SqlParameter("address", incommingPerson.Address)
{
Direction = System.Data.ParameterDirection.Input,
DbType = System.Data.DbType.String
});
cmd.Parameters.Add(new SqlParameter("postcode", incommingPerson.Postcode)
{
Direction = System.Data.ParameterDirection.Input,
DbType = System.Data.DbType.String
});
try
{
cmd.ExecuteNonQuery();
}
catch(Exception ex)
{
connection.Close();
return false;
}
}
connection.Close();
return true;
}
//[Function(Name = "dbo.SPaddNewCustomer")]
//public bool AddInPersonSP
// (
// [Parameter(Name = "email", DbType = "varChar(50)")] string email,
// [Parameter(Name = "firstName", DbType = "varChar(20)")] string firstName,
// [Parameter(Name = "lastName", DbType = "varChar(20)")] string lastName,
// [Parameter(Name = "address ", DbType = "varChar(60)")] string address,
// [Parameter(Name = "postcode", DbType = "varChar(8)")] string postcode
// )
//{
//}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
namespace ExampleWebAPIone.Validation
{
public class ModelValidator
{
//each data type has it own validation
/// <summary>
/// checks to see if end of string is inline with email and has @ simbol if not throw execption
/// </summary>
/// <param name="emailChecked"></param>
/// <returns></returns>
private bool ValidateEmailAddress(string emailChecked)
{
try
{
if ((emailChecked.EndsWith("interhigh.co.uk") || emailChecked.EndsWith("academy21.co.uk")) && (emailChecked.Contains("@")))
{
return true;
}
else
{
throw new Exception();
}
}
catch
{
return false;
}
}
/// <summary>
/// vaildates a name by checking for numbers
/// </summary>
/// <param name="nameChecked"></param>
/// <returns></returns>
private bool ValidateName(string nameChecked)
{
try
{
//go though word
foreach (char c in nameChecked)
{
//if char is number then cannot be name throw exception and return false
if (char.IsDigit(c))
{
throw new Exception();
}
}
//all is well
return true;
}
catch
{
return false;
}
}
/// <summary>
/// validates the length of the address string
/// </summary>
/// <returns></returns>
private bool ValidateAddress(string addressChecked)
{
try
{
if (addressChecked.Length > 60)
throw new Exception();
else
return true;
}
catch
{
return false;
}
}
private bool ValidatePostcode(string postcodeChecked)
{
try
{
if ((postcodeChecked.Length > 8) || (postcodeChecked.Length < 6))
throw new Exception();
else
return true;
}
catch
{
return false;
}
}
}
}
}<file_sep>using DemoLibrary.DataModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
namespace DemoLibrary.APIProcessing
{
public static class SchoolChecklistProcessor
{
/// <summary>
/// connects to an API and gathers the raw data into a data model
/// </summary>
/// <returns></returns>
public async static Task<List<CheckListDataModel>> GetCheckListDataAysnc()
{
//for the address
string Uri = "https://jsonplaceholder.typicode.com/todos";
//attempt connection using default header
using (HttpResponseMessage response = await APIHelper.APIClient.GetAsync(Uri))
{
//check to see if we got a sucessful reponse
if (response.IsSuccessStatusCode)
{
var dataList = await response.Content.ReadAsAsync<List<CheckListDataModel>>();
return dataList;
}
else
{
throw new Exception(response.ReasonPhrase);
}
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Data.Linq.Mapping;
using System.Linq;
using System.Web;
namespace ExampleWebAPIone.Models.DataModels.DataAccess
{
[Table(Name = "Customers")]
public class CustomersDAO
{
private int _Id;
[Column(IsPrimaryKey = true, Storage = "_Id")]
public int Id
{
get { return _Id; }
set { _Id = value; }
}
private string _Email;
[Column(Storage ="_Email")]
public string Email
{
get { return _Email; }
set { _Email = value; }
}
private string _FirstName;
[Column(Storage = "_FirstName")]
public string FirstName
{
get { return _FirstName; }
set { _FirstName = value; }
}
private string _LastName;
[Column(Storage = "_LastName")]
public string LastName
{
get { return _LastName; }
set { _LastName = value; }
}
private string _Address;
[Column(Storage = "_Address")]
public string Address
{
get { return _Address; }
set { _Address = value; }
}
private string _Postcode;
[Column(Storage = "_Postcode")]
public string Postcode
{
get { return _Postcode; }
set { _Postcode = value; }
}
}
} | 72a19113ee75a7a2a256810527a6c571be3ab007 | [
"Markdown",
"C#"
] | 12 | C# | jonnywatson0886/codex | c846688c1b066c0d78c5904176c0e474b27b2c0f | 897f081b21a7b09cf73de380c2f190613a9e28e1 |
refs/heads/master | <repo_name>brothelul/vob-script-api<file_sep>/src/test/java/com/mosesc/vobscriptapi/VobScriptApiApplicationTests.java
package com.mosesc.vobscriptapi;
import com.mosesc.vobscriptapi.entity.VobComponent;
import com.mosesc.vobscriptapi.mapper.VobComponentMapper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class VobScriptApiApplicationTests {
@Autowired
private VobComponentMapper vobComponentMapper;
@Test
public void contextLoads() {
VobComponent vobComponent = vobComponentMapper.selectById(1);
System.out.println(vobComponent);
}
}
<file_sep>/src/main/java/com/mosesc/vobscriptapi/VobScriptApiApplication.java
package com.mosesc.vobscriptapi;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication(scanBasePackages = "com.mosesc")
@MapperScan(basePackages = {"com.mosesc.vobscriptapi.mapper"})
public class VobScriptApiApplication {
public static void main(String[] args) {
SpringApplication.run(VobScriptApiApplication.class, args);
}
}
<file_sep>/src/main/java/com/mosesc/vobscriptapi/mapper/VobComponentMapper.java
package com.mosesc.vobscriptapi.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.mosesc.vobscriptapi.entity.VobComponent;
/**
* @auther mosesc
* @date 12/14/18.
*/
public interface VobComponentMapper extends BaseMapper<VobComponent> {
}
<file_sep>/src/main/java/com/mosesc/vobscriptapi/interceptor/WebInterceptor.java
package com.mosesc.vobscriptapi.interceptor;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @auther mosesc
* @date 12/14/18.
*/
public class WebInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Credentials", "true");
response.setHeader("Access-Control-Allow-Methods", "*");
response.setHeader("Access-Control-Allow-Headers", "Content-Type,Access-Token");
response.setHeader("Access-Control-Expose-Headers", "*");
return true;
}
}
<file_sep>/src/main/java/com/mosesc/vobscriptapi/bo/OutputVobObjBo.java
package com.mosesc.vobscriptapi.bo;
import lombok.Data;
import java.util.List;
@Data
public class OutputVobObjBo {
private String obj;
private List<String> methods;
}
<file_sep>/src/main/java/com/mosesc/vobscriptapi/bo/InputComponentBo.java
package com.mosesc.vobscriptapi.bo;
import lombok.Data;
/**
* @auther mosesc
* @date 12/14/18.
*/
@Data
public class InputComponentBo {
private String name;
private String description;
private String content;
}
<file_sep>/src/main/java/com/mosesc/vobscriptapi/entity/VobComponent.java
package com.mosesc.vobscriptapi.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import lombok.Data;
/**
* @auther mosesc
* @date 12/14/18.
*/
@Data
public class VobComponent {
@TableId(type = IdType.AUTO)
private Integer id;
private String name;
private String description;
private String content;
}
<file_sep>/src/main/java/com/mosesc/vobscriptapi/bo/OutputVobComponentBo.java
package com.mosesc.vobscriptapi.bo;
import lombok.Data;
import java.util.List;
/**
* @auther mosesc
* @date 12/14/18.
*/
@Data
public class OutputVobComponentBo {
private Integer id;
private String name;
private String description;
private String content;
private List<OutputComponentParamVo> params;
}
<file_sep>/src/main/java/com/mosesc/vobscriptapi/service/impl/VobComponentServiceImpl.java
package com.mosesc.vobscriptapi.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mosesc.vobscriptapi.bo.InputComponentBo;
import com.mosesc.vobscriptapi.bo.OutputVobComponentBo;
import com.mosesc.vobscriptapi.entity.VobComponent;
import com.mosesc.vobscriptapi.exception.ValidateFailedException;
import com.mosesc.vobscriptapi.mapper.VobComponentMapper;
import com.mosesc.vobscriptapi.service.VobComponentService;
import com.mosesc.vobscriptapi.utils.ScriptsUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.util.ArrayList;
import java.util.List;
/**
* @auther mosesc
* @date 12/14/18.
*/
@Service
public class VobComponentServiceImpl implements VobComponentService {
@Autowired
private VobComponentMapper vobComponentMapper;
@Override
public List<OutputVobComponentBo> listComponents() {
List<VobComponent> components = vobComponentMapper.selectList(new QueryWrapper<>());
List<OutputVobComponentBo> outputVobComponentBos = new ArrayList<>();
if (components == null || components.size() == 0){
return outputVobComponentBos;
}
components.forEach(component -> {
OutputVobComponentBo outputVobComponentBo = new OutputVobComponentBo();
BeanUtils.copyProperties(component, outputVobComponentBo);
outputVobComponentBo.setParams(ScriptsUtil.initParams(component.getContent()));
outputVobComponentBos.add(outputVobComponentBo);
});
return outputVobComponentBos;
}
@Override
public void saveComponent(InputComponentBo component) {
if (StringUtils.isEmpty(component.getName()) || StringUtils.isEmpty(component.getContent())){
throw new ValidateFailedException("组件名和组件不能为空");
}
VobComponent vobComponent = new VobComponent();
BeanUtils.copyProperties(component, vobComponent);
vobComponentMapper.insert(vobComponent);
}
}
<file_sep>/src/main/java/com/mosesc/vobscriptapi/utils/JsonEntity.java
package com.mosesc.vobscriptapi.utils;
import java.io.Serializable;
public class JsonEntity<T> implements Serializable {
T data;
private int status = 200;
private String message;
public JsonEntity(){}
public JsonEntity(T data){
this.data = data;
}
public JsonEntity(String message){
this.message = message;
}
public JsonEntity(int status, String message){
this.status = status;
this.message = message;
}
public JsonEntity(T data, int status, String message){
this.status = status;
this.message = message;
this.data = data;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public void setData(T data) {
this.data = data;
}
public T getData() {
return data;
}
public void setMessage(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
}
<file_sep>/src/main/java/com/mosesc/vobscriptapi/utils/ScriptsUtil.java
package com.mosesc.vobscriptapi.utils;
import com.mosesc.vobscriptapi.bo.OutputComponentParamVo;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @auther mosesc
* @date 12/14/18.
*/
public class ScriptsUtil {
private static Pattern p2=Pattern.compile("#\\{\\s*(.*?)\\s*\\}");
public static List<OutputComponentParamVo> initParams(String scripts){
List<OutputComponentParamVo> paramVos = new ArrayList<>();
Map<String, Object> tempContainer = new HashMap<>();
Matcher matcher = p2.matcher(scripts);
while(matcher.find()){
String name=matcher.group(1);
OutputComponentParamVo param = new OutputComponentParamVo();
param.setName(name);
Object returnValue = tempContainer.put(name, "tempValue");
if (returnValue == null){
paramVos.add(param);
}
}
return paramVos;
}
}
| c50ae6d040c0f79b75bef24906cd3180965ea80e | [
"Java"
] | 11 | Java | brothelul/vob-script-api | 9ea164667e46696746015796f56d48dd0130a030 | 8e9f9f73ac10e44d52947a0132fcd94bf965d7d4 |
refs/heads/main | <repo_name>823377346/utils<file_sep>/locatCache/LocalCachePutAspect.java
package com.xkcoding.helloworld.service.utils;
import cn.hutool.json.JSONObject;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.core.ParameterNameDiscoverer;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Component
@Aspect
public class LocalCachePutAspect {
private LocalCacheUtils localCacheUtils = new LocalCacheUtils();
/**
* spring 参数名称解析器
*/
private static final ParameterNameDiscoverer LOCAL_VARIABLE_TABLE_PARAMETER_NAME_DISCOVERER
= new LocalVariableTableParameterNameDiscoverer();
/**
* spring el 表达式解析解
*/
private static final ExpressionParser SPEL_EXPRESSION_PARSER = new SpelExpressionParser();
/**
* 切入点
* 切入点为包路径下的:execution(public * org.xx.xx.xx.controller..*(..)):
* org.xx.xx.xx.Controller包下任意类任意返回值的 public 的方法
* <p>
* 切入点为注解的: @annotation(VisitPermission)
* 存在 LocalCacheAnnotation 注解的方法
*/
@Pointcut("@annotation(com.xkcoding.helloworld.service.utils.LocalCachePutAnnotation)")
public void putCache(){
}
@AfterReturning(returning="res",value = "putCache()")
public void toAfter(JoinPoint joinPoint,Object res) throws NoSuchMethodException {
String methodName = joinPoint.getSignature().getName();
Object[] args1 = joinPoint.getArgs();
Class<?> classTarget = joinPoint.getTarget().getClass();
Class<?>[] par = ((MethodSignature) joinPoint.getSignature()).getParameterTypes();
Method targetMethod = classTarget.getMethod(methodName, par);
String[] parameterNames = LOCAL_VARIABLE_TABLE_PARAMETER_NAME_DISCOVERER.getParameterNames(targetMethod);
//获取注解信息
LocalCachePutAnnotation annotation = targetMethod.getAnnotation(LocalCachePutAnnotation.class);
if (annotation == null) {
return;
}
String cacheKey = parseLockName(args1, annotation, parameterNames);
if(annotation.isUpdateData()){
boolean simpleType = isSimpleType(res.getClass());
if(!simpleType){
JSONObject jsonObject = new JSONObject(res);
res = jsonObject.toString();
}
localCacheUtils.update(cacheKey,res,annotation.expireTime());
return;
}
localCacheUtils.delete(cacheKey,true);
}
private String parseLockName(Object[] args, LocalCachePutAnnotation localCacheAnnotation, String[] parameterNames) {
LocalCachePutExtractParamAnnotation[] extractParams = localCacheAnnotation.value();
if (extractParams.length == 0) {
return localCacheAnnotation.key();
}
List<String> fieldValues = new ArrayList<>();
Map<String, Object> paramNameMap = buildParamMap(args, parameterNames);
for (LocalCachePutExtractParamAnnotation extractParam : extractParams) {
String paramName = extractParam.paramName();
Object paramValue = paramNameMap.get(paramName);
String springEL = extractParam.fieldName();
String paramFieldValue = "";
if (!StringUtils.isEmpty(springEL)) {
Expression expression = SPEL_EXPRESSION_PARSER.parseExpression(springEL);
paramFieldValue = expression.getValue(paramValue).toString();
} else {
if (isSimpleType(paramValue.getClass())) {
paramFieldValue = String.valueOf(paramValue);
}
}
fieldValues.add(paramFieldValue);
}
return String.format(localCacheAnnotation.key(), fieldValues.toArray());
}
/**
* 基本类型 int, double, float, long, short, boolean, byte, char, void.
*/
private static boolean isSimpleType(Class<?> clazz) {
return clazz.isPrimitive()
|| clazz.equals(Long.class)
|| clazz.equals(Integer.class)
|| clazz.equals(String.class)
|| clazz.equals(Double.class)
|| clazz.equals(Short.class)
|| clazz.equals(Byte.class)
|| clazz.equals(Character.class)
|| clazz.equals(Float.class)
|| clazz.equals(Boolean.class);
}
/**
* 构建请求参数map
* @param args 参数列表
* @param parameterNames 参数名称列表
* @return key:参数名称 value:参数值
*/
private Map<String, Object> buildParamMap(Object[] args, String[] parameterNames) {
Map<String, Object> paramNameMap = new HashMap<>();
for (int i = 0; i < parameterNames.length; i++) {
paramNameMap.put(parameterNames[i], args[i]);
}
return paramNameMap;
}
}
<file_sep>/locatCache/LocalCachePutExtractParamAnnotation.java
package com.xkcoding.helloworld.service.utils;
import java.lang.annotation.*;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Repeatable(value = LocalCachePutAnnotation.class)
public @interface LocalCachePutExtractParamAnnotation {
/**
* 作为锁的参数名称
*/
String paramName();
/**
* 参数的 属性值。可以为空
*/
String fieldName() default "";
}
<file_sep>/locatCache/LocalCacheGetAnnotation.java
package com.xkcoding.helloworld.service.utils;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface LocalCacheGetAnnotation {
/**
* 提取的参数
*/
LocalCacheGetExtractParamAnnotation[] value();
/**
* 缓存key
* @return
*/
String key() default "";
/**
* 是否更新缓存数据 默认 false
* @return
*/
boolean isUpdateData() default true;
long expireTime() default 360000L;
}
<file_sep>/locatCache/LocalCacheGetAspect.java
package com.xkcoding.helloworld.service.utils;
import cn.hutool.json.JSONObject;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.core.ParameterNameDiscoverer;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
@Component
@Aspect
public class LocalCacheGetAspect {
private LocalCacheUtils localCacheUtils = new LocalCacheUtils();
/**
* spring 参数名称解析器
*/
private static final ParameterNameDiscoverer LOCAL_VARIABLE_TABLE_PARAMETER_NAME_DISCOVERER
= new LocalVariableTableParameterNameDiscoverer();
/**
* spring el 表达式解析解
*/
private static final ExpressionParser SPEL_EXPRESSION_PARSER = new SpelExpressionParser();
/**
* 切入点
* 切入点为包路径下的:execution(public * org.xx.xx.xx.controller..*(..)):
* org.xx.xx.xx.Controller包下任意类任意返回值的 public 的方法
* <p>
* 切入点为注解的: @annotation(VisitPermission)
* 存在 LocalCacheAnnotation 注解的方法
*/
@Pointcut("@annotation(com.xkcoding.helloworld.service.utils.LocalCacheGetAnnotation)")
private void getCache(){
}
@Around(value = "getCache()")
public Object toAround(ProceedingJoinPoint joinPoint) throws Throwable {
Object proceed = null;
Object[] args = joinPoint.getArgs();
try {
//从切面织入点处通过反射机制获取织入点处的方法
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
//获取切入点所在的方法
Method method = signature.getMethod();
String methodName = joinPoint.getSignature().getName();
Class<?> classTarget = joinPoint.getTarget().getClass();
Class<?>[] par = ((MethodSignature) joinPoint.getSignature()).getParameterTypes();
Method targetMethod = classTarget.getMethod(methodName, par);
String[] parameterNames = LOCAL_VARIABLE_TABLE_PARAMETER_NAME_DISCOVERER.getParameterNames(targetMethod);
//获取注解信息
LocalCacheGetAnnotation annotation = method.getAnnotation(LocalCacheGetAnnotation.class);
if (annotation == null) {
return null;
}
String cacheKey = parseLockName(args, annotation, parameterNames);
Object resValue = localCacheUtils.get(cacheKey);
if(resValue != null){
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletResponse response = attributes.getResponse();
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json; charset=utf-8");
PrintWriter out = null;
try {
if(!isSimpleType(resValue.getClass())){
JSONObject jsonObject = new JSONObject(resValue);
resValue = jsonObject.toString();
}
out = response.getWriter();
out.print(resValue);
boolean updateData = annotation.isUpdateData();
if(updateData){
CompletableFuture.runAsync(()->{
try {
// Object newProceed = joinPoint.proceed(args);
Object newProceed = targetMethod.invoke(classTarget.newInstance(), args);
localCacheUtils.put(cacheKey,newProceed,annotation.expireTime());
} catch (Throwable throwable) {
throwable.printStackTrace();
}
});
}
return null;
} catch (IOException e) {
e.printStackTrace();
}
}
proceed = joinPoint.proceed(args);
if(proceed != null){
localCacheUtils.put(cacheKey,proceed,annotation.expireTime());
}
} catch (Throwable throwable) {
proceed = joinPoint.proceed(args);
throwable.printStackTrace();
}
return proceed;
}
private String parseLockName(Object[] args, LocalCacheGetAnnotation localCacheAnnotation, String[] parameterNames) {
LocalCacheGetExtractParamAnnotation[] extractParams = localCacheAnnotation.value();
if (extractParams.length == 0) {
return localCacheAnnotation.key();
}
List<String> fieldValues = new ArrayList<>();
Map<String, Object> paramNameMap = buildParamMap(args, parameterNames);
for (LocalCacheGetExtractParamAnnotation extractParam : extractParams) {
String paramName = extractParam.paramName();
Object paramValue = paramNameMap.get(paramName);
String springEL = extractParam.fieldName();
String paramFieldValue = "";
if (!StringUtils.isEmpty(springEL)) {
Expression expression = SPEL_EXPRESSION_PARSER.parseExpression(springEL);
paramFieldValue = expression.getValue(paramValue).toString();
} else {
if (isSimpleType(paramValue.getClass())) {
paramFieldValue = String.valueOf(paramValue);
}
}
fieldValues.add(paramFieldValue);
}
return String.format(localCacheAnnotation.key(), fieldValues.toArray());
}
/**
* 基本类型 int, double, float, long, short, boolean, byte, char, void.
*/
private static boolean isSimpleType(Class<?> clazz) {
return clazz.isPrimitive()
|| clazz.equals(Long.class)
|| clazz.equals(Integer.class)
|| clazz.equals(String.class)
|| clazz.equals(Double.class)
|| clazz.equals(Short.class)
|| clazz.equals(Byte.class)
|| clazz.equals(Character.class)
|| clazz.equals(Float.class)
|| clazz.equals(Boolean.class);
}
/**
* 构建请求参数map
* @param args 参数列表
* @param parameterNames 参数名称列表
* @return key:参数名称 value:参数值
*/
private Map<String, Object> buildParamMap(Object[] args, String[] parameterNames) {
Map<String, Object> paramNameMap = new HashMap<>();
for (int i = 0; i < parameterNames.length; i++) {
paramNameMap.put(parameterNames[i], args[i]);
}
return paramNameMap;
}
}
| b4112ebf1c61517a3031c7c05d35bd857d1eeba3 | [
"Java"
] | 4 | Java | 823377346/utils | ba0c4f90f30507b5e0ee64e6f30ed3737024e91a | 3a2ca2d936a84a640263441922081afa9b0d3686 |
refs/heads/master | <repo_name>cabotapp/cabot-check-icmp<file_sep>/README.md
Cabot ICMP Check Plugin
=====
This is a plugin for running ICMP (Ping) checks agains a server in Cabot.
## Installation
cabot_check_icmp should come installed with cabot as default however if you need to install it manually, append
cabot_check_icmp
to the variable
CABOT_PLUGINS_ENABLED
in your
conf/production.env
<file_sep>/cabot_check_icmp/tests.py
from django.contrib.auth.models import User
from cabot.cabotapp.tests.tests_basic import LocalTestCase
from cabot.cabotapp.models import StatusCheck, Instance
from cabot.plugins.models import StatusCheckPluginModel
import cabot_check_icmp.plugin
class TestICMPStatusCheckPlugin(LocalTestCase):
def setUp(self):
super(TestICMPStatusCheckPlugin, self).setUp()
self.icmp_check_plugin, created = StatusCheckPluginModel.objects.get_or_create(
slug='cabot_check_icmp'
)
self.icmp_check = StatusCheck.objects.create(
check_plugin=self.icmp_check_plugin,
name = 'Default ICMP Check'
)
self.instance = Instance.objects.create(
name = 'Default Instance',
address = 'localhost'
)
self.instance.status_checks.add(self.icmp_check)
self.instance.save()
# We aren't mocking subprocess.Popen because it's more hassle than its
# worth. The below functions should work absolutely fine.
def test_run_success(self):
self.instance.address = 'localhost' # Always pingable
self.instance.save()
result = self.icmp_check.run()
self.assertTrue(result.succeeded)
def test_run_failure(self):
self.instance.address = '256.256.256.256' # Impossible IP
self.instance.save()
result = self.icmp_check.run()
self.assertFalse(result.succeeded)
<file_sep>/cabot_check_icmp/plugin.py
from django.conf import settings
from django.core.mail import send_mail
from django.core.urlresolvers import reverse
from django import forms
from django.template import Context, Template
from django.dispatch import receiver
from django.db.models.signals import m2m_changed, post_save
from cabot.plugins.models import StatusCheckPlugin, StatusCheckPluginModel
from cabot.cabotapp.models import Instance, StatusCheck, Service
from os import environ as env
import subprocess
import requests
import logging
logger = logging.getLogger(__name__)
class ICMPStatusCheckPlugin(StatusCheckPlugin):
name = "ICMP"
slug = "cabot_check_icmp"
author = "<NAME>"
version = "0.0.1"
font_icon = "glyphicon glyphicon-transfer"
def target(self, check):
instances = check.instance_set.all()
services = check.service_set.all()
if instances:
return instances[0]
elif services:
return services[0]
else:
return None
def run(self, check, result):
instances = check.instance_set.all()
services = check.service_set.all()
if instances:
target = instances[0].address
else:
target = services[0].url
# We need to read both STDOUT and STDERR because ping can write to both, depending on the kind of error. Thanks a lot, ping.
ping_process = subprocess.Popen("ping -c 1 " + target, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True)
response = ping_process.wait()
if response == 0:
result.succeeded = True
else:
output = ping_process.stdout.read()
result.succeeded = False
result.error = output
return result
def description(self, check):
target = self.target(check)
if target:
return 'ICMP Reply from {}'.format(target.name)
else:
return 'ICMP Check with no target.'
| 6f3c62f85d019c2bf26daec914f29aa14d4ab417 | [
"Markdown",
"Python"
] | 3 | Markdown | cabotapp/cabot-check-icmp | fb5919233e1f786edda1e2cf7009af6a5d8bad68 | bff26a34a7f192d9cd91db10512b64fef51d3757 |
refs/heads/master | <file_sep>(function(ext) {
// Cleanup function when the extension is unloaded
ext._shutdown = function() {};
// Status reporting code
// Use this to report missing hardware, plugin or unsupported browser
ext._getStatus = function() {
return {status: 2, msg: 'Ready'};
};
ext.power = function(base, exponent) {
return Math.pow(base, exponent);
};
// Block and block menu descriptions
var descriptor = {
blocks: [
["r", "ID of user %m.users", "id"],
["b", "is user %m.users tracked", "isTracked"],
["r", "user %m.users position %m.coordinate", "position"],
["b", "is user %m.users %m.interaction", "interaction"],
["r", "user %m.users , effector %m.endeffector , coordinate %m.effectoraxis ", "effectorcoordinate"],
],
menus: {
users: ["1","2","3", "4", "5", "6"],
coordinate: ["horizontal", "vertical"],
interaction: ["raising-right-hand", "raising-left-hand", "jumping"],
effectoraxis: ["side", "up", "forward"],
endeffector: ["right-hand", "left-hand", "right-foot", "left-foot"],
}
};
// Register the extension
ScratchExtensions.register('Sample extension', descriptor, ext);
})({}); | bdc092629963fb5bcc79901994365c36fad60091 | [
"JavaScript"
] | 1 | JavaScript | albertcarrillosorolla/ninus-scratch | 04cb41206e801360022e841771a0a9f61a9522d7 | c789001fba6c963fbe7360bc0b0b874b191d8e47 |
refs/heads/master | <repo_name>sixrocketsstrong/gql-java<file_sep>/src/main/java/com/sixrockets/gql/GraphQLJavaUtils.java
package com.sixrockets.gql;
import graphql.language.Field;
import graphql.language.FragmentDefinition;
import graphql.language.FragmentSpread;
import graphql.language.InlineFragment;
import graphql.language.ListType;
import graphql.language.NamedNode;
import graphql.language.NonNullType;
import graphql.language.OperationDefinition;
import graphql.language.SelectionSetContainer;
import graphql.language.Type;
import graphql.language.TypeName;
import graphql.language.VariableDefinition;
import graphql.language.VariableReference;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
public class GraphQLJavaUtils {
public static GQL queryFromField(
Field field,
OperationDefinition def,
List<FragmentDefinition> fragments
) {
GQL val = (def.getOperation().equals(OperationDefinition.Operation.QUERY))
? GQL.query()
: GQL.mutation();
Operation op = val.opWith(field.getName(), field.getAlias());
addArguments(op, field, def);
addSelections(op, field, def, fragments);
return val;
}
public static GQL queryFromField(
String operationName,
Field field,
OperationDefinition def,
List<FragmentDefinition> fragments
) {
GQL val = (def.getOperation().equals(OperationDefinition.Operation.QUERY))
? GQL.query(operationName)
: GQL.mutation(operationName);
Operation op = val.opWith(field.getName(), field.getAlias());
addArguments(op, field, def);
addSelections(op, field, def, fragments);
return val;
}
public static void addSelections(
FieldsAndVariables<?, ?> dest,
SelectionSetContainer<?> selSet,
OperationDefinition def,
List<FragmentDefinition> fragments
) {
if (selSet.getSelectionSet() == null) return;
selSet
.getSelectionSet()
.getSelections()
.stream()
.forEach(
selection -> {
if (selection instanceof NamedNode) {
if (selection instanceof FragmentSpread) {
FragmentSpread spread = (FragmentSpread) selection;
fragments
.stream()
.filter(fd -> fd.getName().equals(spread.getName()))
.findFirst()
.ifPresent(
fDef -> {
Fragment fragment = GQL.fragment(
"f" + UUID.randomUUID().toString().replace("-", ""),
typeString(fDef.getTypeCondition())
);
addSelections(fragment, fDef, def, fragments);
dest.fragment(fragment);
}
);
} else {
com.sixrockets.gql.Field<?> parentSel = dest.selectWith(
((NamedNode<?>) selection).getName()
);
if (selection instanceof Field) {
addArguments(parentSel, (Field) selection, def);
}
if (selection instanceof SelectionSetContainer) {
SelectionSetContainer<?> container = (SelectionSetContainer<?>) selection;
if (
container.getSelectionSet() != null &&
!container.getSelectionSet().getSelections().isEmpty()
) {
addSelections(parentSel, container, def, fragments);
}
}
}
} else if (selection instanceof InlineFragment) {
InlineFragment inlineFragment = (InlineFragment) selection;
Fragment fragment = GQL.fragment(
"f" + UUID.randomUUID().toString().replace("-", ""),
typeString(inlineFragment.getTypeCondition())
);
addSelections(fragment, inlineFragment, def, fragments);
dest.fragment(fragment);
}
}
);
}
public static void addArguments(
FieldsAndVariables dest,
Field field,
OperationDefinition def
) {
field
.getArguments()
.stream()
.forEach(
arg -> {
if (arg.getValue() instanceof VariableReference) {
VariableReference value = (VariableReference) arg.getValue();
Optional<VariableDefinition> varDef = def
.getVariableDefinitions()
.stream()
.filter(d -> d.getName().equals(value.getName()))
.findFirst();
varDef.ifPresent(
d -> dest.variable(arg.getName(), fromType(d.getType()))
);
}
}
);
}
public static com.sixrockets.gql.Type fromType(Type type) {
if (type instanceof NonNullType) {
return com.sixrockets.gql.Type.notNull(
typeString(((NonNullType) type).getType())
);
} else {
return com.sixrockets.gql.Type.nullable(typeString(type));
}
}
private static String typeString(Type type) {
if (type instanceof ListType) {
return "[" + typeString(((ListType) type).getType()) + "]";
} else {
if (type instanceof NonNullType) {
return typeString(((NonNullType) type).getType()) + "!";
} else {
return ((TypeName) type).getName();
}
}
}
}
<file_sep>/pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.sixrockets</groupId>
<artifactId>gql-java</artifactId>
<version>1.0-SNAPSHOT</version>
<name>gql-java</name>
<description>A simple gql-java.</description>
<url>https://github.com/sixrocketsstrong/gql-java</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<lombok.version>edge-SNAPSHOT</lombok.version>
<junit.version>5.6.0</junit.version>
</properties>
<repositories>
<repository>
<id>projectlombok.org</id>
<url>https://projectlombok.org/edge-releases</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>com.graphql-java</groupId>
<artifactId>graphql-java</artifactId>
<version>14.0</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<pluginManagement> <!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<plugin>
<artifactId>maven-site-plugin</artifactId>
<version>3.7.1</version>
</plugin>
<plugin>
<artifactId>maven-project-info-reports-plugin</artifactId>
<version>3.0.0</version>
</plugin>
<!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
<configuration>
<outputDirectory>${basedir}/target</outputDirectory>
<resources>
<resource>
<directory>${basedir}</directory>
<include>bintray.json</include>
<filtering>true</filtering>
</resource>
</resources>
</configuration>
<executions>
<execution>
<id>copy-resources</id>
<phase>process-resources</phase>
<goals>
<goal>copy-resources</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
<compilerArgs>
<arg>-parameters</arg>
</compilerArgs>
<annotationProcessorPaths>
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
</path>
</annotationProcessorPaths>
</configuration>
<executions>
<execution>
<id>test-compile</id>
<goals>
<goal>testCompile</goal>
</goals>
<configuration>
<compilerArgs>
<arg>-parameters</arg>
</compilerArgs>
<annotationProcessorPaths>
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
</path>
</annotationProcessorPaths>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
<plugin>
<artifactId>maven-jar-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
</plugins>
</pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>2.4</version>
<executions>
<execution>
<id>attach-sources</id>
<phase>package</phase>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>3.1.1</version>
<executions>
<execution>
<id>attach-javadocs</id>
<phase>package</phase>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
<reporting>
<plugins>
<plugin>
<artifactId>maven-project-info-reports-plugin</artifactId>
</plugin>
</plugins>
</reporting>
</project>
<file_sep>/README.md

[](https://travis-ci.com/sixrocketsstrong/gql-java)
[  ](https://bintray.com/sixrocketsstrong/maven/gql-java/_latestVersion)
# GQL-Java
GQL-Java is a builder-style DSL for assembling GraphQL queries in Java code. It's designed to let you define static elements and assemble them just-in-time. This is much easier to refactor a client call than `static final String` query constants.
## Getting Started
These instructions will give you a quick overview of how to use GQL-Java to build queries and structure your project for maximum reuse.
### Prerequisites
Java 8+
### Installing
Use the "Download" link above to link to the Bintray repo with instructions on including in your Maven `pom` or Gradle build.
## Versioning
We use [SemVer](http://semver.org/) for versioning. For the versions available, see the [tags on this repository](https://github.com/your/project/tags).
## Authors
* **<NAME>** - *Initial work* - [bangroot](https://github.com/bangroot)
See also the list of [contributors](https://github.com/sixrocketsstrong/gql-java/contributors) who participated in this project.
## License
This project is licensed under the Apache 2.0 License - see the [LICENSE.md](LICENSE.md) file for details
## Acknowledgments
* I wanted something like [gql](https://github.com/apollographql/graphql-tag) for JS. While this is not using a templating engine and what not, I was aiming for similar construction and reuse.
| f1ee4b7ce5ce9b02affa17edf9386e42ebc8a39b | [
"Markdown",
"Java",
"Maven POM"
] | 3 | Java | sixrocketsstrong/gql-java | d46ccc6c5750d571b9a32eaf770d80c73171ed3d | f2f14145ef40b0ffa7f197f4dbcd8babf2f7f448 |
refs/heads/master | <file_sep>$(document).ready(function(){
$('.lesson').click(function(){
lesson = $(this)
if(lesson.hasClass('waiting')) {
return true;
}
if(lesson.hasClass('booked')) {
alert('You cannot cancel this timeslot as a student has already signed up.')
return true;
}
lesson.addClass('waiting');
if (lesson.hasClass('available')) {
id = lesson.attr('data-id');
$.ajax({
type: 'DELETE',
url: '/time_slots/' + id,
data: {nothing: true},
success: function() {
lesson
.removeAttr('id')
.removeClass('waiting')
.removeClass('available')
}
});
} else {
begins_at = lesson.attr('data-begins_at');
$.post('/time_slots/', {time_slot: {begins_at: begins_at}}, function(response) {
lesson
.attr('data-id', response['id'])
.removeClass('waiting')
.addClass('available');
});
}
});
});
<file_sep>class WelcomeController < ApplicationController
def index
@slots = TimeSlot.upcoming
end
end
<file_sep>class TeacherSession < Authlogic::Session::Base
end<file_sep>class StudentSessionsController < ApplicationController
def new
@student_session = StudentSession.new
end
def create
@student_session = StudentSession.new(params[:student_session])
if @student_session.save
flash[:notice] = "Login successful!"
redirect_back_or_default @student_session.student
else
render :action => :new
end
end
def destroy
current_student_session.destroy
flash[:notice] = "Logout successful!"
redirect_back_or_default new_student_session_url
end
end
<file_sep>class Teacher < ActiveRecord::Base
acts_as_authentic
end
<file_sep># Filters added to this controller apply to all controllers in the application.
# Likewise, all the methods added will be available for all controllers.
class ApplicationController < ActionController::Base
helper :all # include all helpers, all the time
protect_from_forgery # See ActionController::RequestForgeryProtection for details
helper_method :current_student_session, :current_student, :current_teacher_session, :current_teacher
private
def current_student_session
return @current_student_session if defined?(@current_student_session)
@current_student_session = StudentSession.find
end
def current_student
return @current_student if defined?(@current_student)
@current_student = current_student_session && current_student_session.student
end
def require_student
unless current_student
store_location
flash[:notice] = "You must be logged in to access this page"
redirect_to new_student_session_url
return false
end
end
def require_no_student
if current_student
store_location
flash[:notice] = "You must be logged out to access this page"
redirect_to student_url
return false
end
end
def current_teacher_session
return @current_teacher_session if defined?(@current_teacher_session)
@current_teacher_session = TeacherSession.find
end
def current_teacher
return @current_teacher if defined?(@current_teacher)
@current_teacher = current_teacher_session && current_teacher_session.teacher
end
def require_teacher
unless current_teacher
store_location
flash[:notice] = "You must be logged in to access this page"
redirect_to new_teacher_session_url
return false
end
end
def require_no_teacher
if current_teacher
store_location
flash[:notice] = "You must be logged out to access this page"
redirect_to teacher_url
return false
end
end
def store_location
session[:return_to] = request.request_uri
end
def redirect_back_or_default(default)
redirect_to(session[:return_to] || default)
session[:return_to] = nil
end
end
<file_sep>class TimeSlotsController < ApplicationController
# GET /time_slots
# GET /time_slots.xml
def index
@time_slots = TimeSlot.all
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @time_slots }
end
end
# GET /time_slots/1
# GET /time_slots/1.xml
def show
@time_slot = TimeSlot.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => @time_slot }
end
end
# GET /time_slots/new
# GET /time_slots/new.xml
def new
@time_slot = TimeSlot.new
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @time_slot }
end
end
# GET /time_slots/1/edit
def edit
@time_slot = TimeSlot.find(params[:id])
end
def create
time_slot = TimeSlot.new(params[:time_slot])
if time_slot.save
render :json => time_slot
else
head :status => 500
end
end
# PUT /time_slots/1
# PUT /time_slots/1.xml
def update
@time_slot = TimeSlot.find(params[:id])
respond_to do |format|
if @time_slot.update_attributes(params[:time_slot])
flash[:notice] = 'TimeSlot was successfully updated.'
format.html { redirect_to(@time_slot) }
format.xml { head :ok }
else
format.html { render :action => "edit" }
format.xml { render :xml => @time_slot.errors, :status => :unprocessable_entity }
end
end
end
def destroy
time_slot = TimeSlot.find(params[:id])
if time_slot.lessons.empty?
time_slot.destroy
head :ok
else
head :status => 500
end
end
end
<file_sep>class StudentsController < ApplicationController
before_filter :require_no_student, :only => [:new, :create]
before_filter :require_student, :only => [:show, :edit, :update]
def show
@student = @current_student
end
def new
@student = Student.new
end
def edit
@student = @current_student
end
def create
@student = Student.new(params[:student])
if @student.save
flash[:notice] = 'Student was successfully created.'
redirect_to :controller => :welcome
else
render :action => :new
end
end
def update
@student = @current_student
if @student.update_attributes(params[:student])
flash[:notice] = 'Student was successfully updated.'
redirect_to :controller => :welcome
else
render :action => :edit
end
end
end
<file_sep>class TimeSlot < ActiveRecord::Base
has_many :lessons
scope :upcoming, lambda {
where :begins_at => upcoming_range
}
scope :free,
joins('LEFT JOIN (SELECT lessons.time_slot_id, count(id) as count FROM lessons GROUP BY time_slot_id) AS ag ON ag.time_slot_id = time_slots.id')
.where('max_students IS NULL OR ag.count IS NULL OR ag.count < max_students')
default_scope order('begins_at')
class << self
def upcoming_range
today = Time.zone.now.beginning_of_day
today..(today + 2.weeks).end_of_day
end
def each_day
day = upcoming_range.first
(0...14).each { |i| yield(day + i.days) }
end
def each_slot(day)
(0...48).each do |offset|
begins_at = day + (offset * 30).minutes
if begins_at + 30.minutes > Time.zone.now
yield(slots[begins_at] || new(:begins_at => begins_at))
end
end
end
def slots
@slots ||= upcoming.index_by(&:begins_at)
end
end
def dom_attributes
attributes = {'data-id' => id, 'data-begins_at' => begins_at}
attributes.delete_if { |_,value| value.nil? }
attributes.merge!('class' => 'available') if id
attributes.merge!('class' => 'booked') if !(lessons.empty?)
attributes
end
end
<file_sep>class Lesson < ActiveRecord::Base
validates_presence_of :time_slot, :student
belongs_to :time_slot
belongs_to :student
end
<file_sep>source 'http://rubygems.org'
gem 'rails', '3.0.0.beta3'
gem 'sqlite3-ruby'
gem 'authlogic', :git => 'git://github.com/odorcicd/authlogic.git', :branch => 'rails3'
gem 'compass', '0.10.0.rc3'
# Use unicorn as the web server
gem 'unicorn'
# Bundle the extra gems:
# gem 'bj'
# gem 'nokogiri', '1.4.1'
# gem 'sqlite3-ruby', :require => 'sqlite3'
# gem 'aws-s3', :require => 'aws/s3'
# Bundle gems for certain environments:
# gem 'rspec', :group => :test
# group :test do
# gem 'webrat'
# end
<file_sep>class TeachersController < ApplicationController
before_filter :require_no_teacher, :only => [:new, :create]
before_filter :require_teacher, :only => [:show, :edit, :update]
def show
@teacher = @current_teacher
end
def new
@teacher = Teacher.new
end
def edit
@teacher = @current_teacher
end
def create
@teacher = Teacher.new(params[:teacher])
if @teacher.save
flash[:notice] = 'Teacher was successfully created.'
redirect_to :controller => :welcome
else
render :action => :new
end
end
def update
@teacher = @current_teacher
if @teacher.update_attributes(params[:teacher])
flash[:notice] = 'Teacher was successfully updated.'
redirect_to :controller => :welcome
else
render :action => :edit
end
end
end
<file_sep>class TimeSlotTimeShouldBeDateTime < ActiveRecord::Migration
def self.up
remove_column :time_slots, :time
add_column :time_slots, :begins_at, :datetime
end
def self.down
end
end
| f9977da9a9f916d7179d19d3eddf1de96258c3d6 | [
"JavaScript",
"Ruby"
] | 13 | JavaScript | teg/school | a23a18f9a0fa93f77ef6698a08c989d71e6a8af4 | dbaa2aeeeab24437c6260ae390fb789e54678d1a |
refs/heads/master | <repo_name>k0a1a/4g-multitcp<file_sep>/README.md
# 4g-multitcp
Aggrigation of multiple 4G uplinks using Multipath TCP
<file_sep>/make-route.sh
#!/bin/bash
#set -o xtrace
IF0='eth10'
IF1='eth11'
IF2='eth12'
IF3='eth13'
IF4='eth14'
TB0='1'
TB1='2'
TB2='3'
TB3='4'
TB4='5'
DUMMY_GW='192.168.0.1'
ifip() {
ip addr show $1 | awk '/inet / {split($2, a, "/"); print a[1]}'
}
ifgw() {
case $1 in
ppp*) ip addr show $1 | awk '/inet / {split($4, a, "/"); print a[1]}';;
eth*) echo $DUMMY_GW ;;
esac
}
## -------------- cleaning ---------------
echo '<<< cleaning..'
## hide errors
exec 3>&2 2> /dev/null
ip route del default scope global
while ip route del 192.168.0.1; do echo -n .; done
ip route flush table $TB0
ip route flush table $TB1
ip route flush table $TB2
ip route flush table $TB3
#ip route flush table $TB4
ip rule del dev $IF0 table $TB0
ip rule del dev $IF1 table $TB1
ip rule del dev $IF2 table $TB2
ip rule del dev $IF3 table $TB3
#ip rule del dev $IF4 table $TB4
ip route del dev $IF0 table $TB0
ip route del dev $IF1 table $TB1
ip route del dev $IF2 table $TB2
ip route del dev $IF3 table $TB3
#ip route del dev $IF4 table $TB4
ip route del default dev $IF0
ip route del default dev $IF1
ip route del default dev $IF2
ip route del default dev $IF3
#ip route del default dev $IF4
while ip rule del from "$(ifip $IF0)"; do echo -n .; done
while ip rule del from "$(ifip $IF1)"; do echo -n .; done
while ip rule del from "$(ifip $IF2)"; do echo -n .; done
while ip rule del from "$(ifip $IF3)"; do echo -n .; done
#while ip rule del from "$(ifip $IF4)"; do echo -n .; done
while ip rule del from all iif $IF0; do echo -n .; done
while ip rule del from all iif $IF1; do echo -n .; done
while ip rule del from all iif $IF2; do echo -n .; done
while ip rule del from all iif $IF3; do echo -n .; done
#while ip rule del from all iif $IF4; do echo -n .; done
ip route flush cache
## unhide errors
exec 2>&3
echo -e "\nok"
## -------------- cleaning done ---------------
echo '<<< setting routes..'
## for eth0 devices doing it here, not in ppp/bond-routes
#ip rule add dev $IF0 lookup $TB0
#ip rule add dev $IF1 lookup $TB1
#ip rule add dev $IF2 lookup $TB2
#ip rule add dev $IF3 lookup $TB3
byAddress() {
echo '<<< using inet addr!'
ip route add $(ifgw $IF0) dev $IF0 src $(ifip $IF0) table $TB0
ip route add $(ifgw $IF1) dev $IF1 src $(ifip $IF1) table $TB1
ip route add $(ifgw $IF2) dev $IF2 src $(ifip $IF2) table $TB2
# ip route add $(ifgw $IF3) dev $IF3 src $(ifip $IF3) table $TB3
ip route add default via $(ifgw $IF0) table $TB0
ip route add default via $(ifgw $IF1) table $TB1
ip route add default via $(ifgw $IF2) table $TB2
# ip route add default via $(ifgw $IF3) table $TB3
ip rule add from $(ifip $IF0) table $TB0 priority 10
ip rule add from $(ifip $IF1) table $TB1 priority 10
ip rule add from $(ifip $IF2) table $TB2 priority 10
# ip rule add from $(ifip $IF3) table $TB3 priority 10
ip route add default scope global \
nexthop via $(ifgw $IF0) dev $IF0 weight 7 \
nexthop via $(ifgw $IF1) dev $IF1 weight 8 \
nexthop via $(ifgw $IF2) dev $IF2 weight 9
# nexthop via $(ifgw $IF3) dev $IF3 weight 10
}
byDevice() {
echo '<<< using dev names!'
ip rule add from $(ifip $IF0) table $TB0
ip rule add from $(ifip $IF1) table $TB1
ip rule add from $(ifip $IF2) table $TB2
# ip route add dev $IF1 table $TB3
# ip route add default dev $IF1 table $TB1
# ip route add default dev $IF2 table $TB2
# ip route add default dev $IF3 table $TB3
ip route add 192.168.0.0/24 dev $IF0 scope link table $TB0 #priority 10
ip route add default via $DUMMY_GW dev $IF0 table $TB0
ip route add 192.168.0.0/24 dev $IF1 scope link table $TB1 #priority 10
ip route add default via $DUMMY_GW dev $IF1 table $TB1
ip route add 192.168.0.0/24 dev $IF2 scope link table $TB2 #priority 10
ip route add default via $DUMMY_GW dev $IF2 table $TB2
ip route add default scope global nexthop via $DUMMY_GW dev $IF0
# ip rule add dev $IF1 table $TB1 #priority 10
# ip rule add dev $IF2 table $TB2 #priority 10
# ip rule add dev $IF3 table $TB3 priority 10
# ip route add default scope global \
# nexthop via $(ifgw $IF0) dev $IF0 weight 7 \
# nexthop via $(ifgw $IF1) dev $IF1 weight 8 \
# nexthop via $(ifgw $IF2) dev $IF2 weight 9
# nexthop via $(ifgw $IF3) dev $IF3 weight 10
}
## run here
#byAddress
byDevice
echo -e "ok"
echo -e "\n>>> ip route show:"
ip route show
echo -e "\n>>> ip rule list:"
ip rule list
echo -e "\n"
exit 0
| 9b5752b5f1b35693d95e35557949ce8242477788 | [
"Markdown",
"Shell"
] | 2 | Markdown | k0a1a/4g-multitcp | abe77178e7f2d5d6b8b9e62bb3098806eef19607 | b83ee7669ec0ecc8ed49980553c2b8f8a32c4077 |
refs/heads/master | <file_sep>import React, { Component } from 'react';
import {
Text,
View,
Image,
Alert,
TextInput,
StyleSheet,
SafeAreaView,
TouchableOpacity,
ScrollView,
} from 'react-native';
import PropTypes from 'prop-types';
import * as firebase from 'firebase';
import { AntDesign, Ionicons } from '@expo/vector-icons';
import colors from './styles/colors';
import logo from '../images/logo.png';
export default class ChangePassword extends Component {
constructor(props) {
super(props);
this.state = {
currentPassword: '',
newPassword: '',
};
}
reauthenticate = (currentPassword) => {
const user = firebase.auth().currentUser;
const cred = firebase.auth.EmailAuthProvider.credential(user.email, currentPassword);
return user.reauthenticateWithCredential(cred);
}
onChangePasswordPress = () => {
const { currentPassword, newPassword } = this.state;
this.reauthenticate(currentPassword)
.then(() => {
const user = firebase.auth().currentUser;
user.updatePassword(newPassword)
.then(() => {
Alert.alert('Password was changed');
}).catch((error) => {
Alert.alert(error.message);
});
}).catch((error) => {
Alert.alert(error.message);
});
}
render() {
const { navigation } = this.props;
const { navigate } = navigation;
const { currentPassword, newPassword } = this.state;
return (
<SafeAreaView style={styles.container}>
<View style={styles.header}>
<Ionicons
size={24}
style={styles.back}
name="md-arrow-back"
color={colors.white}
onPress={() => navigation.goBack()}
/>
<Text style={styles.headerText}>Change Password</Text>
</View>
<View style={styles.logoContainer}>
<Image style={styles.logo} source={logo} />
</View>
<ScrollView style={styles.formContainer}>
<View style={styles.inputGroup}>
<TextInput
secureTextEntry
returnKeyType="next"
value={currentPassword}
placeholder="Current Password"
onChangeText={(text) => { this.setState({ currentPassword: text }); }}
/>
</View>
<View style={styles.inputGroup}>
<TextInput
secureTextEntry
returnKeyType="go"
value={newPassword}
placeholder="New Password"
onChangeText={(text) => { this.setState({ newPassword: text }); }}
/>
</View>
<View style={styles.button}>
<TouchableOpacity
onPress={() => this.onChangePasswordPress()}
style={[styles.addRoute, { backgroundColor: colors.jade }]}
>
<AntDesign
size={16}
name="plus"
color={colors.white}
/>
</TouchableOpacity>
</View>
</ScrollView>
</SafeAreaView>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
header: {
height: 75,
paddingLeft: 10,
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'flex-start',
backgroundColor: colors.jade,
},
headerText: {
fontSize: 25,
paddingTop: 10,
paddingLeft: 70,
color: colors.white,
width: '80%'
},
back: {
paddingTop: 20,
paddingLeft: 15,
color: colors.white,
},
logoContainer: {
paddingTop: '20%',
alignItems: 'center',
},
logo: {
width: 150,
height: 150,
},
formContainer: {
flex: 1,
padding: 35,
},
inputGroup: {
flex: 1,
marginBottom: 15,
borderBottomWidth: 1,
borderBottomColor: colors.jade,
},
addRoute: {
padding: 16,
borderRadius: 4,
alignItems: 'center',
justifyContent: 'center',
},
button: {
paddingTop: 20,
},
preloader: {
top: 0,
left: 0,
right: 0,
bottom: 0,
position: 'absolute',
alignItems: 'center',
justifyContent: 'center',
},
});
ChangePassword.propTypes = {
navigation: PropTypes.shape({
goBack: PropTypes.func.isRequired,
navigate: PropTypes.func.isRequired,
}).isRequired,
};
<file_sep>import * as React from 'react';
import {
Entypo,
Ionicons,
AntDesign,
MaterialCommunityIcons,
} from '@expo/vector-icons';
import PropTypes from 'prop-types';
import { createMaterialBottomTabNavigator } from '@react-navigation/material-bottom-tabs';
import Home from '../home';
import Todo from '../todo';
import colors from '../styles/colors';
import ThingsToKnow from '../thingsToKnow';
import CurrentLocation from '../currentLocation';
const Tab = createMaterialBottomTabNavigator();
export default function TabNav() {
return (
<Tab.Navigator
activeColor={colors.white}
initialRouteName="Explore"
inactiveColor={colors.pebble}
tabBarOptions={{ showlabel: false }}
barStyle={{ backgroundColor: colors.jade }}
>
<Tab.Screen
name="Home"
component={Home}
options={{
tabBarLabel: false,
tabBarIcon: ({ color }) => (
<AntDesign
size={24}
name="home"
color={color}
/>
),
}}
/>
<Tab.Screen
name="Current Location"
component={CurrentLocation}
options={{
tabBarLabel: false,
tabBarIcon: ({ color }) => (
<Entypo
size={24}
color={color}
name="location-pin"
/>
),
}}
/>
<Tab.Screen
name="Things To Know"
component={ThingsToKnow}
options={{
tabBarLabel: false,
tabBarIcon: ({ color }) => (
<MaterialCommunityIcons
size={24}
color={color}
name="lightbulb-on-outline"
/>
),
}}
/>
<Tab.Screen
name="Todos"
component={Todo}
options={{
tabBarLabel: false,
tabBarIcon: ({ color }) => (
<Ionicons
size={24}
name="ios-list"
color={color}
/>
),
}}
/>
</Tab.Navigator>
);
}
TabNav.propTypes = {
color: PropTypes.string,
};
TabNav.defaultProps = {
color: colors.white,
};
<file_sep>import React, { Component } from 'react';
import {
StyleSheet, View, Image, Text, FlatList, SafeAreaView, TouchableOpacity,
} from 'react-native';
import PropTypes from 'prop-types';
import * as firebase from 'firebase';
import { Ionicons, MaterialCommunityIcons } from '@expo/vector-icons';
import colors from '../styles/colors';
export default class ViewClimbingRoutes extends Component {
constructor(props) {
super(props);
this.state = {
climbingRoutes: [],
};
}
componentDidMount() {
firebase.firestore()
.collection('climbing-routes')
.orderBy('createdAt')
.get()
.then((querySnapshot) => {
const list = [];
querySnapshot.forEach((doc) => {
const {
crag, grade, height, img, lat, long, pitches, title,
} = doc.data();
list.push({
id: doc.id,
img,
lat,
crag,
long,
title,
grade,
height,
pitches,
});
});
this.setState({
climbingRoutes: list,
});
});
}
deleteClimbingRoute = (id, index) => {
const { climbingRoutes } = this.state;
firebase.firestore().collection('climbing-routes').doc(id)
.delete()
.then(() => {
climbingRoutes.splice(index, 1);
this.setState({ climbingRoutes });
console.log('Deleted!');
});
};
componentWillUpdate() {
this.componentDidMount();
}
render() {
const { climbingRoutes } = this.state;
const { navigation } = this.props;
return (
<SafeAreaView style={styles.container}>
<View style={styles.header}>
<Ionicons
size={24}
style={styles.back}
name="md-arrow-back"
color={colors.white}
onPress={() => navigation.goBack()}
/>
<Text style={styles.headerText}>Climbing Routes</Text>
</View>
<FlatList
numColumns={1}
horizontal={false}
data={climbingRoutes}
style={styles.cardContainer}
contentContainerStyle={styles.contentContainer}
renderItem={({ item, index }) => (
<View style={{ width: 400 }}>
<View style={styles.card}>
<View style={{ flexDirection: 'row', width: '80%' }}>
<Text style={styles.cardText}>{item.title}</Text>
<TouchableOpacity
style={styles.deleteButton}
onPress={() => this.deleteClimbingRoute(item.id, index)}
>
<MaterialCommunityIcons name="trash-can-outline" size={24} color={colors.white} />
</TouchableOpacity>
</View>
<View>
<Text style={styles.cragText}>
{item.crag}
</Text>
</View>
<View style={styles.cardInfo}>
<View style={{ flexDirection: 'row' }}>
<Text style={{ color: colors.onyx, fontWeight: 'bold' }}>
Grade:
</Text>
<Text>
{item.grade}
</Text>
</View>
<View style={{ flexDirection: 'row' }}>
<Text style={{ color: colors.onyx, fontWeight: 'bold' }}>
Height:
</Text>
<Text>
{item.height}
</Text>
</View>
<View style={{ flexDirection: 'row' }}>
<Text style={{ color: colors.onyx, fontWeight: 'bold' }}>
Pitches:
</Text>
<Text>
{item.pitches}
</Text>
</View>
</View>
<View style={{ alignItems: 'center' }}>
<Image style={styles.cardImage} source={{ uri: item.img }} />
</View>
</View>
</View>
)}
/>
</SafeAreaView>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: colors.jade,
},
input: {
height: 50,
marginTop: 5,
fontSize: 18,
borderRadius: 6,
borderColor: 'grey',
paddingHorizontal: 16,
borderWidth: StyleSheet.hairlineWidth,
},
deleteButton: {
paddingVertical: 16,
alignItems: 'flex-end',
},
header: {
height: 75,
paddingLeft: 10,
marginBottom: 5,
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'flex-start',
backgroundColor: colors.jade,
},
headerText: {
fontSize: 25,
paddingTop: 10,
textAlign: "center",
width: '80%',
color: colors.white,
},
back: {
paddingTop: 20,
paddingLeft: 15,
color: colors.white,
},
contentContainer: {
width: '97%',
paddingTop: 8,
alignItems: 'center',
flexDirection: 'column',
justifyContent: 'center',
},
cardText: {
padding: 10,
fontSize: 25,
color: colors.pebble,
},
cragText: {
fontSize: 16,
fontWeight: '500',
color: colors.onyx,
textAlign: 'center',
},
card: {
padding: 20,
width: '96%',
borderWidth: 3,
borderRadius: 20,
marginBottom: 10,
marginLeft: '2%',
backgroundColor: colors.jade,
borderColor: colors.lightjade,
shadowOffset: {
width: 3,
height: 3,
},
},
cardImage: {
height: 200,
width: '100%',
borderRadius: 5,
resizeMode: 'cover',
},
cardInfo: {
fontWeight: '800',
flexDirection: 'row',
marginHorizontal: 15,
justifyContent: 'space-between',
},
});
ViewClimbingRoutes.propTypes = {
navigation: PropTypes.shape({
goBack: PropTypes.func.isRequired,
navigate: PropTypes.func.isRequired,
}).isRequired,
};
<file_sep>import React, { Component } from 'react'; import {
View,
Text,
Alert,
Image,
Linking,
Platform,
TextInput,
StyleSheet,
Dimensions,
SafeAreaView,
TouchableOpacity,
ActivityIndicator,
} from 'react-native';
import PropTypes from 'prop-types';
import * as firebase from 'firebase';
import debounce from 'lodash/debounce';
import * as Location from 'expo-location';
import Carousel from 'react-native-snap-carousel';
import MapView, { Callout, Marker } from 'react-native-maps';
import { Ionicons, MaterialIcons } from '@expo/vector-icons';
import mapsIcon from '../images/mapsicon.jpg';
import colors from './styles/colors';
const CarouselItem = (props) => {
const {
item, openMapsApp,
} = props;
const {
lat,
img,
long,
crag,
title,
grade,
height,
pitches,
} = item;
return (
<View>
<View style={styles.cardContainer}>
<Text style={styles.cardTitle}>{title}</Text>
<Text style={styles.cragText}>
{crag}
</Text>
<View style={styles.cardInfo}>
<View style={{ flexDirection: 'row' }}>
<Text style={{ color: colors.onyx, fontWeight: 'bold' }}>
Grade:
</Text>
<Text>
{grade}
</Text>
</View>
<View style={{ flexDirection: 'row' }}>
<Text style={{ color: colors.onyx, fontWeight: 'bold' }}>
Height:
</Text>
<Text>
{height}
</Text>
</View>
<View style={{ flexDirection: 'row' }}>
<Text style={{ color: colors.onyx, fontWeight: 'bold' }}>
Pitches:
</Text>
<Text>
{pitches}
</Text>
</View>
</View>
<View style={{ alignItems: 'center' }}>
<Image style={styles.cardImage} source={{ uri: img }} />
</View>
</View>
<TouchableOpacity style={styles.button} onPress={() => openMapsApp({ lat, long })}>
<Image style={styles.googlemaps} source={mapsIcon} />
</TouchableOpacity>
</View>
);
};
export default class Home extends Component {
markers = [];
componentDidMount() {
this.checkIfLoggedIn();
}
checkIfLoggedIn = () => {
const { navigation } = this.props;
const { navigate } = navigation;
firebase.auth().onAuthStateChanged((user) => {
if (user) {
navigate('Home');
} else {
navigate('Login');
}
});
};
retrieveClimbingRoutes = debounce((value = '') => {
firebase.firestore()
.collection('climbing-routes').orderBy('title').startAt(value)
.endAt(`${value}\uf8ff`)
.get()
.then((querySnapshot) => {
const list = [];
querySnapshot.forEach((doc) => {
const {
title, description, crag, grade, height, img, location, pitches, lat, long,
} = doc.data();
list.push({
lat,
img,
long,
crag,
title,
grade,
height,
pitches,
location,
id: doc.id,
description,
});
});
this.setState({ climbingRoutes: list });
})
.catch((error) => {
console.error('getting climbing-routes from database failed', error);
})
.finally(() => {
this.setState({ searching: false });
});
}, 500);
markers = [];
constructor(props) {
super(props);
this.state = {
region: null,
queryString: '',
searching: false,
climbingRoutes: [],
};
this.retrieveClimbingRoutes();
this.getLocationAsync();
}
onCarouselItemChange = (index) => {
const { markers } = this;
const { climbingRoutes } = this.state;
const marker = markers[index];
const location = climbingRoutes[index];
this.map.animateToRegion({
latitudeDelta: 0.09,
longitudeDelta: 0.035,
latitude: location.lat,
longitude: location.long,
});
marker.showCallout();
}
onSearch = (value) => {
this.setState({ queryString: value, searching: true }, this.retrieveClimbingRoutes(value));
}
getLocationAsync = () => {
Location.hasServicesEnabledAsync().then((res) => {
console.info('hasServicesEnabledAsync', res);
}).catch((error) => {
console.error('hasServicesEnabledAsync', error);
});
Location.requestPermissionsAsync().then((res) => {
if (!res.granted) {
Alert.alert('We need your permission to access your location.');
}
}).catch((error) => {
console.error('requestPermissionsAsync', error);
});
Location.getCurrentPositionAsync({
timeout: 10000,
maximumAge: 1000,
accuracy: Location.Accuracy.BestForNavigation,
}).then((res) => {
const { coords: { latitude, longitude } } = res;
const region = {
latitude,
longitude,
latitudeDelta: 1,
longitudeDelta: 1,
};
this.setState({ region });
}).catch((error) => {
Alert.alert('We can\'t get your current position.');
});
}
openMapsApp = ({ lat, long }) => {
const latLngUri = encodeURIComponent(`${lat} ${long}`);
if (Platform.OS === 'ios') {
Linking.openURL(`http://maps.apple.com/?daddr=${latLngUri}`);
} else {
Linking.openURL(`http://maps.google.com/?daddr=${latLngUri}`);
}
}
onMarkerPressed = (location, index) => {
this.map.animateToRegion({
latitudeDelta: 0.09,
longitudeDelta: 0.035,
latitude: location.latitude,
longitude: location.longitude,
});
this.carousel.snapToItem(index);
}
setMarker = (index, ref) => {
const { markers } = this;
if (markers[index] === ref) return;
markers[index] = ref;
this.markers = markers;
}
render() {
const { navigation } = this.props;
const {
region, climbingRoutes, queryString, searching,
} = this.state;
return (
<SafeAreaView style={styles.container}>
<View style={styles.header}>
<Ionicons
size={24}
name="ios-menu"
color={colors.onyx}
style={styles.burger}
onPress={() => navigation.toggleDrawer()}
/>
<Text style={styles.headerText}>Home</Text>
</View>
<View style={styles.searchBar}>
<MaterialIcons
size={24}
name="search"
color={colors.lightjade}
style={{ flex: 1, paddingHorizontal: 12 }}
/>
<TextInput
value={queryString}
style={styles.input}
onChangeText={this.onSearch}
placeholder="Search Climbing Route Titles"
/>
<View style={{ width: 50 }}>
{searching && <ActivityIndicator color="#000" style={{ color: colors.lightjade }} />}
</View>
</View>
<View style={styles.noItemsView}>
{queryString.length > 0 && climbingRoutes.length === 0 && searching === false
&& <Text style={styles.noItemsText}>No items match your search</Text>}
</View>
<MapView
showsCompass
showsTraffic
loadingEnabled
showsUserLocation
style={styles.map}
showsMyLocationButton
initialRegion={region}
ref={(map) => { this.map = map; }}
>
{climbingRoutes.map((marker, index) => (
<Marker
key={marker.id}
title={marker.title}
identifier={marker.id}
ref={(ref) => this.setMarker(index, ref)}
onPress={() => this.onMarkerPressed(marker, index)}
coordinate={{ latitude: marker.lat, longitude: marker.long }}
>
<Callout>
<Text>{marker.title}</Text>
</Callout>
</Marker>
))}
</MapView>
<Carousel
isLooped
itemWidth={300}
data={climbingRoutes}
removeClippedSubviews={false}
containerCustomStyle={styles.carousel}
sliderWidth={Dimensions.get('window').width}
ref={(carousel) => { this.carousel = carousel; }}
onSnapToItem={(index) => this.onCarouselItemChange(index)}
renderItem={(carouselItem) => (
<CarouselItem
{...carouselItem}
openMapsApp={this.openMapsApp}
/>
)}
/>
</SafeAreaView>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
header: {
height: 75,
paddingLeft: 10,
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'flex-start',
backgroundColor: colors.jade,
},
searchBar: {
height: 40,
borderRadius: 6,
borderColor: 'grey',
flexDirection: 'row',
alignItems: 'center',
backgroundColor: colors.white,
justifyContent: 'space-between',
borderWidth: StyleSheet.hairlineWidth,
},
input: {
flex: 10,
fontSize: 18,
height: '100%',
},
headerText: {
fontSize: 25,
width: '80%',
paddingTop: 10,
paddingLeft: 125,
color: colors.white,
},
burger: {
paddingTop: 20,
paddingLeft: 15,
color: colors.white,
},
map: {
flex: 6,
},
carousel: {
bottom: 0,
paddingBottom: 10,
position: 'absolute',
},
cardContainer: {
width: 300,
padding: 5,
height: 190,
borderRadius: 24,
backgroundColor: colors.lightjade,
},
cardTitle: {
fontSize: 20,
fontWeight: 'bold',
color: colors.white,
alignSelf: 'center',
},
cardText: {
fontWeight: '700',
color: colors.white,
textAlign: 'center',
},
cragText: {
fontSize: 16,
fontWeight: '500',
color: colors.onyx,
textAlign: 'center',
},
card: {
width: '96%',
borderRadius: 30,
marginBottom: 10,
marginLeft: '2%',
shadowOpacity: 1,
shadowColor: 'grey',
backgroundColor: colors.lightjade,
shadowOffset: {
width: 3,
height: 3,
},
},
cardImage: {
padding: 5,
height: 100,
width: '70%',
resizeMode: 'cover',
},
cardInfo: {
fontWeight: '800',
flexDirection: 'row',
marginHorizontal: 15,
justifyContent: 'space-between',
},
button: {
paddingTop: 5,
alignItems: 'flex-end',
},
googlemaps: {
width: 35,
height: 35,
borderRadius: 4,
justifyContent: 'flex-end',
},
});
Home.propTypes = {
navigation: PropTypes.shape({
navigate: PropTypes.func.isRequired,
toggleDrawer: PropTypes.func.isRequired,
}).isRequired,
};
CarouselItem.propTypes = {
openMapsApp: PropTypes.func.isRequired,
item: PropTypes.shape({
lat: PropTypes.number.isRequired,
img: PropTypes.string.isRequired,
long: PropTypes.number.isRequired,
crag: PropTypes.string.isRequired,
title: PropTypes.string.isRequired,
grade: PropTypes.string.isRequired,
height: PropTypes.string.isRequired,
pitches: PropTypes.number.isRequired,
}).isRequired,
};
<file_sep>import React from 'react';
import * as firebase from 'firebase';
import { LogBox } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createDrawerNavigator } from '@react-navigation/drawer';
import TabNav from './src/screens/navigation/tab';
import Drawers from './src/screens/navigation/drawer';
import Login from './src/screens/login';
import Support from './src/screens/support';
import Register from './src/screens/register';
import Settings from './src/screens/settings';
import ChangeEmail from './src/screens/changeEmail';
import LoadingScreen from './src/screens/loadingscreen';
import ChangePassword from './src/screens/changePassword';
import CurrentLocation from './src/screens/currentLocation';
import Home from './src/screens/home';
import AddUsers from './src/screens/admin/addUsers';
import AdminHome from './src/screens/admin/adminHome';
import ViewUsers from './src/screens/admin/viewUsers';
import AddThingsToKnow from './src/screens/admin/addThingsToKnow';
import ViewThingsToKnow from './src/screens/admin/viewThingsToKnow';
import AddClimbingRoutes from './src/screens/admin/addClimbingRoutes';
import ViewClimbingRoutes from './src/screens/admin/viewClimbingRoutes';
import ForgotPassword from './src/screens/forgotPassword';
LogBox.ignoreLogs(['Warning: ...']);
LogBox.ignoreAllLogs();
const firebaseConfig = {
measurementId: 'G-4DN0QTY9FG',
projectId: 'positive-altitude',
messagingSenderId: '1052581473655',
storageBucket: 'positive-altitude.appspot.com',
authDomain: 'positive-altitude.firebaseapp.com',
apiKey: '<KEY>',
appId: '1:1052581473655:web:ff8d45ca315a95062c4572',
databaseURL: 'https://positive-altitude.firebaseio.com',
};
if (!firebase.apps.length) firebase.initializeApp(firebaseConfig);
const Drawer = createDrawerNavigator();
export default function App() {
return (
<NavigationContainer>
<Drawer.Navigator drawerContent={(props) => <Drawers {...props} />}>
<Drawer.Screen name="TabNav" component={TabNav} />
<Drawer.Screen name="Loading" component={LoadingScreen} />
<Drawer.Screen name="Login" component={Login} />
<Drawer.Screen name="Register" component={Register} />
<Drawer.Screen name="ForgotPassword" component={ForgotPassword} />
<Drawer.Screen name="Home" component={Home} />
<Drawer.Screen name="Support" component={Support} />
<Drawer.Screen name="Settings" component={Settings} />
<Drawer.Screen name="ChangeEmail" component={ChangeEmail} />
<Drawer.Screen name="ChangePassword" component={ChangePassword} />
<Drawer.Screen name="CurrentLocation" component={CurrentLocation} />
<Drawer.Screen name="AddUsers" component={AddUsers} />
<Drawer.Screen name="AdminHome" component={AdminHome} />
<Drawer.Screen name="ViewUsers" component={ViewUsers} />
<Drawer.Screen name="AddThingsToKnow" component={AddThingsToKnow} />
<Drawer.Screen name="ViewThingsToKnow" component={ViewThingsToKnow} />
<Drawer.Screen name="AddClimbingRoutes" component={AddClimbingRoutes} />
<Drawer.Screen name="ViewClimbingRoutes" component={ViewClimbingRoutes} />
</Drawer.Navigator>
</NavigationContainer>
);
}
<file_sep>import React, { Component } from 'react';
import {
View,
Text,
StyleSheet,
TouchableOpacity,
} from 'react-native';
import PropTypes from 'prop-types';
import * as firebase from 'firebase';
import { Ionicons, AntDesign, Fontisto } from '@expo/vector-icons';
import colors from './styles/colors';
export default class Settings extends Component {
refreshScreen() {
this.setState({ lastRefresh: Date(Date.now()).toString() })
}
render() {
const { navigation } = this.props;
const { navigate } = navigation;
const user = firebase.auth().currentUser;
return (
<View style={styles.container}>
<View style={styles.header}>
<Ionicons
size={24}
style={styles.back}
name="md-arrow-back"
color={colors.white}
onPress={() => navigation.goBack()}
/>
<Text style={styles.headerText}>Settings </Text>
<Ionicons name="ios-refresh"
size={24}
color={colors.white}
onPress={() => this.refreshScreen()}
style={{ alignItems: 'flex-end', paddingTop: 20 }}
/>
</View>
<View>
<View style={styles.profile}>
<Text style={styles.name}>{user.displayName}</Text>
<Text style={styles.current}>
Email:
{' '}
{user.email}
</Text>
</View>
</View>
<View style={{ marginTop: 40, alignItems: 'center' }}>
<View>
<Text style={[styles.title, { color: colors.jade }]}> Change Email </Text>
</View>
<View style={{ marginVertical: 30, width: 150 }}>
<View>
<TouchableOpacity
style={[styles.addList, { borderColor: colors.jade }]}
onPress={() => this.props.navigation.navigate('ChangeEmail')}
>
<Fontisto name="email" size={30} color={colors.jade} />
</TouchableOpacity>
</View>
</View>
<View style={{ marginTop: 40, alignItems: 'center' }}>
<View>
<Text style={[styles.title, { color: colors.jade }]}> Change Password </Text>
</View>
<View style={{ marginVertical: 30, width: 150 }}>
<View>
<TouchableOpacity
style={[styles.addList, { borderColor: colors.jade }]}
onPress={() => this.props.navigation.navigate('ChangePassword')}
>
<AntDesign name="lock" size={30} color={colors.jade} />
</TouchableOpacity>
</View>
</View>
</View>
<View style={{ marginTop: 40, alignItems: 'center' }}>
<View>
<Text style={[styles.title, { color: colors.jade }]}> Delete Account </Text>
</View>
<View style={{ marginVertical: 30, width: 150 }}>
<View>
<TouchableOpacity
style={[styles.addList, { borderColor: colors.jade }]}
onPress={() => firebase.auth().currentUser.delete()}
>
<AntDesign name="deleteuser" size={30} color={colors.jade} />
</TouchableOpacity>
</View>
</View>
</View>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
header: {
height: 75,
paddingLeft: 10,
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'flex-start',
backgroundColor: colors.jade,
},
headerText: {
fontSize: 25,
width: '80%',
paddingTop: 10,
paddingLeft: 110,
color: colors.white,
},
profile: {
marginTop: 64,
alignItems: 'center',
},
name: {
fontSize: 25,
fontWeight: '600',
color: colors.jade,
},
current: {
fontSize: 16,
paddingTop: 20,
color: colors.moss,
},
title: {
fontSize: 25,
color: colors.jade,
},
back: {
paddingTop: 20,
paddingLeft: 15,
color: colors.white,
},
addList: {
padding: 16,
borderWidth: 2,
borderRadius: 4,
alignItems: 'center',
},
});
Settings.propTypes = {
navigation: PropTypes.shape({
goBack: PropTypes.func.isRequired,
navigate: PropTypes.func.isRequired,
}).isRequired,
};
<file_sep>import React, { Component } from 'react';
import {
View,
Text,
StyleSheet,
SafeAreaView,
} from 'react-native';
import PropTypes from 'prop-types';
import MapView from 'react-native-maps';
import * as Location from 'expo-location';
import * as Permissions from 'expo-permissions';
import { Ionicons, Entypo } from '@expo/vector-icons';
import colors from './styles/colors';
export default class CurrentLocation extends Component {
constructor(props) {
super(props);
this.state = {
region: null,
};
this.getLocationAsync();
}
state = {
currentLatitude: 'unknown',
currentAltitude: 'unknown',
currentLongitude: 'unknown',
};
getLocationAsync = async () => {
const { status } = await Permissions.askAsync(Permissions.LOCATION);
if (status !== 'granted') { console.log('We need your permission to access your location.'); }
const location = await Location.getCurrentPositionAsync({
timeout: 1000,
maximumAge: 1000,
accuracy: Location.Accuracy.BestForNavigation,
});
const region = {
latitudeDelta: 0.045,
longitudeDelta: 0.045,
latitude: location.coords.latitude,
altitude: location.coords.altitude,
longitude: location.coords.longitude,
};
this.setState({ region });
}
componentDidMount = () => {
navigator.geolocation.getCurrentPosition(
(position) => {
const currentLatitude = JSON.stringify(position.coords.latitude);
const currentAltitude = JSON.stringify(position.coords.altitude);
const currentLongitude = JSON.stringify(position.coords.longitude);
this.setState({ currentLatitude });
this.setState({ currentAltitude });
this.setState({ currentLongitude });
},
(error) => alert(error.message),
{ enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 },
);
this.watchID = navigator.geolocation.watchPosition((position) => {
console.log(position);
const currentLatitude = JSON.stringify(position.coords.latitude);
const currentAltitude = JSON.stringify(position.coords.altitude);
const currentLongitude = JSON.stringify(position.coords.longitude);
this.setState({ currentLatitude });
this.setState({ currentAltitude });
this.setState({ currentLongitude });
});
};
componentWillUnmount = () => {
navigator.geolocation.clearWatch(this.watchID);
};
render() {
const { region } = this.state;
const { navigation } = this.props;
return (
<SafeAreaView style={styles.container}>
<View style={styles.header}>
<Ionicons
size={24}
style={styles.back}
name="md-arrow-back"
color={colors.white}
onPress={() => navigation.goBack()}
/>
<Text style={styles.headerText}>Current Location</Text>
</View>
<View style={styles.locationContainer}>
<View>
<MapView
showsCompass
showsUserLocation
style={styles.map}
initialRegion={region}
/>
</View>
<View style={styles.locationTextContainer}>
<Text style={styles.locationTextTitle}>You Are Here</Text>
<Text
style={styles.locationText}
>
Longitude:
{' '}
{this.state.currentLongitude}
</Text>
<Text
style={styles.locationText}
>
Latitude:
{' '}
{this.state.currentLatitude}
</Text>
<Text
style={styles.locationText}
>
Altitude:
{' '}
{this.state.currentAltitude}
</Text>
<Entypo name="location-pin" style={{ paddingTop: 30 }} size={84} color={colors.jade} />
</View>
</View>
</SafeAreaView>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
header: {
height: 75,
paddingLeft: 10,
marginBottom: 5,
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'flex-start',
backgroundColor: colors.jade,
},
headerText: {
fontSize: 25,
paddingTop: 10,
width: '80%',
paddingLeft: 68,
color: colors.white,
},
back: {
paddingTop: 20,
paddingLeft: 15,
color: colors.white,
},
map: {
width: 350,
height: 350,
},
locationContainer: {
padding: 16,
alignItems: 'center',
justifyContent: 'center',
},
locationTextContainer: {
paddingTop: 20,
alignItems: 'center',
justifyContent: 'center',
},
locationTextTitle: {
fontSize: 35,
color: colors.moss,
},
locationText: {
fontSize: 18,
marginTop: 16,
color: colors.jade,
alignItems: 'center',
justifyContent: 'center',
},
});
CurrentLocation.propTypes = {
navigation: PropTypes.shape({
goBack: PropTypes.func.isRequired,
navigate: PropTypes.func.isRequired,
}).isRequired,
};
<file_sep>import PropTypes from 'prop-types';
import React, { Component } from 'react';
import { View, StyleSheet, ActivityIndicator } from 'react-native';
import firebase from 'firebase';
import colors from './styles/colors';
class LoadingScreen extends Component {
componentDidMount() {
this.checkIfLoggedIn();
}
checkIfLoggedIn = () => {
const { navigation } = this.props;
const { navigate } = navigation;
firebase.auth().onAuthStateChanged((user) => {
if (user) {
navigate('Home');
} else {
navigate('Login');
}
});
};
render() {
return (
<View style={styles.container}>
<ActivityIndicator size="large" color={colors.jade} />
</View>
);
}
}
export default LoadingScreen;
LoadingScreen.propTypes = {
navigation: PropTypes.shape({
navigate: PropTypes.func.isRequired,
}).isRequired,
};
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
});
<file_sep># PositiveAltitude
Positive Altitude will allow rock-climbers to find and receive directions to climbing routes to their nearest location.
<file_sep>import {
Feather,
Octicons,
AntDesign,
FontAwesome5,
MaterialCommunityIcons,
} from '@expo/vector-icons';
import PropTypes from 'prop-types';
import * as firebase from 'firebase';
import isEmpty from 'lodash/isEmpty';
import React, { useState } from 'react';
import { View, StyleSheet, Alert } from 'react-native';
import { Title, Drawer } from 'react-native-paper';
import { DrawerContentScrollView, DrawerItem } from '@react-navigation/drawer';
import colors from '../styles/colors';
export default function Drawers(props) {
const { currentUser } = firebase.auth();
const { navigation } = props;
const { navigate } = navigation;
const [user, setUser] = useState({});
if (isEmpty(user) && currentUser != null) {
const getUserByIdQuery = firebase.firestore().collection('Users').doc(currentUser.uid);
getUserByIdQuery.get().then((doc) => {
if (!doc.exists) {
setUser({});
} else {
setUser(doc.data());
}
});
} else if (!currentUser && !isEmpty(user)) {
setUser({});
}
return (
<View style={{ flex: 1, backgroundColor: colors.jade }}>
<DrawerContentScrollView {...props}>
<View style={styles.container}>
<View style={styles.userInfoSection}>
<View style={{ flexDirection: 'row', marginTop: 15 }}>
<View style={{ marginLeft: 15, flexDirection: 'column' }}>
<Title style={styles.title}>
{`Hello, ${currentUser ? currentUser.displayName : 'Unknown'}`}
</Title>
</View>
</View>
</View>
<Drawer.Section style={styles.drawerSection} {...props}>
<DrawerItem
icon={({ color, size }) => (
<FontAwesome5
size={size}
color={color}
name="hands-helping"
/>
)}
label="Support"
onPress={() => {
navigation.navigate('Support');
}}
/>
<DrawerItem
icon={({ color, size }) => (
<MaterialCommunityIcons
size={size}
color={color}
name="settings-outline"
/>
)}
label="Settings"
onPress={() => { navigate('Settings'); }}
/>
{user.type === 'Admin'
&& (
<DrawerItem
icon={({ color, size }) => (
<Octicons
size={size}
name="settings"
color={color}
/>
)}
label="Admin"
onPress={() => { navigate('AdminHome'); }}
/>
)}
</Drawer.Section>
</View>
</DrawerContentScrollView>
<Drawer.Section style={styles.bottomDrawerSection}>
<DrawerItem
icon={({ color, size }) => (
<Feather
size={size}
name="log-in"
color={color}
/>
)}
label="Sign Out"
onPress={() => {
firebase.auth().signOut();
Alert.alert('User Signed Out Successfully')
}}
/>
</Drawer.Section>
</View>
);
}
Drawers.propTypes = {
navigation: PropTypes.shape({
navigate: PropTypes.func.isRequired,
}).isRequired,
};
const styles = StyleSheet.create({
container: {
flex: 1,
},
userInfoSection: {
paddingLeft: 10,
},
title: {
fontSize: 20,
marginTop: 3,
color: colors.white,
},
caption: {
fontSize: 14,
lineHeight: 14,
},
row: {
marginTop: 20,
flexDirection: 'row',
alignItems: 'center',
},
section: {
marginRight: 15,
flexDirection: 'row',
alignItems: 'center',
},
paragraph: {
marginRight: 3,
fontWeight: 'bold',
},
drawerSection: {
marginTop: 15,
},
bottomDrawerSection: {
marginBottom: 15,
borderTopWidth: 1,
borderTopColor: colors.onyx,
},
preference: {
paddingVertical: 12,
flexDirection: 'row',
paddingHorizontal: 16,
justifyContent: 'space-between',
},
});
<file_sep>export default colors = {
fog: '#9eafb8',
jade: '#adb8b4',
veil: '#d9d0c7',
dove: '#b3b1af',
onyx: '#30302f',
moss: '#6a7868',
white: '#FFFFFF',
glass: '#c3d2d9',
night: '#1d4154',
quartz: '#d4c5c3',
pebble: '#f2f0f1',
lightjade: 'rgba(211, 222, 217, 0.9)',
};
<file_sep>import React, { Component } from 'react';
import {
View,
Text,
Image,
Alert,
TextInput,
StyleSheet,
ScrollView,
SafeAreaView,
TouchableOpacity,
} from 'react-native';
import 'firebase/firestore';
import * as firebase from 'firebase';
import { AntDesign } from '@expo/vector-icons';
import PropTypes from 'prop-types';
import colors from './styles/colors';
import logo from '../images/logo.png';
export default class Register extends Component {
constructor() {
super();
this.state = {
email: '',
password: '',
displayName: '',
isLoading: false,
};
}
updateInputVal = (val, prop) => {
const { state } = this;
state[prop] = val;
this.setState(state);
}
register = () => {
if (this.state.email === '' || this.state.password < 7 || this.state.displayName === '') {
Alert.alert('Enter all details to register.');
} else {
this.setState({
isLoading: true,
});
firebase
.auth()
.createUserWithEmailAndPassword(this.state.email, this.state.password)
.catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
if (errorCode === 'auth/weak-password') {
Alert.alert('Your password is too weak.');
this.props.navigation.navigate('Register')
} else if (errorCode === 'auth/email-already-in-use') {
Alert.alert('Email is already in use');
this.props.navigation.navigate('Register')
} else if (errorCode === 'auth/invalid-email') {
Alert.alert('Email is invalid');
this.props.navigation.navigate('Register')
} else if (errorCode === 'auth/operation-not-allowed') {
Alert.alert('Something has gone wrong!');
} else {
alert(errorMessage);
}
console.log(error);
}).then((res) => {
firebase.firestore().collection('Users').doc(firebase.auth().currentUser.uid).set({
displayName: this.state.displayName,
}),
res.user.updateProfile({
displayName: this.state.displayName,
});
console.log('User Registered Successfully!');
this.setState({
isLoading: false,
displayName: '',
email: '',
password: '',
});
Alert.alert('User Registered Successfully!');
this.props.navigation.navigate('Login');
})
.catch((error) => this.setState({ errorMessage: error.message }));
this.props.navigation.navigate('Register');
}
}
render() {
if (this.state.isLoading) {
return (
<View />
);
}
return (
<SafeAreaView style={styles.container}>
<View style={styles.logoContainer}>
<Image style={styles.logo} source={logo} />
</View>
<Text style={styles.registerText}>Register</Text>
<ScrollView style={styles.formContainer}>
<View style={styles.inputGroup}>
<TextInput
autoCorrect={false}
autoCapitalize="words"
placeholder="Display Name"
value={this.state.displayName}
onChangeText={(val) => this.updateInputVal(val, 'displayName')}
/>
</View>
<View style={styles.inputGroup}>
<TextInput
placeholder="Email"
autoCorrect={false}
autoCapitalize="none"
value={this.state.email}
keyboardType="email-address"
onChangeText={(val) => this.updateInputVal(val, 'email')}
/>
</View>
<View style={styles.inputGroup}>
<TextInput
maxLength={15}
secureTextEntry
placeholder="<PASSWORD>"
value={this.state.password}
onChangeText={(val) => this.updateInputVal(val, '<PASSWORD>')}
/>
</View>
<View style={styles.button}>
<TouchableOpacity
onPress={() => this.register()}
style={[styles.register, { backgroundColor: colors.jade }]}
>
<AntDesign name="plus" size={24} color={colors.white} />
</TouchableOpacity>
</View>
<View style={styles.text}>
<Text style={styles.signInCont}>Already have an account? </Text>
<TouchableOpacity
onPress={() => this.props.navigation.goBack()}
>
<Text style={styles.signInButton}>
Sign in
</Text>
</TouchableOpacity>
</View>
</ScrollView>
</SafeAreaView>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
logoContainer: {
paddingTop: '20%',
alignItems: 'center',
},
logo: {
width: 150,
height: 150,
},
registerText: {
fontSize: 20,
color: colors.moss,
textAlign: 'center',
paddingVertical: 16,
},
formContainer: {
flex: 1,
padding: 35,
},
inputGroup: {
flex: 1,
marginBottom: 15,
borderBottomWidth: 1,
borderBottomColor: colors.jade,
},
register: {
padding: 16,
borderRadius: 4,
alignItems: 'center',
justifyContent: 'center',
},
button: {
paddingTop: 20,
},
text: {
flexGrow: 1,
marginVertical: 10,
flexDirection: 'row',
alignItems: 'flex-end',
justifyContent: 'center',
},
signInCont: {
fontSize: 16,
color: colors.jade,
},
signInButton: {
fontSize: 16,
fontWeight: '500',
color: colors.moss,
},
});
Register.propTypes = {
navigation: PropTypes.shape({
navigate: PropTypes.func.isRequired,
}).isRequired,
};<file_sep>import {
View,
Text,
Alert,
TextInput,
StyleSheet,
ScrollView,
TouchableOpacity,
ActivityIndicator,
} from 'react-native';
import firebase from 'firebase';
import PropTypes from 'prop-types';
import React, { Component } from 'react';
import * as ImagePicker from 'expo-image-picker';
import { Ionicons, AntDesign, MaterialCommunityIcons } from '@expo/vector-icons';
import colors from '../styles/colors';
export default class AddThingsToKnow extends Component {
constructor() {
super();
this.database = firebase.firestore().collection('thingsToKnow');
this.state = {
img: '',
title: '',
description: '',
isLoading: false,
};
}
inputValueUpdate = (val, prop) => {
const { state } = this;
state[prop] = val;
this.setState(state);
}
onPressButton = () => {
Alert.alert(
'Choose an option',
'Camera or Gallery',
[
{
text: 'Cancel',
onPress: () => console.log('Cancel Pressed'),
style: 'cancel',
},
{
text: 'Camera',
onPress: this.openCamera,
},
{
text: 'Gallery',
onPress: this.openImage,
},
],
{ cancelable: false },
);
}
openCamera = async () => {
const permission = await ImagePicker.requestCameraPermissionsAsync();
if (permission.granted === false) {
return;
}
const picker = await ImagePicker.launchCameraAsync({
base64: true,
allowsEditing: true,
aspect: [1, 1],
});
if (picker.cancelled === true) {
} else if (picker.cancelled === false) {
this.uploadPhoto(picker.uri, this.uid);
}
}
openImage = async () => {
const permission = await ImagePicker.requestCameraRollPermissionsAsync();
if (permission.granted === false) {
return;
}
const picker = await ImagePicker.launchImageLibraryAsync({
base64: true,
allowsEditing: true,
aspect: [1, 1],
});
if (picker.cancelled === true) {
} else if (picker.cancelled === false) {
this.uploadPhoto(picker.uri, this.uid);
}
}
uploadPhoto = async (url, imageName) => {
const time = this.timeAccurate;
const path = `thingsToKnow${imageName}/${time}`;
return new Promise(async (res, rej) => {
const response = await fetch(url);
const file = await response.blob();
const upload = firebase.storage().ref(path).put(file);
upload.on('state_changed', (snapshot) => { }, (err) => {
rej(err);
},
async () => {
const url = await upload.snapshot.ref.getDownloadURL();
res(url);
this.setState({ img: url });
});
});
};
setPickerValue(newValue, othervalue) {
this.setState({
img: `${newValue} (${othervalue})`,
});
this.togglePicker();
}
togglePicker() {
this.setState({
pickerDisplayed: !this.state.pickerDisplayed,
});
}
storeThingsToKnow() {
if (
this.state.img === ''
|| this.state.title === ''
|| this.state.description === ''
) {
alert('Please complete all details');
} else {
this.setState({
isLoading: true,
});
this.database.add({
img: this.state.img,
title: this.state.title,
description: this.state.description,
}).then((res) => {
this.setState({
img: '',
title: '',
description: '',
isLoading: false,
});
this.props.navigation.navigate('viewThingsToKnow');
})
.catch((err) => {
console.error('Error found: ', err);
this.setState({
isLoading: false,
});
});
}
}
render() {
const { navigation } = this.props;
const { navigate } = navigation;
if (this.state.isLoading) {
return (
<View style={styles.preloader}>
<ActivityIndicator size="large" color={colors.night} />
</View>
);
}
return (
<View style={styles.container}>
<View style={styles.header}>
<Ionicons
size={24}
style={styles.back}
name="md-arrow-back"
color={colors.white}
onPress={() => navigation.goBack()}
/>
<Text style={styles.headerText}>Add New Thing To Know</Text>
</View>
<ScrollView style={styles.formContainer}>
<View style={styles.inputGroup}>
<TextInput
numberOfLines={2}
placeholder="Title"
returnKeyType="next"
value={this.state.title}
onChangeText={(val) => this.inputValueUpdate(val, 'title')}
/>
</View>
<View style={styles.inputGroup}>
<TextInput
numberOfLines={2}
returnKeyType="next"
placeholder="Description"
value={this.state.description}
onChangeText={(val) => this.inputValueUpdate(val, 'description')}
/>
</View>
<View style={styles.inputGroup}>
<TouchableOpacity style={styles.button}>
<MaterialCommunityIcons
size={30}
color={colors.fog}
style={styles.camera}
name="camera-plus-outline"
onPress={this.onPressButton}
/>
</TouchableOpacity>
<Text style={{ alignSelf: 'center', color: colors.fog }}>{this.state.img}</Text>
</View>
<View style={styles.button}>
<TouchableOpacity
style={[styles.addRoute, { backgroundColor: colors.night }]}
onPress={() => this.storeThingsToKnow()}
>
<AntDesign name="plus" size={16} color={colors.white} />
</TouchableOpacity>
</View>
</ScrollView>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
header: {
height: 75,
paddingLeft: 10,
flexDirection: 'row',
alignItems: 'center',
backgroundColor: colors.fog,
justifyContent: 'flex-start',
},
headerText: {
fontSize: 22,
width: '80%',
paddingTop: 10,
paddingLeft: 20,
color: colors.white,
},
camera: {
alignSelf: 'flex-start',
},
title: {
fontSize: 25,
color: colors.night,
},
back: {
paddingTop: 20,
paddingLeft: 15,
color: colors.white,
},
formContainer: {
flex: 1,
padding: 35,
},
inputGroup: {
flex: 1,
marginBottom: 15,
borderBottomWidth: 1,
borderBottomColor: colors.night,
},
addRoute: {
padding: 16,
borderRadius: 4,
alignItems: 'center',
justifyContent: 'center',
},
button: {
paddingTop: 20,
},
preloader: {
top: 0,
left: 0,
right: 0,
bottom: 0,
position: 'absolute',
alignItems: 'center',
justifyContent: 'center',
},
});
AddThingsToKnow.propTypes = {
navigation: PropTypes.shape({
goBack: PropTypes.func.isRequired,
navigate: PropTypes.func.isRequired,
}).isRequired,
};
<file_sep>import React, { Component } from 'react';
import {
StyleSheet, Text, View, TouchableOpacity, FlatList, Modal, ActivityIndicator,
} from 'react-native';
import PropTypes from 'prop-types';
import { AntDesign, Ionicons } from '@expo/vector-icons';
import colors from './styles/colors';
import Fire from './firebase/fireFunctions';
import ClimbingToDoList from './climbingToDoList';
import AddClimbingListModal from './addClimbingListModal';
export default class Todo extends Component {
state = {
addClimbingToDoVisible: false,
lists: [],
user: {},
loading: true,
};
componentDidMount() {
firebase = new Fire((error, user) => {
if (error) {
return alert('Something went wrong');
}
firebase.getClimbingLists((lists) => {
this.setState({ lists, user }, () => {
this.setState({ loading: false });
});
});
this.setState({ user });
});
}
componentWillUnmount() {
firebase.detach();
}
toggleAddClimbingToDoModal() {
this.setState({ addClimbingToDoVisible: !this.state.addClimbingToDoVisible });
}
renderList = (list) => <ClimbingToDoList list={list} updateClimbingList={this.updateClimbingList} />;
addClimbingList = (list) => {
firebase.addClimbingList({
name: list.name,
color: list.color,
todos: [],
});
};
updateClimbingList = (list) => {
firebase.updateClimbingList(list);
};
render() {
const { loading, addClimbingToDoVisible, lists } = this.state;
const { navigation } = this.props;
if (loading) {
return (
<View style={styles.container}>
<ActivityIndicator size="large" color={colors.jade} />
</View>
);
}
return (
<View style={styles.container}>
<View style={styles.header}>
<Ionicons
size={24}
style={styles.back}
name="md-arrow-back"
color={colors.white}
onPress={() => navigation.goBack()}
/>
<Text style={styles.headerText}>Todo Lists</Text>
</View>
<Modal
animationType="slide"
visible={addClimbingToDoVisible}
onRequestClose={() => this.toggleAddClimbingToDoModal()}
>
<AddClimbingListModal
addClimbingList={this.addClimbingList}
closeModal={() => this.toggleAddClimbingToDoModal()}
/>
</Modal>
<View style={{ marginTop: 100, alignItems: 'center' }}>
<View>
<Text style={styles.title}> Add New List</Text>
</View>
<View style={{ marginVertical: 30 }}>
<TouchableOpacity
style={styles.addClimbingList}
onPress={() => this.toggleAddClimbingToDoModal()}
>
<AntDesign name="plus" size={16} color={colors.jade} />
</TouchableOpacity>
</View>
<View style={{ height: 320, paddingTop: 20, paddingLeft: 32 }}>
<FlatList
horizontal
data={lists}
keyboardShouldPersistTaps="always"
showsHorizontalScrollIndicator={false}
keyExtractor={(item) => item.id.toString()}
renderItem={({ item }) => this.renderList(item)}
/>
</View>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
header: {
height: 75,
paddingLeft: 10,
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'flex-start',
backgroundColor: colors.jade,
},
headerText: {
fontSize: 25,
paddingTop: 10,
width: '80%',
paddingLeft: 125,
color: colors.white,
},
title: {
fontSize: 25,
color: colors.jade,
},
addClimbingList: {
padding: 16,
borderWidth: 2,
borderRadius: 4,
borderColor: colors.jade,
},
});
Todo.propTypes = {
navigation: PropTypes.shape({
goBack: PropTypes.func.isRequired,
navigate: PropTypes.func.isRequired,
}).isRequired,
};
<file_sep>
import React, { Component } from 'react'
import {
View,
Text,
Alert,
Image,
TextInput,
StyleSheet,
ScrollView,
SafeAreaView,
TouchableOpacity,
} from 'react-native';
import colors from './styles/colors';
import logo from '../images/logo.png';
import * as firebase from 'firebase';
import PropTypes from 'prop-types';
import { AntDesign, Ionicons } from '@expo/vector-icons';
export default class ForgotPassword extends Component {
constructor(props) {
super(props);
this.state = {
emailAddress: ""
};
}
handleEmailChange = email => {
this.setState({ email: email });
};
submitEmail = () => {
firebase
.auth()
.sendPasswordResetEmail(this.state.email)
.then(function () {
Alert.alert("Email Sent");
})
.catch(function (error) {
Alert.alert(error.message);
});
};
render() {
const { navigation } = this.props;
const { navigate } = navigation;
return (
<SafeAreaView style={styles.container}>
<View style={styles.logoContainer}>
<Image style={styles.logo} source={logo} />
</View>
<Text style={styles.loginText}> Forgot your password? </Text>
<ScrollView style={styles.formContainer}>
<Text style={styles.forgotPasswordSubheading}>
Enter your email to find your account
</Text>
<View style={styles.inputGroup}>
<TextInput
autoCorrect={false}
placeholder="Email Address"
autoCapitalize="none"
keyboardType="email-address"
onChangeText={email => this.handleEmailChange(email)}
/>
</View>
<View style={styles.button}>
<TouchableOpacity
style={[styles.forgotPasswordButton, { backgroundColor: colors.jade }]}
onPress={() => this.submitEmail(this.state.email)}
>
<AntDesign name="unlock" size={30} color={colors.white} />
</TouchableOpacity>
<View style={styles.footer}>
<Ionicons
size={45}
style={styles.back}
name="md-arrow-back"
color={colors.jade}
onPress={() => navigation.goBack()}
/>
</View>
</View>
</ScrollView >
</SafeAreaView>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
footer: {
height: 75,
paddingTop: 40,
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'center',
},
forgotPasswordButton: {
borderRadius: 4,
padding: 16,
alignItems: 'center',
justifyContent: 'center',
},
button: {
paddingTop: 20,
},
back: {
color: colors.jade,
},
logoContainer: {
paddingTop: '20%',
alignItems: 'center',
},
inputGroup: {
flex: 1,
marginBottom: 15,
borderBottomWidth: 1,
borderBottomColor: colors.jade,
},
logo: {
width: 150,
height: 150,
},
loginText: {
fontSize: 20,
color: colors.moss,
textAlign: 'center',
paddingVertical: 16,
},
formContainer: {
flex: 1,
padding: 35,
},
inputGroup: {
flex: 1,
marginBottom: 15,
borderBottomWidth: 1,
borderBottomColor: colors.jade,
},
forgotPasswordSubheading: {
fontSize: 18,
fontWeight: "300",
paddingBottom: 30,
color: colors.jade,
},
});
ForgotPassword.propTypes = {
navigation: PropTypes.shape({
goBack: PropTypes.func.isRequired,
navigate: PropTypes.func.isRequired,
}).isRequired,
};
<file_sep>import React from 'react';
import {
View,
Text,
FlatList,
Keyboard,
TextInput,
StyleSheet,
SafeAreaView,
TouchableOpacity,
KeyboardAvoidingView,
} from 'react-native';
import {
AntDesign, Ionicons, MaterialCommunityIcons,
} from '@expo/vector-icons';
import colors from './styles/colors';
export default class ClimbingToDoModal extends React.Component {
state = {
newClimbingToDo: '',
};
toggleClimbingTodoCompleted = (index) => {
const { list } = this.props;
list.todos[index].completed = !list.todos[index].completed;
this.props.updateClimbingList(list);
};
addClimbingToDo = () => {
const { list } = this.props;
if (!list.todos.some((todo) => todo.title === this.state.newClimbingToDo)) {
list.todos.push({ title: this.state.newClimbingToDo, completed: false });
this.props.updateClimbingList(list);
}
this.setState({ newClimbingToDo: '' });
Keyboard.dismiss();
};
deleteClimbingToDo = (index) => {
const { list } = this.props;
list.todos.splice(index, 1);
this.props.updateClimbingList(list);
};
renderTodo = (todo, index) => (
<View style={{ flexDirection: 'row' }}>
<View style={styles.todoContainer}>
<TouchableOpacity onPress={() => this.toggleClimbingTodoCompleted(index)}>
<Ionicons
size={24}
color={colors.dove}
style={{ width: 32 }}
name={todo.completed ? 'ios-square' : 'ios-square-outline'}
/>
</TouchableOpacity>
<Text
style={[
styles.todo,
{
textDecorationLine: todo.completed ? 'line-through' : 'none',
color: todo.completed ? colors.dove : colors.onyx,
},
]}
>
{todo.title}
</Text>
</View>
<View>
<TouchableOpacity
onPress={() => this.deleteClimbingToDo(index)}
style={styles.deleteButton}
>
<MaterialCommunityIcons name="trash-can-outline" size={24} color={colors.onyx} />
</TouchableOpacity>
</View>
</View>
);
render() {
const { list } = this.props;
const taskCount = list.todos.length;
const completedCount = list.todos.filter((todo) => todo.completed).length;
return (
<KeyboardAvoidingView style={{ flex: 1 }} behavior="padding">
<SafeAreaView style={styles.container}>
<TouchableOpacity
style={{
position: 'absolute', top: 64, right: 32, zIndex: 10,
}}
onPress={this.props.closeModal}
>
<AntDesign name="close" size={24} color={colors.onyx} />
</TouchableOpacity>
<View style={[styles.section, styles.header, { borderBottomColor: list.color }]}>
<View>
<Text style={styles.title}>{list.name}</Text>
<Text style={styles.taskCount}>
{completedCount}
{' '}
of
{taskCount}
{' '}
tasks
</Text>
</View>
</View>
<View style={[styles.section, { flex: 3, marginVertical: 16 }]}>
<FlatList
data={list.todos}
keyExtractor={(item) => item.title}
showsVerticalScrollIndicator={false}
renderItem={({ item, index }) => this.renderTodo(item, index)}
/>
</View>
<View style={[styles.section, styles.footer]}>
<TextInput
value={this.state.newClimbingToDo}
style={[styles.input, { borderColor: list.color }]}
onChangeText={(text) => this.setState({ newClimbingToDo: text })}
/>
<TouchableOpacity
onPress={() => this.addClimbingToDo()}
style={[styles.addClimbingToDo, { backgroundColor: list.color }]}
>
<AntDesign name="plus" size={16} color={colors.white} />
</TouchableOpacity>
</View>
</SafeAreaView>
</KeyboardAvoidingView>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
section: {
alignSelf: 'stretch',
},
header: {
marginLeft: 64,
paddingTop: 16,
borderBottomWidth: 3,
justifyContent: 'flex-end',
},
title: {
fontSize: 30,
fontWeight: '800',
color: colors.onyx,
},
taskCount: {
marginTop: 4,
marginBottom: 16,
fontWeight: '600',
color: colors.dove,
},
footer: {
paddingVertical: 16,
flexDirection: 'row',
alignItems: 'center',
paddingHorizontal: 32,
},
input: {
flex: 1,
height: 48,
marginRight: 8,
borderRadius: 6,
paddingHorizontal: 8,
borderWidth: StyleSheet.hairlineWidth,
},
addClimbingToDo: {
padding: 16,
borderRadius: 4,
alignItems: 'center',
justifyContent: 'center',
},
todoContainer: {
width: '90%',
paddingLeft: 32,
paddingVertical: 16,
flexDirection: 'row',
},
deleteButton: {
paddingVertical: 16,
alignSelf: 'flex-end',
},
todo: {
fontSize: 16,
fontWeight: '700',
color: colors.onyx,
},
});
<file_sep>import React, { Component } from 'react';
import {
StyleSheet,
View,
Image,
Text,
SafeAreaView,
} from 'react-native';
import PropTypes from 'prop-types';
import { Fontisto, AntDesign, Ionicons } from '@expo/vector-icons';
import colors from './styles/colors';
import logo from '../images/logo.png';
export default class Support extends Component {
render() {
const { navigation } = this.props;
const { navigate } = navigation;
return (
<SafeAreaView style={styles.container}>
<View style={styles.header}>
<Ionicons
size={24}
style={styles.back}
name="md-arrow-back"
color={colors.white}
onPress={() => navigation.goBack()}
/>
<Text style={styles.headerText}>Support</Text>
</View>
<View style={styles.logoContainer}>
<Image style={styles.logo} source={logo} />
</View>
<View style={[styles.info, { paddingTop: 50 }]}>
<Text>Ask us any questions, and we'll help you find a solution!</Text>
</View>
<View style={styles.info}>
<Text>{'Want us to add a new climbing route location? \nLet us know!'}</Text>
</View>
<Text style={styles.title}>Contact Us</Text>
<View style={styles.info}>
<Fontisto name="email" size={24} style={{ paddingRight: 20 }} />
<Text> <EMAIL></Text>
</View>
<View style={styles.info}>
<AntDesign name="phone" size={24} style={{ paddingRight: 20 }} />
<Text> 028 9097 4669</Text>
</View>
</SafeAreaView>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
header: {
height: 75,
paddingLeft: 10,
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'flex-start',
backgroundColor: colors.jade,
},
headerText: {
fontSize: 25,
paddingTop: 10,
paddingLeft: 120,
color: colors.white,
},
logoContainer: {
paddingTop: '20%',
alignItems: 'center',
},
logo: {
width: 150,
height: 150,
},
back: {
paddingTop: 20,
paddingLeft: 15,
color: colors.white,
},
formContainer: {
flex: 1,
padding: 35,
},
title: {
opacity: 0.9,
fontSize: 25,
marginTop: 40,
color: colors.jade,
textAlign: 'center',
},
info: {
padding: 10,
paddingLeft: 40,
textAlign: 'left',
flexDirection: 'row',
},
});
Support.propTypes = {
navigation: PropTypes.shape({
goBack: PropTypes.func.isRequired,
navigate: PropTypes.func.isRequired,
}).isRequired,
};
<file_sep>import React, { Component } from 'react';
import {
View,
Text,
Alert,
TextInput,
StyleSheet,
TouchableOpacity,
ScrollView,
} from 'react-native';
import * as firebase from 'firebase';
import 'firebase/firestore';
import { Ionicons, AntDesign } from '@expo/vector-icons';
import colors from '../styles/colors';
export default class AddUsers extends Component {
constructor() {
super();
this.state = {
type: '',
email: '',
password: '',
displayName: '',
isLoading: false,
};
}
updateInputVal = (val, prop) => {
const { state } = this;
state[prop] = val;
this.setState(state);
}
register = () => {
if (this.state.email === '' || this.state.password < 7 || this.state.displayName === '' || this.state.displayName === '') {
Alert.alert('Please complete all details to register a user!');
} else {
this.setState({
isLoading: true,
});
firebase
.auth()
.createUserWithEmailAndPassword(this.state.email, this.state.password)
.catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
if (errorCode == 'auth/weak-password') {
Alert.alert('The password is too weak.');
} else if (errorCode == 'auth/email-already-in-use') {
Alert.alert('Email is already in use');
} else if (errorCode == 'auth/invalid-email') {
Alert.alert('Email is invalid');
} else if (errorCode == 'auth/operation-not-allowed') {
Alert.alert('Something has gone wrong!');
} else {
alert(errorMessage);
}
console.log(error);
}).then((res) => {
firebase.firestore().collection('Users').doc(firebase.auth().currentUser.uid).set({
displayName: this.state.displayName,
type: this.state.type,
}),
res.user.updateProfile({
displayName: this.state.displayName,
type: this.state.type,
});
console.log('User Registered Successfully!');
this.setState({
isLoading: false,
displayName: '',
type: '',
email: '',
password: '',
});
Alert.alert('User Registered Successfully!');
this.props.navigation.navigate('viewUsers');
})
.catch((error) => this.setState({ errorMessage: error.message }));
}
}
render() {
const {
isLoading, displayName, type, email, password,
} = this.state;
const { navigation: { goBack } } = this.props;
if (isLoading) {
return (
<View />
);
}
return (
<View style={styles.container}>
<View style={styles.header}>
<Ionicons
size={24}
style={styles.back}
name="md-arrow-back"
color={colors.white}
onPress={() => goBack()}
/>
<Text style={styles.headerText}>Add New User</Text>
</View>
<ScrollView style={styles.formContainer}>
<View style={styles.inputGroup}>
<TextInput
numberOfLines={2}
autoCorrect={false}
value={displayName}
returnKeyType="next"
placeholder="<NAME>"
onChangeText={(val) => this.updateInputVal(val, 'displayName')}
/>
</View>
<View style={styles.inputGroup}>
<TextInput
value={type}
numberOfLines={2}
autoCorrect={false}
returnKeyType="next"
placeholder="User Type (User/Admin)"
onChangeText={(val) => this.updateInputVal(val, 'type')}
/>
</View>
<View style={styles.inputGroup}>
<TextInput
value={email}
numberOfLines={2}
placeholder="Email"
autoCorrect={false}
returnKeyType="next"
autoCapitalize="none"
keyboardType="email-address"
onChangeText={(val) => this.updateInputVal(val, 'email')}
/>
</View>
<View style={styles.inputGroup}>
<TextInput
maxLength={15}
secureTextEntry
value={password}
numberOfLines={2}
returnKeyType="go"
placeholder="Password"
onChangeText={(val) => this.updateInputVal(val, 'password')}
/>
</View>
<View style={styles.button}>
<TouchableOpacity
onPress={() => this.register()}
style={[styles.addRoute, { backgroundColor: colors.glass }]}
>
<AntDesign name="plus" size={16} color={colors.white} />
</TouchableOpacity>
</View>
</ScrollView>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
header: {
height: 75,
paddingLeft: 10,
flexDirection: 'row',
alignItems: 'center',
backgroundColor: colors.fog,
justifyContent: 'flex-start',
},
headerText: {
fontSize: 25,
paddingTop: 10,
width: '80%',
paddingLeft: 80,
color: colors.white,
},
title: {
fontSize: 25,
color: colors.glass,
},
back: {
paddingTop: 20,
paddingLeft: 15,
color: colors.white,
},
formContainer: {
flex: 1,
padding: 35,
},
inputGroup: {
flex: 1,
marginBottom: 15,
borderBottomWidth: 1,
borderBottomColor: colors.glass,
},
addRoute: {
padding: 16,
borderRadius: 4,
alignItems: 'center',
justifyContent: 'center',
},
button: {
paddingTop: 20,
},
preloader: {
top: 0,
left: 0,
right: 0,
bottom: 0,
position: 'absolute',
alignItems: 'center',
justifyContent: 'center',
},
});
| d4c1009c4c0041aa75d0de6a9585166974e779a5 | [
"JavaScript",
"Markdown"
] | 18 | JavaScript | sophiehunsdale/Positive-Altitude | 56c29a4b974f3370d6c84b8ea1b2de459b355abf | 66bb96c60d23a48d40c3f6f32d84798f2a27cbe2 |
refs/heads/master | <file_sep>package util;
import java.util.*;
import java.io.*;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.*;
public class AnalyticsReport {
public static String apikey;
public static String apiurl;
public static String jsonBody;
public static void readJson(String filename) {
try {
File apiFile = new File(filename);
Scanner sc = new Scanner(apiFile);
jsonBody = "";
while (sc.hasNext()) {
jsonBody += sc.nextLine()+"\n";
}
}
catch (Exception e){
System.out.println(e.toString());
}
}
public static void readApiInfo(String filename) {
try {
File apiFile = new File(filename);
Scanner sc = new Scanner(apiFile);
apiurl = sc.nextLine();
apikey = sc.nextLine();
}
catch (Exception e){
System.out.println(e.toString());
}
}
public static String rrsHttpPost() {
HttpPost post;
HttpClient client;
StringEntity entity;
try {
// create HttpPost and HttpClient object
post = new HttpPost(apiurl);
client = HttpClientBuilder.create().build();
// setup output message by copying JSON body into
// apache StringEntity object along with content type
entity = new StringEntity(jsonBody, HTTP.UTF_8);
entity.setContentEncoding(HTTP.UTF_8);
entity.setContentType("text/json");
// add HTTP headers
post.setHeader("Accept", "text/json");
post.setHeader("Accept-Charset", "UTF-8");
// set Authorization header based on the API key
post.setHeader("Authorization", ("Bearer "+apikey));
post.setEntity(entity);
// Call REST API and retrieve response content
HttpResponse authResponse = client.execute(post);
return EntityUtils.toString(authResponse.getEntity());
}
catch (Exception e) {
return e.toString();
}
}
public static void main(String[] args) {
// check for mandatory argments. This program expects 2 arguments
// first argument is full path with file name of JSON file and
// second argument is full path with file name of API file that contains API URL and API Key of request response REST API
try {
// read JSON file name
String jsonFile = "d://data//rrsJson.json";
// read API file name
String apiFile = "d://data//apiInfo.txt";
// call method to read API URL and key from API file
readApiInfo(apiFile);
// call method to read JSON input from the JSON file
readJson(jsonFile);
// print the response from REST API
System.out.println(rrsHttpPost());
}
catch (Exception e) {
System.out.println(e.toString());
}
}
}
| 20761f8c6aa945abf3cbeca24c684b0fdc42370f | [
"Java"
] | 1 | Java | PradiptoCodes/JsonCodesSendToAzure | 362e698cb6103663fe20202c4f437b2432049fb2 | a12daef64dc0ab404b9926719b398a7a14101720 |
refs/heads/master | <repo_name>peterlundkvist/MenuParser<file_sep>/src/main/java/se/mycompany/foodmenu/model/MyMenu.java
package se.mycompany.foodmenu.model;
import com.fasterxml.jackson.annotation.JsonRootName;
import java.util.List;
/**
* Created by peter on 2017-02-03.
*/
@JsonRootName(value = "breakfast_menu")
public class MyMenu {
public List<MyFood> getFood() {
return food;
}
public void setFood(List<MyFood> food) {
this.food = food;
}
private List<MyFood> food;
}
<file_sep>/src/main/java/se/mycompany/Menu.java
package se.mycompany;
import org.apache.commons.io.FileUtils;
import se.mycompany.foodmenu.model.MyFood;
import se.mycompany.foodmenu.model.MyMenu;
import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
/**
* Created by peter on 2017-02-03.
*/
public class Menu {
enum SortOrder { asc, desc }
private static SortOrder ordering;
public static void main(String[] args) throws IOException {
if(args == null || args.length != 2) {
throw new IllegalArgumentException("Please specify these arguments: [json-file|xml-file] [asc|desc]");
}
ordering = SortOrder.valueOf(args[1]);
new Menu().readFile(args[0], args[1]);
}
public void readFile(String fileName, String sortOrder) throws IOException {
MenuParser parser = getSuitableParser(fileName);
String fileContents = FileUtils.readFileToString(new File(fileName));
MyMenu menu = parser.parse(fileContents);
List<MyFood> foodList = menu.getFood();
Collections.sort(foodList);
if(ordering.equals(SortOrder.desc))
Collections.reverse(foodList);
for(MyFood pf : foodList) {
System.out.println(pf);
}
}
private MenuParser getSuitableParser(String fileName) {
if(fileName.indexOf(".json") > 0)
return new JsonParser();
else if(fileName.indexOf(".xml") > 0)
return new XmlParser();
else
throw new IllegalArgumentException("Unknown file type: " + fileName);
}
}
<file_sep>/pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>se.mycompany</groupId>
<artifactId>menu-reader</artifactId>
<version>1.0-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<groupId>com.jolira</groupId>
<artifactId>onejar-maven-plugin</artifactId>
<version>1.4.4</version>
<executions>
<execution>
<goals>
<goal>one-jar</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.0.2</version>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<mainClass>se.mycompany.Menu</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>jaxb2-maven-plugin</artifactId>
<version>2.3</version>
<executions>
<execution>
<id>xjc</id>
<goals>
<goal>xjc</goal>
</goals>
</execution>
</executions>
<configuration>
<!-- The package of your generated sources -->
<packageName>se.mycompany.foodmenu.model.jaxb</packageName>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.2</version>
</dependency>
</dependencies>
</project><file_sep>/src/test/java/se/mycompany/JsonParserTest.java
package se.mycompany;
import org.junit.Test;
import se.mycompany.foodmenu.model.MyMenu;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Paths;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
/**
* Created by peter on 2017-02-03.
*/
public class JsonParserTest {
@Test
public void parseJsonFile() throws URISyntaxException, IOException {
String fileContents = new String(Files.readAllBytes(Paths.get(getClass().getResource("/menu.json").toURI())));
MenuParser menuParser = new JsonParser();
MyMenu breakfastMenu = menuParser.parse(fileContents);
assertEquals(5, breakfastMenu.getFood().size());
}
}
<file_sep>/README.md
# Dagens meny
Litet program som läser in maträtter från en json- eller xml-fil och skriver ut dagens meny i stigande eller fallande ordning.
### Systemkrav
Maven och Java 8
### Start Från kommando-prompt
java -jar target/menu-reader-1.0-SNAPSHOT.one-jar.jar src/test/resources/menu.xml asc
java -jar target/menu-reader-1.0-SNAPSHOT.one-jar.jar src/test/resources/menu.xml desc
java -jar target/menu-reader-1.0-SNAPSHOT.one-jar.jar src/test/resources/menu.json asc
java -jar target/menu-reader-1.0-SNAPSHOT.one-jar.jar src/test/resources/menu.json desc
<file_sep>/src/test/java/se/mycompany/XmlParserTest.java
package se.mycompany;
import org.junit.Test;
import se.mycompany.foodmenu.model.MyMenu;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Paths;
import static org.junit.Assert.assertEquals;
/**
* Created by peter on 2017-02-03.
*/
public class XmlParserTest {
@Test
public void parseXmlFile() throws URISyntaxException, IOException {
String fileContents = new String(Files.readAllBytes(Paths.get(getClass().getResource("/menu.xml").toURI())));
MenuParser menuParser = new XmlParser();
MyMenu breakfastMenu = menuParser.parse(fileContents);
assertEquals(5, breakfastMenu.getFood().size());
}
}
| d39de0afda99751923cec48e63a2c8ff865e5926 | [
"Markdown",
"Java",
"Maven POM"
] | 6 | Java | peterlundkvist/MenuParser | 3b23d352ab430d349c16906bb474b1e187ccc2fd | 079783fd3ec86b05bd04020a07db3a2397c55c69 |
refs/heads/master | <file_sep><?php
session_start ();
include"database.php";
$people=$_SESSION['people'];
$equipe=$_POST['equipe'];
$_SESSION['equipe']=$equipe;
for($i=1;$i<21;$i++){
$q=$db->prepare("UPDATE`equipes`SET`NAME`=0,`Manche1`=0,`Manche2`=0,`Manche3`=0,`Finale`=0,`LIVE`=0,`NEXT`=0,`POOL`=0,`POOL2`=0,`POOL3`=0,`POOL4`=0 WHERE ID='$i' ");
$q->execute();
}
for($i=1;$i<$people+1;$i++){
$l=$i-1;
$name=$equipe[$l];
echo $name;
$q=$db->prepare("UPDATE `equipes` SET NAME='$name' WHERE ID='$i' ");
$q->execute();
$q->closeCursor();
}
header('Location: http://localhost/BeerPong/ranking.php');
die();
?>
<file_sep><?php
define('DB_HOST','localhost');
define('DB_NAME','beerpong');
define('DB_USERNAME','root');
define('DB_PASSWORD','<PASSWORD>');
try{
$db=new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME.";charset=utf8",DB_USERNAME,DB_PASSWORD);
$db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e){
die(' Une erreur est survenue: '.$e->getMessage());
}
?>
<file_sep># OddTournamentOfBeerPong
This is a snipet of code in php for managing a tournament with odd or even teams. The code will be optimized for the beer-pong where you cannot have draw.
The code is under developpement and is not finished yet :)
<file_sep><?php
session_start();
$people=$_POST['people'];
$_SESSION['people']=$people;
$m1=$people;
$_SESSION['m1']=$m1;
$m2=floor($m1/2);
$_SESSION['m2']=$m2;
$m3=floor($m2/2);
$_SESSION['m3']=$m3;
$m4=floor($m3/2);
$_SESSION['m4']=$m4;
$m5=floor($m4/2);
$_SESSION['m5']=$m5;
echo "<form method=post action='update.php'>";
for($i=1;$i<$people+1;$i++){
echo "<input type='text' name='equipe[]' value='équipe ",$i,"'> Equipe ",$i,"<br>";
}
echo "<br><input type='submit' value='Lancer le tournoi!'></form>";
?>
<file_sep><?php
function amax($array){
if(is_array($array)){
$best=null;
foreach($array as $key => $value){
//echo $key;
//echo $value;
if($value==max($array)){
echo $key;
}
}
return $key;
}else{
return $array;
}
}
function notempty($value,$needle){
if(!empty($value)){
echo (in_array($needle, $value))? 'checked':'';
}
}
function wichwin($player1,$player2,$set){
if(in_array($player1, $set)){
return $player1;
}elseif(in_array($player2,$set)){
return $player2;
}else{
return false;
}
}
function wichlose($player1,$player2,$set){
if(in_array($player1, $set)){
return $player2;
}elseif(in_array($player2,$set)){
return $player1;
}else{
return false;
}
}
function winat3($player1,$player2,$player3,$set){
return True;
}
function Howmanypools($players){
if($players%2==0){return $players/2;}else{return floor($players/2);}
}
?><file_sep><html>
<head>
<title>Management of the Tournament</title>
<meta charset="utf-8">
</head>
<body>
<h1>Fenêtre secrète de l'organisateur</h1>
<?php
//initialisation
session_start();
require "functions.php";
include "database.php";
$m1=$_SESSION['people'];
$m2=$_SESSION['m2'];
$m3=$_SESSION['m3'];
$m4=$_SESSION['m4'];
$m5=$_SESSION['m5'];
$poolst1=array();
$teamm1=$_SESSION['equipe'];
//premiere Manche
//répartition des joueurs dans les pools au 1er tour
if($m1%2==0){
$j=0;
for($i=0;$i<($m1/2);$i++){
$l=$i+1;
for($k=0;$k<2;$k++){
$poolst1[$i][]=$teamm1[$j];
$j++;
}
}
$j=1;
$l=1;
for($i=0;$i<$m1/2;$i++){
for($k=0;$k<2;$k++){
$q=$db->prepare("UPDATE `equipes` SET POOL='$j' WHERE ID=$l");
$q->execute();
$q->closeCursor();
$l++;
}
$j++;
}
// questionnaire sur les qualifications du T1:
echo "<div id='t1'><h2>Tour 1: </h2><br><form method='post'>";
for($i=0;$i<$m1/2;$i++){
if(empty($_POST['t1'])){$_POST['t1']=[];}
echo $poolst1[$i][0]." VS ".$poolst1[$i][1],"<br>";
echo "<input type='radio' name='t1[]",$i+1,"' value='",$poolst1[$i][0],"' ",notempty($_POST['t1'],$poolst1[$i][0]),"> ",$poolst1[$i][0],"<br>";
echo "<input type='radio' name='t1[]",$i+1,"' value='",$poolst1[$i][1],"' ",notempty($_POST['t1'],$poolst1[$i][1]),"> ",$poolst1[$i][1],"<br>";
if(!empty($_POST['t1'])){
$winner=wichwin($poolst1[$i][0],$poolst1[$i][1],$_POST['t1']);
$loser=wichlose($poolst1[$i][0],$poolst1[$i][1],$_POST['t1']);
$q=$db->prepare("UPDATE `equipes` SET Manche1='1' WHERE NAME='$winner' ");
$q->execute();
$q=$db->prepare("UPDATE `equipes` SET Manche1='0' WHERE NAME='$loser' ");
$q->execute();
$q->closeCursor();
}
}
echo "<input type='submit' name='Qui a gagné?'></form></div>";
if(!empty($_POST['t1'])){
$teamm2=$_POST['t1'];
$_SESSION['teamm2']=$_POST['t1'];
}
}else{
$j=0;
for($i=0;$i<(floor($m1/2)-1);$i++){
$l=$i+1;
for($k=0;$k<2;$k++){
$poolst1[$i][]=$teamm1[$j];
$j++;
}
}
$j=1;
$l=1;
for($i=0;$i<$m1/2-2;$i++){
for($k=0;$k<2;$k++){
$q=$db->prepare("UPDATE `equipes` SET POOL='$j' WHERE ID=$l");
$q->execute();
$q->closeCursor();
$l++;
}
$j++;
}
$s=$j;
$p=$l;
$j=$m1-3;
for($i=$i;$i<($m1/2)-1;$i++){
for($k=0;$k<3;$k++){
$poolst1[$i][]=$teamm1[$j];
$j++;
$q=$db->prepare("UPDATE `equipes` SET POOL='$s' WHERE ID=$p");
$q->execute();
$q->closeCursor();
$p++;
}
}
// questionnaire sur les qualifications du T1:
echo "<div id='t1'><h2>Tour 1: </h2><br><form method='post'>";
if(empty($_POST['t1'])){$_POST['t1']=[];}
for($i=0;$i<($m1-3)/2;$i++){
echo $poolst1[$i][0]." VS ".$poolst1[$i][1],"<br>";
echo "<input type='radio' name='t1[]",$i+1,"' value='",$poolst1[$i][0],"' ",notempty($_POST['t1'],$poolst1[$i][0]),"> ",$poolst1[$i][0],"<br>";
echo "<input type='radio' name='t1[]",$i+1,"' value='",$poolst1[$i][1],"' ",notempty($_POST['t1'],$poolst1[$i][1]),"> ",$poolst1[$i][1],"<br>";
$winner=wichwin($poolst1[$i][0],$poolst1[$i][1],$_POST['t1']);
$loser=wichlose($poolst1[$i][0],$poolst1[$i][1],$_POST['t1']);
$q=$db->prepare("UPDATE `equipes` SET Manche1='1' WHERE NAME='$winner' ");
$q->execute();
$q=$db->prepare("UPDATE `equipes` SET Manche1='0' WHERE NAME='$loser' ");
$q->execute();
$q->closeCursor();
}
if(empty($_POST['ti11'])){$_POST['ti11']=[];}
if(empty($_POST['ti12'])){$_POST['ti12']=[];}
if(empty($_POST['ti13'])){$_POST['ti13']=[];}
for($i=($m1-3)/2;$i<(($m1-3)/2)+1;$i++){
$p=$i+1;
echo $poolst1[$i][0]." VS ".$poolst1[$i][1],"<br>";
echo "<input type='radio' name='ti11[]",$p,"' value='",$poolst1[$i][0],"' ",notempty($_POST['ti11'],$poolst1[$i][0]),"> ",$poolst1[$i][0],"<br>";
echo "<input type='radio' name='ti11[]",$p,"' value='",$poolst1[$i][1],"' ",notempty($_POST['ti11'],$poolst1[$i][1]),"> ",$poolst1[$i][1],"<br>";
echo $poolst1[$i][1]." VS ".$poolst1[$i][2],"<br>";
echo "<input type='radio' name='ti12[]",$p+1,"' value='",$poolst1[$i][1],"' ",notempty($_POST['ti12'],$poolst1[$i][1]),"> ",$poolst1[$i][1],"<br>";
echo "<input type='radio' name='ti12[]",$p+1,"' value='",$poolst1[$i][2],"' ",notempty($_POST['ti12'],$poolst1[$i][2]),"> ",$poolst1[$i][2],"<br>";
echo $poolst1[$i][0]." VS ".$poolst1[$i][2],"<br>";
echo "<input type='radio' name='ti13[]",$p+2,"' value='",$poolst1[$i][0],"' ",notempty($_POST['ti13'],$poolst1[$i][0]),"> ",$poolst1[$i][0],"<br>";
echo "<input type='radio' name='ti13[]",$p+2,"' value='",$poolst1[$i][2],"' ",notempty($_POST['ti13'],$poolst1[$i][2]),"> ",$poolst1[$i][2],"<br>";
}
echo "<input type='submit' name='Qui a gagné?'></form></div>";
if(!empty($_POST['ti11'])&&!empty($_POST['ti12'])&&!empty($_POST['ti13'])){
$ti11=$_POST['ti11'];
$ti12=$_POST['ti12'];
$ti13=$_POST['ti13'];
$a=array_count_values($ti11);
$b=array_count_values($ti12);
$c=array_count_values($ti13);
$total=array_merge($ti11,$ti12,$ti13);
$vovo=array_count_values($total);
if(max($vovo)==1){
$teamm2=$_POST['t1'];
$random=$total[rand(0,2)];
$winner=$random;
$q=$db->prepare("UPDATE `equipes` SET Manche1='0' WHERE POOL='$m2'");
$q->execute();
$q=$db->prepare("UPDATE `equipes` SET Manche1='1' WHERE NAME='$winner' ");
$q->execute();
$q->closeCursor();
$teamm2[]=$random;
$_SESSION['teamm2']=$teamm2;
}
else{
$d=array_search(max($vovo),$vovo);
$teamm2=$_POST['t1'];
$teamm2[]=$d;
//$q=$db->prepare("UPDATE `equipes` SET Manche1='0' WHERE POOL='$m2'");
//$q->execute();
$q=$db->prepare("UPDATE `equipes` SET Manche1='1' WHERE NAME='$d' ");
$q->execute();
$_SESSION['teamm2']=$teamm2;
}
}
}
$test=count($poolst1,COUNT_RECURSIVE);
//Deuxième manche
$poolst2=array();
//répartition des équipes dans les pools au 2eme tour
if(isset($_SESSION['teamm2'])){$count=count($_SESSION['teamm2']);}else{$count=0;}
if(!empty($_SESSION['teamm2'])&&$test>=4&&$count==$m2){
if($m2%2==0){
$j=0;
for($i=0;$i<($m2/2);$i++){
for($k=0;$k<2;$k++){
$poolst2[$i][]=$_SESSION['teamm2'][$j];
$j++;
}
}
$ko=1;
for($i=0;$i<$m3;$i++){
for($j=0;$j<2;$j++){
$name=$poolst2[$i][$j];
$q=$db->prepare("UPDATE `equipes` SET POOL2='$ko' WHERE NAME='$name'");
$q->execute();
$q->closeCursor();
}
$ko++;
}
// questionnaire sur les qualifications du T2:
echo "<div id='t2'><h2>Tour 2: </h2><br><form method='post'>";
if(empty($_POST['t2'])){$_POST['t2']=[];}
for($i=0;$i<$m2/2;$i++){
echo $poolst2[$i][0]." VS ".$poolst2[$i][1],"<br>";
echo "<input type='radio' name='t2[]",$i+1,"' value='",$poolst2[$i][0],"' ",notempty($_POST['t2'],$poolst2[$i][0]),"> ",$poolst2[$i][0],"<br>";
echo "<input type='radio' name='t2[]",$i+1,"' value='",$poolst2[$i][1],"' ",notempty($_POST['t2'],$poolst2[$i][1]),"> ",$poolst2[$i][1],"<br>";
if(!empty($_POST['t2'])){
$winner=wichwin($poolst2[$i][0],$poolst2[$i][1],$_POST['t2']);
$loser=wichlose($poolst2[$i][0],$poolst2[$i][1],$_POST['t2']);
$q=$db->prepare("UPDATE `equipes` SET Manche2='1' WHERE NAME='$winner' ");
$q->execute();
$q=$db->prepare("UPDATE `equipes` SET Manche2='0' WHERE NAME='$loser' ");
$q->execute();
$q->closeCursor();
}
}
echo "<input type='submit' name='Qui a gagné?'></form><br></div>";
if(!empty($_POST['t2'])){
$teamm3=$_POST['t2'];
$_SESSION['teamm3']=$_POST['t2'];
}
}else{
$j=0;
for($i=0;$i<(floor($m2/2)-1);$i++){
$l=$i+1;
for($k=0;$k<2;$k++){
$poolst2[$i][]=$_SESSION['teamm2'][$j];
$j++;
}
}
$ko=1;
for($i=0;$i<$m2/2-2;$i++){
for($k=0;$k<2;$k++){
$name=$poolst2[$i][$k];
$q=$db->prepare("UPDATE `equipes` SET POOL2='$ko' WHERE NAME='$name'");
$q->execute();
$q->closeCursor();
}
$ko++;
}
$j=$m2-3;
for($i=$i;$i<($m2/2)-1;$i++){
for($k=0;$k<3;$k++){
$poolst2[$i][]=$_SESSION['teamm2'][$j];
$j++;
$name=$poolst2[$i][$k];
$q=$db->prepare("UPDATE `equipes` SET POOL2='$ko' WHERE NAME='$name'");
$q->execute();
$q->closeCursor();
}
}
// questionnaire sur les qualifications du T2:
echo "<div id='t2'><h2>Tour 2: </h2><br><form method='post'>";
if($m2>3){
if(empty($_POST['t2'])){$_POST['t2']=[];}
for($i=0;$i<($m2-3)/2;$i++){
echo $poolst2[$i][0]." VS ".$poolst2[$i][1],"<br>";
echo "<input type='radio' name='t2[]",$i+1,"' value='",$poolst2[$i][0],"' ",notempty($_POST['t2'],$poolst2[$i][0]),"> ",$poolst2[$i][0],"<br>";
echo "<input type='radio' name='t2[]",$i+1,"' value='",$poolst2[$i][1],"' ",notempty($_POST['t2'],$poolst2[$i][1]),"> ",$poolst2[$i][1],"<br>";
$winner=wichwin($poolst2[$i][0],$poolst2[$i][1],$_POST['t2']);
$loser=wichlose($poolst2[$i][0],$poolst2[$i][1],$_POST['t2']);
$q=$db->prepare("UPDATE `equipes` SET Manche2='1' WHERE NAME='$winner' ");
$q->execute();
$q=$db->prepare("UPDATE `equipes` SET Manche2='0' WHERE NAME='$loser' ");
$q->execute();
$q->closeCursor();
}
}else{
$_POST['t2']=[];
}
if(empty($_POST['ti21'])){$_POST['ti21']=[];}
if(empty($_POST['ti22'])){$_POST['ti22']=[];}
if(empty($_POST['ti23'])){$_POST['ti23']=[];}
for($i=($m2-3)/2;$i<(($m2-3)/2)+1;$i++){
$p=$i+1;
echo $poolst2[$i][0]." VS ".$poolst2[$i][1],"<br>";
echo "<input type='radio' name='ti21[]",$p,"' value='",$poolst2[$i][0],"' ",notempty($_POST['ti21'],$poolst2[$i][0]),"> ",$poolst2[$i][0],"<br>";
echo "<input type='radio' name='ti21[]",$p,"' value='",$poolst2[$i][1],"' ",notempty($_POST['ti21'],$poolst2[$i][1]),"> ",$poolst2[$i][1],"<br>";
echo $poolst2[$i][1]." VS ".$poolst2[$i][2],"<br>";
echo "<input type='radio' name='ti22[]",$p+1,"' value='",$poolst2[$i][1],"' ",notempty($_POST['ti22'],$poolst2[$i][1]),"> ",$poolst2[$i][1],"<br>";
echo "<input type='radio' name='ti22[]",$p+1,"' value='",$poolst2[$i][2],"' ",notempty($_POST['ti22'],$poolst2[$i][2]),"> ",$poolst2[$i][2],"<br>";
echo $poolst2[$i][0]." VS ".$poolst2[$i][2],"<br>";
echo "<input type='radio' name='ti23[]",$p+2,"' value='",$poolst2[$i][0],"' ",notempty($_POST['ti23'],$poolst2[$i][0]),"> ",$poolst2[$i][0],"<br>";
echo "<input type='radio' name='ti23[]",$p+2,"' value='",$poolst2[$i][2],"' ",notempty($_POST['ti23'],$poolst2[$i][2]),"> ",$poolst2[$i][2],"<br>";
}
echo "<input type='submit' name='Qui a gagné?'></form></div>";
if(!empty($_POST['ti21'])&&!empty($_POST['ti22'])&&!empty($_POST['ti23'])){
$ti21=$_POST['ti21'];
$ti22=$_POST['ti22'];
$ti23=$_POST['ti23'];
$a=array_count_values($ti21);
$b=array_count_values($ti22);
$c=array_count_values($ti23);
$total=array_merge($ti21,$ti22,$ti23);
$vovo=array_count_values($total);
if(max($vovo)==1){
$teamm3=$_POST['t2'];
$random=$total[rand(0,2)];
$teamm3[]=$random;
$winner=$random;
$q=$db->prepare("UPDATE `equipes` SET Manche2='0' WHERE POOL='$m3'");
$q->execute();
$q=$db->prepare("UPDATE `equipes` SET Manche2='1' WHERE NAME='$winner' ");
$q->execute();
$q->closeCursor();
$_SESSION['teamm3']=$teamm3;
}
else{
$d=array_search(max($vovo),$vovo);
$teamm3=$_POST['t2'];
$teamm3[]=$d;
//$q=$db->prepare("UPDATE `equipes` SET Manche2='0' WHERE POOL='$m3'");
//$q->execute();
$q=$db->prepare("UPDATE `equipes` SET Manche2='1' WHERE NAME='$d' ");
$q->execute();
$_SESSION['teamm3']=$teamm3;
}
}
}
$test=count($poolst2,COUNT_RECURSIVE);
}
//Troisième manche
$poolst3=array();
//répartition des équipes dans les pools au 3eme tour
if(isset($_SESSION['teamm3'])){$count=count($_SESSION['teamm3']);}else{$count=0;}
if(!empty($_SESSION['teamm3'])&&$test>=4&&$count==$m3){
if($m3%2==0){
$j=0;
for($i=0;$i<($m3/2);$i++){
$l=$i+1;
for($k=0;$k<2;$k++){
$poolst3[$i][]=$_SESSION['teamm3'][$j];
$j++;
}
}
$ko=1;
for($i=0;$i<$m4;$i++){
for($j=0;$j<2;$j++){
$name=$poolst3[$i][$j];
$q=$db->prepare("UPDATE `equipes` SET POOL3='$ko' WHERE NAME='$name'");
$q->execute();
$q->closeCursor();
}
$ko++;
}
// questionnaire sur les qualifications du T3:
echo "<div id='t3'><h2>Tour 3: </h2><br><form method='post'>";
if(empty($_POST['t3'])){$_POST['t3']=[];}
for($i=0;$i<$m3/2;$i++){
echo $poolst3[$i][0]." VS ".$poolst3[$i][1],"<br>";
echo "<input type='radio' name='t3[]",$i+1,"' value='",$poolst3[$i][0],"' ",notempty($_POST['t3'],$poolst3[$i][0]),"> ",$poolst3[$i][0],"<br>";
echo "<input type='radio' name='t3[]",$i+1,"' value='",$poolst3[$i][1],"' ",notempty($_POST['t3'],$poolst3[$i][1]),"> ",$poolst3[$i][1],"<br>";
if(!empty($_POST['t3'])){
$winner=wichwin($poolst3[$i][0],$poolst3[$i][1],$_POST['t3']);
$loser=wichlose($poolst3[$i][0],$poolst3[$i][1],$_POST['t3']);
$q=$db->prepare("UPDATE `equipes` SET Manche3='1' WHERE NAME='$winner' ");
$q->execute();
$q=$db->prepare("UPDATE `equipes` SET Manche3='0' WHERE NAME='$loser' ");
$q->execute();
$q->closeCursor();
}
}
echo "<input type='submit' name='Qui a gagné?'></form></div>";
if(!empty($_POST['t3'])){
$teamm4=$_POST['t3'];
$_SESSION['teamm4']=$teamm4;
}
}else{
$j=0;
for($i=0;$i<(floor($m3/2)-1);$i++){
$l=$i+1;
for($k=0;$k<2;$k++){
$poolst3[$i][]=$_SESSION['teamm3'][$j];
$j++;
}
}
$ko=1;
for($i=0;$i<$m3/2-2;$i++){
for($k=0;$k<2;$k++){
$name=$poolst3[$i][$k];
$q=$db->prepare("UPDATE `equipes` SET POOL3='$ko' WHERE NAME='$name'");
$q->execute();
$q->closeCursor();
}
$ko++;
}
$j=$m3-3;
for($i=$i;$i<($m3/2)-1;$i++){
for($k=0;$k<3;$k++){
$poolst3[$i][]=$_SESSION['teamm3'][$j];
$j++;
$name=$poolst3[$i][$k];
$q=$db->prepare("UPDATE `equipes` SET POOL3='$ko' WHERE NAME='$name'");
$q->execute();
$q->closeCursor();
}
}
// questionnaire sur les qualifications du T3:
echo "<div id='t3'><h2>Tour 3: </h2><br><form method='post'>";
if($m3>3){
if(empty($_POST['t3'])){$_POST['t3']=[];}
for($i=0;$i<($m3-3)/2;$i++)
{
echo $poolst3[$i][0]." VS ".$poolst3[$i][1],"<br>";
echo "<input type='radio' name='t3[]",$i+1,"' value='",$poolst3[$i][0],"' ",notempty($_POST['t3'],$poolst3[$i][0]),"> ",$poolst3[$i][0],"<br>";
echo "<input type='radio' name='t3[]",$i+1,"' value='",$poolst3[$i][1],"' ",notempty($_POST['t3'],$poolst3[$i][1]),"> ",$poolst3[$i][1],"<br>";
$winner=wichwin($poolst3[$i][0],$poolst3[$i][1],$_POST['t3']);
$loser=wichlose($poolst3[$i][0],$poolst3[$i][1],$_POST['t3']);
$q=$db->prepare("UPDATE `equipes` SET Manche3='1' WHERE NAME='$winner' ");
$q->execute();
$q=$db->prepare("UPDATE `equipes` SET Manche3='0' WHERE NAME='$loser' ");
$q->execute();
$q->closeCursor();
}
}else{
$_POST['t3']=[];
}
if(empty($_POST['ti31'])){$_POST['ti31']=[];}
if(empty($_POST['ti32'])){$_POST['ti32']=[];}
if(empty($_POST['ti33'])){$_POST['ti33']=[];}
for($i=($m3-3)/2;$i<(($m3-3)/2)+1;$i++){
$p=$i+1;
echo $poolst3[$i][0]." VS ".$poolst3[$i][1],"<br>";
echo "<input type='radio' name='ti31[]",$p,"' value='",$poolst3[$i][0],"' ",notempty($_POST['ti31'],$poolst3[$i][0]),"> ",$poolst3[$i][0],"<br>";
echo "<input type='radio' name='ti31[]",$p,"' value='",$poolst3[$i][1],"' ",notempty($_POST['ti31'],$poolst3[$i][1]),"> ",$poolst3[$i][1],"<br>";
echo $poolst3[$i][1]." VS ".$poolst3[$i][2],"<br>";
echo "<input type='radio' name='ti32[]",$p+1,"' value='",$poolst3[$i][1],"' ",notempty($_POST['ti32'],$poolst3[$i][1]),"> ",$poolst3[$i][1],"<br>";
echo "<input type='radio' name='ti32[]",$p+1,"' value='",$poolst3[$i][2],"' ",notempty($_POST['ti32'],$poolst3[$i][2]),"> ",$poolst3[$i][2],"<br>";
echo $poolst3[$i][0]." VS ".$poolst3[$i][2],"<br>";
echo "<input type='radio' name='ti33[]",$p+2,"' value='",$poolst3[$i][0],"' ",notempty($_POST['ti33'],$poolst3[$i][0]),"> ",$poolst3[$i][0],"<br>";
echo "<input type='radio' name='ti33[]",$p+2,"' value='",$poolst3[$i][2],"' ",notempty($_POST['ti33'],$poolst3[$i][2]),"> ",$poolst3[$i][2],"<br>";
}
echo "<input type='submit' name='Qui a gagné?'></form></div>";
if(!empty($_POST['ti31'])&&!empty($_POST['ti32'])&&!empty($_POST['ti33'])){
$ti31=$_POST['ti31'];
$ti32=$_POST['ti32'];
$ti33=$_POST['ti33'];
$a=array_count_values($ti31);
$b=array_count_values($ti32);
$c=array_count_values($ti33);
$total=array_merge($ti31,$ti32,$ti33);
$vovo=array_count_values($total);
if(max($vovo)==1){
$teamm4=$_POST['t3'];
$random=$total[rand(0,2)];
$teamm4[]=$random;
$winner=$random;
$q=$db->prepare("UPDATE `equipes` SET Manche3='0' WHERE POOL='$m4'");
$q->execute();
$q=$db->prepare("UPDATE `equipes` SET Manche3='1' WHERE NAME='$winner' ");
$q->execute();
$q->closeCursor();
$_SESSION['teamm4']=$teamm4;
}
else{
$d=array_search(max($vovo),$vovo);
$teamm4=$_POST['t3'];
$teamm4[]=$d;
//$q=$db->prepare("UPDATE `equipes` SET Manche3='0' WHERE POOL='$m4'");
//$q->execute();
$q=$db->prepare("UPDATE `equipes` SET Manche3='1' WHERE NAME='$d' ");
$q->execute();
$_SESSION['teamm4']=$teamm4;
}
}
}
$test=count($poolst3,COUNT_RECURSIVE);
}
//Quatrième manche
$poolst4=array();
//répartition des équipes dans les pools au 4eme tour
if(isset($_SESSION['teamm4'])){$count=count($_SESSION['teamm4']);}else{$count=0;}
if(!empty($_SESSION['teamm4'])&&$test>=4&&$count==$m4){
if($m4%2==0){
$j=0;
for($i=0;$i<($m4/2);$i++){
$l=$i+1;
for($k=0;$k<2;$k++){
$poolst4[$i][]=$_SESSION['teamm4'][$j];
$j++;
}
}
$ko=1;
for($i=0;$i<$m5;$i++){
for($j=0;$j<2;$j++){
$name=$poolst4[$i][$j];
$q=$db->prepare("UPDATE `equipes` SET POOL4='$ko' WHERE NAME='$name'");
$q->execute();
$q->closeCursor();
}
$ko++;
}
// questionnaire sur les qualifications du T4:
echo "<div id='t4'><h2>Tour 4: </h2><br><form method='post'>";
if(empty($_POST['t4'])){$_POST['t4']=[];}
for($i=0;$i<$m4/2;$i++){
echo $poolst4[$i][0]." VS ".$poolst4[$i][1],"<br>";
echo "<input type='radio' name='t4[]",$i+1,"' value='",$poolst4[$i][0],"' ",notempty($_POST['t4'],$poolst4[$i][0]),"> ",$poolst4[$i][0],"<br>";
echo "<input type='radio' name='t4[]",$i+1,"' value='",$poolst4[$i][1],"' ",notempty($_POST['t4'],$poolst4[$i][1]),"> ",$poolst4[$i][1],"<br>";
if(!empty($_POST['t4'])){
$winner=wichwin($poolst4[$i][0],$poolst4[$i][1],$_POST['t4']);
$loser=wichlose($poolst4[$i][0],$poolst4[$i][1],$_POST['t4']);
$q=$db->prepare("UPDATE `equipes` SET Finale='1' WHERE NAME='$winner' ");
$q->execute();
$q=$db->prepare("UPDATE `equipes` SET Finale='0' WHERE NAME='$loser' ");
$q->execute();
$q->closeCursor();
}
}
echo "<input type='submit' name='Qui a gagné?'></form></div>";
}else{
$j=0;
for($i=0;$i<(floor($m4/2)-1);$i++){
$l=$i+1;
for($k=0;$k<2;$k++){
$poolst4[$i][]=$_SESSION['teamm4'][$j];
$j++;
}
}
$ko=1;
for($i=0;$i<$m4/2-2;$i++){
for($k=0;$k<2;$k++){
$name=$poolst4[$i][$k];
$q=$db->prepare("UPDATE `equipes` SET Finale='$ko' WHERE NAME='$name'");
$q->execute();
$q->closeCursor();
}
$ko++;
}
$j=$m4-3;
for($i=$i;$i<($m4/2)-1;$i++){
for($k=0;$k<3;$k++){
$poolst4[$i][]=$_SESSION['teamm4'][$j];
$j++;
$name=$poolst4[$i][$k];
$q=$db->prepare("UPDATE `equipes` SET Finale='$ko' WHERE NAME='$name'");
$q->execute();
$q->closeCursor();
}
}
}
$test=count($poolst2,COUNT_RECURSIVE);
}
echo "<br><br>";
?>
<?php
//Gestion des pools
//t1
/*
var_dump($poolst1);
if($m1%2==0){
for($i=0;$i<$m2;$i++){
echo "match",$i+1,"<br>";
for($j=0;$j<2;$j++){
echo $poolst1[$i][$j],"<br>";
}
}
}else{
for($i=0;$i<$m2-1;$i++){
echo "match",$i+1,"<br>";
for($j=0;$j<2;$j++){
echo $poolst1[$i][$j],"<br>";
}
}
for($i=$m2-3;$i<$m2-2;$i++){
$j=1;
}
}
/*
$t1=count($poolst1);
for($i=0;$i<$t1;$i++){
//var_dump($poolst1[$i]);
for($j=0;$j<count($poolst1[$j]);$j++){
echo $j;
}
}
//t2
$t2=count($poolst2);
for($i=0;$i<$t2;$i++){
//var_dump($poolst1[$i]);
for($j=0;$j<count($poolst2[$j]);$j++){
echo $j;
}
}
//t3
$t3=count($poolst3);
for($i=0;$i<$t3;$i++){
//var_dump($poolst1[$i]);
for($j=0;$j<count($poolst3[$j]);$j++){
echo $j;
}
}
//t4
$t4=count($poolst4);
for($i=0;$i<$t4;$i++){
var_dump($poolst1[$i]);
for($j=0;$j<count($poolst4[$j]);$j++){
echo $j;
}
}
*/
?>
</body>
</html>
<file_sep><html>
<head>
<title><NAME></title>
<meta charset="utf-8">
<style rel="stylesheet" type="text/css">
body{
%background-image: url("bg.png");
font-family: Lucida Console;
%color:red;
%font-variant: small-caps;
}
@font-face
{
font-family: 'ballplay';
src:url('ballplay.ttf') format('truetype');
}
.title{
font-family: 'ballplay';
font-size: 37px;
text-decoration: none;
line-height:1;
letter-spacing: 3px;
}
.img{
aposition: absolute;
right: auto;
top: auto;
}
#arbre{
position:static;
width:auto;
%background-image: url("leaderboard.png");
%background-size: cover;
% background-repeat: no-repeat;
}
#M1{
display: flex;
justify-content: space-around;
}
#M2{
display: flex;
justify-content: space-around;
}
#M3{
display: flex;
justify-content: space-around;
}
#M4{
display: flex;
justify-content: space-around;
}
.Pool
{
justify-content: space-around;
border: 2px solid black;
}
.Match
{
display:inline-flex;
}
.Equipe
{
display:inline-flex;
border: 2px solid red;
justify-content: space-around;
width: 50%;
}
.Win
{
border: 2px solid green;
}
</style>
</head>
<body>
<div class="title">Classement du tournoi de </div>
<div class="img">
<img src="BP.png">
</div>
<?php
session_start();
include "database.php";
include "functions.php";
$m1=$_SESSION['m1'];
$m2=$_SESSION['m2'];
$m3=$_SESSION['m3'];
$m4=$_SESSION['m4'];
?>
<div id="arbre">
<div id="M1">
<?php
for($a=1;$a<=Howmanypools($m1);$a++){
echo"<div class='Pool'> Pool $a<br>";
$q=$db->query("SELECT * FROM `equipes` WHERE Pool=$a");
echo "<div class='match'>";
while($row =$q->fetch()){
$name=$row['NAME'];
echo "<div class='Equipe'>".$name."</div>";
}
echo "<br>";
$q=$db->query("SELECT * FROM `equipes` WHERE Pool=$a AND MANCHE1=1");
while($row =$q->fetch()){
$name=$row['NAME'];
echo "<div class='Win'>".$name."</div>";
}
echo "</div></div>";
}
?>
</div>
<div id="M2">
<?php
for($a=1;$a<=Howmanypools($m2);$a++){
echo"<div class='Pool'> Pool $a<br>";
$q=$db->query("SELECT * FROM `equipes` WHERE Pool2=$a AND MANCHE1=1");
echo "<div class='match'>";
while($row =$q->fetch()){
$name=$row['NAME'];
echo "<div class='Equipe'>".$name."</div>";
}
echo "<br>";
$q=$db->query("SELECT * FROM `equipes` WHERE Pool2=$a AND MANCHE2=1");
while($row =$q->fetch()){
$name=$row['NAME'];
echo "<div class='Win'>".$name."</div>";
}
echo "</div></div>";
}
?>
</div>
<div id="M3">
<?php
for($a=1;$a<=Howmanypools($m3);$a++){
echo"<div class='Pool'> Pool $a<br>";
$q=$db->query("SELECT * FROM `equipes` WHERE Pool3=$a AND MANCHE2=1");
echo "<div class='match'>";
while($row =$q->fetch()){
$name=$row['NAME'];
echo "<div class='Equipe'>".$name."</div>";
}
echo "<br>";
$q=$db->query("SELECT * FROM `equipes` WHERE Pool3=$a AND MANCHE3=1");
while($row =$q->fetch()){
$name=$row['NAME'];
echo "<div class='Win'>".$name."</div>";
}
echo "</div></div>";
}
?>
</div>
<div id="M4">
<?php
for($a=1;$a<=Howmanypools($m4);$a++){
echo"<div class='Pool'> Pool $a<br>";
$q=$db->query("SELECT * FROM `equipes` WHERE Pool4=$a AND MANCHE3=1");
echo "<div class='match'>";
while($row =$q->fetch()){
$name=$row['NAME'];
echo "<div class='Equipe'>".$name."</div>";
}
echo "<br>";
$q=$db->query("SELECT * FROM `equipes` WHERE Pool4=$a AND FINALE=1");
while($row =$q->fetch()){
$name=$row['NAME'];
echo "<div class='Win'>".$name."</div>";
}
echo "</div></div>";
}
?>
</div>
</div>
<div class="live">
<h1> Match en cours </h1>
<?php
$count=0;
$q=$db->query("SELECT * FROM `equipes` WHERE LIVE=1");
while($row =$q->fetch()){
$live=$row['NAME'];
echo $live;
echo ($count<1)? " <img src='vs.png'> ":"";
$count++;
}
?>
</div>
<div class="nextMatch">
<h1> Prochain Match </h1>
<?php
$count=0;
$q=$db->query("SELECT * FROM `equipes` WHERE NEXT=1");
while($row =$q->fetch()){
$next=$row['NAME'];
echo $next;
echo ($count<1)? " <img src='vs.png'> ":"";
$count++;
}
?>
</div>
</body>
</html>
<?php
/*
<?php
session_start();
include "database.php";
$teamm1=$_SESSION['equipe'];
$m1=$_SESSION['m1'];
$m2=$_SESSION['m2'];
$m3=$_SESSION['m3'];
$m4=$_SESSION['m4'];
for ($i=0;$i<$m1;$i++){
echo $teamm1[$i]," ";
}
echo "<br";
?>
<?php
$q=$db->query("SELECT * FROM `equipes` WHERE Manche2=0");
while($row =$q->fetch()){
$teamm2[]=$row['NAME'];
}
$m2=floor($m1/2);
for($i=0;$i<$m2;$i++){
echo $teamm2[$i]," ";
}
echo "<br>";
?>
<?php
$q=$db->query("SELECT * FROM `equipes` WHERE Manche3=0");
while($row =$q->fetch()){
$teamm3[]=$row['NAME'];
}
$m3=floor($m2/2);
for($i=0;$i<$m3;$i++){
echo $teamm3[$i]," ";
}
echo "<br>";
?>
<?php
$q=$db->query("SELECT * FROM `equipes` WHERE Finale=0");
while($row =$q->fetch()){
$teamm4[]=$row['NAME'];
}
$m4=floor($m3/2);
for($i=0;$i<$m4;$i++){
echo $teamm4[$i]," ";
}
echo "<br>";
?>
*/
?>
| ee3d8d73cbff98813cfc1be948d999d07f147fa1 | [
"Markdown",
"PHP"
] | 7 | PHP | way2key/Beer_Pong_Turnament | 7b249097ef212c5385a10a9e9ac471dac2894c2c | a37ceeb6a86b9e2f44a3e8aab635181c8b8c349c |
refs/heads/master | <file_sep># ClassConsole
testy
34
<file_sep>using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Crypto();
Console.ReadKey();
byte[] kiv = new byte[16];
RandomNumberGenerator.Create().GetBytes(kiv);
string encrypted = Encrypt("Yeah!", kiv, kiv);
Console.WriteLine(encrypted); // R1/5gYvcxyR2vzPjnT7yaQ==
string decrypted = Decrypt(encrypted, kiv, kiv);
Console.WriteLine(decrypted); // Yeah!
Console.ReadKey();
}
static async void Crypto()
{ // Use default key/iv for demo.
using (Aes algorithm = Aes.Create())
{
using (ICryptoTransform encryptor = algorithm.CreateEncryptor())
using (Stream f = File.Create("serious.bin"))
using (Stream c = new CryptoStream(f, encryptor, CryptoStreamMode.Write))
using (Stream d = new DeflateStream(c, CompressionMode.Compress))
using (StreamWriter w = new StreamWriter(d))
await w.WriteLineAsync("Small and secure!");
using (ICryptoTransform decryptor = algorithm.CreateDecryptor())
using (Stream f = File.OpenRead("serious.bin"))
using (Stream c = new CryptoStream(f, decryptor, CryptoStreamMode.Read))
using (Stream d = new DeflateStream(c, CompressionMode.Decompress))
using (StreamReader r = new StreamReader(d))
Console.WriteLine(await r.ReadLineAsync()); // Small and secure!
}
}
public static string Encrypt(string data, byte[] key, byte[] iv)
{
return Convert.ToBase64String(
Encrypt(Encoding.UTF8.GetBytes(data), key, iv));
}
public static string Decrypt(string data, byte[] key, byte[] iv)
{
return Encoding.UTF8.GetString(
Decrypt(Convert.FromBase64String(data), key, iv));
}
public static byte[] Encrypt(byte[] data, byte[] key, byte[] iv)
{
using (Aes algorithm = Aes.Create())
using (ICryptoTransform encryptor = algorithm.CreateEncryptor(key, iv))
return Crypt(data, encryptor);
}
public static byte[] Decrypt(byte[] data, byte[] key, byte[] iv)
{
using (Aes algorithm = Aes.Create())
using (ICryptoTransform decryptor = algorithm.CreateDecryptor(key, iv))
return Crypt(data, decryptor);
}
static byte[] Crypt(byte[] data, ICryptoTransform cryptor)
{
MemoryStream m = new MemoryStream();
using (Stream c = new CryptoStream(m, cryptor, CryptoStreamMode.Write))
c.Write(data, 0, data.Length);
return m.ToArray();
}
}
}
| 06fb85cb78b07f36a9bac62ce63f7298236c45e5 | [
"Markdown",
"C#"
] | 2 | Markdown | dhoeven/ClassConsole | 39c01a87d3b496f9d32e55bd977895daabadcc7c | 11e311332cca25b8b65f909ad5cc468a727df685 |
refs/heads/main | <file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Den_magiska_fabriken
{
public class Framework
{
public string Name { get; }
public int WoodToUse { get; }
public int SteelToUse { get; }
public int PlasticToUse { get; }
public int PaintToUse { get; }
public int ScrewToUse { get; }
public Framework(string namn, int wood, int iron,
int rubber, int Paint, int screws)
{
Name = namn;
this.WoodToUse = wood;
this.SteelToUse = iron;
this.PlasticToUse = rubber;
this.PaintToUse = Paint;
this.ScrewToUse = screws;
}
public static void Createproduct()
{
Framework axe = new Framework("Hammer", 2, 1, 0, 1, 0);
Framework plunger = new Framework("plunger", 1, 0, 1, 1, 0);
Framework chopsticks = new Framework("chopsticks", 2, 0, 0, 0, 0);
Framework bikecycle = new Framework("bikecycle", 0, 3, 1, 1, 2);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Den_magiska_fabriken
{
public class Warehouse
{
public List<Material> listMaterials;
public static List<int> listOfMaterials;
public List<int> PeekMaterials;
public Warehouse()
{
listMaterials = new List<Material>();
listOfMaterials = new List<int>();
PeekMaterials = new List<int>();
AddList();
}
private void AddList()
{
for (int i = 0; i < Enum.GetNames(typeof(Material)).Length; i++)
{
int randomN = new Random().Next(5, 10);
PeekMaterials.Add(0);
listOfMaterials.Add(randomN);
listMaterials.Add((Material)i);
}
}
public static List<Framework> _mytems = new();
public void Showarehouse()
{
Console.WriteLine("The storage contains the folowing materials: ");
Console.WriteLine($"{"Nr.",1} {"Materials",3} {"Amount",20} ");
for (int i = 0; i < listMaterials.Count; i++)
{
var l = listMaterials[i];
Console.WriteLine($" {i + 1}. {l,3} {listOfMaterials[i],22}");
}
if (_mytems.Count > 0)
{
Console.WriteLine("You own the folowing products: ");
for (int i = 0; i < _mytems.Count; i++)
{
Console.WriteLine(_mytems[i].Name);
}
}
}
public List<int> SendToFactory()
{
Showarehouse();
for (int q = 0; q < listOfMaterials.Count; q++)
{
if (listOfMaterials[q] > 0)
{
Console.WriteLine($" {listMaterials[q],10} Amount: {listOfMaterials[q]}");
}
}
Console.WriteLine("\nUse numbers to pick materials.");
ConsoleKeyInfo Input = Console.ReadKey();
int givingKey = int.Parse(Input.KeyChar.ToString());
if (givingKey < listOfMaterials.Count)
{
if (listOfMaterials[givingKey] > 0)
{
listOfMaterials[givingKey] = listOfMaterials[givingKey] - 1;
PeekMaterials[givingKey] = PeekMaterials[givingKey] + 1;
}
else
{
Console.WriteLine($"There is no more {(Material)givingKey}. Press enter to continue.");
Console.ReadKey();
}
}
List<int> list2 = new List<int>(PeekMaterials.Count);
foreach (int item in PeekMaterials)
list2.Add(item);
for (int i = 0; i < PeekMaterials.Count; i++)
{
PeekMaterials[i] = 0;
}
return list2;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Den_magiska_fabriken
{
public enum Material
{
Wood, Steel, Plastic, Paint, Screw
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Den_magiska_fabriken
{
public class WorkShop
{
private int _woodInFactory;
private int _ironInFactory;
private int _rubberInFactory;
private int _redPaintInFactory;
private int _screwsInFactory;
public void InputMaterial(List<int> GivingMartiral)
{
_woodInFactory = GivingMartiral[0];
_ironInFactory = GivingMartiral[1];
_rubberInFactory = GivingMartiral[2];
_redPaintInFactory = GivingMartiral[3];
_screwsInFactory = GivingMartiral[4];
Works();
}
public void Works()
{
}
private void CreateProduct(Framework recipe)
{
Warehouse._mytems.Add(recipe);
_woodInFactory -= recipe.WoodToUse;
_ironInFactory -= recipe.SteelToUse;
_rubberInFactory -= recipe.PlasticToUse;
_redPaintInFactory -= recipe.PaintToUse;
_screwsInFactory -= recipe.ScrewToUse;
Warehouse.listOfMaterials[0] += _woodInFactory;
Warehouse.listOfMaterials[1] += _ironInFactory;
Warehouse.listOfMaterials[2] += _rubberInFactory;
Warehouse.listOfMaterials[3] += _screwsInFactory;
Warehouse.listOfMaterials[4] += _redPaintInFactory;
_woodInFactory = 0;
_ironInFactory = 0;
_rubberInFactory = 0;
_screwsInFactory = 0;
_redPaintInFactory = 0;
}
}
}
<file_sep>using System;
namespace Den_magiska_fabriken
{
class Program
{
static void Main(string[] args)
{
Framework.Createproduct();
Console.WriteLine("Walcome to my Fatory!");
Warehouse WH = new Warehouse();
WH.Showarehouse();
var WS=new WorkShop();
WS.InputMaterial(WH.PeekMaterials);
}
}
}
| 2dd61e9b6234fcf4c0d1e6fbcfd0858324fe6358 | [
"C#"
] | 5 | C# | Omar-Slik/Den-magiska-fabriken | 854ebe0ab0acb11b45ef186c9efb194b3a91e026 | 946a62060050113ddc5ff7df1e645ca5fc83bceb |
refs/heads/master | <repo_name>marcus58/Reversi-AI<file_sep>/src/AIPlayer.py
import time
import copy
from random import choice, shuffle
from math import log, sqrt
class AIPlayer:
"""
AI 玩家
"""
def __init__(self, color):
"""
玩家初始化
:param color: 下棋方,'X' - 黑棋,'O' - 白棋
"""
self.color=color
self.plays = {} # 记录着法参与模拟的次数,键形如(color, move),即(玩家,落子)
self.wins = {} # 记录着法获胜的次数
self.plays_rave={}
self.wins_rave={}
self.calculation_time = float(30)
self.max_actions=100
self.equivalence = 1000
self.confident = 1.96
def get_move(self, board):
"""
根据当前棋盘状态获取最佳落子位置
:param board: 棋盘
:return: action 最佳落子位置, e.g. 'A1'
"""
if self.color == 'X':
player_name = '黑棋'
else:
player_name = '白棋'
print("请等一会,对方 {}-{} 正在思考中...".format(player_name, self.color))
# -----------------请实现你的算法代码--------------------------------------
action = None
sensible_move=list(board.get_legal_actions(self.color))
if len(sensible_move)==1:
return sensible_move[0]
simulations=0
begin = time.time()
while time.time() - begin < self.calculation_time:
board_copy=copy.deepcopy(board)
color_copy=copy.deepcopy(self.color)
self.run_simulation(board_copy, color_copy)
simulations+=1
print("total simulations=", simulations)
action=self.select_best_move(board)
self.prune(board)
# ------------------------------------------------------------------------
return action
def run_simulation(self, board, color):
plays=self.plays
wins=self.wins
plays_rave=self.plays_rave
wins_rave=self.wins_rave
availables=list(board.get_legal_actions(color))
player = [1,2][color=='O']
visited_states=set()
winner=-1
expand=True
states_list = []
# Simulation
for t in range(1, self.max_actions + 1):
# Selection
# if all moves have statistics info, choose one that have max UCB value
state=self.current_state(board)
actions=[(move, player) for move in availables]
if all(plays.get((action, state)) for action in actions):
total=0
for a, s in plays:
if s==state:
total+=plays.get((a,s))
beta = sqrt(self.equivalence/(3 * total + self.equivalence))
value, action = max(
((1 - beta) * (wins[(action, state)] / plays[(action, state)]) +
beta * (wins_rave[(action[0], state)][player] / plays_rave[(action[0], state)]) +
sqrt(self.confident * log(total) / plays[(action, state)]), action)
for action in actions) # UCT RAVE
else:
action = choice(actions)
move, p=action
board._move(move, color)
color=['X','O'][color=='X']
# Expand
# add only one new child node each time
if expand and (action, state) not in plays:
expand = False
plays[(action, state)] = 0 # action是(move,player)。在棋盘状态s下,玩家player给出着法move的模拟次数
wins[(action, state)] = 0 # 在棋盘状态s下,玩家player给出着法move并胜利的次数
states_list.append((action, state)) # 当前模拟的路径
# 路径上新增加的节点是前面所有节点的子节点,存在于前面各个节点的子树中
for (m, pp), s in states_list:
if (move, s) not in plays_rave:
plays_rave[(move, s)] = 0 # 棋盘状态s下的着法move的模拟次数,不论是由谁在何时给出的
wins_rave[(move, s)] = {} # 棋盘状态s下着法move中记录着所有玩家在该着法move出现的时候的胜利次数,不论是由谁在何时给出的
wins_rave[(move, s)][1] = 0
wins_rave[(move, s)][2] = 0
visited_states.add((action, state))
b_list = list(board.get_legal_actions('X'))
w_list = list(board.get_legal_actions('O'))
is_over = len(b_list) == 0 and len(w_list) == 0
if is_over:
winner, diff=board.get_winner()
winner+=1 #winner==1 'X' wins, winner==2 'O' wins
break
player = [1,2][color=='O']
# Back-propagation
for i, ((m_root, p), s_root) in enumerate(states_list):
action = (m_root, p)
if (action, s_root) in plays:
plays[(action, s_root)] += 1 # all visited moves
if player == winner and player in action:
wins[(action, s_root)] += 1 # only winner's moves
for ((m_sub, p), s_sub) in states_list[i:]:
plays_rave[(m_sub, s_root)] += 1 # 状态s_root的所有子节点的模拟次数增加1
if winner in wins_rave[(m_sub, s_root)]:
wins_rave[(m_sub, s_root)][winner] += 1 # 在状态s_root的所有子节点中,将获胜的玩家的胜利次数增加1
def current_state(self, board):
state=[]
for i in range(8):
for j in range(8):
if board._board[i][j]=='X':
state.append((i*8+j,1))
if board._board[i][j]=='O':
state.append((i*8+j,2))
return tuple(state)
def select_best_move(self, board):
"""
select by win percentage
"""
player = [1,2][self.color=='O']
board_state=self.current_state(board)
availables=list(board.get_legal_actions(self.color))
percent_wins, move = max(
(self.wins.get(((move, player), board_state), 0) /
self.plays.get(((move, player), board_state), 1),
move)
for move in availables)
for x in sorted(
((100 * self.wins.get(((move, player), board_state), 0) /
self.plays.get(((move, player), board_state), 1),
100 * self.wins_rave.get((move, board_state), {}).get(player, 0) /
self.plays_rave.get((move, board_state), 1),
self.wins.get(((move, player), board_state), 0),
self.plays.get(((move, player), board_state), 1),
self.wins_rave.get((move, board_state), {}).get(player, 0),
self.plays_rave.get((move, board_state), 1),
move)
for move in availables),
reverse=True):
print('{6}: {0:.2f}%--{1:.2f}% ({2} / {3})--({4} / {5})'.format(*x))
return move
def prune(self, board):
count=len(self.current_state(board))
keys=list(self.plays)
for a, s in keys:
if len(s) < count + 2:
del self.plays[(a, s)]
del self.wins[(a, s)]
keys = list(self.plays_rave)
for m, s in keys:
if len(s) < count + 2:
del self.plays_rave[(m, s)]
del self.wins_rave[(m, s)]
<file_sep>/src/Random_player.py
#导入随机包
import random
class RandomPlayer:
"""
随机玩家, 随机返回一个合法落子位置
"""
def __init__(self, color):
"""
玩家初始化
:param color: 下棋方,'X' - 黑棋,'O' - 白棋
"""
self.color = color
def random_choice(self, board):
"""
从合法落子位置中随机选一个落子位置
:param board: 棋盘
:return: 随机合法落子位置, e.g. 'A1'
"""
# 用 list() 方法获取所有合法落子位置坐标列表
action_list = list(board.get_legal_actions(self.color))
# 如果 action_list 为空,则返回 None,否则从中选取一个随机元素,即合法的落子坐标
if len(action_list) == 0:
return None
else:
return random.choice(action_list)
def get_move(self, board):
"""
根据当前棋盘状态获取最佳落子位置
:param board: 棋盘
:return: action 最佳落子位置, e.g. 'A1'
"""
if self.color == 'X':
player_name = '黑棋'
else:
player_name = '白棋'
print("请等一会,对方 {}-{} 正在思考中...".format(player_name, self.color))
action = self.random_choice(board)
return action
#if __name__ == '__main__':
# # 导入棋盘文件
# from board import Board
# # 棋盘初始化
# board = Board()
# # 打印初始化棋盘
# board.display()
# # 玩家初始化,输入黑棋玩家
# black_player = RandomPlayer("X")
# # 黑棋玩家的随机落子位置
# black_action = black_player.get_move(board)
# print("黑棋玩家落子位置: %s"%(black_action))
# # 打印白方被翻转的棋子位置
# print("黑棋落子后反转白棋的棋子坐标:",board._move(black_action,black_player.color))
# # 打印黑棋随机落子后的棋盘
# board.display()
# # 玩家初始化,输入白棋玩家
# white_player = RandomPlayer("O")
# # 白棋玩家的随机落子位置
# white_action = white_player.get_move(board)
# print("白棋玩家落子位置:%s"%(white_action))
# # 打印黑棋方被翻转的棋子位置
# print("白棋落子后反转黑棋的棋子坐标:",board._move(white_action,white_player.color))
# # 打印白棋随机落子后的棋盘
# board.display()
<file_sep>/src/AlphagoPlayer.py
import time
import copy
from multiprocessing.dummy import Pool as ThreadPool
from random import choice, shuffle
from math import log, sqrt, fabs
class AlphagoPlayer:
"""
AI 玩家
"""
def __init__(self, color):
"""
玩家初始化
:param color: 下棋方,'X' - 黑棋,'O' - 白棋
"""
self.color=color
self.root=None
self.start_time=None
self.calculation_time = float(58)
self.max_actions=60
self.equivalence = 1000
self.moves=[4,5][self.color=='O']
self.Cp = 1.414
self.priority_table=[['A0', 'A8', 'H1', 'H8'],
['C3', 'D3', 'E3', 'F3', 'C4', 'D4', 'E4', 'F4', 'C5', 'D5', 'E5', 'F5', 'C6', 'D6', 'E6', 'F6'],
['A3', 'A4', 'A5', 'A6', 'H3', 'H4', 'H5', 'H6', 'C1', 'D1', 'H1', 'F1', 'C8', 'D8', 'H8', 'F8'],
['B3', 'B4', 'B5', 'B6', 'G3', 'G4', 'G5', 'G6', 'C2', 'D2', 'G2', 'F2', 'C7', 'D7', 'G7', 'F7'],
['B1', 'A2', 'B2', 'G2', 'G1', 'H2', 'B7', 'A7', 'B8', 'G7', 'H7', 'G8']]
def get_move(self, board):
"""
根据当前棋盘状态获取最佳落子位置
:param board: 棋盘
:return: action 最佳落子位置, e.g. 'A1'
"""
if self.color == 'X':
player_name = '黑棋'
else:
player_name = '白棋'
print("请等一会,对方 {}-{} 正在思考中...".format(player_name, self.color))
# -----------------请实现你的算法代码--------------------------------------
action = None
sensible_move=list(board.get_legal_actions(self.color))
if len(sensible_move)==1:
return sensible_move[0]
self.root=Node(self.color, board)
action=self.uct_search()
self.moves+=2
# ------------------------------------------------------------------------
return action
def uct_search(self):
self.start_time=time.time()
simulation_count=self.multi_simulation(self.root)
print("silulations=",simulation_count)
max_win_percent, chosen_child = self.best_child(self.root, 0)
print("max win percentage is", max_win_percent)
return chosen_child.pre_move
def multi_simulation(self, node):
count=0
while time.time()-self.start_time<self.calculation_time:
v = self.tree_policy(node)
reward = self.default_policy(v)
self.back_up(v, reward)
count += 1
if node.fully_expandable():
break
if len(node.children)==0:
return count
pool=ThreadPool(len(node.children))
counts=pool.map(self.simulation, node.children)
pool.close()
pool.join()
count+=sum(counts)
return count
def simulation(self, node):
count=0
while time.time()-self.start_time<self.calculation_time:
v = self.tree_policy(node)
reward = self.default_policy(v)
self.back_up(v, reward)
count += 1
return count
def best_child(self, node, c):
child_value = [1 - child.Q / child.N + c*sqrt(log(node.N) / child.N) for child in node.children]
value = max(child_value)
idx = child_value.index(value)
return value, node.children[idx]
def tree_policy(self, node):
while not node.terminal():
if node.fully_expandable():
value, node = self.best_child(node, self.Cp)
else:
return self.expand(node)
return node
def expand(self, node):
chosen_move = choice(node.remain_valid_moves)
node.add_child(chosen_move)
return node.children[-1]
def default_policy(self, node):
cur_color=node.color
board=copy.deepcopy(node.board)
num_moves=0
while self.moves+num_moves<64:
if self.moves+num_moves<56:
valid_set=self.get_priority_valid_moves(board, self.priority_table, cur_color)
if len(valid_set) == 0:
num_moves += 1
cur_color = ['X','O'][cur_color=='X']
continue
move = choice(valid_set)
else:
valid_set=list(board.get_legal_actions(cur_color))
if len(valid_set) == 0:
num_moves += 1
cur_color = ['X','O'][cur_color=='X']
continue
move = choice(valid_set)
board._move(move, cur_color)
cur_color = ['X','O'][cur_color=='X']
num_moves += 1
return self.score(board, self.color)
def get_priority_valid_moves(self, board, priority_table, color):
valid_moves=[]
availables=list(board.get_legal_actions(color))
for priority in priority_table:
for point in priority:
if point in availables:
valid_moves.append(point)
if len(valid_moves)>0:
break
return valid_moves
def score(self, board, color):
score=0
op_color=['X','O'][color=='X']
for i in range(8):
for j in range(8):
if board._board[i][j] == color:
score += 1
if board._board[i][j] == op_color:
score -= 1
return score
def back_up(self, node, reward):
while node is not None:
node.N += 128
if node.color == self.color:
node.Q += 64 + reward
else:
node.Q += 64 - reward
node = node.parent
class Node(object):
def __init__(self, color, board, parent=None, pre_move=None):
self.color = color
self.board=board
self.parent = parent
self.children=[]
self.pre_move = pre_move
self.remain_valid_moves=list(self.board.get_legal_actions(self.color))
self.N = 0
self.Q = 0
def add_child(self, choose_move):
self.remain_valid_moves.remove(choose_move)
board=copy.deepcopy(self.board)
board._move(choose_move, self.color)
child=Node(['X','O'][self.color=='X'], board, self, choose_move)
self.children.append(child)
def fully_expandable(self):
return len(self.remain_valid_moves) == 0
def terminal(self):
return len(self.remain_valid_moves) == 0 and len(self.children) == 0
<file_sep>/src/abAIPlayer.py
import time
import random
class abAIPlayer:
"""
AI 玩家
"""
def __init__(self, color):
"""
玩家初始化
:param color: 下棋方,'X' - 黑棋,'O' - 白棋
"""
self.color=color
self.calculation_time = float(45)
def get_move(self, board):
"""
根据当前棋盘状态获取最佳落子位置
:param board: 棋盘
:return: action 最佳落子位置, e.g. 'A1'
"""
if self.color == 'X':
player_name = '黑棋'
else:
player_name = '白棋'
print("请等一会,对方 {}-{} 正在思考中...".format(player_name, self.color))
# -----------------请实现你的算法代码--------------------------------------
begin = time.time()
action = None
op_color=['X','O'][self.color=='X']
best_val = -1000
my_moves = []
sensible_move=list(board.get_legal_actions(self.color))
if len(sensible_move)==1:
return sensible_move[0]
for move in sensible_move:
flip_positions=board._move(move,self.color)
val = self.alpha_beta(board, op_color, self.color, -1000, 1000, begin)
board.backpropagation(move, flip_positions, self.color)
if val > best_val:
best_val = val
my_moves=[move]
elif val == best_val:
my_moves.append(move)
action=random.choice(my_moves)
# ------------------------------------------------------------------------
return action
def alpha_beta(self, board, color, op_color, alphav, betav, begin):
"""
通过alpha-beta剪枝搜索获取估值
Args:
board: 游戏状态
color: 当前玩家
op_color: 对手玩家
alphav: alpha初始值
betav: beta初始值
begin:开始时间
Return:
当前棋盘状态的估值
对于叶节点:
-- Max方获胜,则估值为diff
-- Min方获胜,则估值为-diff
-- 平局,则估值为0
"""
#先根据当前棋盘state判断是否已经结束,结果如何,并根据结果赋予估值
b_list = list(board.get_legal_actions('X'))
w_list = list(board.get_legal_actions('O'))
is_over = len(b_list) == 0 and len(w_list) == 0
if is_over:
winner, diff = board.get_winner()
if winner==2:
return 0
if (winner==0 and self.color=='X') or (winner==1 and self.color=='O'):
return diff
else:
return -diff
#若还没有结束,则开始递归搜索
for move in list(board.get_legal_actions(color)):
if time.time()-begin>self.calculation_time:
break
flip_positions=board._move(move, color)
val=self.alpha_beta(board, op_color, color, alphav, betav, begin)
board.backpropagation(move, flip_positions, color)
#跟极大极小搜索同理,但是在α值大于β值时返回(即剪枝)
#若当前计算己方(α方)落子情况,则计算α值
if color==self.color:
if val>alphav:
alphav=val
if alphav>=betav:
return betav
#否则计算β值
else:
if val<betav:
betav=val
if betav<=alphav:
return alphav
#计算己方落子(α方),返回极大值
if color==self.color:
return alphav
#否则返回极小值(β方)
else:
return betav
#if __name__ == '__main__':
# # 导入黑白棋文件
# from game import Game
# from Human_player import HumanPlayer
# # 人类玩家黑棋初始化
# black_player = HumanPlayer("X")
# # AI 玩家 白棋初始化
# white_player = AIPlayer("O")
# # 游戏初始化,第一个玩家是黑棋,第二个玩家是白棋
# game = Game(black_player, white_player)
# # 开始下棋
# game.run()
<file_sep>/src/Human_player.py
class HumanPlayer:
"""
人类玩家
"""
def __init__(self, color):
"""
玩家初始化\n",
:param color: 下棋方,'X' - 黑棋,'O' - 白棋\n",
"""
self.color = color
def get_move(self, board):
"""
根据当前棋盘输入人类合法落子位置
:param board: 棋盘
:return: 人类下棋落子位置
"""
# 如果 self.color 是黑棋 "X",则 player 是 "黑棋",否则是 "白棋"
if self.color == "X":
player="黑棋"
else:
player="白棋"
# 人类玩家输入落子位置,如果输入 'Q', 则返回 'Q'并结束比赛。
# 如果人类玩家输入棋盘位置,e.g. 'A1',
# 首先判断输入是否正确,然后再判断是否符合黑白棋规则的落子位置
while True:
action=input("请'{}-{}'方输入一个合法的坐标(e.g. 'D3',若不想进行,请务必输入'Q'结束游戏。):".format(player,self.color))
# 如果人类玩家输入 Q 则表示想结束比赛
if action=="Q" or action=="q":
return "Q"
else:
row, col = action[1].upper(), action[0].upper()
# 检查人类输入是否正确
if row in '12345678' and col in 'ABCDEFGH':
# 检查人类输入是否为符合规则的可落子位置
if action in board.get_legal_actions(self.color):
return action
else:
print("你的输入不合法,请重新输入!")
#if __name__ == '__main__':
# from board import Board
# # 棋盘初始化
# board = Board()
# # 打印初始化后棋盘
# board.display()
# # 人类玩家黑棋初始化
# black_player = HumanPlayer("X")
# # 人类玩家黑棋落子位置
# action = black_player.get_move(board)
# # 如果人类玩家输入 'Q',则表示想结束比赛,
# # 现在只展示人类玩家的输入结果。
# if action=="Q":
# print("结束游戏:",action)
# else:
# # 打印白方被翻转的棋子位置
# print("黑棋落子后反转白棋的棋子坐标:",board._move(action,black_player.color))
# # 打印人类玩家黑棋落子后的棋盘
# board.display()
| 7874ee2005cb7fad8e4f63aed9badc2d99930317 | [
"Python"
] | 5 | Python | marcus58/Reversi-AI | 9f1ebabfaf10d7901c486c66f46a7cbaba94d6df | d2e4127fc74f2ed4b34fa02cac0e66af5a9e1bc1 |
refs/heads/master | <file_sep>class Video:
def __init__(self, video_id, title):
self.id = video_id
self.title = title
def jsonify(self):
return {
'id':self.id,
'title':self.title
}<file_sep># TierMaker
TierMaker for Videos
<file_sep>import re
class Parser():
def __init__(self, URLS):
self.URLS = URLS
self.urlList = self.urlsToList()
def urlsToList(self):
return re.split('\n', self.URLS)
<file_sep>from googleapiclient.discovery import build
import json
from video import Video
class Connector():
def __init__(self):
self.key = self.getAPIKey()
self.youtubeAPI = build('youtube', 'v3', developerKey=self.key)
def getAPIKey(self):
KEY = ''
try:
with open('keys.json', 'r') as f:
json_data = json.load(f)
KEY = json_data["API_KEY"]
except Exception as e:
print(e," :Could not read API-Keys file")
return KEY
def getVideosFromURLS(self, urls):
video_list = []
try:
if len(urls) > 0:
for url in urls:
matching_videos = self.youtubeAPI.videos().list(part='id, snippet', id=url).execute()
if len(matching_videos['items']) > 0:
vid = Video(matching_videos['items'][0]['id'] , matching_videos['items'][0]['snippet']['title'])
video_list.append(vid.jsonify())
else:
print("No video found")
return video_list
except Exception as e:
print(e)<file_sep>import React, { Component, useEffect, useState } from 'react';
import NavBar from './components/NavBar'
import Home from './components/Home'
import Tier from './components/Tier'
import deepPurple from '@material-ui/core/colors/deepPurple';
import { createTheme } from '@material-ui/core/styles';
import { ThemeProvider } from 'styled-components'
import './css/App.css';
function App(){
const [page, setPage] = useState('home');
const [tierList, setTierList] = useState(false);
const [URL, setURL] = useState('');
const theme = createTheme({
palette: {
primary: {
main: deepPurple[500],
dark: deepPurple[800],
verydark: deepPurple[900],
light: deepPurple[300],
contrastText: "#ede7f6"
},
secondary: {
main: '#ce93d8',
},
},
spacing: [0, 2, 3, 5, 8]
});
return (
<ThemeProvider theme={theme}>
<div style={{alignItems: 'center'}}>
<div>
<NavBar handleClick={setPage} state={page} bcolor={theme.palette.primary.dark} tcolor={theme.palette.primary.contrastText}/>
</div>
<div>
{{
'home': <Home />,
'tier': <Tier setURL={setURL} theme={theme}/>
}[page]}
</div>
</div>
</ThemeProvider>
);
}
export default App;<file_sep>import React, { Component } from 'react';
import Box from '@material-ui/core/Box';
class Home extends Component {
constructor(props) {
super(props);
}
render () {
return(
<Box sx={{width:'50%', top:'25%',left:'25%', padding: '10px', position:'absolute', textAlign:'center', border: '1px double grey' }}>
<div>Welcome to TierMaker, Video Edition</div>
</Box>
);
}
}
export default Home;<file_sep>import React, { Component } from 'react';
import AppBar from '@material-ui/core/AppBar'
import Toolbar from '@material-ui/core/Toolbar'
import Typography from '@material-ui/core/Typography'
import ViewListRoundedIcon from '@material-ui/icons/ViewListRounded';
import { Button, IconButton, Icon } from '@material-ui/core';
class NavBar extends Component {
constructor(props) {
super(props);
}
createTier = () => {
this.props.handleClick("tier");
}
handlePages(){
this.props.handleClick("home");
}
render () {
const Logo = () => (
<Icon>
<img src={"./icons/shadowtiericon.png"} height={25} width={25}/>
</Icon>
)
return(
console.log(this.props.bcolor),
<div>
<AppBar style={{background:this.props.bcolor}} position="static" boxShadow={10}>
<Toolbar>
<Button><img onClick={() => this.handlePages()} style={{ flex: 0.1 }} src="./logos/tiermakerlogo.jpg" alt="logo" /></Button>
<div style={{ flex: 0.35 }}></div>
<Button onClick={() => this.props.handleClick("tier")} variant="outlined" size="Medium" style={{border: '1px double deeppurple', background:this.props.bcolor, color:this.props.tcolor}}
startIcon={<Logo />}>
Rate Some Videos
</Button>
</Toolbar>
</AppBar>
</div>
);
}
}
export default NavBar;
//ViewListRoundedIcon<file_sep>from flask import Flask, request
from parse import Parser
from connector import Connector
app = Flask(__name__)
connector = Connector()
@app.route('/api/handleURLS', methods=['POST'])
def handleURLs():
data = request.get_json()
print(data)
p = Parser(data['URLS'])
print(p.urlList)
videos = connector.getVideosFromURLS(p.urlList)
print("VIDEOS")
print(videos)
return {'videos':videos}
if __name__ == '__main__':
app.run()
| e48b5c97910cfe511ef1e24b4677e65c745c80df | [
"Markdown",
"Python",
"JavaScript"
] | 8 | Python | Taoudi/TierMaker | a055394909c46d2ff4eff245f2b89044f0832960 | b880857e09fd62b191b74e81206a622bf371bbb0 |
refs/heads/main | <repo_name>AngelCellaCenerini/Personal-Experiments<file_sep>/WaterFootprint_CART212/js/MessageFo.js
class MessageFo extends Message{
constructor(){
super();
this.string = `Over 1 billion people in developing countries
do not have access to safe drinking water.`;
this.switch = 16500;
this.duration2 = 5;
}
}
<file_sep>/WaterFootprint/js/HighScore.js
class HighScore{
constructor(string1, string2){
this.x = 375;
this.y1 = 45;
this.y2 = 115;
this.y3 = 145;
this.string1 = string1;
this.string2 = string2;
this.activeH = false;
this.activeS = false;
}
displayHighScore(){
if (this.activeH){
push();
let r = random(0, 255);
fill(251, 167, 14, r);
textSize(60);
text(`HIGH SCORE`, this.x, this.y1);
pop();
}
}
displayScore(){
if (this.activeS){
push();
fill(255);
textSize(26);
text(this.string1, this.x, this.y2);
text(this.string2, this.x, this.y3);
pop();
}
}
deactivate(){
if (this.activeH || this.activeS){
this.activeH = false;
this.activeS = false;
}
}
}
<file_sep>/WaterFootprint_CART212_2/js/MessageFi.js
class MessageFi extends Message{
constructor(){
super();
this.string = `Disproportionate mismatch between freshwater demand and availability.`;
this.switch = 24000;
this.duration2 = 4;
}
}
<file_sep>/WaterFootprint_CART212 - Copy/js/script.js
"use strict";
/**
Water Footprint
<NAME>
CART212 Final Project
*/
let timerInstructions = 4;
// let timerInstructions2 = 30;
let timerInstructions2 = 5;
let timerUserInput = 2;
let timerActive = 80;
let timerInterruption = 4;
let timerPassive = 10;
let timerAnimation1 = 1;
let timerAnimation2 = 1;
let timerAnimation3 = 1;
let timerAnimation4 = 3;
let timerScreen1 = 2;
let waltzIntro = undefined;
let waltzInterruption = undefined;
let waltz = undefined;
let myFont = undefined;
let lights = undefined;
let avatar = undefined;
let userInput = undefined;
let userInputs = [];
let stopCommand = undefined;
let stopCommands = [];
let instructions = {
active: false
}
let instructions2 = {
active: false
}
let button = {
active: false
}
let button2 = {
active: false
}
let fadedText = {
x: 375,
y1: 115,
y2: 145,
active: false
}
let highlight = {
active: false
}
let waterfall = undefined;
let waterfallImage = undefined;
let bigWaterfall = undefined;
let bigWaterfallImage = undefined;
let splash = undefined;
let splashImage = undefined;
let drop = undefined;
let drop2 = undefined;
let dropImage = undefined;
let waves = undefined;
let waveRImage = undefined;
let waveLImage = undefined;
// Score
let score1 = undefined;
let score2 = undefined;
// Objects
let cow = undefined;
let cowImage = undefined;
let cotton = undefined;
let cottonImage = undefined;
// Messages
let message = undefined;
let message2 = undefined;
// Finale
let screen1 = {
active: false
}
let screenImage = undefined;
let fadingEffect = {
x: 0,
y: 0,
width: 800,
height: 700,
vx: 0,
vy: 0,
opacity: 255,
active: false
}
let state = `title` // Title, Animation, active, Passive
/**
Description of preload
*/
function preload() {
myFont = loadFont('assets/pixelated.otf');
lights = loadImage('assets/images/lightGIF6.gif');
avatar = loadImage('assets/images/clown.png');
waterfallImage = loadImage('assets/images/waterfall.gif');
bigWaterfallImage = loadImage('assets/images/bigWaterfall.gif');
splashImage = loadImage('assets/images/splash2.gif');
dropImage = loadImage('assets/images/goccia.png');
waveRImage = loadImage('assets/images/waveR.gif');;
waveLImage = loadImage('assets/images/waveL.gif');;
// Objects
cowImage = loadImage('assets/images/cow.gif');
cottonImage = loadImage('assets/images/cotton.gif');
// Finale
screenImage = loadImage('assets/images/prova.gif');
// SFX
waltzIntro = loadSound('assets/sounds/intro.mp3');
waltzInterruption = loadSound('assets/sounds/interruptionB.mp3');
waltz = loadSound('assets/sounds/soundtrack.mp3');
}
/**
Description of setup
*/
function setup() {
createCanvas(750, 630);
noStroke();
// noCursor();
textFont(myFont);
textAlign(CENTER, CENTER);
rectMode(CENTER);
imageMode(CENTER);
// Objects
cow = new Product(cowImage);
cotton = new Product(cottonImage);
// Scores
let stringA1 = `1KG BEEF`;
let stringA2 = `+ 15 000 LITRES`;
score1 = new HighScore(stringA1, stringA2);
let stringB1 = `1KG BEEF`;
let stringB2 = `+ 15 000 LITRES`;
score2 = new HighScore(stringB1, stringB2);
// Waterfall
waterfall = new Waterfall(waterfallImage);
// Big Waterfall
bigWaterfall = new BigWaterfall(bigWaterfallImage);
// Splash
splash = new Splash(splashImage);
// Drops
drop = new Drop(dropImage);
drop2 = new Drop(dropImage);
// Side Waves
waves = new Wave(waveLImage, waveRImage);
// Message
message = new Message();
message2 = new MessageS();
}
/**
Description of draw()
*/
function draw() {
background(30);
if (state === `title`){
titleText();
}
else if (state === `active`){
activeTimer();
// User Platform
push();
fill(139, 217, 199);
rect(120, 290, 75, 18);
pop();
// Avatar
image(avatar, 120, 240);
// Lights
image(lights, width/2, 155);
// Faded Score
if (fadedText.active){
push();
fill(255, 50);
textSize(26);
text(`WHAT'S NEXT?`, fadedText.x, fadedText.y1);
text(`+ MORE WATER!`, fadedText.x, fadedText.y2);
pop();
}
// Scores
// Cow
score1.displayHighScore();
score1.displayScore();
// Cotton
score2.displayHighScore();
score2.displayScore();
triggerAnimation();
// Waterfall
waterfall.update();
// Splash
splash.update();
// Drop
// drop.update();
// Black Border
push();
fill(30);
rect(width/2, 632, 250, 220);
pop();
// Waterfall
bigWaterfall.update();
// Base
push();
noFill();
stroke(255);
strokeWeight(5);
rect(width/2, 370, 200, 300);
pop();
instructionsTimer();
instructionsTimer2();
if (instructions.active === true && instructions2.active === false){
push();
fill(255);
textSize(23);
text(`Press the ENTER key!`, width/2, 574);
pop();
}
// Stop Command
if (instructions2.active){
push();
fill(255);
textSize(23);
text(`Press the BACKSPACE key
to stop the water consumption!`, width/2, 574);
pop();
}
// Water Dripping
// Highlight
if (button.active){
push();
fill(255);
rect(width/2, 574, 210, 30);
fill(0);
textSize(23);
text(`ENTER key pressed`, width/2, 570);
pop();
}
if (button2.active){
push();
fill(255);
rect(width/2, 574, 230, 30);
fill(0);
textSize(23);
text(`BACKSPACE key pressed`, width/2, 570);
pop();
}
// Message
message.update();
message2.update();
// Side Waves
waves.update();
}
else if (state === `interruption`){
// waltz.pause();
// interruptionTimer();
setTimeout( ()=>{
switchToActiveState();
}, 2000);
playMusic();
// waltz.pause();
// if(waltz.isPlaying){
// waltz.pause();
// }
// User Platform
push();
fill(139, 217, 199);
rect(120, 290, 75, 18);
pop();
// Avatar
image(avatar, 120, 240);
// Lights
image(lights, width/2, 155);
// Faded Score
push();
fill(255, 50);
textSize(26);
text(`OH`, fadedText.x, fadedText.y1);
text(`IT STOPPED`, fadedText.x, fadedText.y2);
pop();
// Drop
drop2.timing = 200;
drop2.update();
// Black Border
push();
fill(30);
rect(width/2, 632, 250, 220);
pop();
// Base
push();
noFill();
stroke(255);
strokeWeight(5);
rect(width/2, 370, 200, 300);
pop();
}
else if (state === `passive`){
passiveTimer();
}
else if (state === `animation1`){
windowResized();
animation1Timer();
image(screenImage, width/4, height/2, 645, 542);
image(screenImage, 3*width/4, height/2, 645, 542);
}
else if (state === `animation2`){
background(0);
animation2Timer();
image(screenImage, width/6, height/2, 450, 378);
image(screenImage, width/2, height/2, 450, 378);
image(screenImage, 5*width/6, height/2, 450, 378);
}
else if (state === `animation3`){
background(0);
animation3Timer();
image(screenImage, width/6, height/4, 375, 315);
image(screenImage, width/2, height/4, 375, 315);
image(screenImage, 5*width/6, height/4, 375, 315);
image(screenImage, width/6, 3*height/4, 375, 315);
image(screenImage, width/2, 3*height/4, 375, 315);
image(screenImage, 5*width/6, 3*height/4, 375, 315);
}
else if (state === `animation4`){
background(0);
animation4Timer();
image(screenImage, width/4, height/6, 250, 210);
image(screenImage, width/2, height/6, 250, 210);
image(screenImage, 3*width/4, height/6, 250, 210);
image(screenImage, width/4, height/2, 250, 210);
image(screenImage, width/2, height/2, 250, 210);
image(screenImage, 3*width/4, height/2, 250, 210);
image(screenImage, width/4, 5*height/6, 250, 210);
image(screenImage, width/2, 5*height/6, 250, 210);
image(screenImage, 3*width/4, 5*height/6, 250, 210);
screen1Timer();
coverPic();
}
else if (state === `credits`){
background(0);
endingText();
fadeIn();
setTimeout( ()=>{
fadingEffect.active = true;
}, 2000);
}
}
function fadeIn(){
let fading = 0.5;
push();
fill(0, fadingEffect.opacity);
fadingEffect.x = width/2;
fadingEffect.y = height/2;
rect(fadingEffect.x, fadingEffect.y, fadingEffect.width, fadingEffect.height);
pop();
if (fadingEffect.active){
fadingEffect.opacity -= fading;
}
}
function titleText(){
// Text
push();
fill(255);
textSize(45);
text(`WATER FOOTPRINT`, width/2, height/2);
textSize(22);
text(`Press SPACEBAR to start`, width/2, 440);
pop();
}
function instructionsTimer(){
if(frameCount % 60 === 0 && timerInstructions > 0){
timerInstructions --;
}
if(timerInstructions === 0){
instructions.active = true;
// instructions2.active = false;
// timerInstructions2 = 8;
// if(userInputs.length > 1){
//
// // Add Input
// userInputs.push(userInput);
// // Waterfall
// waterfall.active = true;
//
// // Splash
// setTimeout( ()=>{
// splash.active = true;
// }, 2200);
// }
}
}
function instructionsTimer2(){
if(frameCount % 60 === 0 && timerInstructions2 > 0){
timerInstructions2 --;
}
if(timerInstructions2 === 0){
if(stopCommands.length < 3){
instructions2.active = true;
}
else{
return
}
}
}
function triggerAnimation(){
// Cow
cow.display();
if(cow.active){
setTimeout( ()=>{
cow.active = false;
score1.deactivate();
fadedText.active = true;
}, 3000);
}
// Cotton
cotton.display();
if(cotton.active){
setTimeout(()=>{
cotton.active = false;
score2.deactivate();
fadedText.active = true;
}, 3000);
}
}
function activeTimer(){
if(frameCount % 60 === 0 && timerActive > 0){
timerActive --;
}
if(timerActive === 0){
state = `passive`;
}
}
function switchToActiveState(){
setTimeout( ()=>{
state = `active`;
// playMusic();
// timerInterruption = 2;
if (waltzInterruption.isPlaying){
waltzInterruption.stop();
}
}, 2000);
}
function interruptionTimer(){
if(frameCount % 60 === 0 && timerInterruption > 0){
timerInterruption --;
}
if(timerInterruption === 0){
state = `active`;
playMusic();
// timerInterruption = 2;
if (waltzInterruption.isPlaying){
waltzInterruption.stop();
}
}
}
function passiveTimer(){
if(frameCount % 60 === 0 && timerPassive > 0){
timerPassive --;
}
if(timerPassive === 0){
state = `animation1`;
}
}
function windowResized() {
resizeCanvas(windowWidth, windowHeight);
}
function animation1Timer(){
if(frameCount % 60 === 0 && timerAnimation1 > 0){
timerAnimation1 --;
}
if(timerAnimation1 === 0){
state = `animation2`;
}
}
function animation2Timer(){
if(frameCount % 60 === 0 && timerAnimation2 > 0){
timerAnimation2 --;
}
if(timerAnimation2 === 0){
state = `animation3`;
}
}
function animation3Timer(){
if(frameCount % 60 === 0 && timerAnimation3 > 0){
timerAnimation3 --;
}
if(timerAnimation3 === 0){
state = `animation4`;
}
}
function animation4Timer(){
if(frameCount % 60 === 0 && timerAnimation4 > 0){
timerAnimation4 --;
}
if(timerAnimation4 === 0){
state = `credits`;
}
}
function screen1Timer(){
if(frameCount % 60 === 0 && timerScreen1 > 0){
timerScreen1 --;
}
if(timerScreen1 === 0){
screen1.active = true;
}
}
function coverPic(){
push();
fill(30);
if (screen1.active){
rect( width/4, height/6, 250, 210);
}
rect(width/2, height/6, 250, 210);
rect(3*width/4, height/6, 250, 210);
rect(width/4, height/2, 250, 210);
rect(width/2, height/2, 250, 210);
rect(3*width/4, height/2, 250, 210);
rect(width/4, 5*height/6, 250, 210);
rect(width/2, 5*height/6, 250, 210);
rect(3*width/4, 5*height/6, 250, 210);
// Text
fill(255);
textSize(32);
if (screen1.active){
text(`ITALY
30 L per day`, width/4, height/6);
}
text(`ITALY
30 L per day`, width/2, height/6);
text(`ITALY
30 L per day`, 3*width/4, height/6);
text(`ITALY
30 L per day`, width/4, height/2);
text(`ITALY
30 L per day`, width/2, height/2);
text(`ITALY
30 L per day`, 3*width/4, height/2);
text(`ITALY
30 L per day`, width/4, 5*height/6);
text(`ITALY
30 L per day`, width/2, 5*height/6);
text(`ITALY
30 L per day`, 3*width/4, 5*height/6);
pop();
}
function displayAlerts(){
push();
fill(255);
rect();
pop();
}
function endingText(){
// Text
push();
fill(255);
textSize(45);
text(`WATER FOOTPRINT`, width/2, height/2);
textSize(22);
text(`CART212 - <NAME>`, width/2, 440);
pop();
}
//
function keyPressed(){
if ( keyCode === 32 && state === `title`){
state = `active`;
waltzIntro.loop();
}
if ( keyCode === 13 && state === `active`){
// Sound
if (waltzIntro.isPlaying){
waltzIntro.stop();
}
// if(userInputs.length < 1){
// playMusic();
waltz.loop();
// }
// if(userInputs.length < 0){
// Add Input
userInputs.push(userInput);
// Waterfall
waterfall.active = true;
// Splash
setTimeout( ()=>{
splash.active = true;
}, 2200);
// }
// Reset Command
instructions.active = false;
timerInstructions = 7;
// Start Button
if (keyIsPressed && button2.active === false && instructions2.active === false){
button.active = true;
// instructions2.active = false;
// timerInstructions2 = 8;
}
// Cow
if (userInputs.length < 2){
cow.activate();
setTimeout(()=>{
score1.activeH = true;
score1.activeS = true;
}, 3000);
}
if (userInputs.length < 3 && userInputs.length > 1){
cotton.activate();
setTimeout(()=>{
score2.activeH = true;
score2.activeS = true;
fadedText.active = false;
}, 3000);
}
// // Waterfall
// waterfall.active = true;
//
// // Splash
// setTimeout( ()=>{
// splash.active = true;
// }, 2200);
}
else if (keyCode === 8 && state === `active` && instructions2.active === true){
// Reset Stop Command
instructions2.active = false;
timerInstructions2 = 10;
timerInstructions = 3;
button2.active = true;
setTimeout( ()=>{
if(stopCommands.length < 4){
state = `interruption`;
// interruptionTimer();
// timerInterruption = 2;
if(waltz.isPlaying){
waltzInterruption.play();
}
}
}, 1000);
// Keep Track of Inputs
stopCommands.push(stopCommand);
}
}
function keyReleased(){
if (state === `active` && button.active === true && keyCode === 13){
if(stopCommands.length < 3){
button.active = false;
}
else{
return;
}
}
else if (state === `active` && button2.active === true && keyCode === 8){
button2.active = false;
timerInstructions = 4;
}
}
function playMusic(){
if(state === `active`){
waltz.loop();
}
else if(state === `interruption`){
waltz.pause();
}
}
<file_sep>/WaterFootprint/js/MessageFi.js
class MessageFi extends Message{
constructor(){
super();
this.string = `Disproportionate mismatch between
freshwater demand and availability.`;
this.switch = 13000;
this.duration2 = 6;
}
}
<file_sep>/cp3Templates/js/script.js
"use strict";
/**
Title of Project
Author Name
This is a template. You must fill in the title,
author, and this description to match your project!
*/
/**
Description of preload
// */
// function preload() {
//
// }
//
//
// /**
// Description of setup
// */
// function setup() {
//
// }
//
//
// /**
// Description of draw()
// */
// function draw() {
//
// }
trackKeyboardInput();
// User Input affects page
// let temp1 = document.getElementById(`t1`);
// let temp2 = document.getElementById(`t2`);
// let temp3 = document.getElementById(`t3`);
// let temp4 = document.getElementById(`t4`);
//
// temp1.addEventListener(`keydown`, key1);
//
// function key1(){
// if (event.keyCode === )
// }
function trackKeyboardInput(){
// Check Key pressed by User
$(document).on(`keydown`, (function(event) {
// User presses 'P'
if ( event.which === 49){
$(`#t1`).css(`opacity`, `100`);
$(`#t2`).css(`opacity`, `0`);
$(`#t3`).css(`opacity`, `0`);
$(`#t4`).css(`opacity`, `0`);
}
else if (event.which === 50 ){
$(`#t1`).css(`opacity`, `0`);
$(`#t2`).css(`opacity`, `100`);
$(`#t3`).css(`opacity`, `0`);
$(`#t4`).css(`opacity`, `0`);
}
else if (event.which === 51 ){
$(`#t1`).css(`opacity`, `0`);
$(`#t2`).css(`opacity`, `0`);
$(`#t3`).css(`opacity`, `100`);
$(`#t4`).css(`opacity`, `0`);
}
else if (event.which === 52 ){
$(`#t1`).css(`opacity`, `0`);
$(`#t2`).css(`opacity`, `0`);
$(`#t3`).css(`opacity`, `0`);
$(`#t4`).css(`opacity`, `100`);
}
}))
kjashdkashdkas
}
<file_sep>/WaterFootprint_CART212/js/MessageT.js
class MessageT extends Message{
constructor(){
super();
this.string = `By 2035, the world’s water consumption
will increase by 15%.`;
this.switch = 13000;
this.duration2 = 3;
}
}
<file_sep>/README.md
# Personal_Experiments
Projects outside CART263 class
<file_sep>/WaterFootprint/js/MessageT.js
class MessageT extends Message{
constructor(){
super();
this.string = `By 2035, the world’s water consumption
will increase by 15%.`;
this.switch = 70000;
}
}
<file_sep>/WaterFootprint/js/MessageFo.js
class MessageFo extends Message{
constructor(){
super();
this.string = `Over 1 billion people in developing
countries do not have access
to safe drinking water.`;
this.switch = 3000;
}
}
<file_sep>/WaterFootprint_CART212 - Copy/js/Drop.js
class Drop {
constructor(image){
this.x = 375;
this.y = -5;
this.vx = 0;
this.vy = 0;
this.speed = 0.08;
this.limit = 600;
this.image = image;
this.active = false;
this.timing = 2000;
}
update(){
setTimeout( ()=>{
this.active = true;
}, this.timing);
this.move();
this.reset();
this.display();
setTimeout( ()=>{
this.active = false;
}, 8090);
}
move(){
if (this.active){
this.x += this.vx;
this.y += this.vy;
this.vy += this.speed;
}
}
reset(){
if (this.active){
if (this.y > this.limit){
this.y = -2;
this.vy = 0;
}
}
}
display(){
if (this.active){
image(this.image, this.x, this.y);
}
}
}
<file_sep>/WaterFootprint/js/Avatar.js
class Avatar{
constructor(image1, image2, image3, image4, imageA, imageB){
this.x = 120;
this.x2 = 630;
this.y = 260;
this.image1 = image1;
this.image2 = image2;
this.image3 = image3;
this.image4 = image4;
this.imageA = imageA;
this.imageB = imageB;
this.active1 = true;
this.active2 = false;
this.active3 = false;
this.active4 = false;
}
thumbsUp(){
this.active1 = false;
this.active2 = true;
this.thumbsDown();
}
thumbsDown(){
setTimeout( ()=>{
this.active1 = true;
this.active2 = false;
}, 5000);
}
fuckIt(){
this.active1 = false;
this.active4 = true;
}
display(){
if(this.active1){
image(this.image1, this.x, this.y);
image(this.imageA, this.x2, this.y);
}
if(this.active2){
image(this.image2, this.x, this.y);
image(this.imageB, this.x2, this.y);
}
if(this.active3){
image(this.image3, this.x, this.y);
image(this.image3, this.x2, this.y);
}
if(this.active4){
image(this.image4, this.x, this.y);
image(this.image4, this.x2, this.y);
}
}
}
<file_sep>/WaterFootprint/js/script.js
"use strict";
/**
Title of Project
Author Name
This is a template. You must fill in the title,
author, and this description to match your project!
*/
let timerInstructions = 4;
let timerInstructions2 = 26;
let timerUserInput = 2;
let timerActive = 4;
let timerAnimation1 = 2;
let timerAnimation2 = 1;
let timerAnimation3 = 1;
let timerAnimation4 = 19;
let timerScreen1 = 4;
let timerScreen2 = 5;
let timerScreen3 = 6;
let timerScreen4 = 7;
let timerScreen5 = 8;
let timerScreen6 = 9;
let timerScreen7 = 10;
let timerScreen8 = 11;
let timerScreen9 = 12;
let waltzIntro = undefined;
let waltzInterruption = undefined;
let waltz = undefined;
let myFont = undefined;
let baseImage = undefined;
let lights = undefined;
let avatar = undefined;
let avatarImage1 = undefined;
let avatarImage2 = undefined;
let avatarImage3 = undefined;
let avatarImage4 = undefined;
let avatarImageA = undefined;
let avatarImageB = undefined;
let userInput = undefined;
let userInputs = [];
let stopCommand = undefined;
let stopCommands = [];
let interruption = {
active: false
}
let instructions = {
active: false
}
let instructions2 = {
active: false
}
let button = {
active: false
}
let button2 = {
active: false
}
let fadedText = {
x: 375,
y1: 115,
y2: 145,
active: false
}
let highlight = {
active: false
}
let waterfall = undefined;
let waterfallImage = undefined;
let bigWaterfall = undefined;
let bigWaterfallImage = undefined;
let splash = undefined;
let splashImage = undefined;
let drop = undefined;
let drop2 = undefined;
let dropImage = undefined;
let waves = undefined;
let waveRImage = undefined;
let waveLImage = undefined;
// Scores
let score1 = undefined;
let score2 = undefined;
let score3 = undefined;
let score4 = undefined;
let score5 = undefined;
let score6 = undefined;
let score7 = undefined;
let score8 = undefined;
// Objects
let coffee = undefined;
let coffeeImage = undefined;
let apple = undefined;
let appleImage = undefined;
let bread = undefined;
let breadImage = undefined;
let cotton = undefined;
let cottonImage = undefined;
let chocolate = undefined;
let chocolateImage = undefined;
let phone = undefined;
let phoneImage = undefined;
let jeans = undefined;
let jeansImage = undefined;
let cow = undefined;
let cowImage = undefined;
// Messages
let message = undefined;
let message2 = undefined;
let message3 = undefined;
let message4 = undefined;
let message5 = undefined;
let message6 = undefined;
// Finale
let screen1 = {
active: false
}
let screen2 = {
active: false
}
let screen3 = {
active: false
}
let screen4 = {
active: false
}
let screen5 = {
active: false
}
let screen6 = {
active: false
}
let screen7 = {
active: false
}
let screen8 = {
active: false
}
let screen9 = {
active: false
}
let screenImage = undefined;
let fadingEffect = {
x: 0,
y: 0,
width: 800,
height: 700,
vx: 0,
vy: 0,
opacity: 255,
active: false
}
let state = `title` // Title, Animation, active, Passive
/**
Description of preload
*/
function preload() {
myFont = loadFont('assets/pixelated.otf');
baseImage = loadImage('assets/images/base3.png');
lights = loadImage('assets/images/lightGIF6.gif');
avatarImage1 = loadImage('assets/images/handDefault.png');
avatarImage2 = loadImage('assets/images/thumbsU.gif');
avatarImage3 = loadImage('assets/images/handStop.png');
avatarImage4 = loadImage('assets/images/handK.gif');
avatarImageA = loadImage('assets/images/handDefaultF.png');
avatarImageB = loadImage('assets/images/thumbsUF.gif');
waterfallImage = loadImage('assets/images/waterfall.gif');
bigWaterfallImage = loadImage('assets/images/bigWaterfall.gif');
splashImage = loadImage('assets/images/splash2.gif');
dropImage = loadImage('assets/images/goccia.png');
waveRImage = loadImage('assets/images/waveR.gif');;
waveLImage = loadImage('assets/images/waveL.gif');;
// Objects
coffeeImage = loadImage('assets/images/coffe.gif');
appleImage = loadImage('assets/images/apple.gif');
breadImage = loadImage('assets/images/bread.gif');
cottonImage = loadImage('assets/images/cotton2.gif');
chocolateImage = loadImage('assets/images/chocolate.gif');
phoneImage = loadImage('assets/images/phone.gif');
jeansImage = loadImage('assets/images/jeans.gif');
cowImage = loadImage('assets/images/cow2.gif');
// Finale
screenImage = loadImage('assets/images/finalScreen.gif');
// SFX
waltzIntro = loadSound('assets/sounds/intro.mp3');
waltzInterruption = createAudio('assets/sounds/interruptionB.mp3');
waltz = createAudio('assets/sounds/soundtrack.mp3');
}
/**
Description of setup
*/
function setup() {
createCanvas(750, 630);
noStroke();
// noCursor();
textFont(myFont);
textAlign(CENTER, CENTER);
rectMode(CENTER);
imageMode(CENTER);
userStartAudio();
// Avatar
avatar = new Avatar(avatarImage1, avatarImage2, avatarImage3, avatarImage4, avatarImageA, avatarImageB);
// Objects
coffee = new Product(coffeeImage);
apple = new Product(appleImage);
bread = new Product(breadImage);
cotton = new Product(cottonImage);
chocolate = new Product(chocolateImage);
phone = new Product(phoneImage);
jeans = new Product(jeansImage);
cow = new Product(cowImage);
// Scores
// Coffee
let stringC1 = `1 CUP (125 ml) COFFEE`;
let stringC2 = `+ 132 LITRES`;
score3 = new HighScore(stringC1, stringC2);
// Apple
let stringD1 = `1 APPLE`;
let stringD2 = `+ 70 LITRES`;
score4 = new HighScore(stringD1, stringD2);
// Bread
let stringE1 = `1KG BREAD`;
let stringE2 = `+ 1600 LITRES`;
score5 = new HighScore(stringE1, stringE2);
// Cotton
let stringB1 = `1KG COTTON FABRIC`;
let stringB2 = `+ 10 000 LITRES`;
score2 = new HighScore(stringB1, stringB2);
// Chocolate
let stringF1 = `100G CHOCOLATE`;
let stringF2 = `+ 1700 LITRES`;
score6 = new HighScore(stringF1, stringF2);
// Phone
let stringG1 = `1 SMARTPHONE`;
let stringG2 = `+ 12 000 LITRES`;
score7 = new HighScore(stringG1, stringG2);
// Jeans
let stringH1 = `1 PAIR JEANS`;
let stringH2 = `+ 8 000 LITRES`;
score8 = new HighScore(stringH1, stringH2);
// Cow
let stringA1 = `1KG BEEF`;
let stringA2 = `+ 15 000 LITRES`;
score1 = new HighScore(stringA1, stringA2);
// Waterfall
waterfall = new Waterfall(waterfallImage);
// Big Waterfall
bigWaterfall = new BigWaterfall(bigWaterfallImage);
// Splash
splash = new Splash(splashImage);
// Drops
drop = new Drop(dropImage);
drop2 = new Drop(dropImage);
// Side Waves
waves = new Wave(waveLImage, waveRImage);
// Message
message = new Message();
message2 = new MessageS();
message3 = new MessageT();
message4 = new MessageFo();
message5 = new MessageFi();
message6 = new MessageSi();
}
/**
Description of draw()
*/
function draw() {
background(30);
if (state === `title`){
titleText();
}
else if (state === `active`){
if(waves.active){
activeTimer();
}
// User Platform
push();
fill(139, 217, 199);
rect(120, 310, 75, 18);
rect(630, 310, 75, 18);
pop();
// Avatar
avatar.display();
// image(avatar, 120, 250);
// Lights
image(lights, width/2, 155);
// Faded Score
if (fadedText.active){
push();
fill(255, 50);
textSize(26);
text(`WHAT'S NEXT?`, fadedText.x, fadedText.y1);
text(`+ MORE WATER!`, fadedText.x, fadedText.y2);
pop();
}
// Scores
// Coffee
score3.displayHighScore();
score3.displayScore();
// Apple
score4.displayScore();
// Bread
score5.displayHighScore();
score5.displayScore();
// Cotton
score2.displayHighScore();
score2.displayScore();
// Chocolate
score6.displayScore();
// Phone
score7.displayHighScore();
score7.displayScore();
// Jeans
score8.displayScore();
// Cow
score1.displayScore();
// Display Products
triggerAnimation();
automaticAnimationJeans();
automaticAnimationCow();
// Waterfall
waterfall.update();
// Splash
splash.update();
// Drop
// drop.update();
// Black Border
push();
fill(30);
rect(width/2, 642, 250, 220);
pop();
// Waterfall
bigWaterfall.update();
// Base
image(baseImage, width/2, 400);
// push();
// noFill();
// stroke(255);
// strokeWeight(5);
// rect(width/2, 370, 200, 300);
// pop();
instructionsTimer();
instructionsTimer2();
if (instructions.active === true && instructions2.active === false){
push();
fill(255);
textSize(23);
text(`Press the ENTER key!`, width/2, 574);
pop();
}
// Stop Command
if (instructions2.active === true && button2.active === false){
push();
fill(255);
textSize(23);
text(`Press the BACKSPACE key
to stop the water consumption!`, width/2, 574);
pop();
}
// Water Dripping
// Highlight
if (button.active){
push();
fill(255);
rect(width/2, 574, 210, 30);
fill(0);
textSize(23);
text(`ENTER key pressed`, width/2, 570);
pop();
}
if (button2.active){
push();
fill(255);
rect(width/2, 574, 230, 30);
fill(0);
textSize(23);
text(`BACKSPACE key pressed`, width/2, 570);
pop();
}
// Side Waves
waves.update();
// interruption
if(interruption.active){
displayInterruption();
}
// Message
message.update();
message2.update();
message3.update();
}
else if (state === `animation1`){
windowResized();
animation1Timer();
image(screenImage, width/4, height/2, 645, 542);
image(screenImage, 3*width/4, height/2, 645, 542);
}
else if (state === `animation2`){
background(0);
animation2Timer();
image(screenImage, width/6, height/2, 450, 378);
image(screenImage, width/2, height/2, 450, 378);
image(screenImage, 5*width/6, height/2, 450, 378);
}
else if (state === `animation3`){
background(0);
animation3Timer();
image(screenImage, width/6, height/4, 375, 315);
image(screenImage, width/2, height/4, 375, 315);
image(screenImage, 5*width/6, height/4, 375, 315);
image(screenImage, width/6, 3*height/4, 375, 315);
image(screenImage, width/2, 3*height/4, 375, 315);
image(screenImage, 5*width/6, 3*height/4, 375, 315);
}
else if (state === `animation4`){
background(0);
// switchToEnding();
animation4Timer();
image(screenImage, width/4, height/6, 250, 210);
image(screenImage, width/2, height/6, 250, 210);
image(screenImage, 3*width/4, height/6, 250, 210);
image(screenImage, width/4, height/2, 250, 210);
image(screenImage, width/2, height/2, 250, 210);
image(screenImage, 3*width/4, height/2, 250, 210);
image(screenImage, width/4, 5*height/6, 250, 210);
image(screenImage, width/2, 5*height/6, 250, 210);
image(screenImage, 3*width/4, 5*height/6, 250, 210);
// Screens
screen1Timer();
screen2Timer();
screen3Timer();
screen4Timer();
screen5Timer();
screen6Timer();
screen7Timer();
screen8Timer();
screen9Timer();
// Squares
coverPic();
// Messages
message4.x = width/2;
message4.update();
message5.x = width/2;
message5.update();
message6.x = width/2;
message6.update();
}
else if (state === `credits`){
background(0);
endingText();
fadeIn();
setTimeout( ()=>{
fadingEffect.active = true;
}, 2000);
}
}
function fadeIn(){
let fading = 0.5;
push();
fill(0, fadingEffect.opacity);
fadingEffect.x = width/2;
fadingEffect.y = height/2;
rect(fadingEffect.x, fadingEffect.y, fadingEffect.width, fadingEffect.height);
pop();
if (fadingEffect.active){
fadingEffect.opacity -= fading;
}
}
function titleText(){
// Text
push();
fill(255);
textSize(45);
text(`WATER FOOTPRINT`, width/2, height/2);
textSize(22);
text(`Press SPACEBAR to start`, width/2, 440);
pop();
}
function instructionsTimer(){
if (!instructions2.active){
if(frameCount % 60 === 0 && timerInstructions > 0){
timerInstructions --;
}
if(timerInstructions === 0){
if (userInputs.length < 6){
instructions.active = true;
}
}
}
}
function instructionsTimer2(){
if(frameCount % 60 === 0 && timerInstructions2 > 0){
timerInstructions2 --;
}
if(timerInstructions2 === 0){
if(stopCommands.length < 3 && instructions2.active === false){
instructions2.active = true;
timerInstructions = 4;
}
}
}
function triggerAnimation(){
// Coffee
coffee.display();
if(coffee.active){
setTimeout( ()=>{
coffee.active = false;
score3.deactivate();
fadedText.active = true;
}, 3500);
}
// Apple
apple.display();
if(apple.active){
setTimeout( ()=>{
apple.active = false;
score4.deactivate();
fadedText.active = true;
}, 3500);
}
// Bread
bread.display();
if(bread.active){
setTimeout( ()=>{
bread.active = false;
score5.deactivate();
fadedText.active = true;
}, 3500);
}
// Cotton
cotton.display();
if(cotton.active){
setTimeout(()=>{
cotton.active = false;
score2.deactivate();
fadedText.active = true;
}, 3500);
}
// Chocolate
chocolate.display();
if(chocolate.active){
setTimeout( ()=>{
chocolate.active = false;
score6.deactivate();
fadedText.active = true;
}, 3500);
}
// Phone
phone.display();
if(phone.active){
setTimeout( ()=>{
phone.active = false;
score7.deactivate();
fadedText.active = true;
}, 3500);
}
}
function automaticAnimationJeans(){
// Jeans
jeans.display();
if(jeans.active){
setTimeout( ()=>{
jeans.active = false;
score8.deactivate();
fadedText.active = true;
}, 3500);
}
}
function automaticAnimationCow(){
// Cow
cow.display();
if(cow.active){
setTimeout( ()=>{
cow.active = false;
score1.deactivate();
fadedText.active = true;
}, 3500);
}
}
function activeTimer(){
if(frameCount % 60 === 0 && timerActive > 0){
timerActive --;
}
if(timerActive === 0){
state = `animation1`;
}
}
function displayInterruption(){
// Redraw Canvas
push();
fill(30);
rect(width/2, height/2, 750, 630);
pop();
// User Platform
push();
fill(139, 217, 199);
rect(120, 310, 75, 18);
rect(630, 310, 75, 18);
pop();
// Avatar
avatar.active1 = false;
avatar.active3 = true;
avatar.display();
// image(avatar, 120, 250);
// Lights
image(lights, width/2, 155);
// Faded Score
push();
fill(255, 50);
textSize(26);
text(`OH`, fadedText.x, fadedText.y1);
text(`IT STOPPED`, fadedText.x, fadedText.y2);
pop();
// Drop
drop2.timing = 200;
drop2.update();
// Black Border
push();
fill(30);
rect(width/2, 642, 250, 220);
pop();
// Base
image(baseImage, width/2, 400);
// push();
// noFill();
// stroke(255);
// strokeWeight(5);
// rect(width/2, 370, 200, 300);
// pop();
// // Return to Active
// setTimeout( ()=>{
// interruption.active = false;
// console.log(interruption.active);
// }, 4000);
}
function returnToActive(){
// Return to Active
setTimeout( ()=>{
interruption.active = false;
avatar.active3 = false;
avatar.active1 = true;
// if(waltzInterruption.isPlaying){
waltzInterruption.stop();
waltz.play();
}, 6000);
}
function returnToActive2(){
// Return to Active
setTimeout( ()=>{
interruption.active = false;
avatar.active3 = false;
avatar.active1 = true;
// if(waltzInterruption.isPlaying){
waltzInterruption.stop();
waltz.play();
}, 3000);
}
function windowResized() {
resizeCanvas(windowWidth, windowHeight);
}
function animation1Timer(){
if(frameCount % 60 === 0 && timerAnimation1 > 0){
timerAnimation1 --;
}
if(timerAnimation1 === 0){
state = `animation2`;
}
}
function animation2Timer(){
if(frameCount % 60 === 0 && timerAnimation2 > 0){
timerAnimation2 --;
}
if(timerAnimation2 === 0){
state = `animation3`;
}
}
function animation3Timer(){
if(frameCount % 60 === 0 && timerAnimation3 > 0){
timerAnimation3 --;
}
if(timerAnimation3 === 0){
state = `animation4`;
}
}
function animation4Timer(){
if(frameCount % 60 === 0 && timerAnimation4 > 0){
timerAnimation4 --;
}
if(timerAnimation4 === 0){
state = `credits`;
}
}
function switchToEnding(){
if (waltz.isPlaying){
return;
}
else{
setTimeout( ()=>{
state = `credits`;
}, 500);
}
}
function screen1Timer(){
if(frameCount % 60 === 0 && timerScreen1 > 0){
timerScreen1 --;
}
if(timerScreen1 === 0){
screen1.active = true;
}
}
function screen2Timer(){
if(frameCount % 60 === 0 && timerScreen2 > 0){
timerScreen2 --;
}
if(timerScreen2 === 0){
screen2.active = true;
}
}
function screen3Timer(){
if(frameCount % 60 === 0 && timerScreen3 > 0){
timerScreen3 --;
}
if(timerScreen3 === 0){
screen3.active = true;
}
}
function screen4Timer(){
if(frameCount % 60 === 0 && timerScreen4 > 0){
timerScreen4 --;
}
if(timerScreen4 === 0){
screen4.active = true;
}
}
function screen5Timer(){
if(frameCount % 60 === 0 && timerScreen5 > 0){
timerScreen5 --;
}
if(timerScreen5 === 0){
screen5.active = true;
}
}
function screen6Timer(){
if(frameCount % 60 === 0 && timerScreen6 > 0){
timerScreen6 --;
}
if(timerScreen6 === 0){
screen6.active = true;
}
}
function screen7Timer(){
if(frameCount % 60 === 0 && timerScreen7 > 0){
timerScreen7 --;
}
if(timerScreen7 === 0){
screen7.active = true;
}
}
function screen8Timer(){
if(frameCount % 60 === 0 && timerScreen8 > 0){
timerScreen8 --;
}
if(timerScreen8 === 0){
screen8.active = true;
}
}
function screen9Timer(){
if(frameCount % 60 === 0 && timerScreen9 > 0){
timerScreen9 --;
}
if(timerScreen9 === 0){
screen9.active = true;
}
}
function coverPic(){
push();
fill(30);
if (screen1.active){
rect( width/4, height/6, 250, 210);
}
if (screen2.active){
rect(width/2, height/6, 250, 210);
}
if (screen3.active){
rect(3*width/4, height/6, 250, 210);
}
if (screen4.active){
rect(width/4, height/2, 250, 210);
}
if (screen5.active){
rect(width/2, height/2, 250, 210);
}
if (screen6.active){
rect(3*width/4, height/2, 250, 210);
}
if (screen7.active){
rect(width/4, 5*height/6, 250, 210);
}
if (screen8.active){
rect(width/2, 5*height/6, 250, 210);
}
if (screen9.active){
rect(3*width/4, 5*height/6, 250, 210);
}
// Text
fill(255);
textSize(28);
if (screen1.active){
text(`CHINA
362 trillion gallons
per year`, width/4, height/6);
}
if (screen2.active){
text(`USA
216 trillion gallons
per year`, width/2, height/6);
}
if (screen3.active){
text(`BRAZIL
95 trillion gallons
per year`, 3*width/4, height/6);
}
if (screen4.active){
text(`RUSSIA
71 trillion gallons
per year`, width/4, height/2);
}
if (screen5.active){
text(`MEXICO
53 trillion gallons
per year`, width/2, height/2);
}
if (screen6.active){
text(`INDIA
30 trillion gallons
per year`, 3*width/4, height/2);
}
if (screen7.active){
text(`ENGLAND / FRANCE
20 trillion gallons
per year`, width/4, 5*height/6);
}
if (screen8.active){
text(`CANADA
19 trillion gallons
per year`, width/2, 5*height/6);
}
if (screen9.active){
text(`AUSTRALIA
12 trillion gallons
per year`, 3*width/4, 5*height/6);
}
pop();
}
function displayAlerts(){
push();
fill(255);
rect();
pop();
}
function endingText(){
// Text
push();
fill(255);
textSize(45);
text(`WATER FOOTPRINT`, width/2, height/2);
textSize(22);
text(`CART212 - <NAME>`, width/2, 440);
pop();
}
//
function keyPressed(){
if ( keyCode === 32 && state === `title`){
state = `active`;
waltzIntro.loop();
}
if ( keyCode === 13 && state === `active`){
// Sound
if (waltzIntro.isPlaying){
waltzIntro.stop();
}
if(userInputs.length < 1){
// playMusic();
waltz.play();
}
if(userInputs.length < 6 && instructions.active === true){
// Add Input
userInputs.push(userInput);
avatar.thumbsUp();
console.log(userInputs.length);
// Waterfall
waterfall.active = true;
// Splash
setTimeout( ()=>{
splash.active = true;
}, 2200);
}
// Reset Command
instructions.active = false;
timerInstructions = 7;
if(userInputs.length < 5 && userInputs.length > 2){
timerInstructions = 32;
}
// Start Button
if (keyIsPressed && button2.active === false && instructions2.active === false){
button.active = true;
// instructions2.active = false;
// timerInstructions2 = 8;
}
if (!instructions2.active){
// Coffee
if (userInputs.length < 2 && interruption.active === false){
coffee.activate();
setTimeout(()=>{
score3.activeH = true;
score3.activeS = true;
fadedText.active = false;
}, 3000);
}
// Apple
if ((userInputs.length < 3 && userInputs.length > 1) && interruption.active === false){
apple.activate();
setTimeout(()=>{
score4.activeS = true;
fadedText.active = false;
}, 3000);
}
// Bread
if ((userInputs.length < 4 && userInputs.length > 2) && interruption.active === false){
bread.activate();
setTimeout(()=>{
score5.activeH = true;
score5.activeS = true;
fadedText.active = false;
}, 3000);
}
// Cotton
if ((userInputs.length < 5 && userInputs.length > 3) && interruption.active === false){
cotton.activate();
setTimeout(()=>{
score2.activeH = true;
score2.activeS = true;
fadedText.active = false;
}, 3000);
}
// Chocolate
if ((userInputs.length < 6 && userInputs.length > 4) && interruption.active === false){
chocolate.activate();
setTimeout(()=>{
score6.activeS = true;
fadedText.active = false;
}, 3000);
}
// Phone
if ((userInputs.length < 7 && userInputs.length > 5) && interruption.active === false){
// userInputs.push(userInput);
phone.activate();
setTimeout(()=>{
score7.activeH = true;
score7.activeS = true;
fadedText.active = false;
userInputs.push(userInput);
}, 3000);
}
}
// Passive Mode
// // Cow
// if (userInputs.length < 2){
// cow.activate();
// setTimeout(()=>{
// score1.activeH = true;
// score1.activeS = true;
// }, 3000);
//
// }
// // Waterfall
// waterfall.active = true;
//
// // Splash
// setTimeout( ()=>{
// splash.active = true;
// }, 2200);
}
else if (keyCode === 8 && state === `active`){
if(instructions2.active){
timerInstructions = 4;
if(userInputs.length < 4){
timerInstructions = 30;
}
// Reset Stop Command
// if(userInputs.length > 2){
// instructions2.active = false;
// timerInstructions = 40;
if(stopCommands.length < 1){
timerInstructions2 = 15;
instructions2.active = false;
}
// else if(stopCommands.length > 2){
// timerInstructions2 = 28;
// }
// console.log(userInputs.length);
// console.log(timerInstructions2);
// }
// if(userInputs.length > 3 && stopCommands.length > 5){
// console.log(userInputs.length);
// instructions2.active = false;
// timerInstructions2 = 28;
// console.log(userInputs.length);
// console.log(timerInstructions2);
// }
if(stopCommands.length < 3){
button2.active = true;
instructions2.active = false;
}
// if(button2.active){
// instructions2.active = false;
// }
drop2.y = -5;
drop2.vy = 0;
setTimeout( ()=>{
if(stopCommands.length < 2){
interruption.active = true;
// if(waltz.isPlaying){
waltz.pause();
waltzInterruption.loop();
returnToActive();
}
else if(stopCommands.length < 4){
interruption.active = true;
// if(waltz.isPlaying){
waltz.pause();
waltzInterruption.loop();
returnToActive2();
}
}, 1000);
}
// // Reset Stop Command
// instructions2.active = false;
// timerInstructions2 = 10;
// timerInstructions = 3;
// button2.active = true;
//
// drop2.y = -5;
// drop2.vy = 0;
//
//
// setTimeout( ()=>{
// if(stopCommands.length < 4){
// interruption.active = true;
// // if(waltz.isPlaying){
// waltz.pause();
// waltzInterruption.loop();
// returnToActive();
// // playMusic();
// // }
//
// // waltz.pause();
// // setTimeout( ()=>{
// // if(waltz.isPaused){
// // waltz.play();
// // }
// // }, 4000);
// // waltzInterruption.play();
// // playMusic();
// }
// }, 1000);
// setTimeout( ()=>{
//
// }, 1000);
// setTimeout( ()=>{
// if(stopCommands.length < 4){
// interruption.active = true;
// setTimeout( ()=>{
// interruption.active = false;
// waltzInterruption.pause();
// if (waltz.isPaused){
// waltz.play();
// }
//
// console.log(interruption.active);
// }, 4000);
// playMusic();
// }
// }, 1000);
//
// // Keep Track of Inputs
if (stopCommands.length < 4 && button2.active === true){
stopCommands.push(stopCommand);
console.log(stopCommands.length);
}
// if(stopCommands.length < 4){
//
// }
}
}
function keyReleased(){
if (state === `active` && button.active === true && keyCode === 13){
if(stopCommands.length < 3 && userInputs.length < 7){
button.active = false;
}
}
else if (state === `active` && button2.active === true && keyCode === 8){
button2.active = false;
// instructions2.active = false;
if (stopCommands.length < 4){
instructions2.active = false;
if(stopCommands.length > 1){
timerInstructions2 = 21;
}
if(stopCommands.length < 4 && stopCommands.length > 2){
setTimeout( ()=>{
userInputs.length = 10;
button.active = true;
avatar.fuckIt();
// setTimeout( ()=>{
jeans.activate();
// }, 2000);
setTimeout( ()=>{
cow.activate();
}, 6000);
dunno();
}, 5000);
}
}
timerInstructions = 4;
// setTimeout( ()=>{
// waltz.play();
// }, 4000);
}
}
function dunno(){
// Waterfall
waterfall.active = true;
setTimeout( ()=>{
waterfall.active = true;
}, 6000);
// Splash
setTimeout( ()=>{
splash.active = true;
}, 2200);
setTimeout( ()=>{
splash.active = true;
}, 8200);
setTimeout( ()=>{
setTimeout(()=>{
score8.activeS = true;
fadedText.active = false;
}, 3000);
}, 400);
setTimeout( ()=>{
setTimeout(()=>{
score1.activeS = true;
fadedText.active = false;
}, 2000);
}, 8000);
setTimeout(automaticAnimationJeans, 4000);
setTimeout(automaticAnimationCow, 9000);
setTimeout( ()=>{
bigWaterfall.active = true;
}, 15000);
setTimeout( ()=>{
waves.active = true;
}, 19000);
}
<file_sep>/WaterFootprint/js/MessageSi.js
class MessageSi extends Message{
constructor(){
super();
this.string = `Water demand will grow by 55% by 2050.
6 billion people will face clean water scarcity.`;
this.switch = 8000;
}
}
<file_sep>/WaterFootprint_CART212_2/js/BigWaterfall.js
class BigWaterfall{
constructor(image){
this.x1 = 150;
this.x2 = 600;
this.y = -600;
this.vx = 0;
this.vy = 0;
this.speed = 2;
this.limit = 315;
this.active = false;
this.image = image;
}
update(){
// this.activate();
this.move();
this.display();
}
// activate(){
// setTimeout( ()=>{
// this.active = true;
// }, 20000);
// }
move(){
if (this.active){
this.x += this.vx;
this.y += this.vy;
this.vy += this.speed;
if(this.y > this.limit){
this.vy = 0;
this.speed = 0;
}
}
}
display(){
if (this.active){
image(this.image, this.x1, this.y);
image(this.image, this.x2, this.y);
}
}
}
<file_sep>/WaterFootprint/js/MessageS.js
class MessageS extends Message{
constructor(){
super();
this.string = `By 2025, 2/3 of the world’s population
may face water shortages.`;
this.switch = 50000;
}
}
| 0b29bde1926c09a3e322978acc8378e8683fdb6d | [
"JavaScript",
"Markdown"
] | 16 | JavaScript | AngelCellaCenerini/Personal-Experiments | 553c1bd703b30b506e324a7da5add8ecead369bf | 07ce50103f902be3c3816f1116e3a8991aa64b3b |
refs/heads/master | <repo_name>MSwaney/share-tutorials<file_sep>/spec/models/category_spec.rb
require 'spec_helper'
describe Category do
it { should have_many :tutorials }
it { should validate_presence_of :name }
end
<file_sep>/app/controllers/tutorials_controller.rb
class TutorialsController < ApplicationController
before_action :authorize, only: [:new, :create]
def index
@tutorials = Tutorial.sort_order
end
def new
@tutorial = Tutorial.new
end
def show
@tutorial = Tutorial.find(params[:id])
@comment = Comment.new
@comments = Comment.where(:tutorial_id => params[:id]).sort_order
end
def create
@tutorial = current_user.tutorials.new(tutorial_params)
if @tutorial.save
flash[:notice] = "Your tutorial has been added."
redirect_to '/'
else
render 'new'
end
end
private
def tutorial_params
params.require(:tutorial).permit(:description, :link, :category_id, :user_id)
end
end
<file_sep>/config/initializers/session_store.rb
# Be sure to restart your server when you modify this file.
Tic::Application.config.session_store :cookie_store, key: '_tic_session'
<file_sep>/app/models/tutorial.rb
class Tutorial < ActiveRecord::Base
validates :category, presence: true
validates :link, presence: true
validates :description, presence: true, length: {maximum: 75}
has_many :likes
has_many :comments
belongs_to :category
belongs_to :user
validates_format_of :link, :with => /\./
before_save :verify_http
def ordered_comments
self.comments.order("created_at DESC")
end
def liked_by(user)
Like.where(user_id: user.id, tutorial_id: self.id).count > 0
end
def self.sort_order
Tutorial.all.order('created_at DESC')
end
private
def verify_http
if !self.link.include? "//"
self.link = 'http://' + self.link
end
end
end
<file_sep>/spec/support/user_helper.rb
require 'spec_helper'
def sign_up_and_log_in
user = FactoryGirl.create(:user)
Category.create(name: 'Ruby', slug: 'ruby')
visit root_path
click_link "Log In"
fill_in 'Email', :with => user.email
fill_in 'Password', :with => <PASSWORD>
click_button("Log In")
end<file_sep>/spec/factories.rb
FactoryGirl.define do
factory :user do |f|
f.name "foo"
f.password "<PASSWORD>"
f.password_confirmation { |u| u.<PASSWORD> }
f.email "<EMAIL>"
end
end <file_sep>/README.rdoc
Share Your Tutorials
====================
A website for aspiring developers to share and comment on the latest programming tutorials.
This was my first Rails app at Epicodus.
I built this along with Mac Eisenberg
Buit with Rails 4.0. Testing with RSpec and Capybara.
Live Demo
=========
[Share Your Tutorials](http://coding-tutorials.herokuapp.com)
<file_sep>/app/helpers/comments_helper.rb
module CommentsHelper
def comment_link_helper(tutorial)
if tutorial.comments.count > 0
link_to(pluralize(tutorial.comments.count, "comment"), tutorial_path(tutorial.id))
else
link_to "Leave the first comment!", tutorial_path(tutorial.id)
end
end
end
<file_sep>/app/controllers/comments_controller.rb
class CommentsController < ApplicationController
def create
@comment = Comment.create(comment_params)
if @comment.save
redirect_to tutorial_path(@comment.tutorial)
else
flash[:notice] = "Please add your comment."
redirect_to tutorial_path(@comment.tutorial)
end
end
def destroy
@comment = Comment.find(params[:id])
@comment.destroy
flash[:notice] = "Comment deleted."
redirect_to tutorial_path(:id => @comment.tutorial.id)
end
private
def comment_params
params.require(:comment).permit(:content, :tutorial_id, :user_id)
end
end
<file_sep>/spec/features/user_features_spec.rb
require 'spec_helper'
feature 'sign in to account' do
scenario 'user enters correct info' do
sign_up_and_log_in
page.should have_content "Logged in"
end
scenario 'user enters correct info' do
user = FactoryGirl.create(:user)
visit root_path
click_link "Log In"
fill_in 'Email', :with => user.email
fill_in 'Password', :with => "<PASSWORD>"
click_button("Log In")
page.should have_content "invalid"
end
end
feature 'user can post a tutorial' do
scenario 'user submits a valid tutorial' do
sign_up_and_log_in
click_on("Submit A Tutorial!")
fill_in 'Description', :with => 'new tutorial hey'
fill_in 'Link', :with => 'hello.com'
select('Ruby', :from => 'Category')
click_button("Submit Tutorial")
page.should have_content "Your tutorial has been added"
end
scenario 'user submits a tutorial without category' do
sign_up_and_log_in
click_on("Submit A Tutorial!")
fill_in 'Description', :with => 'new tutorial hey'
fill_in 'Link', :with => 'hello.com'
click_button("Submit Tutorial")
page.should have_content "Category can't be blank"
end
end
<file_sep>/spec/models/like_spec.rb
require 'spec_helper'
describe Like do
it { should belong_to :user }
it { should belong_to :tutorial }
end<file_sep>/spec/models/user_spec.rb
require 'spec_helper'
describe User do
it { should have_many :tutorials }
it { should have_many :likes }
it { should have_many :comments }
it { should validate_presence_of :email }
it { should validate_presence_of :name }
end<file_sep>/app/controllers/likes_controller.rb
class LikesController < ApplicationController
def create
@like = current_user.likes.create(like_params)
redirect_to '/'
end
private
def like_params
params.require(:like).permit(:tutorial_id, :user_id)
end
end
<file_sep>/app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
def authorize
redirect_to login_url, alert: "Please log in" if current_user.nil?
end
private
def current_user
@current_user ||= User.find(session[:user_id]) if session[:user_id]
end
def categories
Category.all
end
# helper_method :categories
helper_method :current_user, :categories
end
<file_sep>/app/models/comment.rb
class Comment < ActiveRecord::Base
validates :content, presence: true
validates :user_id, presence: true
belongs_to :tutorial
belongs_to :user
def self.sort_order
Comment.all.order('created_at DESC')
end
end
<file_sep>/Gemfile
source 'https://rubygems.org'
gem 'rails'
gem 'pg'
gem 'sass-rails'
gem 'uglifier'
gem 'coffee-rails'
gem 'jquery-rails'
gem 'turbolinks'
gem 'jbuilder'
gem 'bcrypt-ruby', '~> 3.0.0'
gem 'zurb-foundation'
group :production do
gem 'rails_12factor'
end
group :test, :development do
gem 'rspec-rails'
gem 'pry'
end
group :test do
gem 'shoulda-matchers'
gem 'factory_girl_rails'
gem 'capybara'
gem 'selenium'
gem 'launchy'
end<file_sep>/app/models/user.rb
class User < ActiveRecord::Base
has_secure_password
has_many :tutorials
has_many :likes
has_many :comments
validates_format_of :email, :with => /\A[0-9._%a-z\-]+@(?:[0-9a-z\-]+\.)+[a-z]{2,4}\z/i
validates_presence_of :name
validates_presence_of :email
end<file_sep>/spec/models/tutorial_spec.rb
require 'spec_helper'
describe Tutorial do
it { should validate_presence_of :description }
it { should validate_presence_of :link }
it { should validate_presence_of :category }
it { should belong_to :category}
it { should belong_to :user }
it { should have_many :comments }
it { should have_many :likes }
it "checks to see if it has been liked by the current user" do
user = User.create(name: 'matt', email: '<EMAIL>', password: '<PASSWORD>', password_confirmation: '<PASSWORD>')
tutorial = Tutorial.create(description: 'Things', link: 'www.example.com', user_id: 21, category_id: 1)
like = Like.create(tutorial_id: tutorial.id, user_id: 55)
tutorial.liked_by(user).should eq false
end
it "checks to see if it has been liked by the current user" do
user = User.create(name: 'matt', email: '<EMAIL>', password: '<PASSWORD>', password_confirmation: '<PASSWORD>')
tutorial = Tutorial.create(description: 'Things', link: 'www.example.com', user_id: user.id, category_id: 1)
like = Like.create(tutorial_id: tutorial.id, user_id: user.id)
tutorial.liked_by(user).should eq true
end
it "checks to see if it has been liked by the current user" do
user = User.create(name: 'matt', email: '<EMAIL>', password: '<PASSWORD>', password_confirmation: '<PASSWORD>')
category = Category.create(name: 'Ruby', slug: 'Ruby')
tutorial = Tutorial.new(description: 'Things', link: 'www.example.com', user_id: user.id, category_id: category.id )
tutorial.save
tutorial.link.should eq "http://www.example.com"
end
end
<file_sep>/spec/models/comment_spec.rb
require 'spec_helper'
describe Comment do
it { should validate_presence_of :content }
it { should validate_presence_of :user_id }
it { should belong_to :tutorial }
it { should belong_to :user }
it "checks to see if a comments are sorted by date" do
user = User.create(name: 'matt', email: '<EMAIL>', password: '<PASSWORD>', password_confirmation: '<PASSWORD>')
category = Category.create(name: "Ruby", slug: "Ruby")
tutorial = Tutorial.create(description: 'Things', link: 'www.example.com', user_id: 21, category_id: category.id)
comment1 = user.comments.create(content: "Great tutorial", tutorial_id: tutorial.id)
comment2 = user.comments.create(content: "Awesome", tutorial_id: tutorial.id)
Comment.sort_order.first.should eq comment2
end
end | 6398fb3ce54480b83f773cf6c02b0f89f686a676 | [
"RDoc",
"Ruby"
] | 19 | Ruby | MSwaney/share-tutorials | 105f29b0b5f832bf99bea600b265bebdd0c1befc | bd6ac986a5453cd52b11683cb759f38ece07b892 |
refs/heads/master | <repo_name>matiaseidis/minimum-spanning-tree<file_sep>/mst/Kruskal.py
'''
Created on 28/6/2015
@author: matiaseidis
'''
from mst.UWeightedGraph import UWeightedGraph
from mst.UnionFind import UnionFind
def minimum_spanning_tree(tree):
result = []
uf = UnionFind(len(tree.V())+1)
edges = sorted(tree.E(), key=byWeight)
while edges:
minor_edge = edges[0]
edges.remove(minor_edge)
v = minor_edge[0]
w = minor_edge[1]
if not uf.connected(v, w):
result.append(minor_edge)
uf.connect(v, w)
return result
def byWeight(edge):
return edge[2]
g = UWeightedGraph()
g.add_edge(1,10,9)
g.add_edge(1,3,3)
g.add_edge(1,2,6)
g.add_edge(3,10,9)
g.add_edge(3,2,4)
g.add_edge(10,9,8)
g.add_edge(10,8,18)
g.add_edge(9,3,9)
g.add_edge(9,4,8)
g.add_edge(3,4,2)
g.add_edge(4,2,2)
g.add_edge(4,5,9)
g.add_edge(2,5,9)
g.add_edge(9,5,7)
g.add_edge(9,8,10)
g.add_edge(9,7,9)
g.add_edge(7,8,3)
g.add_edge(6,8,4)
g.add_edge(7,6,1)
g.add_edge(5,6,4)
g.add_edge(5,7,5)
print(minimum_spanning_tree(g))
<file_sep>/mst/WeightedQuickUnion.py
'''
Created on 28/6/2015
@author: matiaseidis
'''
class UnionFind:
def __init__(self, size):
self.size = size
self.components = [i for i in range(0, size)]
self.tree_sizes = [1] * size
def connect(self, a, b):
a_root = self.root(a)
b_root = self.root(b)
if(a_root is not b_root):
if(self.tree_sizes[a_root] < self.tree_sizes[b_root]):
self.components[a_root] = b_root
self.tree_sizes[b_root] += self.tree_sizes[a_root]
else:
self.components[b_root] = a_root
self.tree_sizes[a_root] += self.tree_sizes[b_root]
def connected(self, a, b):
return self.root(a) is self.root(b)
def root(self, a):
while a is not self.components[a]:
# path compression optimization
self.components[a] = self.components[self.components[a]]
a = self.components[a]
return a
# short test
# uf = UnionFind(3)
# print(uf.connected(0, 1))
# print(uf.connected(0, 2))
# uf.connect(0, 2)
# print(uf.connected(0, 1))
# print(uf.connected(0, 2))
<file_sep>/mst/UWeightedGraph.py
'''
Created on 28/6/2015
@author: matiaseidis
'''
class UWeightedGraph:
def __init__(self):
self.edges = []
self.v = set()
def add_edge(self, v, w, weight):
self.edges.append((v,w,weight))
self.v.add(v)
self.v.add(w)
def E(self):
return self.edges
def V(self):
return self.v
<file_sep>/mst/__init__.py
__author__ = 'us'
| 5b4fde29802abdbc16861f2fa701d8022b2607fc | [
"Python"
] | 4 | Python | matiaseidis/minimum-spanning-tree | 0addf0e99ceb8daedb2c819e1bfb6da5165e8507 | ee0969db0b0be13b4417ae5672062bdce532df1a |
refs/heads/main | <file_sep>import React from 'react';
const TodoList = (props) => {
//have access to all the todos we will pass the tasks as a prop
const todos= props.tasks.map((todo, index) => {
//whenever we use .map we use a unique key pass index as a parameter
return <Todo content={todo} key= {index} id= {index} onDelete={props.onDelete} />
})
return (
<div className= "list-wrapper">
{todos}
</div>
);
}
// windows key + . X
// Displaying the content of the task string
const Todo= (props) => {
return(
<div className= 'list-item'>
{props.content}
<button class="delete" onClick={() => {props.onDelete(props.id)}}> ❌ </button>
</div>
)
}
export default TodoList;
<file_sep>import React, { Component } from 'react';
import "./Styles/styles.css";
import Header from "./Components/Header";
import Todos from "./Components/Todos";
import Submit from "./Components/Submit";
import List from "./Components/List";
// import Widgets from "./Components/Widgets";
import { Container, Row, Col } from "reactstrap";
class App extends Component {
state = {
tasks: ['Avocado', 'Tomatoes', 'Bell Peppers']
};
handleSubmit = tasks => {
this.setState({ tasks: [...this.state.tasks, tasks] });
}
handleDelete = (index) => {
const newArr = [...this.state.tasks];
newArr.splice(index, 1);
this.setState({ tasks: newArr });
}
render() {
return (
<>
<Container>
<Row>
<Col md="10">
<div></div>
</Col>
<Col md="2">
{/* <Widgets /> */}
</Col>
</Row>
</Container>
<div className='wrapper'>
<div className='card frame'>
<Header numTodos={this.state.tasks.length} />
<Todos tasks={this.state.tasks} onDelete={this.handleDelete} />
<Submit onFormSubmit={this.handleSubmit} />
</div>
</div>
</>
);
}
}
export default App;
| b46e10a4b3bd43b0a19656422be18a11bff01d2f | [
"JavaScript"
] | 2 | JavaScript | Daniellecr99/Todo-App | f80b1a4900b4f3709cfd3eddacf0d2f63e26735a | 4dbcaef7375f5b1af626ec43e4fcf381b202d05b |
refs/heads/master | <file_sep>// Get data from API with fetch request
const apiUrl = "http://localhost:3000/api/furniture";
async function getAllItems(apiUrl) {
let result = await fetch(apiUrl)
return result.json()
};
export default getAllItems;<file_sep>//Create an array to get data stored in local storage
function getIdStored() {
let products = [];
var items = localStorage.getItem("cart");
items = JSON.parse(items);
console.log(items);
items.forEach(element => {
products.push(element.id);
});
return products
}
export default getIdStored;<file_sep>import getValueDataForm from "./_getValueDataForm.js";
// Fetch orderId from local storage to confirlm the order
function fetchOrderId() {
let objectRequest = getValueDataForm();
let request = new XMLHttpRequest();
request.open("POST", "http://localhost:3000/api/furniture/order");
request.setRequestHeader("Content-Type", "application/json");
request.send(objectRequest);
request.onreadystatechange = function () {
if (this.readyState == XMLHttpRequest.DONE) {
localStorage.setItem("order", this.responseText);
console.log(this.responseText);
alert(" Your order has been validated")
window.location.href = "confirmation.html";
}
};
}
export default fetchOrderId;<file_sep>// Get the order number stored in local storage
function getOrder() {
if (localStorage.getItem("order")) {
let confirmationNumber = document.querySelector("#orderNumber");
confirmationNumber.innerHTML = " " + JSON.parse(localStorage.getItem("order")).orderId;
};
};
export default getOrder;<file_sep>// Update Cart icon with right quantity
function updateCartIcon() {
let cartStorage = localStorage.getItem("cart");
if (cartStorage !== null) {
const cart = JSON.parse(cartStorage);
document.querySelector(".cartIndex").textContent = cart.length;
}
};
export default updateCartIcon;<file_sep>// Add total prices
let cartData = JSON.parse(localStorage.getItem("cart"));
function getTotalPrice(cartData) {
let price = 0;
cartData.forEach(function(cartItem) {
price += cartItem.price
})
return price
}
export default getTotalPrice;<file_sep>import getCartItems from "./_getCartItemsAjaxRequest.js";
import deleteOneItem from "./_deleteOneItem.js";
// Define constants
const url = "http://localhost:3000/api/furniture/";
// Create DOM elements to display cart row with selected items
export function displayCartRow(element, index) {
let idItem = element["id"];
let varnishItem = element["varnish"]
let infoItem = JSON.parse(getCartItems(url, idItem));
let productInfo = document.createElement("div");
document.querySelector(".cartContent").appendChild(productInfo);
productInfo.className = "productSummary";
let productTitle = document.createElement("h3");
productTitle.id = "itemTitleCart";
productTitle.innerText = infoItem["name"];
productInfo.appendChild(productTitle);
let productLink = document.createElement("a");
productLink.classList.add("productLink");
productLink.href = `product.html?id=${infoItem._id}`;
productInfo.appendChild(productLink);
let productImage = document.createElement("img");
productImage.id = "itemImageCart";
productImage.src = infoItem["imageUrl"];
productImage.href = `product.html?id=${infoItem._id}`;
productLink.appendChild(productImage);
let productVarnish = document.createElement("p");
productVarnish.id = "itemVarnishCart";
productVarnish.innerText = varnishItem;
productInfo.appendChild(productVarnish);
let productPrice = document.createElement("p");
productPrice.id = "itemPriceCart";
productPrice.innerText = infoItem.price / 100 + ` €`;
productInfo.appendChild(productPrice);
let productDelete = document.createElement("i");
productDelete.id = "removeItemCart";
productDelete.className = "fas fa-trash-alt";
productInfo.appendChild(productDelete);
productDelete.value = idItem;
console.log(productDelete.value);
productDelete.addEventListener("click", e => {
deleteOneItem(index);
location.reload();
});
return productInfo;
}
// Create DOM elements to display a button to empty cart
export function displayClearCartButton() {
let clearCart = document.createElement("button");
document.querySelector(".cartContent").appendChild(clearCart);
clearCart.className = "clearCartButton";
clearCart.textContent = "Empty the cart";
clearCart.addEventListener("click", () => {
localStorage.clear();
location.reload();
});
return clearCart
}
// Create DOM elements to display total cart price
export function displayPrice(amount) {
let totalPriceOrder = document.createElement("p");
totalPriceOrder.id = "totalPriceOrder";
totalPriceOrder.innerText = "The total amount of your order is " + amount / 100 + ` €`;
return totalPriceOrder
}
// Create DOM elements to display container when cart is empty
export function displayEmptyCart() {
let emptyCartContainer = document.createElement("div");
emptyCartContainer.className = "emptyCartContainer";
let displayEmptyCart = document.createElement("div");
displayEmptyCart.textContent = "Your cart is empty";
displayEmptyCart.className = "emptyCart";
emptyCartContainer.appendChild(displayEmptyCart);
let displayDiscoverButton = document.createElement("a");
displayDiscoverButton.textContent = "Discover our products";
displayDiscoverButton.href = "index.html"
displayDiscoverButton.className = "discoverButton";
emptyCartContainer.appendChild(displayDiscoverButton);
document.getElementById("registrationForm").style.display = "none";
return emptyCartContainer
}
// Display cart page according to the local storage content
export function displayCart(cartData) {
let cartContent = null;
if (cartData === null) {
cartContent = displayEmptyCart()
} else {
cartContent = document.createElement("div");
cartContent.className = "cartContainer";
cartData.forEach(function (cartItem, index) {
const cartRow = displayCartRow(cartItem, index)
cartContent.appendChild(cartRow);
});
}
return cartContent
}
<file_sep>function getCartItems(url, idItem) {
var item;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
item = this.responseText;
}
};
xhttp.open("GET", url + idItem, false);
xhttp.send();
return item;
}
export default getCartItems;<file_sep>
import getIdStored from "./_getIdStored.js";
//Get value fields entered by user
function getValueDataForm() {
let products = getIdStored();
let contact = {
firstName: document.getElementById("firstname").value,
lastName: document.getElementById("lastname").value,
email: document.getElementById("email").value,
city: document.getElementById("city").value,
address: document.getElementById("address").value,
};
let object = {
contact,
products,
};
let objectRequest = JSON.stringify(object);
return objectRequest
}
export default getValueDataForm;<file_sep>// Delete one specific item in cart
function deleteOneItem(index) {
const cartStorage = localStorage.getItem("cart");
if (cartStorage !== null) {
const cart = JSON.parse(cartStorage);
cart.splice(index,1);
if (cart.length === 0) {
localStorage.removeItem("cart");
} else {
localStorage.setItem("cart", JSON.stringify(cart));
}
}
};
export default deleteOneItem;<file_sep>
var articles = loadDoc();
document.getElementById('furniturePictures').innerHTML += 'Bonjour';
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
return this.responseText;
}
};
xhttp.open("GET", "http://localhost:3000/api/furniture", true);
xhttp.send();
}
<file_sep>import fetchOrderId from "../controllers/form/_fetchOrderId.js";
// Function which uppercases the first letter of a string
function ucFirst(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
// Define RegEx
const regexNames = /^[a-zA-Z ,.'-]+$/;
const regexAddress = /([0-9]{1,3}(([,. ]?){1}[-a-zA-Zàâäéèêëïîôöùûüç']+)*)/;
const regexCity = /((([,. ]?){1}[-a-zA-Zàâäéèêëïîôöùûüç']+)*)/;
const regexEmail = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
// If succeed RegEx validation, the post ajax request can execute
function createOrderValidationNumber() {
// Define an array with required details to validate the form
const fields = [
{
datakey: "firstname",
regex: regexNames
},
{
datakey: "lastname",
regex: regexNames
},
{
datakey: "email",
regex: regexEmail
},
{
datakey: "city",
regex: regexCity
},
{
datakey: "address",
regex: regexAddress
},
]
// Regex validation form
var form_Ok = true;
for (let i = 0; i < fields.length; i++) {
const field = fields[i];
const value = document.getElementById(field.datakey).value;
if (value == "" || field.regex.exec(value) == null) {
form_Ok = false
const missingDetails = document.getElementById(`miss${ucFirst(field.datakey)}`);
missingDetails.textContent = `${ucFirst(field.datakey)} is missing or unvalid`;
missingDetails.style.color = "red";
}
}
if (form_Ok) {
fetchOrderId();
}
};
export default createOrderValidationNumber;
<file_sep>import updateCartIcon from "../controllers/cart/_updateCartIcon.js";
import createOrderValidationNumber from "../pages/form.js";
import { displayCart, displayPrice, displayEmptyCart, displayClearCartButton } from "../controllers/cart/_displayCartPageComponents.js"
import getTotalPrice from "../controllers/cart/_getTotalPrice.js";
async function displayCartPage() {
// Define selectors
const cartContainerEl = document.querySelector(".cartContent");
const confirmationOrderEl = document.getElementById("sendButton");
// Call the below function to update the items quantity in the cart icon
updateCartIcon();
// Get cart data from local storage
const cartData = await JSON.parse(localStorage.getItem("cart"));
let cartContent = null;
let priceContent = null;
let clearButton = null;
if (cartData === null) {
// Display empty cart whan cartData is null
cartContent = displayEmptyCart()
cartContainerEl.appendChild(cartContent);
} else {
let totalPrice = getTotalPrice(cartData)
// Display page components with cartData
cartContent = displayCart(cartData)
priceContent = displayPrice(totalPrice)
clearButton = displayClearCartButton()
// Append different components to the cart page
cartContainerEl.appendChild(cartContent);
cartContainerEl.appendChild(priceContent);
cartContainerEl.appendChild(clearButton);
}
confirmationOrderEl.onclick = () => createOrderValidationNumber();
}
displayCartPage();
| 9775d17efad6331f082ad21363faa91f4fd3c5f9 | [
"JavaScript"
] | 13 | JavaScript | FlorineMty/FlorineMoutoussamy_5_28112020 | cd9d24fbbe9635278d3a78ea308175b1ae25244d | 2d8589a903ca9504e88fd6293037a11075d904e8 |
refs/heads/master | <repo_name>cartersteinhoff/csharp<file_sep>/Program.cs
using System;
namespace first_c_
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("hicarttasasdfsdfsdfdfester Hello Worakksdfasdfasdfkk a;ldsfjlaksdjfld!");
System.Console.WriteLine("Rubesdfnasdf,s welcomedd to the show!!!!!!!! 2");
System.Console.WriteLine("TESTTEST1WHAAAAAAAT");
}
}
}
| 6f5f6d78dca59e7cf29910ec2267d3236306b1c0 | [
"C#"
] | 1 | C# | cartersteinhoff/csharp | 6ecfb27a391088d95f9b4cff5accb70459b5b4e9 | ed67c090008fcc629bc068192d2ce50bd2f8bb97 |
refs/heads/master | <file_sep>/*
Compare two version numbers version1 and version2.
If version1 > version2 return 1, if version1 < version2 return -1,
otherwise return 0.
*/
#include<stdio.h>
#include<string.h>
int compareVersion(char *version1, char *version2);
void main(){
char v1[]="1";
char v2[]="2";
printf("op:%d\n",compareVersion(v1,v2));
}
int compareVersion(char *version1, char *version2){
char *pos1,*pos2;
char *val1,*val2;
int v1,v2;
val1=strtok_r(version1,".",&pos1);
val2=strtok_r(version2,".",&pos2);
while(val1 || val2) {
//printf("%s..%s\n",val1,val2);
v1=val1?atoi(val1):0;
v2=val2?atoi(val2):0;
//printf("%d..%d\n",v1,v2);
if(v1==v2){
val1=strtok_r(NULL,".",&pos1);
val2=strtok_r(NULL,".",&pos2);
}
else{
return (v1>v2?1:-1);
}
}
return 0;
}
<file_sep>#include<stdio.h>
#include<stdlib.h>
typedef struct Node
{
int key;
struct Node *left, *right;
}Node;
/* utility that allocates a new Node with the given key */
Node* newNode(int key)
{
Node* node = malloc(sizeof(Node));
node->key = key;
node->left = node->right = NULL;
return (node);
}
void inorder(Node* root){
if(root){
inorder(root->left);
printf("%d ",root->key);
inorder(root->right);
}
//printf("\n");
}
void fixleft(Node *root) {
static Node *prev=NULL;
if(root) {
fixleft(root->left);
root->left=prev;
prev=root;
fixleft(root->right);
}
}
Node *treetodll(Node *root){
Node *curr=root;
Node *prev=NULL;
fixleft(root);
while(curr->right)
curr=curr->right;
while(curr){
curr->right=prev;
prev=curr;
curr=curr->left;
}
return prev;
}
void traverselist(Node *head){
Node *temp=head;
while(temp){
printf("%d ",temp->key);
temp=temp->right;
}
printf("\n");
}
void main() {
Node *head;
Node * root = newNode(5);
root->left = newNode(3);
root->right = newNode(7);
root->left->left = newNode(2);
root->left->right = newNode(4);
root->right->left = newNode(6);
root->right->right = newNode(8);
//root->right->left->right = newNode(8);
inorder(root);
printf("\n");
head=treetodll(root);
traverselist(head);
}
<file_sep>//Bit vector implementation
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define SET(n,pos) (n|=(1<<pos))
#define CLEAR(n,pos) (n^=(1<<pos))
#define ISSET(n,pos) !!(n&(1<<pos))
typedef struct bit_vector{
void *ptr;
int size;
}BVEC;
int init_bitvec(BVEC *vec,int size){
int bytes= (size-1)/8+1;
vec->ptr=malloc(bytes);
if(!vec->ptr)
return -1;
memset(vec->ptr,0,bytes);
vec->size=size;
return 1;
}
int set_bitvec(BVEC *vec, int pos){
int byte;
int offset;
char val;
char *bytepos;
if(pos<=0 || pos>vec->size)
return -1;
byte=(pos-1)/8;
offset=(pos-1)%8;
bytepos=(char*)vec->ptr+byte;
SET(*bytepos,offset);
return 1;
}
int clear_bitvec(BVEC *vec, int pos){
int byte;
int offset;
char val;
char *bytepos;
if(pos<=0 || pos>vec->size)
return -1;
byte=(pos-1)/8;
offset=(pos-1)%8;
bytepos=(char*)vec->ptr+byte;
CLEAR(*bytepos,offset);
return 1;
}
int is_bitset(BVEC *vec, int pos){
int byte;
int offset;
char val;
char *bytepos;
if(pos<=0 || pos>vec->size)
return -1;
byte=(pos-1)/8;
offset=(pos-1)%8;
bytepos=(char*)vec->ptr+byte;
return (ISSET(*bytepos,offset));
}
void free_bitvec(BVEC *vec){
free(vec->ptr);
}
void main(){
int i;
BVEC my_bitvector;
init_bitvec(&my_bitvector,100);
int arr[]={34,3,45,67,89,23,12,1,99,7,100};
for(i=0;i<11;++i){
set_bitvec(&my_bitvector,arr[i]);
}
for(i=0;i<my_bitvector.size;++i){
if(is_bitset(&my_bitvector,i+1)){
printf("%d ",i+1);
clear_bitvec(&my_bitvector,i+1);
}
}
printf("\n next set \n");
for(i=0;i<my_bitvector.size;++i){
if(is_bitset(&my_bitvector,i+1)){
printf("%d ",i+1);
clear_bitvec(&my_bitvector,i+1);
}
}
free_bitvec(&my_bitvector);
}
<file_sep>/*
Generate all possible strings from given set of characters.
Repetitions allowed.
*/
#include<stdio.h>
int size;
void strgen(int n, char *, char*);
void main() {
char str[]={'x','y','z'};
char gen[3];
size=3;
strgen(0,str,gen);
}
void strgen(int n, char *str, char* gen){
if(n==size) {
int i;
for(i=0;i<size;++i)
printf("%c",gen[i]);
printf("\n");
}
else {
int i;
for(i=0;i<size;++i) {
gen[n]=str[i];
strgen(n+1,str,gen);
}
}
}
<file_sep>/*
Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words.
For example, given
s = "leetcode",
dict = ["leet", "code"].
Return true because "leetcode" can be segmented as "leet code".
*/
#include<iostream>
#include<string>
#include<unordered_set>
using namespace std;
bool wordBreak(string s, unordered_set<string> &dict);
int main() {
unordered_set<string> dict;
dict.insert("a");
dict.insert("abc");
dict.insert("b");
dict.insert("cd");
string s="abcd";
cout<<wordBreak(s,dict);
}
bool wordBreak(string s, unordered_set<string> &dict) {
bool dyn[s.size()];
for(int i=0;i<s.size();++i)
dyn[i]=false;
int i=0;
int j;
while(i<s.size()) {
string t=s.substr(0,i+1);
if(dict.find(t)!=dict.end()) {
dyn[i]=true;
}
if(dyn[i]==true) {
j=i+1;
while(j<s.size()) {
string ts=s.substr(i+1,j-i);
cout<<ts<<" ";
if(dict.find(ts)!=dict.end()) {
dyn[j]=true;
}
j++;
}
if(dyn[j-1]==true) {
return true;
}
}
i++;
}
//for(int i=0;i<s.size();++i)
//cout<<dyn[i];
return false;
}
<file_sep>/*
Given an array of size n, find the majority element.
The majority element is the element that appears more than ⌊ n/2 ⌋ times.
*/
#include<stdio.h>
int majorityElement(int a[],int n);
void main(){
int a[]={2,3,4,3,4,3,2,3,3,9,0,3,3,3,4};
printf("Maj element:%d\n",majorityElement(a,15));
}
int majorityElement(int num[], int n) {
int i;
int maj;
int count=0;
for(i=0;i<n;++i){
if(count==0){
maj=num[i];
count=1;
}
else if(num[i]==maj){
count++;
}
else{
count--;
}
}
return maj;
}
<file_sep>/*
A Generic Stack Implemenation.
*/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct my_stack{
void *ptr;
int size;
int elem_size;
int top;
}STACK;
int push(STACK *st, void* val) {
if(st->top==st->size) {
void *temp=realloc(st->ptr,2*st->size*st->elem_size);
if(!temp) {
return 0;
}
st->ptr=temp;
st->size*=2;
}
void *loc=st->ptr+(st->elem_size*st->top);
memcpy(loc,val,st->elem_size);
st->top++;
return 1;
}
int init_stack(STACK* st, int size, int elem_size) {
st->ptr=malloc(size*elem_size);
if(!st->ptr) {
return 0;
}
st->size=size;
st->elem_size=elem_size;
st->top=0;
return 1;
}
void *pop(STACK* st) {
void *val;
if(st->top==0)
return NULL;
st->top--;
val= st->top*st->elem_size+st->ptr;
return val;
}
void main() {
int i;
float *v, val[]={1.23,1.44,4.56,8.99,9.04,9,9,7.0};
STACK k;
init_stack(&k,3,sizeof(float));
for(i=0;i<8;i++) {
push(&k,(void*)&val[i]);
}
for(i=0;i<=7;i++) {
v=(float*)pop(&k);
if(!v)
printf("Empty!\n");
else
printf("%f\n",*v);
}
/*
for(i=0;i<5;i++) {
push(&k,(void*)&val[i]);
}
for(i=0;i<=7;i++) {
v=(float*)pop(&k);
if(!v)
printf("Empty!\n");
else
printf("%f\n",*v);
} */
}
<file_sep>/*
All possible permuatation of a string.
*/
#include<stdio.h>
void swap(char *a, char *b);
void permute(int k,int n, char str[]) ;
void main() {
char a[5]="ABCD";
permute(0,4,a);
}
void swap(char *a, char *b) {
char ch=*a;
*a=*b;
*b=ch;
}
void permute(int k,int n, char str[]) {
if(k==n) {
printf("%s\n",str);
}
else {
int i;
for(i=k;i<n;++i) {
swap(str+i,str+k);
permute(k+1,n,str);
swap(str+k,str+i);
}
}
}
<file_sep>//Find the missing element in a list of contiguous elements.
//O(log(n)) algorithm
#include<stdio.h>
int missing_element(int[],int,int);
void main(){
int a[]={4,5,6,7,8,9,10,11,12,14};
printf("Missing element:%d\n",missing_element(a,0,9));
}
//Similar to binary search
int missing_element(int a[],int beg,int end){
int mid;
if(beg>=end)
return -1;
mid=(beg+end)/2;
//difference will be 2 in case the missing number at the boundary
//>1 or ==2 will suffice for condition
if((a[mid+1]-a[mid])>1)
return a[mid]+1;
if((a[mid]-a[beg])>(mid-beg))
return missing_element(a,beg,mid);
else
return missing_element(a,mid+1,end);
}
<file_sep>/*
Given an array of integers which is initially increasing and then decreasing, find the maximum value in the array.
*/
#include<stdio.h>
int getmax(int a[],int n);
void main(){
//int a[]={1,2,3,4,5,6,7,8,9,10,9,8,7,6,5};
int arr[] = {1, 3, 50, 10, 9, 7, 6};
printf("%d",getmax(arr,7));
}
int getmax(int a[],int n){
int mid=0;
if(n==1)
return a[0];
mid=n/2;
if(a[mid-1]>a[mid])
return getmax(a,mid);
else
return getmax(a+mid,n-mid);
}
<file_sep>/*
There are 2 sorted arrays A and B of size m and n.
Write an algorithm to find the median of the array obtained after merging the above 2 arrays(i.e. array of length m+n).
The complexity should be O(log(n))
credits: http://yucoding.blogspot.com/2013/01/leetcode-question-50-median-of-two.html
*/
#include<iostream>
using namespace std;
int getatpos(int A[],int m, int B[],int n,int k) ;
float medianofsorted(int A[],int m, int B[],int n) ;
//Driver Program
int main() {
int A[]={5,6,7,8,9,10,11,12,13,14};
int B[]={21};
cout<<medianofsorted(A,10,B,1);
return 0;
}
int getatpos(int A[],int m, int B[],int n,int k) {
if(m>n)
return getatpos(B,n,A,m,k);
if(m==0)
return B[k-1];
if(k==1)
return min(A[0],B[0]);
int p=min(m,k/2);
int q=k-p;
if(A[p-1]>B[q-1]) {
return getatpos(A,m,B+q,n,k-q);
}
else {
return getatpos(A+p,m,B,n,k-p);
}
}
float medianofsorted(int A[],int m, int B[],int n) {
int k=(m+n)/2+1;
if((m+n)%2==1)
return getatpos(A,m,B,n,k);
else
return (getatpos(A,m,B,n,k)+getatpos(A,m,B,n,k-1))/2.0;
}
<file_sep>//Rotate array by k elements to right.
//For eg: if a[]={1,2,3,4,5} and k=2, o/p:a[]={4,5,1,2,3}
#include<stdio.h>
void rotate(int nums[], int n, int k);
void reverse(int a[],int beg,int end);
void swap(int *a, int *b);
void main(){
int a[]={1,2,3,4,5,6,7,8,9,10};
rotate(a,10,2);
}
//Reverse n-k and k elements seperately.
//Reverse the entire list again.
//If it is to rotate to left, reverse k and n-k sepereately, and reverse the entire list.
void rotate(int nums[], int n, int k) {
k=k%n;
reverse(nums,0,n-k-1);
reverse(nums,n-k,n-1);
reverse(nums,0,n-1);
}
void reverse(int a[],int beg,int end){
if(beg>=end)
return;
swap(&a[beg],&a[end]);
reverse(a,beg+1,end-1);
}
void swap(int *a, int *b){
int t=*a;
*a=*b;
*b=t;
}
<file_sep>/*
Suppose a sorted array is rotated at some pivot unknown to you beforehand.
(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
Find the minimum element.
You may assume no duplicate exists in the array.
*/
/*C Code*/
int findMin(int num[], int n) {
int mid;
if(n==1)
return num[0];
mid=n/2;
if(num[mid-1]>num[mid])
return num[mid];
if(num[mid]>num[n-1])
return findMin(num+mid,n-mid);
return findMin(num,mid);
}
| 409e948e67f954eac40483f771a024a7e7448a7d | [
"C",
"C++"
] | 13 | C | franklinio/pebbles | 7f79a1560d753e5b57dc69e8e2f73d8193d48f0a | a0ea158ed1fd331465e3dac1b4f6ab1e7215da2f |
refs/heads/main | <repo_name>aamtman/javascript-challenge<file_sep>/UFO-level-1/StarterCode/static/js/app.js
// from data.js
var tableData = data;
var tableBody = d3.select("tbody");
function buildData(data){
tableBody.html("");
data.forEach((tableRow)=>{
var Row= tableBody.append("tr");
Object.values(tableRow).forEach((Value)=>{
var tableCell=Row.append("td");
tableCell.text(Value);
})
})
}
// YOUR CODE HERE!
buildData(tableData)
function filterData(){
var tableDate = d3.select ("#datetime").property("value");
var filterData = tableData;
filterData= filterData.filter(datarow=>datarow.datetime===tableDate);
buildData(filterData);
}
d3.selectAll("#filter-btn").on("click",filterData);
var $tbody = d3.select("tbody");
var button = d3.select("#filter-btn");
var inputFieldDate = d3.select("#datetime");
var inputFieldCity = d3.select("#city");
var columns = ["datetime", "city", "state", "country", "shape", "comments"]
// Inputing the data into the HTML
var addData = (dataInput) => {
dataInput.forEach(ufoSightings => {
var row = $tbody.append("tr");
columns.forEach(column => row.append("td").text(ufoSightings[column])
)
});
}
addData(tableData);
// Creating an Event Listener for the Button
// Setting up the Filter Button for Date and City
button.on("click", () => {
d3.event.preventDefault();
var inputDate = inputFieldDate.property("value").trim();
// console.log(inputDate)
// trim the inputs
var filterDate = tableData.filter(tableData => tableData.datetime === inputDate);
$tbody.html("");
let response = {
filterDate
}
if(response.filterDate.length !== 0) {
addData(filterDate);
}
// add comment if not sightings
else {
$tbody.append("tr").append("td").text("No Sightings Here...Move On...");
}
}) | 82cc0bfe0944cb0d32883d89fbcd2c23616b23a6 | [
"JavaScript"
] | 1 | JavaScript | aamtman/javascript-challenge | 407e79f3ccd2d729aed6e57f4132f6c9b1e024d0 | e05d12022156230448eebcad8affe6fd64012771 |
refs/heads/master | <repo_name>neziriemin/phallinta<file_sep>/h3.md
# Kurssin pitäjänä toimii <NAME>.
Työvälineisiin kuuluu oma tietokone (Acer Aspire V15 Touche), internet yhteys sekä DataTravel USB livetikku, tikulle on asennettu xUbuntu.
Tehtävän löytyy linkistä: http://terokarvinen.com/2018/aikataulu-%e2%80%93-palvelinten-hallinta-ict4tn022-3004-ti-ja-3002-to-%e2%80%93-loppukevat-2018-5p
# Tehtävät
# c) Laita /srv/salt/ gittiin. Tee uusi moduli. Kloonaa varastosi toiselle koneelle (tai poista /srv/salt ja palauta se kloonaamalla) ja jatka sillä.
Aloitin tehtävän asentamalla gitin komennolla "sudo apt-get -y install git", sekä antamalla käskyn jolla git ei pyydä jatkuvasti näppäilemään salasanaa kun kopioin muutokset gitistä githubiin "$ git config --global credential.helper "cache --timeout=3600" ".
Tämän jälkeen kirjauduin githubiin aikaisemmin tehdyillä tunnuksilla ja loin sinne uuden "repositoryn" nimeltä salt.
Kopioin repositoryn tietokoneen srv kansioon komennolla "git clone:kloonauslinkki_löytyy_githubista", HUOM. srv kansioon tarvitsee sudo oikeudet jotta muutoksia voi tehdä.
Tein muutoksia README.md tiedostoon, tallensin sen ja annoin komentoriviltä komennon "$ git add . && git commit; git pull && git push", kun tein tämän ensimmäisen kerran, git pyysi antamaan github käyttäjätunnuksen ja salasanan.
Avasin githubin ja näin että kyseiset muutokset tuli voimaan.
Viimeiseksi, kloonasin tekemäni salt repositoryn uudelle koneelle.
Ohjeet gitin asentamiseen löytyvät linkistä: http://terokarvinen.com/2016/publish-your-project-with-github
# d) Näytä omalla salt-varastollasi esimerkit komennoista ‘git log’, ‘git diff’ ja ‘git blame’. Selitä tulokset.
Komento git log:
commit <PASSWORD>
Author: Emin <<EMAIL>>
Date: Mon Nov 12 11:36:44 2018 +0000
just a test
Tällä komennolla näkyy muutokset jotka on tallennettu, sekä tiedot siitä että kuka on tehnyt muutokset ja mihin aikaan ne tehtiin.
Komento git diff
diff --git a/h3 b/h3
index d2dc797..aec402c 100644
--- a/h3
+++ b/h3
@@ -20,6 +20,16 @@ c
Tällä komennolla näkyy muutokset joita ei ole vielä tallennettu.
Komento git blame h3:
4689be34 (Emin 2018-11-12 11:52:21 +0000 1) # Kurssin pitäjänä toimii Tero Karvinen.
4689be34 (Emin 2018-11-12 11:52:21 +0000 2)
416af8d6 (Emin 2018-11-12 12:19:48 +0000 3) Työvälineisiin kuuluu oma tietokone (Acer Aspire V15 Touche), internet yhteys sekä DataTravel USB livetikku, tikulle on asennettu xUbuntu.
416af8d6 (Emin 2018-11-12 12:19:48 +0000 4)
Tällä komennolla näkyy ketä on tehnyt muutokset ja mihin aikaan. Komentoa voi käyttää hyväkseen esim ryhmätyöskentelyssä.
# e) Tee tyhmä muutos gittiin, älä tee commit:tia. Tuhoa huonot muutokset ‘git reset –hard’. Huomaa, että tässä toiminnossa ei ole peruutusnappia.
Poistin salt kansiosta README.md tiedoston. Annoin komennon "git reset --hard" jolla sain takaisin viimeiseksi tallentamani tilan. Eli README.md tiedosto palautui.
# f) Tee uusi salt-moduli. Voit asentaa ja konfiguroida minkä vain uuden ohjelman: demonin, työpöytäohjelman tai komentokehotteesta toimivan ohjelman. Käytä tarvittaessa ‘find -printf “%T+ %p\n”|sort’ löytääksesi uudet asetustiedostot.
Automatisoin sysstatin. Tein sysstatin automatisoinnin viimeviikolla h2 tehtävässä.
Käytin h2 ohjeita tässä tehtävässä. Eli asensin sysstatin, kopioin etc/default hakemistossa olevan sysstat tiedoston /srv/salt hakemistoon, loin sls tiedoston johon lisäsin paketin latauksen, ja uudelleenkäynnistyksen watch tekniikalla.
Ohjeet löytyy linkistä: https://linuxtehtavatdotblog.wordpress.com/2018/11/06/palvelinten-hallinta-h2/
Lisäsin kansiot githubiin ja siirryin eri koneelle. Toisella koneella kirjauduin githubiin ja kopioin kaikki aikaisemmin tehdyt tehtävät uudelle koneelle. Annoin komennon " sudo salt '*' state.apply sysstat ". komento toimi ja sain sysstatin asennettua ilman virheilmoituksia.
Lähteet:
<NAME>
http://terokarvinen.com/
Salt minion & master http://terokarvinen.com/2018/salt-quickstart-salt-stack-master-and-slave-on-ubuntu-linux
States http://terokarvinen.com/2018/pkg-file-service-control-daemons-with-salt-change-ssh-server-port
Github ABC http://terokarvinen.com/2016/publish-your-project-with-github
<NAME>
https://wordpress.com/post/linuxtehtavatdotblog.wordpress.com/100
<file_sep>/saltscript.sh
#!/bin/bash
# Copyright 2018 <NAME> http://TeroKarvinen.com GPL 3
# Edited by <NAME>
echo "Updating packages and installing salt-minion"
sudo apt -y update
sudo apt -y install salt-minion
echo -e 'master: 192.168.1.83 \nid: orja' |sudo tee /etc/salt/minion
sudo systemctl restart salt-minion
<file_sep>/README.md
# saltprojekti
| debadfcffae745022b2cb53b1a2e5a6411f45e78 | [
"Markdown",
"Shell"
] | 3 | Markdown | neziriemin/phallinta | dd4ab06aed296411c562cafa63b0aa875444e960 | 4cd5f230e990b982af901067f12530460bee8c6d |
refs/heads/master | <file_sep>/* Program Name: List-Split
* Description: There is a function that splits an original linked list into two different ones.
* Latest Modification Date: Thu 11/01/2018
* Author: GitHub @mannuscritto
* Version: 0.1.0
*/
#include <stdio.h>
#include <stdlib.h>
#include <locale.h>
struct node {
int value;
struct node *next;
};
typedef struct node snode;
snode *newNode, *pointer, *back, *temp;
snode *front = NULL, *rear = NULL;
snode* createNode(int val) {
newNode = (snode *)malloc(sizeof(snode));
if (newNode == NULL) {
printf("\nO nó não foi alocado!\n");
} else {
newNode->value = val;
newNode->next = NULL;
return newNode;
}
}
void insertion(int val, int pos) {
int count = 0, i;
newNode = createNode(val);
pointer = front;
while (pointer != NULL) {
pointer = pointer->next;
count++;
}
if (pos == 1) {
if (front == NULL) {
front = rear = newNode;
front->next = NULL;
rear->next = NULL;
} else {
temp = front;
front = newNode;
front->next = temp;
}
printf("\nValor %d inserido com sucesso!\n", val);
} else if (pos > 1 && pos <= count) {
pointer = front;
for (i = 1; i < pos; i++) {
back = pointer;
pointer = pointer->next;
}
back->next = newNode;
newNode->next = pointer;
printf("\nValor %d inserido com sucesso!\n", val);
} else if (pos == count+1) {
if (front == NULL) {
front = rear = newNode;
front->next = NULL;
rear->next = NULL;
} else {
rear->next = newNode;
rear = newNode;
rear->next = NULL;
}
printf("\nValor %d inserido com sucesso!\n", val);
} else {
printf("\nA posição escolhida não existe!\n");
}
}
//Remover
void deletion(int pos) {
int count = 0, i, vlr;
if (front == NULL) {
printf("\nNão existem elementos para deletar!\n");
} else {
pointer = front;
if (pos == 1) {
vlr = front->value;
front = pointer->next;
printf("\nValor %d deletado com sucesso!\n", vlr);
} else {
while (pointer != NULL) {
pointer = pointer->next;
count++;
}
if (pos > 0 && pos <= count) {
pointer = front;
for (i = 1; i < pos; i++) {
back = pointer;
pointer = pointer->next;
}
back->next = pointer->next;
} else {
printf("\nA posição escolhida não existe!\n");
}
free(pointer);
printf("\nElemento deleteado com sucesso!\n");
}
}
}
//Teste função mostrar
void display() {
if (front == NULL) {
printf("\nImpossível imprimir valores! A lista está vazia!\n");
return;
} else {
printf("|");
for (pointer = front; pointer != NULL; pointer = pointer->next) {
printf(" %d |", pointer->value);
}
printf("\n");
}
}
void displayItem(int pos) {
if (front == NULL) {
printf("\nImpossível imprimir valores! A lista está vazia!\n");
return;
} else {
int count = 0, i;
pointer = front;
while (pointer != NULL) {
pointer = pointer->next;
count++;
}
pointer = front;
if (pos > 0 && pos <= count) {
for (i = 1; i < pos; i++) {
pointer = pointer->next;
}
printf("\n| %d |\n", pointer->value);
} else {
printf("\nA posição escolhida não existe!\n");
}
}
}
int main(int argc, char** argv) {
setlocale(LC_ALL, "Portuguese");
int opt, vlr, pos;
while (1) {
system("cls");
printf("MENU\n\n");
printf("\tInserir [1]\n");
printf("\tDeletar [2]\n");
printf("\tImprimir [3]\n");
printf("\tExibir item [4]\n");
printf("\tSair [0]\n");
printf("Digite a opção: ");
scanf("%d", &opt);
switch (opt) {
case 1:
printf("\nDigite o valor do item: ");
do {
scanf("%d", &vlr);
} while(vlr < 0);
printf("\nDigite a posição para inserir %d: ", vlr);
do {
scanf("%d", &pos);
} while(pos < 0);
insertion(vlr, pos);
break;
case 2:
printf("\nDigite a posição para remover %d: ", vlr);
do {
scanf("%d", &pos);
} while(pos < 0);
deletion(pos);
break;
case 3:
display();
break;
case 4:
printf("\nDigite a posição para exibir: ");
do {
scanf("%d", &pos);
} while(pos < 0);
displayItem(pos);
break;
case 0:
exit(0);
break;
default:
printf("\nOpção Inválida!\n");
}
system("pause");
}
return 0;
}
| 6bc0ce4419a09459594546288b8ddde47d3b7100 | [
"C"
] | 1 | C | mannuscritto/list-split | c86faaa69a5ca60980a92a24ff2497f51349e4fd | 925936c3136b802efc2cb8155e3d7e76d3af385b |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.